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