Skip to content

abso-core

Public

abso is version control for agents: the client, the engine and a server you can run on your own Cloudflare account.

Check passed
MCP
code on this site's /mcp
CLI
none: the JSON below is the answer
JSON
/christopher/abso-core/files/src/engine/graph.ts?version=128&format=json
1,273 linesFirst import 83% · codex-capacity-chair 17%Last change codex-capacity-chair in version 128, 9 versions changed it

You're reading version 128. The newest is 318, and 26 versions since then changed this file. Go to the newestCompare with 318

1// The graph: every atom ever accepted, plus labels. Sets of atoms (states of
2// the codebase) are separate values; the graph only answers questions about
3// atoms and keeps indexes so those questions are cheap.
4
5import {
6 atomId,
7 attrKey,
8 gapKey,
9 isAtomId,
10 isStartNode,
11 lineId,
12 lineKey,
13 parseKey,
14 posKey,
15 seqOf,
16 startNode,
17} from "./keys.ts";
18import {
19 type GraphStateStorage,
20 type StateMap,
21 storedArray,
22 storedLists,
23 storedMap,
24 storedNumbers,
25} from "./state-source.ts";
26import {
27 ATTR_NAMES,
28 type Atom,
29 type AtomId,
30 EngineError,
31 type InsertRun,
32 type Key,
33 type Label,
34 type LineId,
35 type NodeId,
36 REASON_KINDS,
37 type Reason,
38} from "./types.ts";
40/**
41 * Where a line was written and what it says. Its text never changes. A move
42 * can give it another parent in a set, even in another file: `view.parentOf`
43 * and `view.fileOf` say where it is in a set.
44 */
45export interface LineInfo {
46 readonly id: LineId;
47 readonly atom: AtomId;
48 readonly k: number;
49 /** The file it was written in. */
50 readonly file: string;
51 /** The node it was written after. */
52 readonly parent: NodeId;
53 readonly text: string;
56/** One relocation of a line, by the atom that made it; `k` is its place in that atom's moves. */
57export interface RelocationInfo {
58 readonly atom: AtomId;
59 readonly line: LineId;
60 readonly parent: NodeId;
61 readonly k: number;
64/** A `together` reason seen from one end: `other` is the atom at the far end. */
65export interface TogetherLink {
66 readonly other: AtomId;
67 readonly text: string;
68 /** The atom that carries the reason. */
69 readonly from: AtomId;
72export const GRAPH_FORMAT = "ai-first-vcs.graph";
74/** The saved form of a graph. Atoms are in seq order. */
75export interface GraphJSON {
76 readonly format: typeof GRAPH_FORMAT;
77 readonly version: 1;
78 readonly atoms: readonly Atom[];
79 readonly labels: readonly Label[];
82/**
83 * An index entry that holds a lone value as itself, and a list only once there
84 * are two (#46): most keys name one atom, and a list for each costs more than
85 * the value.
86 */
87function pushOne<K, V>(map: StateMap<K, V | V[]>, key: K, value: V): void {
88 const had = map.get(key);
89 if (had === undefined) map.set(key, value);
90 else if (Array.isArray(had)) {
91 had.push(value);
92 map.set(key, had);
93 } else map.set(key, [had, value]);
96function listOf<V>(had: V | V[] | undefined): readonly V[] {
97 return had === undefined ? EMPTY : Array.isArray(had) ? had : [had];
100function pushIndex<K, V>(map: StateMap<K, V[]>, key: K, value: V): void {
101 const list = map.get(key);
102 if (list) {
103 list.push(value);
104 map.set(key, list);
105 } else map.set(key, [value]);
108const EMPTY: readonly never[] = Object.freeze([]);
110/**
111 * A run whose lines are read when asked for (#46, text on disk): a few fields
112 * and a shared reader, where an object with its own accessor cost about 400
113 * bytes a run.
114 */
115class LazyRun implements InsertRun {
116 readonly file: string;
117 readonly parent: NodeId;
118 readonly #text: (start: number, length: number) => readonly string[];
119 readonly #start: number;
120 readonly #length: number;
121 constructor(
122 file: string,
123 parent: NodeId,
124 text: (start: number, length: number) => readonly string[],
125 start: number,
126 length: number,
127 ) {
128 this.file = file;
129 this.parent = parent;
130 this.#text = text;
131 this.#start = start;
132 this.#length = length;
133 }
134 get lines(): readonly string[] {
135 return this.#text(this.#start, this.#length);
136 }
137 toJSON(): InsertRun {
138 return { file: this.file, parent: this.parent, lines: this.lines };
139 }
142/** Characters of atoms' text a graph that keeps text elsewhere holds at most (#46): about 8 MB. */
143const TEXT_CACHE = 4_000_000;
144/** How many list items (deletes and keys) are kept read back (#46): publishes and syncs meet few atoms, but one reformat's atom can hold 100,000. */
145const LIST_CACHE = 50_000;
147/** An atom's deletes and claim keys: kept in the log rather than in memory when the graph has a `lists` reader (#46). */
148export interface AtomLists {
149 readonly deletes: readonly LineId[];
150 readonly writes: readonly Key[];
151 readonly reads: readonly Key[];
152 readonly holds: readonly Key[];
155function listItems(l: AtomLists): number {
156 return l.deletes.length + l.writes.length + l.reads.length + l.holds.length;
159function frozenList<T>(xs: readonly T[]): readonly T[] {
160 return xs.length === 0 ? (EMPTY as readonly T[]) : Object.freeze([...xs]);
163/**
164 * An atom whose deletes, writes, reads and holds are read back through `read` (#46). The getters live on the
165 * prototype, so each atom keeps one reader and a fixed shape, not four closures in a dictionary-mode object.
166 */
167class ListedAtom {
168 readonly #read: () => AtomLists;
169 constructor(fields: object, read: () => AtomLists) {
170 Object.assign(this, fields);
171 this.#read = read;
172 }
173 get deletes(): readonly LineId[] {
174 return this.#read().deletes;
175 }
176 get writes(): readonly Key[] {
177 return this.#read().writes;
178 }
179 get reads(): readonly Key[] {
180 return this.#read().reads;
181 }
182 get holds(): readonly Key[] {
183 return this.#read().holds;
184 }
185 toJSON(): object {
186 return { ...this, ...this.#read() };
187 }
190/** A growable array of 32-bit integers: a line's fields cost 4 bytes each, not an object and its strings (#46). */
191interface NumberIndex {
192 readonly length: number;
193 push(n: number): void;
194 at(i: number): number;
195 set(i: number, n: number): void;
198class Ints implements NumberIndex {
199 #buf: Int32Array | Uint8Array;
200 /** bytes: values 0-255 only, one byte each. */
201 constructor(bytes = false) {
202 this.#buf = bytes ? new Uint8Array(1024) : new Int32Array(1024);
203 }
204 length = 0;
205 push(n: number): void {
206 if (this.length === this.#buf.length) {
207 const bigger =
208 this.#buf instanceof Uint8Array ? new Uint8Array(this.#buf.length * 2) : new Int32Array(this.#buf.length * 2);
209 bigger.set(this.#buf);
210 this.#buf = bigger;
211 }
212 this.#buf[this.length++] = n;
213 }
214 at(i: number): number {
215 return this.#buf[i]!;
216 }
217 set(i: number, n: number): void {
218 this.#buf[i] = n;
219 }
222/**
223 * A line id's place in the graph's line arrays, or -1: "a<seq>.<k>" is line
224 * `base[seq] + k`. Hand-parsed, as seqOf is, with the same rules: no leading
225 * zeros, and k within the lines its atom wrote.
226 */
227function parseLineId(id: string): { seq: number; k: number } | undefined {
228 if (typeof id !== "string") return undefined;
229 const n = id.length;
230 if (n < 4 || id.charCodeAt(0) !== 97 /* a */) return undefined;
231 let i = 1;
232 let seq = 0;
233 const seqStart = i;
234 for (; i < n; i++) {
235 const c = id.charCodeAt(i);
236 if (c === 46 /* . */) break;
237 if (c < 48 || c > 57) return undefined;
238 seq = seq * 10 + (c - 48);
239 }
240 if (i === seqStart || i >= n - 1 || i - seqStart > 15 || (i - seqStart > 1 && id.charCodeAt(seqStart) === 48))
241 return undefined;
242 const kStart = ++i;
243 let k = 0;
244 for (; i < n; i++) {
245 const c = id.charCodeAt(i);
246 if (c < 48 || c > 57) return undefined;
247 k = k * 10 + (c - 48);
248 }
249 if (i - kStart > 15 || (i - kStart > 1 && id.charCodeAt(kStart) === 48)) return undefined;
250 return { seq, k };
253export class Graph {
254 readonly #storage?: GraphStateStorage;
255 #atoms: Atom[] = [];
256 #lamport: number[] = [];
257 // Lines, packed (#46): line n is the k-th line atom seq wrote, n = #lineBase[seq] + k. Each holds its
258 // atom's seq, the file it was written in (an index into #paths) and its parent (a line's n, or -1 - a
259 // path's index for a file's start). Its text stays in the atom. Ids and LineInfo objects are made only
260 // when asked for, so a line costs about 16 bytes here instead of a record, its id and its parent's id.
261 #lineBase: number[] = [];
262 #lineAtom: NumberIndex = new Ints();
263 #lineFile: NumberIndex = new Ints();
264 #lineParent: NumberIndex = new Ints();
265 /** Lines' text, when the graph keeps it; without it, it comes from `texts` (#46, text on disk). */
266 #lineText: string[] | undefined = [];
267 get #lineTotal(): number {
268 return this.#lineAtom.length;
269 }
270 /** Where an atom's lines' text is when the graph doesn't keep it: each run's lines, by the atom's seq. */
271 #texts: ((seq: number) => readonly (readonly string[])[]) | undefined;
272 /** Recently read atoms' text, flattened, most recent last, up to TEXT_CACHE characters. */
273 #textCache = new Map<number, readonly string[]>();
274 #textCached = 0;
276 /**
277 * `texts`, when given, says where each atom's lines' text can be read back
278 * (#46): the graph then keeps no text, only each line's place, and reads an
279 * atom's text when a line of it is asked for, keeping the most recent.
280 */
281 constructor(
282 options: {
283 texts?: (seq: number) => readonly (readonly string[])[];
284 lists?: (seq: number) => AtomLists;
285 storage?: GraphStateStorage;
286 } = {},
287 ) {
288 if (options.texts) {
289 this.#texts = options.texts;
290 this.#lineText = undefined;
291 }
292 if (options.lists) this.#lists = options.lists;
293 this.#storage = options.storage;
294 if (options.storage) {
295 const storage = options.storage;
296 const numbers = (name: string): NumberIndex => storedNumbers(storage, name);
297 this.#atoms = storedArray<Atom>(storage, "atoms", (atom) =>
298 freezeAtom(
299 atom,
300 (id) => id,
301 (author) => author,
302 ),
303 );
304 this.#lamport = storedArray(storage, "lamport");
305 this.#lineBase = storedArray(storage, "line-base");
306 this.#paths = storedArray(storage, "paths");
307 this.#movers = storedArray(storage, "movers");
308 this.#atomFiles = storedArray(storage, "atom-files");
309 this.#atomDeletes = storedArray(storage, "atom-deletes");
310 this.#lineAtom = numbers("line-atom");
311 this.#lineFile = numbers("line-file");
312 this.#lineParent = numbers("line-parent");
313 this.#deleter = numbers("deleter");
314 this.#replacing = numbers("replacing");
315 this.#lineText = storedArray(storage, "line-text");
316 this.#pathIndex = storedMap(storage, "path-index");
317 this.#moreDeleterPages = storedLists<number>(storage, "more-deleters", (key) =>
318 JSON.stringify(["number", Number(key)]),
319 );
320 this.#writersPages = storedLists<AtomId>(storage, "writers", (key) => key);
321 this.#readersPages = storedLists<AtomId>(storage, "readers", (key) => key);
322 this.#holdersPages = storedLists<AtomId>(storage, "holders", (key) => key);
323 this.#dependentsPages = storedLists<AtomId>(storage, "dependents");
324 this.#resolversPages = storedLists<AtomId>(storage, "resolvers");
325 this.#together = storedMap(storage, "together");
326 this.#fileAtomPages = storedLists<AtomId>(storage, "file-atoms");
327 this.#runStarts = storedMap(storage, "run-starts");
328 this.#relocationPages = storedLists<RelocationInfo>(storage, "relocations");
329 this.#relocatedToPages = storedLists<RelocationInfo>(storage, "relocated-to");
330 this.#relocatedToCodePages = storedLists<RelocationInfo>(storage, "relocated-to-code", (key) =>
331 JSON.stringify(["number", Number(key)]),
332 );
333 this.#labels = storedMap(storage, "labels");
334 }
335 }
337 /** Where an atom's key and delete lists are when the graph doesn't keep them (#46): the stored atom. */
338 #lists: ((seq: number) => AtomLists) | undefined;
339 /** Recently read atoms' lists, most recent last, up to LIST_CACHE atoms. */
340 #listCache = new Map<number, AtomLists>();
341 #listCached = 0;
343 /** An atom's deletes, writes, reads and holds, read back from where they are stored. */
344 #listsOf(seq: number): AtomLists {
345 const hit = this.#listCache.get(seq);
346 if (hit) {
347 this.#listCache.delete(seq);
348 this.#listCache.set(seq, hit);
349 return hit;
350 }
351 const got = this.#lists!(seq);
352 const lists: AtomLists = {
353 deletes: frozenList(got.deletes),
354 writes: frozenList(got.writes),
355 reads: frozenList(got.reads),
356 holds: frozenList(got.holds),
357 };
358 this.#listCache.set(seq, lists);
359 this.#listCached += listItems(lists);
360 for (const [old, kept] of this.#listCache) {
361 if (this.#listCached <= LIST_CACHE || old === seq) break;
362 this.#listCache.delete(old);
363 this.#listCached -= listItems(kept);
364 }
365 return lists;
366 }
368 /** The reader an atom's lists use; made apart from add() so it keeps no atom alive (see #reader). */
369 #listReader(seq: number): () => AtomLists {
370 return () => this.#listsOf(seq);
371 }
373 /**
374 * A claim key as the index keeps it (#46): a line's L:, P: and G: keys by its n (n * 4, + 1, + 2), so the
375 * index holds numbers rather than one string per line; start-node and attribute keys stay strings. A key
376 * naming a line the graph doesn't have stays a string, which nothing has claimed.
377 */
378 #code(key: Key): Key | number {
379 const t = key.charCodeAt(0);
380 if (key.charCodeAt(1) !== 58 || key.charCodeAt(2) === 94) return key; // not "X:", or a start node "^"
381 const k = t === 76 ? 0 : t === 80 ? 1 : t === 71 ? 2 : -1; // L, P, G
382 if (k < 0) return key;
383 const n = this.#lineN(key.slice(2));
384 return n < 0 ? key : n * 4 + k;
385 }
387 /** An atom's lines' text, in k order. */
388 #textOf(seq: number): readonly string[] {
389 const hit = this.#textCache.get(seq);
390 if (hit) {
391 this.#textCache.delete(seq);
392 this.#textCache.set(seq, hit);
393 return hit;
394 }
395 const flat = this.#texts!(seq).flat();
396 let chars = 0;
397 for (const t of flat) chars += t.length + 1;
398 this.#textCache.set(seq, flat);
399 this.#textCached += chars;
400 for (const [old, lines] of this.#textCache) {
401 if (this.#textCached <= TEXT_CACHE || old === seq) break;
402 this.#textCache.delete(old);
403 for (const t of lines) this.#textCached -= t.length + 1;
404 }
405 return flat;
406 }
408 /**
409 * The reader an atom's runs use. Made in a function of its own: a closure made inside add() would
410 * keep add()'s whole scope alive, the atom as given with all its text included.
411 */
412 #reader(seq: number): (start: number, length: number) => readonly string[] {
413 return (start, length) => this.#textOf(seq).slice(start, start + length);
414 }
416 /** Line n's text. */
417 #text(n: number): string {
418 if (this.#lineText) return this.#lineText[n]!;
419 const seq = this.#lineAtom.at(n);
420 return this.#textOf(seq)[n - this.#lineBase[seq]!]!;
421 }
422 #paths: string[] = [];
423 #pathIndex: StateMap<string, number> = new Map();
424 /** The first atom that deletes each line (its seq), or -1; a line deleted by more than one has the rest in #moreDeleters. */
425 #deleter: NumberIndex = new Ints();
426 #moreDeleters: StateMap<number, number[]> = new Map();
427 #moreDeleterPages: ReturnType<typeof storedLists<number>> | undefined;
428 #writers: StateMap<Key | number, AtomId | AtomId[]> = new Map();
429 #writersPages: ReturnType<typeof storedLists<AtomId>> | undefined;
430 #readers: StateMap<Key | number, AtomId | AtomId[]> = new Map();
431 #readersPages: ReturnType<typeof storedLists<AtomId>> | undefined;
432 #holders: StateMap<Key | number, AtomId | AtomId[]> = new Map();
433 #holdersPages: ReturnType<typeof storedLists<AtomId>> | undefined;
434 #dependents: StateMap<AtomId, AtomId | AtomId[]> = new Map();
435 #dependentsPages: ReturnType<typeof storedLists<AtomId>> | undefined;
436 #resolvers: StateMap<AtomId, AtomId | AtomId[]> = new Map();
437 #resolversPages: ReturnType<typeof storedLists<AtomId>> | undefined;
438 #together: StateMap<AtomId, TogetherLink[]> = new Map();
439 #fileAtoms: StateMap<string, AtomId[]> = new Map();
440 #fileAtomPages: ReturnType<typeof storedLists<AtomId>> | undefined;
441 /** First lines of runs (their n), by the node they were written after: a line's n, or -1 - a path's index. */
442 #runStarts: StateMap<number, number | number[]> = new Map();
443 /** 1 for the first line of a run whose atom deleted the line it hangs off: the run replaces it. */
444 #replacing: NumberIndex = new Ints(true);
445 #relocations: StateMap<LineId, RelocationInfo[]> = new Map();
446 #relocationPages: ReturnType<typeof storedLists<RelocationInfo>> | undefined;
447 #relocatedTo: StateMap<NodeId, RelocationInfo[]> = new Map();
448 #relocatedToPages: ReturnType<typeof storedLists<RelocationInfo>> | undefined;
449 /** The same relocations by node code (a line's n, or -1 - a path's index), for views laid out by number. */
450 #relocatedToCode: StateMap<number, RelocationInfo[]> = new Map();
451 #relocatedToCodePages: ReturnType<typeof storedLists<RelocationInfo>> | undefined;
452 #movers: AtomId[] = [];
453 #atomFiles: (readonly string[])[] = [];
454 /** Each atom's deleted lines by n, packed (#46), or undefined when it deletes none. */
455 #atomDeletes: (readonly number[] | Int32Array | undefined)[] = [];
456 #labels: StateMap<string, Label> = new Map();
457 /** Each author's name kept once (#46). */
458 #authors = new Map<string, string>();
460 /** Number of atoms (also the seq the next atom gets). */
461 get size(): number {
462 return this.#atoms.length;
463 }
465 /** The id the next accepted atom must have. */
466 nextId(): AtomId {
467 return atomId(this.#atoms.length);
468 }
470 has(id: AtomId): boolean {
471 const seq = this.#seq(id);
472 return seq >= 0 && seq < this.#atoms.length;
473 }
475 atom(id: AtomId): Atom {
476 const seq = this.#seq(id);
477 const atom = seq >= 0 ? this.#atoms[seq] : undefined;
478 if (!atom) throw new EngineError("unknown-atom", `no atom ${id}`);
479 return atom;
480 }
482 /** All atoms in seq order. */
483 atoms(): readonly Atom[] {
484 return this.#atoms;
485 }
487 /** lamport(a) = 1 + max lamport of its deps; 0 for an atom with no deps (such as a0). */
488 lamport(id: AtomId): number {
489 this.atom(id);
490 return this.#lamport[this.#seq(id)]!;
491 }
493 /** Compare by priority (lamport, then seq). Negative when a comes first (is lower). */
494 comparePriority(a: AtomId, b: AtomId): number {
495 return this.lamport(a) - this.lamport(b) || this.#seq(a) - this.#seq(b);
496 }
498 line(id: LineId): LineInfo | undefined {
499 const n = this.#lineN(id);
500 if (n < 0) return undefined;
501 const seq = this.#lineAtom.at(n);
502 return {
503 id,
504 atom: this.#atoms[seq]!.id,
505 k: n - this.#lineBase[seq]!,
506 file: this.#paths[this.#lineFile.at(n)]!,
507 parent: this.#nodeName(this.#lineParent.at(n)),
508 text: this.#text(n),
509 };
510 }
512 /** A line's text, or undefined for an unknown line: line(id).text without making the record. */
513 lineText(id: LineId): string | undefined {
514 const n = this.#lineN(id);
515 return n < 0 ? undefined : this.#text(n);
516 }
518 /** The atom that wrote a line, or undefined: line(id).atom without making the record. */
519 lineAtom(id: LineId): AtomId | undefined {
520 const n = this.#lineN(id);
521 return n < 0 ? undefined : this.#atoms[this.#lineAtom.at(n)]!.id;
522 }
524 /** The file a line was written in, or undefined: line(id).file without making the record. */
525 lineFile(id: LineId): string | undefined {
526 const n = this.#lineN(id);
527 return n < 0 ? undefined : this.#paths[this.#lineFile.at(n)];
528 }
530 /** The node a line was written after, or undefined: line(id).parent without making the record. */
531 lineParent(id: LineId): NodeId | undefined {
532 const n = this.#lineN(id);
533 return n < 0 ? undefined : this.#nodeName(this.#lineParent.at(n));
534 }
536 // By number, for views (#46) ------------------------------------------------------
537 // A line's n and a node's code (a line's n, or -1 - a path's index for a file's start) as the graph
538 // keeps them, so a view can lay files out as arrays of numbers. For the engine's own use.
540 /** A line id's n, or -1 for an unknown line. */
541 lineN(id: LineId): number {
542 return this.#lineN(id);
543 }
545 /** A line's id from its n. */
546 lineIdOf(n: number): LineId {
547 return this.#lineName(n);
548 }
550 /** The lines an atom deletes, from the graph's own packed copy (#46): never a read of the log. */
551 deletedLines(id: AtomId): readonly LineId[] {
552 const ns = this.#atomDeletes[this.#seq(id)];
553 if (!ns) return EMPTY;
554 const out: LineId[] = new Array(ns.length);
555 for (let i = 0; i < ns.length; i++) out[i] = this.#lineName(ns[i]!);
556 return out;
557 }
559 /** How many lines an atom deletes, without reading its lists. */
560 deleteCount(id: AtomId): number {
561 return this.#atomDeletes[this.#seq(id)]?.length ?? 0;
562 }
564 textOf(n: number): string {
565 return this.#text(n);
566 }
568 /** The seq of the atom that wrote line n. */
569 writerSeqOf(n: number): number {
570 return this.#lineAtom.at(n);
571 }
573 /** Line n's k: its place among its atom's lines. */
574 kOf(n: number): number {
575 return n - this.#lineBase[this.#lineAtom.at(n)]!;
576 }
578 /** The atom id with this seq, as the graph keeps it. */
579 idOfSeq(seq: number): AtomId {
580 return this.#atoms[seq]!.id;
581 }
583 lamportOfSeq(seq: number): number {
584 return this.#lamport[seq]!;
585 }
587 /** The file line n was written in. */
588 writtenIn(n: number): string {
589 return this.#paths[this.#lineFile.at(n)]!;
590 }
592 /** The code of the node line n was written after. */
593 parentCodeOf(n: number): number {
594 return this.#lineParent.at(n);
595 }
597 /** A node's code, or undefined for a node the graph doesn't know (a start node of a file nothing was written in). */
598 codeOf(node: NodeId): number | undefined {
599 return this.#nodeCode(node);
600 }
602 /** The node a code names. */
603 nodeOf(code: number): NodeId {
604 return this.#nodeName(code);
605 }
607 /** The start node's code for a path, or undefined when nothing was ever written in it. */
608 startCodeOf(path: string): number | undefined {
609 const p = this.#pathIndex.get(path);
610 return p === undefined ? undefined : -1 - p;
611 }
613 /** The lines (their n) written right after a node, as childrenOf, into `out`. */
614 childrenN(code: number, out: number[]): void {
615 if (
616 code >= 0 &&
617 code + 1 < this.#lineTotal &&
618 this.#lineAtom.at(code + 1) === this.#lineAtom.at(code) &&
619 this.#lineParent.at(code + 1) === code
620 )
621 out.push(code + 1);
622 const starts = this.#runStarts.get(code);
623 if (starts === undefined) return;
624 if (Array.isArray(starts)) out.push(...starts);
625 else out.push(starts);
626 }
628 replacesN(n: number): boolean {
629 return this.#replacing.at(n) === 1;
630 }
632 /** The seqs of every atom that deletes line n (none: an empty list, shared). */
633 deleterSeqsOf(n: number): readonly number[] {
634 return [...this.eachDeleterSeqOf(n)];
635 }
636 *eachDeleterSeqOf(n: number): IterableIterator<number> {
637 const first = this.#deleter.at(n);
638 if (first < 0) return;
639 yield first;
640 if (this.#moreDeleterPages) yield* this.#moreDeleterPages.values(String(n));
641 else yield* this.#moreDeleters.get(n) ?? EMPTY;
642 }
644 /** Every relocation that puts a line right after the node with this code. */
645 relocatedToCode(code: number): readonly RelocationInfo[] {
646 if (this.#relocatedToCodePages) return [...this.eachRelocatedToCode(code)];
647 return this.#relocatedToCode.get(code) ?? EMPTY;
648 }
649 *eachRelocatedToCode(code: number): IterableIterator<RelocationInfo> {
650 if (this.#relocatedToCodePages) yield* this.#relocatedToCodePages.values(String(code));
651 else yield* this.#relocatedToCode.get(code) ?? EMPTY;
652 }
654 /** How many lines every atom together has written. */
655 get lineCount(): number {
656 return this.#lineTotal;
657 }
659 /** A line id's n, or -1 when no accepted atom wrote it. */
660 #lineN(id: LineId): number {
661 const p = parseLineId(id);
662 if (!p || p.seq >= this.#atoms.length) return -1;
663 const base = this.#lineBase[p.seq]!;
664 const end = p.seq + 1 < this.#lineBase.length ? this.#lineBase[p.seq + 1]! : this.#lineTotal;
665 return p.k < end - base ? base + p.k : -1;
666 }
668 /** A line's id from its n. */
669 #lineName(n: number): LineId {
670 const seq = this.#lineAtom.at(n);
671 return `${this.#atoms[seq]!.id}.${n - this.#lineBase[seq]!}`;
672 }
674 /** A node's code: a line's n, or -1 - a path's index for a start node; undefined when unknown. */
675 #nodeCode(node: NodeId): number | undefined {
676 if (isStartNode(node)) {
677 const p = this.#pathIndex.get(node.slice(1));
678 return p === undefined ? undefined : -1 - p;
679 }
680 const n = this.#lineN(node);
681 return n < 0 ? undefined : n;
682 }
684 #nodeName(code: number): NodeId {
685 return code >= 0 ? this.#lineName(code) : startNode(this.#paths[-1 - code]!);
686 }
688 #pathOf(file: string): number {
689 let p = this.#pathIndex.get(file);
690 if (p === undefined) {
691 p = this.#paths.push(file) - 1;
692 this.#pathIndex.set(file, p);
693 }
694 return p;
695 }
697 /** The line ids an atom inserted, in k order. */
698 linesOf(id: AtomId): LineId[] {
699 const atom = this.atom(id);
700 const out: LineId[] = [];
701 const seq = atom.seq;
702 const count = (seq + 1 < this.#lineBase.length ? this.#lineBase[seq + 1]! : this.#lineTotal) - this.#lineBase[seq]!;
703 for (let k = 0; k < count; k++) out.push(lineId(id, k));
704 return out;
705 }
707 /** Every atom that deletes this line (across the whole graph). */
708 deletersOf(line: LineId): readonly AtomId[] {
709 const n = this.#lineN(line);
710 if (n < 0) return EMPTY;
711 return [...this.eachDeleterSeqOf(n)].map((seq) => this.#atoms[seq]!.id);
712 }
714 writersOf(key: Key): readonly AtomId[] {
715 return [...this.eachWriterOf(key)];
716 }
717 *eachWriterOf(key: Key): IterableIterator<AtomId> {
718 const code = this.#code(key);
719 if (this.#writersPages) yield* this.#writersPages.values(JSON.stringify([typeof code, code]));
720 else yield* listOf(this.#writers.get(code));
721 }
723 /** Atoms whose implicit reads include the key. */
724 readersOf(key: Key): readonly AtomId[] {
725 return [...this.eachReaderOf(key)];
726 }
727 *eachReaderOf(key: Key): IterableIterator<AtomId> {
728 const code = this.#code(key);
729 if (this.#readersPages) yield* this.#readersPages.values(JSON.stringify([typeof code, code]));
730 else yield* listOf(this.#readers.get(code));
731 }
733 /** Atoms whose explicit holds include the key. */
734 holdersOf(key: Key): readonly AtomId[] {
735 return [...this.eachHolderOf(key)];
736 }
737 *eachHolderOf(key: Key): IterableIterator<AtomId> {
738 const code = this.#code(key);
739 if (this.#holdersPages) yield* this.#holdersPages.values(JSON.stringify([typeof code, code]));
740 else yield* listOf(this.#holders.get(code));
741 }
743 /** Every atom that inserts or deletes a line of the file, in seq order. */
744 atomsIn(file: string): readonly AtomId[] {
745 if (this.#fileAtomPages) return [...this.#fileAtomPages.values(file)];
746 return this.#fileAtoms.get(file) ?? EMPTY;
747 }
748 *eachAtomIn(file: string): IterableIterator<AtomId> {
749 if (this.#fileAtomPages) yield* this.#fileAtomPages.values(file);
750 else yield* this.#fileAtoms.get(file) ?? EMPTY;
751 }
752 hasAtomsIn(file: string): boolean {
753 return this.#fileAtomPages ? this.#fileAtomPages.length(file) > 0 : this.#fileAtoms.has(file);
754 }
756 /** Unique historical file paths, streamed without collecting their names. */
757 *knownFiles(): IterableIterator<string> {
758 yield* this.#fileAtomPages ? this.#fileAtomPages.keys() : this.#fileAtoms.keys();
759 }
761 /**
762 * The files an atom inserts, deletes or moves lines in, or sets attributes
763 * of, sorted. For lines, the file each was written in (or, for a move to a
764 * start node, that file): a set's moves can have taken them elsewhere.
765 */
766 filesOf(id: AtomId): readonly string[] {
767 this.atom(id);
768 return this.#atomFiles[this.#seq(id)]!;
769 }
771 /** Lines written right after a node (not counting moves), in seq order. */
772 childrenOf(node: NodeId): LineId[] {
773 const out: LineId[] = [];
774 const code = this.#nodeCode(node);
775 if (code === undefined) return out;
776 // The next line of the same run hangs off this one.
777 if (
778 code >= 0 &&
779 code + 1 < this.#lineTotal &&
780 this.#lineAtom.at(code + 1) === this.#lineAtom.at(code) &&
781 this.#lineParent.at(code + 1) === code
782 ) {
783 out.push(this.#lineName(code + 1));
784 }
785 for (const n of listOf(this.#runStarts.get(code))) out.push(this.#lineName(n));
786 return out;
787 }
789 /** Whether a line starts a run whose atom deleted the line it hangs off. */
790 replaces(line: LineId): boolean {
791 const n = this.#lineN(line);
792 return n >= 0 && this.#replacing.at(n) === 1;
793 }
795 /** Every relocation of a line, in seq order. */
796 relocationsOf(line: LineId): readonly RelocationInfo[] {
797 if (this.#relocationPages) return [...this.eachRelocationOf(line)];
798 return this.#relocations.get(line) ?? EMPTY;
799 }
800 *eachRelocationOf(line: LineId): IterableIterator<RelocationInfo> {
801 if (this.#relocationPages) yield* this.#relocationPages.values(line);
802 else yield* this.#relocations.get(line) ?? EMPTY;
803 }
805 /** Every relocation that puts a line right after this node, in seq order. */
806 relocatedTo(node: NodeId): readonly RelocationInfo[] {
807 if (this.#relocatedToPages) return [...this.#relocatedToPages.values(node)];
808 return this.#relocatedTo.get(node) ?? EMPTY;
809 }
811 /** Atoms that move lines, in seq order. */
812 movers(): readonly AtomId[] {
813 return this.#movers;
814 }
816 /** Atoms that list this one directly in their deps. */
817 dependentsOf(id: AtomId): readonly AtomId[] {
818 return [...this.eachDependentOf(id)];
819 }
820 *eachDependentOf(id: AtomId): IterableIterator<AtomId> {
821 if (this.#dependentsPages) yield* this.#dependentsPages.values(id);
822 else yield* listOf(this.#dependents.get(id));
823 }
825 /** Atoms whose `resolves` names this one. */
826 resolversOf(id: AtomId): readonly AtomId[] {
827 return [...this.eachResolverOf(id)];
828 }
829 *eachResolverOf(id: AtomId): IterableIterator<AtomId> {
830 if (this.#resolversPages) yield* this.#resolversPages.values(id);
831 else yield* listOf(this.#resolvers.get(id));
832 }
834 /** `together` reasons touching this atom, in either direction. */
835 togetherLinks(id: AtomId): readonly TogetherLink[] {
836 return this.#together.get(id) ?? EMPTY;
837 }
839 /**
840 * The atom plus everything it depends on, transitively. Computed on demand
841 * and not cached: a cached set per atom costs memory quadratic in the length
842 * of a dependency chain. Use `dependsOn` to ask about one pair.
843 */
844 closure(id: AtomId): Set<AtomId> {
845 return this.closureOf([id]);
846 }
848 /** The atoms plus everything they depend on, transitively. */
849 closureOf(ids: Iterable<AtomId>): Set<AtomId> {
850 const out = new Set<AtomId>();
851 const stack: AtomId[] = [];
852 for (const id of ids) {
853 this.atom(id);
854 if (!out.has(id)) {
855 out.add(id);
856 stack.push(id);
857 }
858 }
859 while (stack.length > 0) {
860 for (const d of this.atom(stack.pop()!).deps) {
861 if (!out.has(d)) {
862 out.add(d);
863 stack.push(d);
864 }
865 }
866 }
867 return out;
868 }
870 /** Whether `b` is in the closure of `a` (an atom is in its own closure). */
871 dependsOn(a: AtomId, b: AtomId): boolean {
872 const atom = this.atom(a);
873 this.atom(b);
874 return a === b || this.#reaches(atom.deps, b);
875 }
877 /**
878 * Whether `target` is reachable along deps from any of `from` (themselves
879 * included). A dependency always has a lower lamport than its dependent, so
880 * the search never descends below the target's lamport.
881 */
882 #reaches(from: Iterable<AtomId>, target: AtomId): boolean {
883 const floor = this.#lamport[this.#seq(target)]!;
884 const seen = new Set<AtomId>();
885 const stack = [...from];
886 while (stack.length > 0) {
887 const cur = stack.pop()!;
888 if (cur === target) return true;
889 if (seen.has(cur)) continue;
890 seen.add(cur);
891 if (this.#lamport[this.#seq(cur)]! <= floor) continue;
892 for (const d of this.atom(cur).deps) if (!seen.has(d)) stack.push(d);
893 }
894 return false;
895 }
897 /**
898 * Accept an atom into the graph. It must carry the next id and seq, and
899 * everything it touches must come from atoms in its dependency closure.
900 * The atom is frozen. Adding to the graph does not add it to any set.
901 */
902 add(atom: Atom): void {
903 if (this.#storage) this.#storage.transaction(() => this.#add(atom));
904 else this.#add(atom);
905 }
907 #add(atom: Atom): void {
908 validateShape(atom);
909 const seq = this.#atoms.length;
910 const bad = (why: string): never => {
911 throw new EngineError("bad-atom", `atom ${atom.id}: ${why}`);
912 };
913 if (atom.seq !== seq || atom.id !== atomId(seq)) bad(`expected id ${atomId(seq)} with seq ${seq}`);
915 const deps = new Set<AtomId>();
916 for (const d of atom.deps) {
917 if (!this.has(d)) bad(`dependency ${d} is not in the graph`);
918 if (deps.has(d)) bad(`dependency ${d} listed twice`);
919 deps.add(d);
920 }
921 for (const d of [...atom.needs, ...atom.resolves]) {
922 if (!deps.has(d)) bad(`${d} is in needs/resolves but not in deps`);
923 }
924 for (const r of atom.reasons) if (!this.has(r.to)) bad(`reason points at unknown atom ${r.to}`);
926 // Everything it touches must come from its closure. Derived deps name the
927 // writers directly, so this is usually one lookup per writer.
928 const below = new Map<AtomId, boolean>();
929 const inClosure = (writer: AtomId): boolean => {
930 let hit = below.get(writer);
931 if (hit === undefined) {
932 hit = deps.has(writer) || this.#reaches(deps, writer);
933 below.set(writer, hit);
934 }
935 return hit;
936 };
937 const checkLine = (line: LineId, what: string): void => {
938 const writer = this.lineAtom(line);
939 if (writer === undefined) return bad(`${what} names unknown line ${line}`);
940 if (!inClosure(writer)) bad(`${what} names line ${line} but ${writer} is not in its closure`);
941 };
943 for (const run of atom.inserts) {
944 if (isStartNode(run.parent)) {
945 if (run.parent !== startNode(run.file)) bad(`run in ${run.file} starts at ${run.parent}`);
946 } else {
947 // The parent may have been moved into run.file, so its own file can differ.
948 checkLine(run.parent, "an insert");
949 }
950 }
951 const moved = new Set<LineId>();
952 for (const m of atom.moves ?? []) {
953 checkLine(m.line, "a move");
954 if (!isStartNode(m.parent)) checkLine(m.parent, "a move");
955 if (m.line === m.parent) bad(`moves ${m.line} after itself`);
956 if (moved.has(m.line)) bad(`moves ${m.line} twice`);
957 moved.add(m.line);
958 if (!atom.writes.includes(posKey(m.line)) || !atom.writes.includes(gapKey(m.parent))) {
959 bad(`moves ${m.line} without writing ${posKey(m.line)} and ${gapKey(m.parent)}`);
960 }
961 }
962 const deleted = new Set<LineId>();
963 for (const line of atom.deletes) {
964 checkLine(line, "a delete");
965 if (deleted.has(line)) bad(`deletes ${line} twice`);
966 deleted.add(line);
967 }
968 const writes = new Set(atom.writes);
969 for (const line of deleted) if (!writes.has(lineKey(line))) bad(`deletes ${line} without writing ${lineKey(line)}`);
970 for (const key of [...atom.writes, ...atom.reads, ...atom.holds]) {
971 const parsed = parseKey(key);
972 if (parsed.kind === "line") checkLine(parsed.node, `key ${key}`);
973 else if ((parsed.kind === "gap" || parsed.kind === "pos") && !isStartNode(parsed.node))
974 checkLine(parsed.node, `key ${key}`);
975 }
977 // Accept.
978 const frozen = freezeAtom(
979 atom,
980 (id) => this.#atoms[seqOf(id)]!.id,
981 (author) => {
982 if (this.#storage) return author;
983 let a = this.#authors.get(author);
984 if (a === undefined) this.#authors.set(author, (a = author));
985 return a;
986 },
987 this.#texts ? this.#reader(seq) : undefined,
988 this.#lists ? this.#listReader(seq) : undefined,
989 );
990 this.#atoms.push(this.#storage ? atom : frozen);
991 let lam = 0;
992 for (const d of deps) lam = Math.max(lam, this.lamport(d) + 1);
993 this.#lamport.push(lam);
995 // The run starts' parents and the deleted lines, as codes, before this atom's own lines exist.
996 // The atom as given: with lists kept elsewhere, the frozen one reads them back from the log.
997 const deletes = atom.deletes.length > 0 ? new Set(atom.deletes) : undefined;
998 const deletedN = atom.deletes.map((line) => this.#lineN(line));
999 this.#atomDeletes.push(deletedN.length > 0 ? (this.#storage ? deletedN : Int32Array.from(deletedN)) : undefined);
1000 this.#lineBase.push(this.#lineTotal);
1001 for (const run of atom.inserts) {
1002 const file = this.#pathOf(run.file);
1003 let parent = isStartNode(run.parent) ? -1 - file : this.#lineN(run.parent);
1004 const first = this.#lineTotal;
1005 pushOne(this.#runStarts, parent, first);
1006 for (let i = 0; i < run.lines.length; i++) {
1007 const n = this.#lineTotal;
1008 this.#lineAtom.push(seq);
1009 this.#lineFile.push(file);
1010 this.#lineParent.push(parent);
1011 this.#lineText?.push(run.lines[i]!);
1012 this.#deleter.push(-1);
1013 this.#replacing.push(i === 0 && deletes?.has(run.parent) ? 1 : 0);
1014 parent = n;
1017 (frozen.moves ?? []).forEach((m, i) => {
1018 const info: RelocationInfo = Object.freeze({ atom: frozen.id, line: m.line, parent: m.parent, k: i });
1019 if (this.#relocationPages) this.#relocationPages.append(m.line, info);
1020 else pushIndex(this.#relocations, m.line, info);
1021 if (this.#relocatedToPages) this.#relocatedToPages.append(m.parent, info);
1022 else pushIndex(this.#relocatedTo, m.parent, info);
1023 const parentCode = isStartNode(m.parent) ? -1 - this.#pathOf(m.parent.slice(1)) : this.#lineN(m.parent);
1024 if (this.#relocatedToCodePages) this.#relocatedToCodePages.append(String(parentCode), info);
1025 else pushIndex(this.#relocatedToCode, parentCode, info);
1026 });
1027 if (frozen.moves) this.#movers.push(frozen.id);
1028 for (const n of deletedN) {
1029 if (this.#deleter.at(n) < 0) this.#deleter.set(n, seq);
1030 else if (this.#moreDeleterPages) this.#moreDeleterPages.append(String(n), seq);
1031 else pushIndex(this.#moreDeleters, n, seq);
1033 for (const key of new Set(atom.writes)) {
1034 const code = this.#code(key);
1035 if (this.#writersPages) this.#writersPages.append(JSON.stringify([typeof code, code]), frozen.id);
1036 else pushOne(this.#writers, code, frozen.id);
1038 for (const key of new Set(atom.reads)) {
1039 const code = this.#code(key);
1040 if (this.#readersPages) this.#readersPages.append(JSON.stringify([typeof code, code]), frozen.id);
1041 else pushOne(this.#readers, code, frozen.id);
1043 for (const key of new Set(atom.holds)) {
1044 const code = this.#code(key);
1045 if (this.#holdersPages) this.#holdersPages.append(JSON.stringify([typeof code, code]), frozen.id);
1046 else pushOne(this.#holders, code, frozen.id);
1048 for (const d of deps) {
1049 if (this.#dependentsPages) this.#dependentsPages.append(d, frozen.id);
1050 else pushOne(this.#dependents, d, frozen.id);
1052 for (const r of new Set(frozen.resolves)) {
1053 if (this.#resolversPages) this.#resolversPages.append(r, frozen.id);
1054 else pushOne(this.#resolvers, r, frozen.id);
1056 const files = new Set<string>();
1057 for (const run of atom.inserts) files.add(run.file);
1058 for (const n of deletedN) files.add(this.#paths[this.#lineFile.at(n)]!);
1059 for (const a of frozen.attrs ?? []) files.add(a.file);
1060 for (const m of frozen.moves ?? []) {
1061 files.add(this.lineFile(m.line)!);
1062 files.add(isStartNode(m.parent) ? m.parent.slice(1) : this.lineFile(m.parent)!);
1064 this.#atomFiles.push(Object.freeze([...files].sort()));
1065 for (const file of files) {
1066 if (this.#fileAtomPages) this.#fileAtomPages.append(file, frozen.id);
1067 else pushIndex(this.#fileAtoms, file, frozen.id);
1069 for (const r of frozen.reasons) {
1070 if (r.kind !== "together" || r.to === frozen.id) continue;
1071 pushIndex(this.#together, frozen.id, { other: r.to, text: r.text, from: frozen.id });
1072 pushIndex(this.#together, r.to, { other: frozen.id, text: r.text, from: frozen.id });
1076 // Labels -----------------------------------------------------------------
1078 /**
1079 * Add or replace a label. Label names may not look like atom ids. A base is
1080 * resolved to its head only when it is used, never followed further, so
1081 * bases may name each other in any shape.
1082 */
1083 setLabel(label: Label): void {
1084 this.#putLabel(label, (name) => this.#labels.has(name));
1087 #putLabel(label: Label, isLabel: (name: string) => boolean): void {
1088 const bad = (why: string): never => {
1089 throw new EngineError("bad-label", `label ${JSON.stringify(label?.name)}: ${why}`);
1090 };
1091 if (typeof label !== "object" || label === null) bad("not an object");
1092 if (typeof label.name !== "string" || label.name === "") bad("needs a name");
1093 if (isAtomId(label.name)) bad("a label name may not look like an atom id");
1094 if (!this.has(label.head)) bad(`head ${label.head} is not in the graph`);
1095 if (
1096 label.base !== undefined &&
1097 !(typeof label.base === "string" && (isLabel(label.base) || this.has(label.base)))
1098 ) {
1099 bad(`base ${label.base} is neither a label nor an atom`);
1101 if (label.base === label.name) bad("a label cannot be its own base");
1102 if (typeof label.title !== "string" || typeof label.message !== "string") bad("needs a title and message");
1103 if (label.follows !== undefined && !Array.isArray(label.follows)) bad("follows must be a list of label names");
1104 const copy: Label = {
1105 name: label.name,
1106 head: label.head,
1107 ...(label.base !== undefined ? { base: label.base } : {}),
1108 title: label.title,
1109 message: label.message,
1110 ...(label.follows !== undefined ? { follows: Object.freeze([...label.follows]) } : {}),
1111 };
1112 this.#labels.set(label.name, Object.freeze(copy));
1115 label(name: string): Label | undefined {
1116 return this.#labels.get(name);
1119 /** Labels sorted by name. */
1120 labels(): Label[] {
1121 return [...this.#labels.values()].sort((a, b) => (a.name < b.name ? -1 : a.name > b.name ? 1 : 0));
1124 /**
1125 * Remove a label. Labels that used it as their base get its head atom as
1126 * their base instead, so their contents don't change.
1127 */
1128 removeLabel(name: string): boolean {
1129 return this.#storage ? this.#storage.transaction(() => this.#removeLabel(name)) : this.#removeLabel(name);
1132 #removeLabel(name: string): boolean {
1133 const gone = this.#labels.get(name);
1134 if (!gone) return false;
1135 this.#labels.delete(name);
1136 for (const label of [...this.#labels.values()]) {
1137 if (label.base === name) this.#labels.set(label.name, Object.freeze({ ...label, base: gone.head }));
1139 return true;
1142 // JSON -------------------------------------------------------------------
1144 toJSON(): GraphJSON {
1145 return { format: GRAPH_FORMAT, version: 1, atoms: this.#atoms, labels: this.labels() };
1148 /** Load a saved graph. Every atom is re-validated as it is added. */
1149 static fromJSON(data: unknown): Graph {
1150 const bad = (why: string): never => {
1151 throw new EngineError("bad-json", why);
1152 };
1153 if (typeof data !== "object" || data === null) bad("graph JSON must be an object");
1154 const obj = data as Partial<GraphJSON>;
1155 if (obj.format !== GRAPH_FORMAT) bad(`format must be ${GRAPH_FORMAT}`);
1156 if (obj.version !== 1) bad(`unsupported version ${String(obj.version)}`);
1157 if (!Array.isArray(obj.atoms) || !Array.isArray(obj.labels)) bad("atoms and labels must be arrays");
1158 const graph = new Graph();
1159 for (const atom of obj.atoms!) graph.add(atom);
1160 // Labels may name each other as bases, in any order and any shape.
1161 const names = new Set<string>();
1162 for (const label of obj.labels!) {
1163 const name: unknown = (label as Partial<Label> | null)?.name;
1164 if (typeof name !== "string") return bad("every label needs a name");
1165 if (names.has(name)) bad(`label ${name} appears twice`);
1166 names.add(name);
1168 for (const label of obj.labels!) {
1169 try {
1170 graph.#putLabel(label, (name) => names.has(name));
1171 } catch (err) {
1172 if (err instanceof EngineError) bad(err.message);
1173 throw err;
1176 return graph;
1179 #seq(id: AtomId): number {
1180 return typeof id === "string" ? seqOf(id) : -1;
1184function validateShape(atom: Atom): void {
1185 const bad = (why: string): never => {
1186 throw new EngineError("bad-atom", `atom ${String((atom as { id?: unknown }).id)}: ${why}`);
1187 };
1188 if (typeof atom !== "object" || atom === null) bad("not an object");
1189 if (typeof atom.id !== "string" || !Number.isInteger(atom.seq)) bad("needs id and seq");
1190 if (typeof atom.author !== "string" || typeof atom.message !== "string") bad("needs author and message");
1191 if (typeof atom.time !== "number" || !Number.isFinite(atom.time)) bad("time must be a finite number");
1192 const lists = ["inserts", "deletes", "writes", "reads", "holds", "needs", "resolves", "reasons", "deps"] as const;
1193 for (const name of lists) if (!Array.isArray(atom[name])) bad(`${name} must be an array`);
1194 for (const run of atom.inserts as readonly InsertRun[]) {
1195 if (typeof run.file !== "string" || run.file === "" || run.file.includes("\n")) bad("a run needs a file path");
1196 if (typeof run.parent !== "string") bad("a run needs a parent");
1197 if (!Array.isArray(run.lines) || run.lines.length === 0) bad("a run needs at least one line");
1198 for (const text of run.lines) {
1199 if (typeof text !== "string" || text.includes("\n") || text.includes("\r"))
1200 bad("run lines must be strings without line breaks");
1203 if (atom.attrs !== undefined) {
1204 if (!Array.isArray(atom.attrs)) bad("attrs must be an array");
1205 for (const a of atom.attrs) {
1206 if (typeof a?.file !== "string" || a.file === "" || a.file.includes("\n") || !ATTR_NAMES.includes(a.name))
1207 bad("an attr needs a file and a name");
1208 if (a.value !== null && typeof a.value !== "string") bad("an attr value is a string or null");
1209 if (!atom.writes.includes(attrKey(a.file, a.name))) bad(`sets ${a.name} of ${a.file} without writing its key`);
1212 if (atom.moves !== undefined) {
1213 if (!Array.isArray(atom.moves) || atom.moves.length === 0) bad("moves must be a non-empty array");
1214 for (const m of atom.moves) {
1215 if (typeof m?.line !== "string" || typeof m.parent !== "string") bad("a move needs a line and a parent");
1218 for (const name of ["deletes", "writes", "reads", "holds", "needs", "resolves", "deps"] as const) {
1219 for (const x of atom[name]) if (typeof x !== "string") bad(`${name} must hold strings`);
1221 for (const r of atom.reasons as readonly Reason[]) {
1222 if (typeof r.to !== "string" || typeof r.text !== "string" || !REASON_KINDS.includes(r.kind)) {
1223 bad("a reason needs to, kind (together, because-of or supersedes) and text");
1228/**
1229 * A frozen copy of an atom. An empty list is one shared frozen list, and atom
1230 * ids and authors are the graph's own strings (`canon`, `author`), so each is
1231 * kept once however often it's named (#46).
1232 */
1233function freezeAtom(
1234 atom: Atom,
1235 canon: (id: AtomId) => AtomId,
1236 author: (name: string) => string,
1237 text?: (start: number, length: number) => readonly string[],
1238 lists?: () => AtomLists,
1239): Atom {
1240 const list = <T>(xs: readonly T[], f?: (x: T) => T): readonly T[] =>
1241 xs.length === 0 ? EMPTY : Object.freeze(f ? xs.map(f) : [...xs]);
1242 // With text kept elsewhere (#46), a run's lines are read when asked for.
1243 let k = 0;
1244 const run = (r: InsertRun): InsertRun => {
1245 if (!text) return Object.freeze({ file: r.file, parent: r.parent, lines: Object.freeze([...r.lines]) });
1246 const start = k;
1247 const length = r.lines.length;
1248 k += length;
1249 return Object.freeze(new LazyRun(r.file, r.parent, text, start, length));
1250 };
1251 const copy: Atom = {
1252 id: atom.id,
1253 seq: atom.seq,
1254 author: author(atom.author),
1255 message: atom.message,
1256 time: atom.time,
1257 inserts: Object.freeze(atom.inserts.map(run)),
1258 ...(lists
1259 ? {}
1260 : { deletes: list(atom.deletes), writes: list(atom.writes), reads: list(atom.reads), holds: list(atom.holds) }),
1261 needs: list(atom.needs, canon),
1262 resolves: list(atom.resolves, canon),
1263 reasons: list(atom.reasons, (r) => Object.freeze({ to: canon(r.to), kind: r.kind, text: r.text })),
1264 deps: list(atom.deps, canon),
1265 ...(atom.attrs && atom.attrs.length > 0
1266 ? { attrs: Object.freeze(atom.attrs.map((a) => Object.freeze({ file: a.file, name: a.name, value: a.value }))) }
1267 : {}),
1268 ...(atom.moves
1269 ? { moves: Object.freeze(atom.moves.map((m) => Object.freeze({ line: m.line, parent: m.parent }))) }
1270 : {}),
1271 } as Atom;
1272 return Object.freeze(lists ? (new ListedAtom(copy, lists) as unknown as Atom) : copy);