Skip to content

abso-core

Public

abso is version control for agents: the client, the engine and a server you can run on your own Cloudflare account.

Check passed
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=143&format=json
1,393 linesFirst import 74% · codex-capacity-chair 26%Last change codex-capacity-chair in version 139, 16 versions changed it

You're reading version 143. The newest is 318, and 19 versions since then changed this file. Go to the newestCompare with 318

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