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=148&format=json
1,395 linesFirst import 74% · codex-capacity-chair 26%Last change codex-capacity-chair in version 148, 17 versions changed it

You're reading version 148. The newest is 318, and 18 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 if (!this.has(id)) throw new EngineError("unknown-atom", `no 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.idOfSeq(seq),
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.idOfSeq(this.#lineAtom.at(n));
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 if (!Number.isSafeInteger(seq) || seq < 0 || seq >= this.#atoms.length)
590 throw new EngineError("unknown-atom", `no atom at sequence ${seq}`);
591 return atomId(seq);
592 }
594 lamportOfSeq(seq: number): number {
595 return this.#lamport[seq]!;
596 }
598 /** The file line n was written in. */
599 writtenIn(n: number): string {
600 return this.#paths[this.#lineFile.at(n)]!;
601 }
603 /** The code of the node line n was written after. */
604 parentCodeOf(n: number): number {
605 return this.#lineParent.at(n);
606 }
608 /** A node's code, or undefined for a node the graph doesn't know (a start node of a file nothing was written in). */
609 codeOf(node: NodeId): number | undefined {
610 return this.#nodeCode(node);
611 }
613 /** The node a code names. */
614 nodeOf(code: number): NodeId {
615 return this.#nodeName(code);
616 }
618 /** The start node's code for a path, or undefined when nothing was ever written in it. */
619 startCodeOf(path: string): number | undefined {
620 const p = this.#pathIndex.get(path);
621 return p === undefined ? undefined : -1 - p;
622 }
624 /** The lines (their n) written right after a node, as childrenOf, into `out`. */
626 childrenN(code: number, out: number[]): void {
627 for (const n of this.eachChildN(code)) out.push(n);
628 }
629 *eachChildN(code: number): IterableIterator<number> {
630 if (
631 code >= 0 &&
632 code + 1 < this.#lineTotal &&
633 this.#lineAtom.at(code + 1) === this.#lineAtom.at(code) &&
634 this.#lineParent.at(code + 1) === code
635 )
636 yield code + 1;
637 if (this.#runStartPages) yield* this.#runStartPages.values(String(code));
638 else yield* listOf(this.#runStarts.get(code));
639 }
641 get hasOrderedChildren(): boolean {
642 return this.#storage !== undefined;
643 }
644 /** Synchronous derived work against one graph identity. Scratch never commits. */
645 withProjectionScratch<T>(operation: (scratch: GraphStateStorage) => T): T {
646 if (!this.#storage) throw new Error("projection scratch requires persistent graph storage");
647 const size = this.size;
648 const lines = this.lineCount;
649 return withProjectionScratch(
650 this.#storage,
651 () => {
652 if (this.size !== size || this.lineCount !== lines) throw new Error("projection graph identity changed");
653 },
654 operation,
655 );
656 }
657 #childPriority(n: number): string {
658 const seq = this.writerSeqOf(n);
659 return orderedChildKey({
660 n,
661 replaces: this.replacesN(n) ? 1 : 0,
662 lamport: this.lamportOfSeq(seq),
663 seq,
664 k: this.kOf(n),
665 });
666 }
667 /** Persistent layout order with a strict successor cursor; moves are separate. */
668 *orderedChildrenN(code: number, after?: number): IterableIterator<number> {
669 if (!this.#storage) throw new Error("ordered children require indexed storage");
670 const index = new OrderedIndex(this.#storage, "ordered-children", String(code));
671 if (this.#storage.read("ordered-children", "format") !== 2)
672 throw new Error("ordered children require fresh adoption");
673 const count = code >= 0 ? this.#childCounts!.at(code, this.#lineTotal) : index.size;
674 if ((code < 0 || count > 0) && (count !== index.size || count !== this.#runStartPages!.length(String(code))))
675 throw new Error("ordered child index count mismatch");
676 let implicit: number | undefined;
677 if (
678 code >= 0 &&
679 code + 1 < this.#lineTotal &&
680 this.#lineAtom.at(code + 1) === this.#lineAtom.at(code) &&
681 this.#lineParent.at(code + 1) === code
682 )
683 implicit = code + 1;
684 // Most historical run lines have no explicit child. With zero or one
685 // child, traversal needs no priority decoding or radix lookup. Keep the
686 // format/count checks above even on this path.
687 if (count === 0 && (after === undefined || after === implicit)) {
688 if (implicit !== undefined && after !== implicit) yield implicit;
689 return;
690 }
691 const cursor = after === undefined ? undefined : this.#childPriority(after);
692 if (implicit !== undefined && cursor !== undefined && this.#childPriority(implicit) <= cursor) implicit = undefined;
693 for (const n of index.values(cursor)) {
694 if (implicit !== undefined && this.#childPriority(implicit) < this.#childPriority(n)) {
695 yield implicit;
696 implicit = undefined;
697 }
698 yield n;
699 }
700 if (implicit !== undefined) yield implicit;
701 }
703 replacesN(n: number): boolean {
704 return this.#replacing.at(n) === 1;
705 }
707 /** The seqs of every atom that deletes line n (none: an empty list, shared). */
708 deleterSeqsOf(n: number): readonly number[] {
709 return [...this.eachDeleterSeqOf(n)];
710 }
711 *eachDeleterSeqOf(n: number): IterableIterator<number> {
712 const first = this.#deleter.at(n);
713 if (first < 0) return;
714 yield first;
715 if (this.#moreDeleterPages) yield* this.#moreDeleterPages.values(String(n));
716 else yield* this.#moreDeleters.get(n) ?? EMPTY;
717 }
719 /** Every relocation that puts a line right after the node with this code. */
720 relocatedToCode(code: number): readonly RelocationInfo[] {
721 if (this.#relocatedToCodePages) return [...this.eachRelocatedToCode(code)];
722 return this.#relocatedToCode.get(code) ?? EMPTY;
723 }
724 *eachRelocatedToCode(code: number): IterableIterator<RelocationInfo> {
725 if (this.#relocatedToCodePages) yield* this.#relocatedToCodePages.values(String(code));
726 else yield* this.#relocatedToCode.get(code) ?? EMPTY;
727 }
729 /** How many lines every atom together has written. */
730 get lineCount(): number {
731 return this.#lineTotal;
732 }
734 /** A line id's n, or -1 when no accepted atom wrote it. */
735 #lineN(id: LineId): number {
736 const p = parseLineId(id);
737 if (!p || p.seq >= this.#atoms.length) return -1;
738 const base = this.#lineBase[p.seq]!;
739 const end = p.seq + 1 < this.#lineBase.length ? this.#lineBase[p.seq + 1]! : this.#lineTotal;
740 return p.k < end - base ? base + p.k : -1;
741 }
743 /** A line's id from its n. */
744 #lineName(n: number): LineId {
745 const seq = this.#lineAtom.at(n);
746 return `${this.idOfSeq(seq)}.${n - this.#lineBase[seq]!}`;
747 }
749 /** A node's code: a line's n, or -1 - a path's index for a start node; undefined when unknown. */
750 #nodeCode(node: NodeId): number | undefined {
751 if (isStartNode(node)) {
752 const p = this.#pathIndex.get(node.slice(1));
753 return p === undefined ? undefined : -1 - p;
754 }
755 const n = this.#lineN(node);
756 return n < 0 ? undefined : n;
757 }
759 #nodeName(code: number): NodeId {
760 return code >= 0 ? this.#lineName(code) : startNode(this.#paths[-1 - code]!);
761 }
763 #pathOf(file: string): number {
764 let p = this.#pathIndex.get(file);
765 if (p === undefined) {
766 p = this.#paths.push(file) - 1;
767 this.#pathIndex.set(file, p);
768 }
769 return p;
770 }
772 /** The line ids an atom inserted, in k order. */
773 linesOf(id: AtomId): LineId[] {
774 const atom = this.atom(id);
775 const out: LineId[] = [];
776 const seq = atom.seq;
777 const count = (seq + 1 < this.#lineBase.length ? this.#lineBase[seq + 1]! : this.#lineTotal) - this.#lineBase[seq]!;
778 for (let k = 0; k < count; k++) out.push(lineId(id, k));
779 return out;
780 }
782 /** Every atom that deletes this line (across the whole graph). */
783 deletersOf(line: LineId): readonly AtomId[] {
784 const n = this.#lineN(line);
785 if (n < 0) return EMPTY;
786 return [...this.eachDeleterSeqOf(n)].map((seq) => this.idOfSeq(seq));
787 }
789 writersOf(key: Key): readonly AtomId[] {
790 return [...this.eachWriterOf(key)];
791 }
792 *eachWriterOf(key: Key): IterableIterator<AtomId> {
793 const code = this.#code(key);
794 if (this.#writersPages) yield* this.#writersPages.values(JSON.stringify([typeof code, code]));
795 else yield* listOf(this.#writers.get(code));
796 }
798 /** Atoms whose implicit reads include the key. */
799 readersOf(key: Key): readonly AtomId[] {
800 return [...this.eachReaderOf(key)];
801 }
802 *eachReaderOf(key: Key): IterableIterator<AtomId> {
803 const code = this.#code(key);
804 if (this.#readersPages) yield* this.#readersPages.values(JSON.stringify([typeof code, code]));
805 else yield* listOf(this.#readers.get(code));
806 }
808 /** Atoms whose explicit holds include the key. */
809 holdersOf(key: Key): readonly AtomId[] {
810 return [...this.eachHolderOf(key)];
811 }
812 *eachHolderOf(key: Key): IterableIterator<AtomId> {
813 const code = this.#code(key);
814 if (this.#holdersPages) yield* this.#holdersPages.values(JSON.stringify([typeof code, code]));
815 else yield* listOf(this.#holders.get(code));
816 }
818 /** Every atom that inserts or deletes a line of the file, in seq order. */
819 atomsIn(file: string): readonly AtomId[] {
820 if (this.#fileAtomPages) return [...this.#fileAtomPages.values(file)];
821 return this.#fileAtoms.get(file) ?? EMPTY;
822 }
823 *eachAtomIn(file: string): IterableIterator<AtomId> {
824 if (this.#fileAtomPages) yield* this.#fileAtomPages.values(file);
825 else yield* this.#fileAtoms.get(file) ?? EMPTY;
826 }
827 hasAtomsIn(file: string): boolean {
828 return this.#fileAtomPages ? this.#fileAtomPages.length(file) > 0 : this.#fileAtoms.has(file);
829 }
831 /** Unique historical file paths, streamed without collecting their names. */
832 *knownFiles(): IterableIterator<string> {
833 yield* this.#fileAtomPages ? this.#fileAtomPages.keys() : this.#fileAtoms.keys();
834 }
836 /**
837 * The files an atom inserts, deletes or moves lines in, or sets attributes
838 * of, sorted. For lines, the file each was written in (or, for a move to a
839 * start node, that file): a set's moves can have taken them elsewhere.
840 */
841 filesOf(id: AtomId): readonly string[] {
842 if (!this.has(id)) throw new EngineError("unknown-atom", `no atom ${id}`);
843 return this.#atomFiles[this.#seq(id)]!;
844 }
846 /** Lines written right after a node (not counting moves), in seq order. */
848 childrenOf(node: NodeId): LineId[] {
849 const code = this.#nodeCode(node);
850 return code === undefined ? [] : [...this.eachChildN(code)].map((n) => this.#lineName(n));
851 }
853 /** Whether a line starts a run whose atom deleted the line it hangs off. */
854 replaces(line: LineId): boolean {
855 const n = this.#lineN(line);
856 return n >= 0 && this.#replacing.at(n) === 1;
857 }
859 /** Every relocation of a line, in seq order. */
860 relocationsOf(line: LineId): readonly RelocationInfo[] {
861 if (this.#relocationPages) return [...this.eachRelocationOf(line)];
862 return this.#relocations.get(line) ?? EMPTY;
863 }
864 *eachRelocationOf(line: LineId): IterableIterator<RelocationInfo> {
865 if (this.#relocationPages) yield* this.#relocationPages.values(line);
866 else yield* this.#relocations.get(line) ?? EMPTY;
867 }
869 /** Every relocation that puts a line right after this node, in seq order. */
870 relocatedTo(node: NodeId): readonly RelocationInfo[] {
871 if (this.#relocatedToPages) return [...this.#relocatedToPages.values(node)];
872 return this.#relocatedTo.get(node) ?? EMPTY;
873 }
875 /** Atoms that move lines, in seq order. */
876 movers(): readonly AtomId[] {
877 return this.#movers;
878 }
880 /** Atoms that list this one directly in their deps. */
881 dependentsOf(id: AtomId): readonly AtomId[] {
882 return [...this.eachDependentOf(id)];
883 }
884 *eachDependentOf(id: AtomId): IterableIterator<AtomId> {
885 if (this.#dependentsPages) yield* this.#dependentsPages.values(id);
886 else yield* listOf(this.#dependents.get(id));
887 }
889 /** Atoms whose `resolves` names this one. */
890 resolversOf(id: AtomId): readonly AtomId[] {
891 return [...this.eachResolverOf(id)];
892 }
893 *eachResolverOf(id: AtomId): IterableIterator<AtomId> {
894 if (this.#resolversPages) yield* this.#resolversPages.values(id);
895 else yield* listOf(this.#resolvers.get(id));
896 }
898 /** `together` reasons touching this atom, in either direction. */
899 togetherLinks(id: AtomId): readonly TogetherLink[] {
900 return [...this.eachTogetherLink(id)];
901 }
902 *eachTogetherLink(id: AtomId): IterableIterator<TogetherLink> {
903 if (this.#togetherPages) yield* this.#togetherPages.values(id);
904 else yield* this.#together.get(id) ?? EMPTY;
905 }
907 /**
908 * The atom plus everything it depends on, transitively. Computed on demand
909 * and not cached: a cached set per atom costs memory quadratic in the length
910 * of a dependency chain. Use `dependsOn` to ask about one pair.
911 */
912 closure(id: AtomId): Set<AtomId> {
913 return this.closureOf([id]);
914 }
916 /** The atoms plus everything they depend on, transitively. */
917 closureOf(ids: Iterable<AtomId>): Set<AtomId> {
918 const out = new Set<AtomId>();
919 const stack: AtomId[] = [];
920 for (const id of ids) {
921 this.atom(id);
922 if (!out.has(id)) {
923 out.add(id);
924 stack.push(id);
925 }
926 }
927 while (stack.length > 0) {
928 for (const d of this.atom(stack.pop()!).deps) {
929 if (!out.has(d)) {
930 out.add(d);
931 stack.push(d);
932 }
933 }
934 }
935 return out;
936 }
938 /** Whether `b` is in the closure of `a` (an atom is in its own closure). */
939 dependsOn(a: AtomId, b: AtomId): boolean {
940 const atom = this.atom(a);
941 this.atom(b);
942 return a === b || this.#reaches(atom.deps, b);
943 }
945 /**
946 * Whether `target` is reachable along deps from any of `from` (themselves
947 * included). A dependency always has a lower lamport than its dependent, so
948 * the search never descends below the target's lamport.
949 */
950 #reaches(from: Iterable<AtomId>, target: AtomId): boolean {
951 const floor = this.#lamport[this.#seq(target)]!;
952 if (this.#storage) {
953 // Roots belong to the current atom's dependency list, not its history.
954 const roots = [...from];
955 if (roots.includes(target)) return true;
956 if (roots.every((id) => this.#lamport[this.#seq(id)]! <= floor)) return false;
957 return this.withProjectionScratch((scratch) => {
958 let length = 0;
959 const push = (id: AtomId): void => {
960 if (scratch.read("seen", id)) return;
961 scratch.write("seen", id, true);
962 scratch.write("stack", String(length++), id);
963 };
964 for (const id of roots) push(id);
965 while (length > 0) {
966 const key = String(--length);
967 const current = scratch.read("stack", key) as AtomId;
968 scratch.remove("stack", key);
969 if (this.#lamport[this.#seq(current)]! <= floor) continue;
970 for (const dependency of this.atom(current).deps) {
971 if (dependency === target) return true;
972 push(dependency);
973 }
974 }
975 return false;
976 });
977 }
978 const seen = new Set<AtomId>();
979 const stack = [...from];
980 while (stack.length > 0) {
981 const cur = stack.pop()!;
982 if (cur === target) return true;
983 if (seen.has(cur)) continue;
984 seen.add(cur);
985 if (this.#lamport[this.#seq(cur)]! <= floor) continue;
986 for (const d of this.atom(cur).deps) if (!seen.has(d)) stack.push(d);
987 }
988 return false;
989 }
991 /**
992 * Accept an atom into the graph. It must carry the next id and seq, and
993 * everything it touches must come from atoms in its dependency closure.
994 * The atom is frozen. Adding to the graph does not add it to any set.
995 */
996 add(atom: Atom): void {
997 if (this.#storage) this.#storage.transaction(() => this.#add(atom));
998 else this.#add(atom);
999 }
1001 #add(atom: Atom): void {
1002 if (this.#storage && this.#storage.read("ordered-children", "format") !== 2) {
1003 if (this.#atoms.length !== 0) throw new Error("ordered children require fresh adoption");
1004 this.#storage.write("ordered-children", "format", 2);
1007 validateShape(atom);
1008 const seq = this.#atoms.length;
1009 const bad = (why: string): never => {
1010 throw new EngineError("bad-atom", `atom ${atom.id}: ${why}`);
1011 };
1012 if (atom.seq !== seq || atom.id !== atomId(seq)) bad(`expected id ${atomId(seq)} with seq ${seq}`);
1014 const deps = new Set<AtomId>();
1015 for (const d of atom.deps) {
1016 if (!this.has(d)) bad(`dependency ${d} is not in the graph`);
1017 if (deps.has(d)) bad(`dependency ${d} listed twice`);
1018 deps.add(d);
1020 for (const d of [...atom.needs, ...atom.resolves]) {
1021 if (!deps.has(d)) bad(`${d} is in needs/resolves but not in deps`);
1023 for (const r of atom.reasons) if (!this.has(r.to)) bad(`reason points at unknown atom ${r.to}`);
1025 // Everything it touches must come from its closure. Derived deps name the
1026 // writers directly, so this is usually one lookup per writer.
1027 const below = new Map<AtomId, boolean>();
1028 const inClosure = (writer: AtomId): boolean => {
1029 let hit = below.get(writer);
1030 if (hit === undefined) {
1031 hit = deps.has(writer) || this.#reaches(deps, writer);
1032 below.set(writer, hit);
1034 return hit;
1035 };
1036 const checkLine = (line: LineId, what: string): void => {
1037 const writer = this.lineAtom(line);
1038 if (writer === undefined) return bad(`${what} names unknown line ${line}`);
1039 if (!inClosure(writer)) bad(`${what} names line ${line} but ${writer} is not in its closure`);
1040 };
1042 for (const run of atom.inserts) {
1043 if (isStartNode(run.parent)) {
1044 if (run.parent !== startNode(run.file)) bad(`run in ${run.file} starts at ${run.parent}`);
1045 } else {
1046 // The parent may have been moved into run.file, so its own file can differ.
1047 checkLine(run.parent, "an insert");
1050 const moved = new Set<LineId>();
1051 for (const m of atom.moves ?? []) {
1052 checkLine(m.line, "a move");
1053 if (!isStartNode(m.parent)) checkLine(m.parent, "a move");
1054 if (m.line === m.parent) bad(`moves ${m.line} after itself`);
1055 if (moved.has(m.line)) bad(`moves ${m.line} twice`);
1056 moved.add(m.line);
1057 if (!atom.writes.includes(posKey(m.line)) || !atom.writes.includes(gapKey(m.parent))) {
1058 bad(`moves ${m.line} without writing ${posKey(m.line)} and ${gapKey(m.parent)}`);
1061 const deleted = new Set<LineId>();
1062 for (const line of atom.deletes) {
1063 checkLine(line, "a delete");
1064 if (deleted.has(line)) bad(`deletes ${line} twice`);
1065 deleted.add(line);
1067 const writes = new Set(atom.writes);
1068 for (const line of deleted) if (!writes.has(lineKey(line))) bad(`deletes ${line} without writing ${lineKey(line)}`);
1069 for (const key of [...atom.writes, ...atom.reads, ...atom.holds]) {
1070 const parsed = parseKey(key);
1071 if (parsed.kind === "line") checkLine(parsed.node, `key ${key}`);
1072 else if ((parsed.kind === "gap" || parsed.kind === "pos") && !isStartNode(parsed.node))
1073 checkLine(parsed.node, `key ${key}`);
1076 // Accept.
1077 const frozen = freezeAtom(
1078 atom,
1079 (id) => this.#atoms[seqOf(id)]!.id,
1080 (author) => {
1081 if (this.#storage) return author;
1082 let a = this.#authors.get(author);
1083 if (a === undefined) this.#authors.set(author, (a = author));
1084 return a;
1085 },
1086 this.#texts ? this.#reader(seq) : undefined,
1087 this.#lists ? this.#listReader(seq) : undefined,
1088 );
1089 this.#atoms.push(this.#storage ? atom : frozen);
1090 let lam = 0;
1091 for (const d of deps) lam = Math.max(lam, this.lamport(d) + 1);
1092 this.#lamport.push(lam);
1094 // The run starts' parents and the deleted lines, as codes, before this atom's own lines exist.
1095 // The atom as given: with lists kept elsewhere, the frozen one reads them back from the log.
1096 const deletes = atom.deletes.length > 0 ? new Set(atom.deletes) : undefined;
1097 const deletedN = atom.deletes.map((line) => this.#lineN(line));
1098 this.#atomDeletes.push(deletedN.length > 0 ? (this.#storage ? deletedN : Int32Array.from(deletedN)) : undefined);
1099 this.#lineBase.push(this.#lineTotal);
1100 for (const run of atom.inserts) {
1101 const file = this.#pathOf(run.file);
1102 let parent = isStartNode(run.parent) ? -1 - file : this.#lineN(run.parent);
1103 const first = this.#lineTotal;
1104 if (parent >= 0) this.#childCounts?.increment(parent, first);
1105 if (this.#storage)
1106 new OrderedIndex(this.#storage, "ordered-children", String(parent)).insert(
1107 orderedChildKey({
1108 n: first,
1109 replaces: deletes?.has(run.parent) ? 1 : 0,
1110 lamport: lam,
1111 seq,
1112 k: first - this.#lineBase[seq]!,
1113 }),
1114 first,
1115 );
1117 if (this.#runStartPages) this.#runStartPages.append(String(parent), first);
1118 else pushOne(this.#runStarts, parent, first);
1119 for (let i = 0; i < run.lines.length; i++) {
1120 const n = this.#lineTotal;
1121 this.#childCounts?.append(n);
1122 this.#lineAtom.push(seq);
1123 this.#lineFile.push(file);
1124 this.#lineParent.push(parent);
1125 this.#lineText?.push(run.lines[i]!);
1126 this.#deleter.push(-1);
1127 this.#replacing.push(i === 0 && deletes?.has(run.parent) ? 1 : 0);
1128 parent = n;
1131 (frozen.moves ?? []).forEach((m, i) => {
1132 const info: RelocationInfo = Object.freeze({ atom: frozen.id, line: m.line, parent: m.parent, k: i });
1133 if (this.#relocationPages) this.#relocationPages.append(m.line, info);
1134 else pushIndex(this.#relocations, m.line, info);
1135 if (this.#relocatedToPages) this.#relocatedToPages.append(m.parent, info);
1136 else pushIndex(this.#relocatedTo, m.parent, info);
1137 const parentCode = isStartNode(m.parent) ? -1 - this.#pathOf(m.parent.slice(1)) : this.#lineN(m.parent);
1138 if (this.#relocatedToCodePages) this.#relocatedToCodePages.append(String(parentCode), info);
1139 else pushIndex(this.#relocatedToCode, parentCode, info);
1140 });
1141 if (frozen.moves) this.#movers.push(frozen.id);
1142 for (const n of deletedN) {
1143 if (this.#deleter.at(n) < 0) this.#deleter.set(n, seq);
1144 else if (this.#moreDeleterPages) this.#moreDeleterPages.append(String(n), seq);
1145 else pushIndex(this.#moreDeleters, n, seq);
1147 for (const key of new Set(atom.writes)) {
1148 const code = this.#code(key);
1149 if (this.#writersPages) this.#writersPages.append(JSON.stringify([typeof code, code]), frozen.id);
1150 else pushOne(this.#writers, code, frozen.id);
1152 for (const key of new Set(atom.reads)) {
1153 const code = this.#code(key);
1154 if (this.#readersPages) this.#readersPages.append(JSON.stringify([typeof code, code]), frozen.id);
1155 else pushOne(this.#readers, code, frozen.id);
1157 for (const key of new Set(atom.holds)) {
1158 const code = this.#code(key);
1159 if (this.#holdersPages) this.#holdersPages.append(JSON.stringify([typeof code, code]), frozen.id);
1160 else pushOne(this.#holders, code, frozen.id);
1162 for (const d of deps) {
1163 if (this.#dependentsPages) this.#dependentsPages.append(d, frozen.id);
1164 else pushOne(this.#dependents, d, frozen.id);
1166 for (const r of new Set(frozen.resolves)) {
1167 if (this.#resolversPages) this.#resolversPages.append(r, frozen.id);
1168 else pushOne(this.#resolvers, r, frozen.id);
1170 const files = new Set<string>();
1171 for (const run of atom.inserts) files.add(run.file);
1172 for (const n of deletedN) files.add(this.#paths[this.#lineFile.at(n)]!);
1173 for (const a of frozen.attrs ?? []) files.add(a.file);
1174 for (const m of frozen.moves ?? []) {
1175 files.add(this.lineFile(m.line)!);
1176 files.add(isStartNode(m.parent) ? m.parent.slice(1) : this.lineFile(m.parent)!);
1178 this.#atomFiles.push(Object.freeze([...files].sort()));
1179 for (const file of files) {
1180 if (this.#fileAtomPages) this.#fileAtomPages.append(file, frozen.id);
1181 else pushIndex(this.#fileAtoms, file, frozen.id);
1183 for (const r of frozen.reasons) {
1184 if (r.kind !== "together" || r.to === frozen.id) continue;
1186 const forward = { other: r.to, text: r.text, from: frozen.id };
1187 const reverse = { other: frozen.id, text: r.text, from: frozen.id };
1188 if (this.#togetherPages) {
1189 this.#togetherPages.append(frozen.id, forward);
1190 this.#togetherPages.append(r.to, reverse);
1191 } else {
1192 pushIndex(this.#together, frozen.id, forward);
1193 pushIndex(this.#together, r.to, reverse);
1198 // Labels -----------------------------------------------------------------
1200 /**
1201 * Add or replace a label. Label names may not look like atom ids. A base is
1202 * resolved to its head only when it is used, never followed further, so
1203 * bases may name each other in any shape.
1204 */
1205 setLabel(label: Label): void {
1206 this.#putLabel(label, (name) => this.#labels.has(name));
1209 #putLabel(label: Label, isLabel: (name: string) => boolean): void {
1210 const bad = (why: string): never => {
1211 throw new EngineError("bad-label", `label ${JSON.stringify(label?.name)}: ${why}`);
1212 };
1213 if (typeof label !== "object" || label === null) bad("not an object");
1214 if (typeof label.name !== "string" || label.name === "") bad("needs a name");
1215 if (isAtomId(label.name)) bad("a label name may not look like an atom id");
1216 if (!this.has(label.head)) bad(`head ${label.head} is not in the graph`);
1217 if (
1218 label.base !== undefined &&
1219 !(typeof label.base === "string" && (isLabel(label.base) || this.has(label.base)))
1220 ) {
1221 bad(`base ${label.base} is neither a label nor an atom`);
1223 if (label.base === label.name) bad("a label cannot be its own base");
1224 if (typeof label.title !== "string" || typeof label.message !== "string") bad("needs a title and message");
1225 if (label.follows !== undefined && !Array.isArray(label.follows)) bad("follows must be a list of label names");
1226 const copy: Label = {
1227 name: label.name,
1228 head: label.head,
1229 ...(label.base !== undefined ? { base: label.base } : {}),
1230 title: label.title,
1231 message: label.message,
1232 ...(label.follows !== undefined ? { follows: Object.freeze([...label.follows]) } : {}),
1233 };
1234 this.#labels.set(label.name, Object.freeze(copy));
1237 label(name: string): Label | undefined {
1238 return this.#labels.get(name);
1241 /** Labels sorted by name. */
1242 labels(): Label[] {
1243 return [...this.#labels.values()].sort((a, b) => (a.name < b.name ? -1 : a.name > b.name ? 1 : 0));
1246 /**
1247 * Remove a label. Labels that used it as their base get its head atom as
1248 * their base instead, so their contents don't change.
1249 */
1250 removeLabel(name: string): boolean {
1251 return this.#storage ? this.#storage.transaction(() => this.#removeLabel(name)) : this.#removeLabel(name);
1254 #removeLabel(name: string): boolean {
1255 const gone = this.#labels.get(name);
1256 if (!gone) return false;
1257 this.#labels.delete(name);
1258 for (const label of [...this.#labels.values()]) {
1259 if (label.base === name) this.#labels.set(label.name, Object.freeze({ ...label, base: gone.head }));
1261 return true;
1264 // JSON -------------------------------------------------------------------
1266 toJSON(): GraphJSON {
1267 return { format: GRAPH_FORMAT, version: 1, atoms: this.#atoms, labels: this.labels() };
1270 /** Load a saved graph. Every atom is re-validated as it is added. */
1271 static fromJSON(data: unknown): Graph {
1272 const bad = (why: string): never => {
1273 throw new EngineError("bad-json", why);
1274 };
1275 if (typeof data !== "object" || data === null) bad("graph JSON must be an object");
1276 const obj = data as Partial<GraphJSON>;
1277 if (obj.format !== GRAPH_FORMAT) bad(`format must be ${GRAPH_FORMAT}`);
1278 if (obj.version !== 1) bad(`unsupported version ${String(obj.version)}`);
1279 if (!Array.isArray(obj.atoms) || !Array.isArray(obj.labels)) bad("atoms and labels must be arrays");
1280 const graph = new Graph();
1281 for (const atom of obj.atoms!) graph.add(atom);
1282 // Labels may name each other as bases, in any order and any shape.
1283 const names = new Set<string>();
1284 for (const label of obj.labels!) {
1285 const name: unknown = (label as Partial<Label> | null)?.name;
1286 if (typeof name !== "string") return bad("every label needs a name");
1287 if (names.has(name)) bad(`label ${name} appears twice`);
1288 names.add(name);
1290 for (const label of obj.labels!) {
1291 try {
1292 graph.#putLabel(label, (name) => names.has(name));
1293 } catch (err) {
1294 if (err instanceof EngineError) bad(err.message);
1295 throw err;
1298 return graph;
1301 #seq(id: AtomId): number {
1302 return typeof id === "string" ? seqOf(id) : -1;
1306function validateShape(atom: Atom): void {
1307 const bad = (why: string): never => {
1308 throw new EngineError("bad-atom", `atom ${String((atom as { id?: unknown }).id)}: ${why}`);
1309 };
1310 if (typeof atom !== "object" || atom === null) bad("not an object");
1311 if (typeof atom.id !== "string" || !Number.isInteger(atom.seq)) bad("needs id and seq");
1312 if (typeof atom.author !== "string" || typeof atom.message !== "string") bad("needs author and message");
1313 if (typeof atom.time !== "number" || !Number.isFinite(atom.time)) bad("time must be a finite number");
1314 const lists = ["inserts", "deletes", "writes", "reads", "holds", "needs", "resolves", "reasons", "deps"] as const;
1315 for (const name of lists) if (!Array.isArray(atom[name])) bad(`${name} must be an array`);
1316 for (const run of atom.inserts as readonly InsertRun[]) {
1317 if (typeof run.file !== "string" || run.file === "" || run.file.includes("\n")) bad("a run needs a file path");
1318 if (typeof run.parent !== "string") bad("a run needs a parent");
1319 if (!Array.isArray(run.lines) || run.lines.length === 0) bad("a run needs at least one line");
1320 for (const text of run.lines) {
1321 if (typeof text !== "string" || text.includes("\n") || text.includes("\r"))
1322 bad("run lines must be strings without line breaks");
1325 if (atom.attrs !== undefined) {
1326 if (!Array.isArray(atom.attrs)) bad("attrs must be an array");
1327 for (const a of atom.attrs) {
1328 if (typeof a?.file !== "string" || a.file === "" || a.file.includes("\n") || !ATTR_NAMES.includes(a.name))
1329 bad("an attr needs a file and a name");
1330 if (a.value !== null && typeof a.value !== "string") bad("an attr value is a string or null");
1331 if (!atom.writes.includes(attrKey(a.file, a.name))) bad(`sets ${a.name} of ${a.file} without writing its key`);
1334 if (atom.moves !== undefined) {
1335 if (!Array.isArray(atom.moves) || atom.moves.length === 0) bad("moves must be a non-empty array");
1336 for (const m of atom.moves) {
1337 if (typeof m?.line !== "string" || typeof m.parent !== "string") bad("a move needs a line and a parent");
1340 for (const name of ["deletes", "writes", "reads", "holds", "needs", "resolves", "deps"] as const) {
1341 for (const x of atom[name]) if (typeof x !== "string") bad(`${name} must hold strings`);
1343 for (const r of atom.reasons as readonly Reason[]) {
1344 if (typeof r.to !== "string" || typeof r.text !== "string" || !REASON_KINDS.includes(r.kind)) {
1345 bad("a reason needs to, kind (together, because-of or supersedes) and text");
1350/**
1351 * A frozen copy of an atom. An empty list is one shared frozen list, and atom
1352 * ids and authors are the graph's own strings (`canon`, `author`), so each is
1353 * kept once however often it's named (#46).
1354 */
1355function freezeAtom(
1356 atom: Atom,
1357 canon: (id: AtomId) => AtomId,
1358 author: (name: string) => string,
1359 text?: (start: number, length: number) => readonly string[],
1360 lists?: () => AtomLists,
1361): Atom {
1362 const list = <T>(xs: readonly T[], f?: (x: T) => T): readonly T[] =>
1363 xs.length === 0 ? EMPTY : Object.freeze(f ? xs.map(f) : [...xs]);
1364 // With text kept elsewhere (#46), a run's lines are read when asked for.
1365 let k = 0;
1366 const run = (r: InsertRun): InsertRun => {
1367 if (!text) return Object.freeze({ file: r.file, parent: r.parent, lines: Object.freeze([...r.lines]) });
1368 const start = k;
1369 const length = r.lines.length;
1370 k += length;
1371 return Object.freeze(new LazyRun(r.file, r.parent, text, start, length));
1372 };
1373 const copy: Atom = {
1374 id: atom.id,
1375 seq: atom.seq,
1376 author: author(atom.author),
1377 message: atom.message,
1378 time: atom.time,
1379 inserts: Object.freeze(atom.inserts.map(run)),
1380 ...(lists
1381 ? {}
1382 : { deletes: list(atom.deletes), writes: list(atom.writes), reads: list(atom.reads), holds: list(atom.holds) }),
1383 needs: list(atom.needs, canon),
1384 resolves: list(atom.resolves, canon),
1385 reasons: list(atom.reasons, (r) => Object.freeze({ to: canon(r.to), kind: r.kind, text: r.text })),
1386 deps: list(atom.deps, canon),
1387 ...(atom.attrs && atom.attrs.length > 0
1388 ? { attrs: Object.freeze(atom.attrs.map((a) => Object.freeze({ file: a.file, name: a.name, value: a.value }))) }
1389 : {}),
1390 ...(atom.moves
1391 ? { moves: Object.freeze(atom.moves.map((m) => Object.freeze({ line: m.line, parent: m.parent }))) }
1392 : {}),
1393 } as Atom;
1394 return Object.freeze(lists ? (new ListedAtom(copy, lists) as unknown as Atom) : copy);