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