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