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=57&format=json
1,117 linesFirst import 100%Last change First import in version 0, 1 version changed it

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