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