- 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=110&format=json
1,198 linesFirst import 91% · codex-capacity-chair 9%Last change codex-capacity-chair in version 109, 2 versions changed it
You're reading version 110. The newest is 318, and 33 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 } 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 => {
290 const values = storedArray<number>(storage, name);
291 return {
292 get length() {
293 return values.length;
294 },
295 push: (value) => {
296 values.push(value);
297 },
298 at: (index) => values[index]!,
299 set: (index, value) => {
300 values[index] = value;
301 },
302 };
303 };
304 this.#atoms = storedArray<Atom>(storage, "atoms", (atom) =>
305 freezeAtom(
306 atom,
307 (id) => id,
308 (author) => author,
309 ),
310 );
311 this.#lamport = storedArray(storage, "lamport");
312 this.#lineBase = storedArray(storage, "line-base");
313 this.#paths = storedArray(storage, "paths");
314 this.#movers = storedArray(storage, "movers");
315 this.#atomFiles = storedArray(storage, "atom-files");
316 this.#atomDeletes = storedArray(storage, "atom-deletes");
317 this.#lineAtom = numbers("line-atom");
318 this.#lineFile = numbers("line-file");
319 this.#lineParent = numbers("line-parent");
320 this.#deleter = numbers("deleter");
321 this.#replacing = numbers("replacing");
322 this.#lineText = storedArray(storage, "line-text");
323 this.#pathIndex = storedMap(storage, "path-index");
324 this.#moreDeleters = storedMap(storage, "more-deleters");
325 this.#writers = storedMap(storage, "writers");
326 this.#readers = storedMap(storage, "readers");
327 this.#holders = storedMap(storage, "holders");
328 this.#dependents = storedMap(storage, "dependents");
329 this.#resolvers = storedMap(storage, "resolvers");
330 this.#together = storedMap(storage, "together");
331 this.#fileAtoms = storedMap(storage, "file-atoms");
332 this.#runStarts = storedMap(storage, "run-starts");
333 this.#relocations = storedMap(storage, "relocations");
334 this.#relocatedTo = storedMap(storage, "relocated-to");
335 this.#relocatedToCode = storedMap(storage, "relocated-to-code");
336 this.#labels = storedMap(storage, "labels");
337 }
338 }
340 /** Where an atom's key and delete lists are when the graph doesn't keep them (#46): the stored atom. */
341 #lists: ((seq: number) => AtomLists) | undefined;
342 /** Recently read atoms' lists, most recent last, up to LIST_CACHE atoms. */
343 #listCache = new Map<number, AtomLists>();
344 #listCached = 0;
346 /** An atom's deletes, writes, reads and holds, read back from where they are stored. */
347 #listsOf(seq: number): AtomLists {
348 const hit = this.#listCache.get(seq);
349 if (hit) {
350 this.#listCache.delete(seq);
351 this.#listCache.set(seq, hit);
352 return hit;
353 }
354 const got = this.#lists!(seq);
355 const lists: AtomLists = {
356 deletes: frozenList(got.deletes),
357 writes: frozenList(got.writes),
358 reads: frozenList(got.reads),
359 holds: frozenList(got.holds),
360 };
361 this.#listCache.set(seq, lists);
362 this.#listCached += listItems(lists);
363 for (const [old, kept] of this.#listCache) {
364 if (this.#listCached <= LIST_CACHE || old === seq) break;
365 this.#listCache.delete(old);
366 this.#listCached -= listItems(kept);
367 }
368 return lists;
369 }
371 /** The reader an atom's lists use; made apart from add() so it keeps no atom alive (see #reader). */
372 #listReader(seq: number): () => AtomLists {
373 return () => this.#listsOf(seq);
374 }
376 /**
377 * 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
378 * index holds numbers rather than one string per line; start-node and attribute keys stay strings. A key
379 * naming a line the graph doesn't have stays a string, which nothing has claimed.
380 */
381 #code(key: Key): Key | number {
382 const t = key.charCodeAt(0);
383 if (key.charCodeAt(1) !== 58 || key.charCodeAt(2) === 94) return key; // not "X:", or a start node "^"
384 const k = t === 76 ? 0 : t === 80 ? 1 : t === 71 ? 2 : -1; // L, P, G
385 if (k < 0) return key;
386 const n = this.#lineN(key.slice(2));
387 return n < 0 ? key : n * 4 + k;
388 }
390 /** An atom's lines' text, in k order. */
391 #textOf(seq: number): readonly string[] {
392 const hit = this.#textCache.get(seq);
393 if (hit) {
394 this.#textCache.delete(seq);
395 this.#textCache.set(seq, hit);
396 return hit;
397 }
398 const flat = this.#texts!(seq).flat();
399 let chars = 0;
400 for (const t of flat) chars += t.length + 1;
401 this.#textCache.set(seq, flat);
402 this.#textCached += chars;
403 for (const [old, lines] of this.#textCache) {
404 if (this.#textCached <= TEXT_CACHE || old === seq) break;
405 this.#textCache.delete(old);
406 for (const t of lines) this.#textCached -= t.length + 1;
407 }
408 return flat;
409 }
411 /**
412 * The reader an atom's runs use. Made in a function of its own: a closure made inside add() would
413 * keep add()'s whole scope alive, the atom as given with all its text included.
414 */
415 #reader(seq: number): (start: number, length: number) => readonly string[] {
416 return (start, length) => this.#textOf(seq).slice(start, start + length);
417 }
419 /** Line n's text. */
420 #text(n: number): string {
421 if (this.#lineText) return this.#lineText[n]!;
422 const seq = this.#lineAtom.at(n);
423 return this.#textOf(seq)[n - this.#lineBase[seq]!]!;
424 }
425 #paths: string[] = [];
426 #pathIndex: StateMap<string, number> = new Map();
427 /** The first atom that deletes each line (its seq), or -1; a line deleted by more than one has the rest in #moreDeleters. */
428 #deleter: NumberIndex = new Ints();
429 #moreDeleters: StateMap<number, number[]> = new Map();
430 #writers: StateMap<Key | number, AtomId | AtomId[]> = new Map();
431 #readers: StateMap<Key | number, AtomId | AtomId[]> = new Map();
432 #holders: StateMap<Key | number, AtomId | AtomId[]> = new Map();
433 #dependents: StateMap<AtomId, AtomId | AtomId[]> = new Map();
434 #resolvers: StateMap<AtomId, AtomId | AtomId[]> = new Map();
435 #together: StateMap<AtomId, TogetherLink[]> = new Map();
436 #fileAtoms: StateMap<string, AtomId[]> = new Map();
437 /** First lines of runs (their n), by the node they were written after: a line's n, or -1 - a path's index. */
438 #runStarts: StateMap<number, number | number[]> = new Map();
439 /** 1 for the first line of a run whose atom deleted the line it hangs off: the run replaces it. */
440 #replacing: NumberIndex = new Ints(true);
441 #relocations: StateMap<LineId, RelocationInfo[]> = new Map();
442 #relocatedTo: StateMap<NodeId, RelocationInfo[]> = new Map();
443 /** The same relocations by node code (a line's n, or -1 - a path's index), for views laid out by number. */
444 #relocatedToCode: StateMap<number, RelocationInfo[]> = new Map();
445 #movers: AtomId[] = [];
446 #atomFiles: (readonly string[])[] = [];
447 /** Each atom's deleted lines by n, packed (#46), or undefined when it deletes none. */
448 #atomDeletes: (readonly number[] | Int32Array | undefined)[] = [];
449 #labels: StateMap<string, Label> = new Map();
450 /** Each author's name kept once (#46). */
451 #authors = new Map<string, string>();
453 /** Number of atoms (also the seq the next atom gets). */
454 get size(): number {
455 return this.#atoms.length;
456 }
458 /** The id the next accepted atom must have. */
459 nextId(): AtomId {
460 return atomId(this.#atoms.length);
461 }
463 has(id: AtomId): boolean {
464 const seq = this.#seq(id);
465 return seq >= 0 && seq < this.#atoms.length;
466 }
468 atom(id: AtomId): Atom {
469 const seq = this.#seq(id);
470 const atom = seq >= 0 ? this.#atoms[seq] : undefined;
471 if (!atom) throw new EngineError("unknown-atom", `no atom ${id}`);
472 return atom;
473 }
475 /** All atoms in seq order. */
476 atoms(): readonly Atom[] {
477 return this.#atoms;
478 }
480 /** lamport(a) = 1 + max lamport of its deps; 0 for an atom with no deps (such as a0). */
481 lamport(id: AtomId): number {
482 this.atom(id);
483 return this.#lamport[this.#seq(id)]!;
484 }
486 /** Compare by priority (lamport, then seq). Negative when a comes first (is lower). */
487 comparePriority(a: AtomId, b: AtomId): number {
488 return this.lamport(a) - this.lamport(b) || this.#seq(a) - this.#seq(b);
489 }
491 line(id: LineId): LineInfo | undefined {
492 const n = this.#lineN(id);
493 if (n < 0) return undefined;
494 const seq = this.#lineAtom.at(n);
495 return {
496 id,
497 atom: this.#atoms[seq]!.id,
498 k: n - this.#lineBase[seq]!,
499 file: this.#paths[this.#lineFile.at(n)]!,
500 parent: this.#nodeName(this.#lineParent.at(n)),
501 text: this.#text(n),
502 };
503 }
505 /** A line's text, or undefined for an unknown line: line(id).text without making the record. */
506 lineText(id: LineId): string | undefined {
507 const n = this.#lineN(id);
508 return n < 0 ? undefined : this.#text(n);
509 }
511 /** The atom that wrote a line, or undefined: line(id).atom without making the record. */
512 lineAtom(id: LineId): AtomId | undefined {
513 const n = this.#lineN(id);
514 return n < 0 ? undefined : this.#atoms[this.#lineAtom.at(n)]!.id;
515 }
517 /** The file a line was written in, or undefined: line(id).file without making the record. */
518 lineFile(id: LineId): string | undefined {
519 const n = this.#lineN(id);
520 return n < 0 ? undefined : this.#paths[this.#lineFile.at(n)];
521 }
523 /** The node a line was written after, or undefined: line(id).parent without making the record. */
524 lineParent(id: LineId): NodeId | undefined {
525 const n = this.#lineN(id);
526 return n < 0 ? undefined : this.#nodeName(this.#lineParent.at(n));
527 }
529 // By number, for views (#46) ------------------------------------------------------
530 // 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
531 // keeps them, so a view can lay files out as arrays of numbers. For the engine's own use.
533 /** A line id's n, or -1 for an unknown line. */
534 lineN(id: LineId): number {
535 return this.#lineN(id);
536 }
538 /** A line's id from its n. */
539 lineIdOf(n: number): LineId {
540 return this.#lineName(n);
541 }
543 /** The lines an atom deletes, from the graph's own packed copy (#46): never a read of the log. */
544 deletedLines(id: AtomId): readonly LineId[] {
545 const ns = this.#atomDeletes[this.#seq(id)];
546 if (!ns) return EMPTY;
547 const out: LineId[] = new Array(ns.length);
548 for (let i = 0; i < ns.length; i++) out[i] = this.#lineName(ns[i]!);
549 return out;
550 }
552 /** How many lines an atom deletes, without reading its lists. */
553 deleteCount(id: AtomId): number {
554 return this.#atomDeletes[this.#seq(id)]?.length ?? 0;
555 }
557 textOf(n: number): string {
558 return this.#text(n);
559 }
561 /** The seq of the atom that wrote line n. */
562 writerSeqOf(n: number): number {
563 return this.#lineAtom.at(n);
564 }
566 /** Line n's k: its place among its atom's lines. */
567 kOf(n: number): number {
568 return n - this.#lineBase[this.#lineAtom.at(n)]!;
569 }
571 /** The atom id with this seq, as the graph keeps it. */
572 idOfSeq(seq: number): AtomId {
573 return this.#atoms[seq]!.id;
574 }
576 lamportOfSeq(seq: number): number {
577 return this.#lamport[seq]!;
578 }
580 /** The file line n was written in. */
581 writtenIn(n: number): string {
582 return this.#paths[this.#lineFile.at(n)]!;
583 }
585 /** The code of the node line n was written after. */
586 parentCodeOf(n: number): number {
587 return this.#lineParent.at(n);
588 }
590 /** A node's code, or undefined for a node the graph doesn't know (a start node of a file nothing was written in). */
591 codeOf(node: NodeId): number | undefined {
592 return this.#nodeCode(node);
593 }
595 /** The node a code names. */
596 nodeOf(code: number): NodeId {
597 return this.#nodeName(code);
598 }
600 /** The start node's code for a path, or undefined when nothing was ever written in it. */
601 startCodeOf(path: string): number | undefined {
602 const p = this.#pathIndex.get(path);
603 return p === undefined ? undefined : -1 - p;
604 }
606 /** The lines (their n) written right after a node, as childrenOf, into `out`. */
607 childrenN(code: number, out: number[]): void {
608 if (
609 code >= 0 &&
610 code + 1 < this.#lineTotal &&
611 this.#lineAtom.at(code + 1) === this.#lineAtom.at(code) &&
612 this.#lineParent.at(code + 1) === code
613 )
614 out.push(code + 1);
615 const starts = this.#runStarts.get(code);
616 if (starts === undefined) return;
617 if (Array.isArray(starts)) out.push(...starts);
618 else out.push(starts);
619 }
621 replacesN(n: number): boolean {
622 return this.#replacing.at(n) === 1;
623 }
625 /** The seqs of every atom that deletes line n (none: an empty list, shared). */
626 deleterSeqsOf(n: number): readonly number[] {
627 const first = this.#deleter.at(n);
628 if (first < 0) return EMPTY;
629 const more = this.#moreDeleters.get(n);
630 return more ? [first, ...more] : [first];
631 }
633 /** Every relocation that puts a line right after the node with this code. */
634 relocatedToCode(code: number): readonly RelocationInfo[] {
635 return this.#relocatedToCode.get(code) ?? EMPTY;
636 }
638 /** How many lines every atom together has written. */
639 get lineCount(): number {
640 return this.#lineTotal;
641 }
643 /** A line id's n, or -1 when no accepted atom wrote it. */
644 #lineN(id: LineId): number {
645 const p = parseLineId(id);
646 if (!p || p.seq >= this.#atoms.length) return -1;
647 const base = this.#lineBase[p.seq]!;
648 const end = p.seq + 1 < this.#lineBase.length ? this.#lineBase[p.seq + 1]! : this.#lineTotal;
649 return p.k < end - base ? base + p.k : -1;
650 }
652 /** A line's id from its n. */
653 #lineName(n: number): LineId {
654 const seq = this.#lineAtom.at(n);
655 return `${this.#atoms[seq]!.id}.${n - this.#lineBase[seq]!}`;
656 }
658 /** A node's code: a line's n, or -1 - a path's index for a start node; undefined when unknown. */
659 #nodeCode(node: NodeId): number | undefined {
660 if (isStartNode(node)) {
661 const p = this.#pathIndex.get(node.slice(1));
662 return p === undefined ? undefined : -1 - p;
663 }
664 const n = this.#lineN(node);
665 return n < 0 ? undefined : n;
666 }
668 #nodeName(code: number): NodeId {
669 return code >= 0 ? this.#lineName(code) : startNode(this.#paths[-1 - code]!);
670 }
672 #pathOf(file: string): number {
673 let p = this.#pathIndex.get(file);
674 if (p === undefined) {
675 p = this.#paths.push(file) - 1;
676 this.#pathIndex.set(file, p);
677 }
678 return p;
679 }
681 /** The line ids an atom inserted, in k order. */
682 linesOf(id: AtomId): LineId[] {
683 const atom = this.atom(id);
684 const out: LineId[] = [];
685 const seq = atom.seq;
686 const count = (seq + 1 < this.#lineBase.length ? this.#lineBase[seq + 1]! : this.#lineTotal) - this.#lineBase[seq]!;
687 for (let k = 0; k < count; k++) out.push(lineId(id, k));
688 return out;
689 }
691 /** Every atom that deletes this line (across the whole graph). */
692 deletersOf(line: LineId): readonly AtomId[] {
693 const n = this.#lineN(line);
694 if (n < 0) return EMPTY;
695 const first = this.#deleter.at(n);
696 if (first < 0) return EMPTY;
697 const more = this.#moreDeleters.get(n);
698 const out = [this.#atoms[first]!.id];
699 if (more) for (const seq of more) out.push(this.#atoms[seq]!.id);
700 return out;
701 }
703 writersOf(key: Key): readonly AtomId[] {
704 return listOf(this.#writers.get(this.#code(key)));
705 }
707 /** Atoms whose implicit reads include the key. */
708 readersOf(key: Key): readonly AtomId[] {
709 return listOf(this.#readers.get(this.#code(key)));
710 }
712 /** Atoms whose explicit holds include the key. */
713 holdersOf(key: Key): readonly AtomId[] {
714 return listOf(this.#holders.get(this.#code(key)));
715 }
717 /** Every atom that inserts or deletes a line of the file, in seq order. */
718 atomsIn(file: string): readonly AtomId[] {
719 return this.#fileAtoms.get(file) ?? EMPTY;
720 }
722 /**
723 * The files an atom inserts, deletes or moves lines in, or sets attributes
724 * of, sorted. For lines, the file each was written in (or, for a move to a
725 * start node, that file): a set's moves can have taken them elsewhere.
726 */
727 filesOf(id: AtomId): readonly string[] {
728 this.atom(id);
729 return this.#atomFiles[this.#seq(id)]!;
730 }
732 /** Lines written right after a node (not counting moves), in seq order. */
733 childrenOf(node: NodeId): LineId[] {
734 const out: LineId[] = [];
735 const code = this.#nodeCode(node);
736 if (code === undefined) return out;
737 // The next line of the same run hangs off this one.
738 if (
739 code >= 0 &&
740 code + 1 < this.#lineTotal &&
741 this.#lineAtom.at(code + 1) === this.#lineAtom.at(code) &&
742 this.#lineParent.at(code + 1) === code
743 ) {
744 out.push(this.#lineName(code + 1));
745 }
746 for (const n of listOf(this.#runStarts.get(code))) out.push(this.#lineName(n));
747 return out;
748 }
750 /** Whether a line starts a run whose atom deleted the line it hangs off. */
751 replaces(line: LineId): boolean {
752 const n = this.#lineN(line);
753 return n >= 0 && this.#replacing.at(n) === 1;
754 }
756 /** Every relocation of a line, in seq order. */
757 relocationsOf(line: LineId): readonly RelocationInfo[] {
758 return this.#relocations.get(line) ?? EMPTY;
759 }
761 /** Every relocation that puts a line right after this node, in seq order. */
762 relocatedTo(node: NodeId): readonly RelocationInfo[] {
763 return this.#relocatedTo.get(node) ?? EMPTY;
764 }
766 /** Atoms that move lines, in seq order. */
767 movers(): readonly AtomId[] {
768 return this.#movers;
769 }
771 /** Atoms that list this one directly in their deps. */
772 dependentsOf(id: AtomId): readonly AtomId[] {
773 return listOf(this.#dependents.get(id));
774 }
776 /** Atoms whose `resolves` names this one. */
777 resolversOf(id: AtomId): readonly AtomId[] {
778 return listOf(this.#resolvers.get(id));
779 }
781 /** `together` reasons touching this atom, in either direction. */
782 togetherLinks(id: AtomId): readonly TogetherLink[] {
783 return this.#together.get(id) ?? EMPTY;
784 }
786 /**
787 * The atom plus everything it depends on, transitively. Computed on demand
788 * and not cached: a cached set per atom costs memory quadratic in the length
789 * of a dependency chain. Use `dependsOn` to ask about one pair.
790 */
791 closure(id: AtomId): Set<AtomId> {
792 return this.closureOf([id]);
793 }
795 /** The atoms plus everything they depend on, transitively. */
796 closureOf(ids: Iterable<AtomId>): Set<AtomId> {
797 const out = new Set<AtomId>();
798 const stack: AtomId[] = [];
799 for (const id of ids) {
800 this.atom(id);
801 if (!out.has(id)) {
802 out.add(id);
803 stack.push(id);
804 }
805 }
806 while (stack.length > 0) {
807 for (const d of this.atom(stack.pop()!).deps) {
808 if (!out.has(d)) {
809 out.add(d);
810 stack.push(d);
811 }
812 }
813 }
814 return out;
815 }
817 /** Whether `b` is in the closure of `a` (an atom is in its own closure). */
818 dependsOn(a: AtomId, b: AtomId): boolean {
819 const atom = this.atom(a);
820 this.atom(b);
821 return a === b || this.#reaches(atom.deps, b);
822 }
824 /**
825 * Whether `target` is reachable along deps from any of `from` (themselves
826 * included). A dependency always has a lower lamport than its dependent, so
827 * the search never descends below the target's lamport.
828 */
829 #reaches(from: Iterable<AtomId>, target: AtomId): boolean {
830 const floor = this.#lamport[this.#seq(target)]!;
831 const seen = new Set<AtomId>();
832 const stack = [...from];
833 while (stack.length > 0) {
834 const cur = stack.pop()!;
835 if (cur === target) return true;
836 if (seen.has(cur)) continue;
837 seen.add(cur);
838 if (this.#lamport[this.#seq(cur)]! <= floor) continue;
839 for (const d of this.atom(cur).deps) if (!seen.has(d)) stack.push(d);
840 }
841 return false;
842 }
844 /**
845 * Accept an atom into the graph. It must carry the next id and seq, and
846 * everything it touches must come from atoms in its dependency closure.
847 * The atom is frozen. Adding to the graph does not add it to any set.
848 */
849 add(atom: Atom): void {
850 if (this.#storage) this.#storage.transaction(() => this.#add(atom));
851 else this.#add(atom);
852 }
854 #add(atom: Atom): void {
855 validateShape(atom);
856 const seq = this.#atoms.length;
857 const bad = (why: string): never => {
858 throw new EngineError("bad-atom", `atom ${atom.id}: ${why}`);
859 };
860 if (atom.seq !== seq || atom.id !== atomId(seq)) bad(`expected id ${atomId(seq)} with seq ${seq}`);
862 const deps = new Set<AtomId>();
863 for (const d of atom.deps) {
864 if (!this.has(d)) bad(`dependency ${d} is not in the graph`);
865 if (deps.has(d)) bad(`dependency ${d} listed twice`);
866 deps.add(d);
867 }
868 for (const d of [...atom.needs, ...atom.resolves]) {
869 if (!deps.has(d)) bad(`${d} is in needs/resolves but not in deps`);
870 }
871 for (const r of atom.reasons) if (!this.has(r.to)) bad(`reason points at unknown atom ${r.to}`);
873 // Everything it touches must come from its closure. Derived deps name the
874 // writers directly, so this is usually one lookup per writer.
875 const below = new Map<AtomId, boolean>();
876 const inClosure = (writer: AtomId): boolean => {
877 let hit = below.get(writer);
878 if (hit === undefined) {
879 hit = deps.has(writer) || this.#reaches(deps, writer);
880 below.set(writer, hit);
881 }
882 return hit;
883 };
884 const checkLine = (line: LineId, what: string): void => {
885 const writer = this.lineAtom(line);
886 if (writer === undefined) return bad(`${what} names unknown line ${line}`);
887 if (!inClosure(writer)) bad(`${what} names line ${line} but ${writer} is not in its closure`);
888 };
890 for (const run of atom.inserts) {
891 if (isStartNode(run.parent)) {
892 if (run.parent !== startNode(run.file)) bad(`run in ${run.file} starts at ${run.parent}`);
893 } else {
894 // The parent may have been moved into run.file, so its own file can differ.
895 checkLine(run.parent, "an insert");
896 }
897 }
898 const moved = new Set<LineId>();
899 for (const m of atom.moves ?? []) {
900 checkLine(m.line, "a move");
901 if (!isStartNode(m.parent)) checkLine(m.parent, "a move");
902 if (m.line === m.parent) bad(`moves ${m.line} after itself`);
903 if (moved.has(m.line)) bad(`moves ${m.line} twice`);
904 moved.add(m.line);
905 if (!atom.writes.includes(posKey(m.line)) || !atom.writes.includes(gapKey(m.parent))) {
906 bad(`moves ${m.line} without writing ${posKey(m.line)} and ${gapKey(m.parent)}`);
907 }
908 }
909 const deleted = new Set<LineId>();
910 for (const line of atom.deletes) {
911 checkLine(line, "a delete");
912 if (deleted.has(line)) bad(`deletes ${line} twice`);
913 deleted.add(line);
914 }
915 const writes = new Set(atom.writes);
916 for (const line of deleted) if (!writes.has(lineKey(line))) bad(`deletes ${line} without writing ${lineKey(line)}`);
917 for (const key of [...atom.writes, ...atom.reads, ...atom.holds]) {
918 const parsed = parseKey(key);
919 if (parsed.kind === "line") checkLine(parsed.node, `key ${key}`);
920 else if ((parsed.kind === "gap" || parsed.kind === "pos") && !isStartNode(parsed.node))
921 checkLine(parsed.node, `key ${key}`);
922 }
924 // Accept.
925 const frozen = freezeAtom(
926 atom,
927 (id) => this.#atoms[seqOf(id)]!.id,
928 (author) => {
929 if (this.#storage) return author;
930 let a = this.#authors.get(author);
931 if (a === undefined) this.#authors.set(author, (a = author));
932 return a;
933 },
934 this.#texts ? this.#reader(seq) : undefined,
935 this.#lists ? this.#listReader(seq) : undefined,
936 );
937 this.#atoms.push(this.#storage ? atom : frozen);
938 let lam = 0;
939 for (const d of deps) lam = Math.max(lam, this.lamport(d) + 1);
940 this.#lamport.push(lam);
942 // The run starts' parents and the deleted lines, as codes, before this atom's own lines exist.
943 // The atom as given: with lists kept elsewhere, the frozen one reads them back from the log.
944 const deletes = atom.deletes.length > 0 ? new Set(atom.deletes) : undefined;
945 const deletedN = atom.deletes.map((line) => this.#lineN(line));
946 this.#atomDeletes.push(deletedN.length > 0 ? (this.#storage ? deletedN : Int32Array.from(deletedN)) : undefined);
947 this.#lineBase.push(this.#lineTotal);
948 for (const run of atom.inserts) {
949 const file = this.#pathOf(run.file);
950 let parent = isStartNode(run.parent) ? -1 - file : this.#lineN(run.parent);
951 const first = this.#lineTotal;
952 pushOne(this.#runStarts, parent, first);
953 for (let i = 0; i < run.lines.length; i++) {
954 const n = this.#lineTotal;
955 this.#lineAtom.push(seq);
956 this.#lineFile.push(file);
957 this.#lineParent.push(parent);
958 this.#lineText?.push(run.lines[i]!);
959 this.#deleter.push(-1);
960 this.#replacing.push(i === 0 && deletes?.has(run.parent) ? 1 : 0);
961 parent = n;
962 }
963 }
964 (frozen.moves ?? []).forEach((m, i) => {
965 const info: RelocationInfo = Object.freeze({ atom: frozen.id, line: m.line, parent: m.parent, k: i });
966 pushIndex(this.#relocations, m.line, info);
967 pushIndex(this.#relocatedTo, m.parent, info);
968 pushIndex(
969 this.#relocatedToCode,
970 isStartNode(m.parent) ? -1 - this.#pathOf(m.parent.slice(1)) : this.#lineN(m.parent),
971 info,
972 );
973 });
974 if (frozen.moves) this.#movers.push(frozen.id);
975 for (const n of deletedN) {
976 if (this.#deleter.at(n) < 0) this.#deleter.set(n, seq);
977 else pushIndex(this.#moreDeleters, n, seq);
978 }
979 for (const key of new Set(atom.writes)) pushOne(this.#writers, this.#code(key), frozen.id);
980 for (const key of new Set(atom.reads)) pushOne(this.#readers, this.#code(key), frozen.id);
981 for (const key of new Set(atom.holds)) pushOne(this.#holders, this.#code(key), frozen.id);
982 for (const d of deps) pushOne(this.#dependents, d, frozen.id);
983 for (const r of new Set(frozen.resolves)) pushOne(this.#resolvers, r, frozen.id);
984 const files = new Set<string>();
985 for (const run of atom.inserts) files.add(run.file);
986 for (const n of deletedN) files.add(this.#paths[this.#lineFile.at(n)]!);
987 for (const a of frozen.attrs ?? []) files.add(a.file);
988 for (const m of frozen.moves ?? []) {
989 files.add(this.lineFile(m.line)!);
990 files.add(isStartNode(m.parent) ? m.parent.slice(1) : this.lineFile(m.parent)!);
991 }
992 this.#atomFiles.push(Object.freeze([...files].sort()));
993 for (const file of files) pushIndex(this.#fileAtoms, file, frozen.id);
994 for (const r of frozen.reasons) {
995 if (r.kind !== "together" || r.to === frozen.id) continue;
996 pushIndex(this.#together, frozen.id, { other: r.to, text: r.text, from: frozen.id });
997 pushIndex(this.#together, r.to, { other: frozen.id, text: r.text, from: frozen.id });
998 }
999 }
1001 // Labels -----------------------------------------------------------------
1003 /**
1004 * Add or replace a label. Label names may not look like atom ids. A base is
1005 * resolved to its head only when it is used, never followed further, so
1006 * bases may name each other in any shape.
1007 */
1008 setLabel(label: Label): void {
1009 this.#putLabel(label, (name) => this.#labels.has(name));
1010 }
1012 #putLabel(label: Label, isLabel: (name: string) => boolean): void {
1013 const bad = (why: string): never => {
1014 throw new EngineError("bad-label", `label ${JSON.stringify(label?.name)}: ${why}`);
1015 };
1016 if (typeof label !== "object" || label === null) bad("not an object");
1017 if (typeof label.name !== "string" || label.name === "") bad("needs a name");
1018 if (isAtomId(label.name)) bad("a label name may not look like an atom id");
1019 if (!this.has(label.head)) bad(`head ${label.head} is not in the graph`);
1020 if (
1021 label.base !== undefined &&
1022 !(typeof label.base === "string" && (isLabel(label.base) || this.has(label.base)))
1023 ) {
1024 bad(`base ${label.base} is neither a label nor an atom`);
1025 }
1026 if (label.base === label.name) bad("a label cannot be its own base");
1027 if (typeof label.title !== "string" || typeof label.message !== "string") bad("needs a title and message");
1028 if (label.follows !== undefined && !Array.isArray(label.follows)) bad("follows must be a list of label names");
1029 const copy: Label = {
1030 name: label.name,
1031 head: label.head,
1032 ...(label.base !== undefined ? { base: label.base } : {}),
1033 title: label.title,
1034 message: label.message,
1035 ...(label.follows !== undefined ? { follows: Object.freeze([...label.follows]) } : {}),
1036 };
1037 this.#labels.set(label.name, Object.freeze(copy));
1038 }
1040 label(name: string): Label | undefined {
1041 return this.#labels.get(name);
1042 }
1044 /** Labels sorted by name. */
1045 labels(): Label[] {
1046 return [...this.#labels.values()].sort((a, b) => (a.name < b.name ? -1 : a.name > b.name ? 1 : 0));
1047 }
1049 /**
1050 * Remove a label. Labels that used it as their base get its head atom as
1051 * their base instead, so their contents don't change.
1052 */
1053 removeLabel(name: string): boolean {
1054 return this.#storage ? this.#storage.transaction(() => this.#removeLabel(name)) : this.#removeLabel(name);
1055 }
1057 #removeLabel(name: string): boolean {
1058 const gone = this.#labels.get(name);
1059 if (!gone) return false;
1060 this.#labels.delete(name);
1061 for (const label of [...this.#labels.values()]) {
1062 if (label.base === name) this.#labels.set(label.name, Object.freeze({ ...label, base: gone.head }));
1063 }
1064 return true;
1065 }
1067 // JSON -------------------------------------------------------------------
1069 toJSON(): GraphJSON {
1070 return { format: GRAPH_FORMAT, version: 1, atoms: this.#atoms, labels: this.labels() };
1071 }
1073 /** Load a saved graph. Every atom is re-validated as it is added. */
1074 static fromJSON(data: unknown): Graph {
1075 const bad = (why: string): never => {
1076 throw new EngineError("bad-json", why);
1077 };
1078 if (typeof data !== "object" || data === null) bad("graph JSON must be an object");
1079 const obj = data as Partial<GraphJSON>;
1080 if (obj.format !== GRAPH_FORMAT) bad(`format must be ${GRAPH_FORMAT}`);
1081 if (obj.version !== 1) bad(`unsupported version ${String(obj.version)}`);
1082 if (!Array.isArray(obj.atoms) || !Array.isArray(obj.labels)) bad("atoms and labels must be arrays");
1083 const graph = new Graph();
1084 for (const atom of obj.atoms!) graph.add(atom);
1085 // Labels may name each other as bases, in any order and any shape.
1086 const names = new Set<string>();
1087 for (const label of obj.labels!) {
1088 const name: unknown = (label as Partial<Label> | null)?.name;
1089 if (typeof name !== "string") return bad("every label needs a name");
1090 if (names.has(name)) bad(`label ${name} appears twice`);
1091 names.add(name);
1092 }
1093 for (const label of obj.labels!) {
1094 try {
1095 graph.#putLabel(label, (name) => names.has(name));
1096 } catch (err) {
1097 if (err instanceof EngineError) bad(err.message);
1098 throw err;
1099 }
1100 }
1101 return graph;
1102 }
1104 #seq(id: AtomId): number {
1105 return typeof id === "string" ? seqOf(id) : -1;
1106 }
1107}
1109function validateShape(atom: Atom): void {
1110 const bad = (why: string): never => {
1111 throw new EngineError("bad-atom", `atom ${String((atom as { id?: unknown }).id)}: ${why}`);
1112 };
1113 if (typeof atom !== "object" || atom === null) bad("not an object");
1114 if (typeof atom.id !== "string" || !Number.isInteger(atom.seq)) bad("needs id and seq");
1115 if (typeof atom.author !== "string" || typeof atom.message !== "string") bad("needs author and message");
1116 if (typeof atom.time !== "number" || !Number.isFinite(atom.time)) bad("time must be a finite number");
1117 const lists = ["inserts", "deletes", "writes", "reads", "holds", "needs", "resolves", "reasons", "deps"] as const;
1118 for (const name of lists) if (!Array.isArray(atom[name])) bad(`${name} must be an array`);
1119 for (const run of atom.inserts as readonly InsertRun[]) {
1120 if (typeof run.file !== "string" || run.file === "" || run.file.includes("\n")) bad("a run needs a file path");
1121 if (typeof run.parent !== "string") bad("a run needs a parent");
1122 if (!Array.isArray(run.lines) || run.lines.length === 0) bad("a run needs at least one line");
1123 for (const text of run.lines) {
1124 if (typeof text !== "string" || text.includes("\n") || text.includes("\r"))
1125 bad("run lines must be strings without line breaks");
1126 }
1127 }
1128 if (atom.attrs !== undefined) {
1129 if (!Array.isArray(atom.attrs)) bad("attrs must be an array");
1130 for (const a of atom.attrs) {
1131 if (typeof a?.file !== "string" || a.file === "" || a.file.includes("\n") || !ATTR_NAMES.includes(a.name))
1132 bad("an attr needs a file and a name");
1133 if (a.value !== null && typeof a.value !== "string") bad("an attr value is a string or null");
1134 if (!atom.writes.includes(attrKey(a.file, a.name))) bad(`sets ${a.name} of ${a.file} without writing its key`);
1135 }
1136 }
1137 if (atom.moves !== undefined) {
1138 if (!Array.isArray(atom.moves) || atom.moves.length === 0) bad("moves must be a non-empty array");
1139 for (const m of atom.moves) {
1140 if (typeof m?.line !== "string" || typeof m.parent !== "string") bad("a move needs a line and a parent");
1141 }
1142 }
1143 for (const name of ["deletes", "writes", "reads", "holds", "needs", "resolves", "deps"] as const) {
1144 for (const x of atom[name]) if (typeof x !== "string") bad(`${name} must hold strings`);
1145 }
1146 for (const r of atom.reasons as readonly Reason[]) {
1147 if (typeof r.to !== "string" || typeof r.text !== "string" || !REASON_KINDS.includes(r.kind)) {
1148 bad("a reason needs to, kind (together, because-of or supersedes) and text");
1149 }
1150 }
1151}
1153/**
1154 * A frozen copy of an atom. An empty list is one shared frozen list, and atom
1155 * ids and authors are the graph's own strings (`canon`, `author`), so each is
1156 * kept once however often it's named (#46).
1157 */
1158function freezeAtom(
1159 atom: Atom,
1160 canon: (id: AtomId) => AtomId,
1161 author: (name: string) => string,
1162 text?: (start: number, length: number) => readonly string[],
1163 lists?: () => AtomLists,
1164): Atom {
1165 const list = <T>(xs: readonly T[], f?: (x: T) => T): readonly T[] =>
1166 xs.length === 0 ? EMPTY : Object.freeze(f ? xs.map(f) : [...xs]);
1167 // With text kept elsewhere (#46), a run's lines are read when asked for.
1168 let k = 0;
1169 const run = (r: InsertRun): InsertRun => {
1170 if (!text) return Object.freeze({ file: r.file, parent: r.parent, lines: Object.freeze([...r.lines]) });
1171 const start = k;
1172 const length = r.lines.length;
1173 k += length;
1174 return Object.freeze(new LazyRun(r.file, r.parent, text, start, length));
1175 };
1176 const copy: Atom = {
1177 id: atom.id,
1178 seq: atom.seq,
1179 author: author(atom.author),
1180 message: atom.message,
1181 time: atom.time,
1182 inserts: Object.freeze(atom.inserts.map(run)),
1183 ...(lists
1184 ? {}
1185 : { deletes: list(atom.deletes), writes: list(atom.writes), reads: list(atom.reads), holds: list(atom.holds) }),
1186 needs: list(atom.needs, canon),
1187 resolves: list(atom.resolves, canon),
1188 reasons: list(atom.reasons, (r) => Object.freeze({ to: canon(r.to), kind: r.kind, text: r.text })),
1189 deps: list(atom.deps, canon),
1190 ...(atom.attrs && atom.attrs.length > 0
1191 ? { attrs: Object.freeze(atom.attrs.map((a) => Object.freeze({ file: a.file, name: a.name, value: a.value }))) }
1192 : {}),
1193 ...(atom.moves
1194 ? { moves: Object.freeze(atom.moves.map((m) => Object.freeze({ line: m.line, parent: m.parent }))) }
1195 : {}),
1196 } as Atom;
1197 return Object.freeze(lists ? (new ListedAtom(copy, lists) as unknown as Atom) : copy);
1198}