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