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=119&format=json
1,208 linesFirst import 90% · codex-capacity-chair 10%Last change codex-capacity-chair in version 119, 5 versions changed it

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