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=162&format=json
1,648 linesFirst import 60% · codex-capacity-chair 40%Last change codex-capacity-chair in version 162, 20 versions changed it

You're reading version 162. The newest is 318, and 15 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 readonlyStoredArray,
24 type StateMap,
25 storedArray,
26 storedLists,
27 storedMap,
28 storedNumbers,
29} from "./state-source.ts";
30import { StoredText } from "./stored-text.ts";
31import {
32 ATTR_NAMES,
33 type Atom,
34 type AtomId,
35 EngineError,
36 type InsertRun,
37 type Key,
38 type Label,
39 type LineId,
40 type NodeId,
41 REASON_KINDS,
42 type Reason,
43} from "./types.ts";
45/**
46 * Where a line was written and what it says. Its text never changes. A move
47 * can give it another parent in a set, even in another file: `view.parentOf`
48 * and `view.fileOf` say where it is in a set.
49 */
50export interface LineInfo {
51 readonly id: LineId;
52 readonly atom: AtomId;
53 readonly k: number;
54 /** The file it was written in. */
55 readonly file: string;
56 /** The node it was written after. */
57 readonly parent: NodeId;
58 readonly text: string;
61/** One relocation of a line, by the atom that made it; `k` is its place in that atom's moves. */
62export interface RelocationInfo {
63 readonly atom: AtomId;
64 readonly line: LineId;
65 readonly parent: NodeId;
66 readonly k: number;
69/** A `together` reason seen from one end: `other` is the atom at the far end. */
70export interface TogetherLink {
71 readonly other: AtomId;
72 readonly text: string;
73 /** The atom that carries the reason. */
74 readonly from: AtomId;
77export const GRAPH_FORMAT = "ai-first-vcs.graph";
79/** The saved form of a graph. Atoms are in seq order. */
80export interface GraphJSON {
81 readonly format: typeof GRAPH_FORMAT;
82 readonly version: 1;
83 readonly atoms: readonly Atom[];
84 readonly labels: readonly Label[];
87/**
88 * An index entry that holds a lone value as itself, and a list only once there
89 * are two (#46): most keys name one atom, and a list for each costs more than
90 * the value.
91 */
92function pushOne<K, V>(map: StateMap<K, V | V[]>, key: K, value: V): void {
93 const had = map.get(key);
94 if (had === undefined) map.set(key, value);
95 else if (Array.isArray(had)) {
96 had.push(value);
97 map.set(key, had);
98 } else map.set(key, [had, value]);
101function listOf<V>(had: V | V[] | undefined): readonly V[] {
102 return had === undefined ? EMPTY : Array.isArray(had) ? had : [had];
105function pushIndex<K, V>(map: StateMap<K, V[]>, key: K, value: V): void {
106 const list = map.get(key);
107 if (list) {
108 list.push(value);
109 map.set(key, list);
110 } else map.set(key, [value]);
113const EMPTY: readonly never[] = Object.freeze([]);
115/**
116 * A run whose lines are read when asked for (#46, text on disk): a few fields
117 * and a shared reader, where an object with its own accessor cost about 400
118 * bytes a run.
119 */
120class LazyRun implements InsertRun {
121 readonly file: string;
122 readonly parent: NodeId;
123 readonly #text: (start: number, length: number) => readonly string[];
124 readonly #start: number;
125 readonly #length: number;
126 constructor(
127 file: string,
128 parent: NodeId,
129 text: (start: number, length: number) => readonly string[],
130 start: number,
131 length: number,
132 ) {
133 this.file = file;
134 this.parent = parent;
135 this.#text = text;
136 this.#start = start;
137 this.#length = length;
138 }
139 get lines(): readonly string[] {
140 return this.#text(this.#start, this.#length);
141 }
142 toJSON(): InsertRun {
143 return { file: this.file, parent: this.parent, lines: this.lines };
144 }
147/** Characters of atoms' text a graph that keeps text elsewhere holds at most (#46): about 8 MB. */
148const TEXT_CACHE = 4_000_000;
149/** 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. */
150const LIST_CACHE = 50_000;
152/** An atom's deletes and claim keys: kept in the log rather than in memory when the graph has a `lists` reader (#46). */
153export interface AtomLists {
154 readonly deletes: readonly LineId[];
155 readonly writes: readonly Key[];
156 readonly reads: readonly Key[];
157 readonly holds: readonly Key[];
160function listItems(l: AtomLists): number {
161 return l.deletes.length + l.writes.length + l.reads.length + l.holds.length;
164function frozenList<T>(xs: readonly T[]): readonly T[] {
165 return xs.length === 0 ? (EMPTY as readonly T[]) : Object.freeze([...xs]);
168/**
169 * An atom whose deletes, writes, reads and holds are read back through `read` (#46). The getters live on the
170 * prototype, so each atom keeps one reader and a fixed shape, not four closures in a dictionary-mode object.
171 */
172class ListedAtom {
173 readonly #read: () => AtomLists;
174 constructor(fields: object, read: () => AtomLists) {
175 Object.assign(this, fields);
176 this.#read = read;
177 }
178 get deletes(): readonly LineId[] {
179 return this.#read().deletes;
180 }
181 get writes(): readonly Key[] {
182 return this.#read().writes;
183 }
184 get reads(): readonly Key[] {
185 return this.#read().reads;
186 }
187 get holds(): readonly Key[] {
188 return this.#read().holds;
189 }
190 toJSON(): object {
191 return { ...this, ...this.#read() };
192 }
195/** A growable array of 32-bit integers: a line's fields cost 4 bytes each, not an object and its strings (#46). */
196interface NumberIndex {
197 readonly length: number;
198 push(n: number): void;
199 at(i: number): number;
200 set(i: number, n: number): void;
203class Ints implements NumberIndex {
204 #buf: Int32Array | Uint8Array;
205 /** bytes: values 0-255 only, one byte each. */
206 constructor(bytes = false) {
207 this.#buf = bytes ? new Uint8Array(1024) : new Int32Array(1024);
208 }
209 length = 0;
210 push(n: number): void {
211 if (this.length === this.#buf.length) {
212 const bigger =
213 this.#buf instanceof Uint8Array ? new Uint8Array(this.#buf.length * 2) : new Int32Array(this.#buf.length * 2);
214 bigger.set(this.#buf);
215 this.#buf = bigger;
216 }
217 this.#buf[this.length++] = n;
218 }
219 at(i: number): number {
220 return this.#buf[i]!;
221 }
222 set(i: number, n: number): void {
223 this.#buf[i] = n;
224 }
227/**
228 * A line id's place in the graph's line arrays, or -1: "a<seq>.<k>" is line
229 * `base[seq] + k`. Hand-parsed, as seqOf is, with the same rules: no leading
230 * zeros, and k within the lines its atom wrote.
231 */
232function parseLineId(id: string): { seq: number; k: number } | undefined {
233 if (typeof id !== "string") return undefined;
234 const n = id.length;
235 if (n < 4 || id.charCodeAt(0) !== 97 /* a */) return undefined;
236 let i = 1;
237 let seq = 0;
238 const seqStart = i;
239 for (; i < n; i++) {
240 const c = id.charCodeAt(i);
241 if (c === 46 /* . */) break;
242 if (c < 48 || c > 57) return undefined;
243 seq = seq * 10 + (c - 48);
244 }
245 if (i === seqStart || i >= n - 1 || i - seqStart > 15 || (i - seqStart > 1 && id.charCodeAt(seqStart) === 48))
246 return undefined;
247 const kStart = ++i;
248 let k = 0;
249 for (; i < n; i++) {
250 const c = id.charCodeAt(i);
251 if (c < 48 || c > 57) return undefined;
252 k = k * 10 + (c - 48);
253 }
254 if (i - kStart > 15 || (i - kStart > 1 && id.charCodeAt(kStart) === 48)) return undefined;
255 return { seq, k };
258export class Graph {
259 readonly #storage?: GraphStateStorage;
260 readonly #childCounts?: ChildCounts;
261 #atoms: Atom[] = [];
262 #lamport: number[] = [];
263 // Lines, packed (#46): line n is the k-th line atom seq wrote, n = #lineBase[seq] + k. Each holds its
264 // atom's seq, the file it was written in (an index into #paths) and its parent (a line's n, or -1 - a
265 // path's index for a file's start). Its text stays in the atom. Ids and LineInfo objects are made only
266 // when asked for, so a line costs about 16 bytes here instead of a record, its id and its parent's id.
267 #lineBase: number[] = [];
268 #lineAtom: NumberIndex = new Ints();
269 #lineFile: NumberIndex = new Ints();
270 #lineParent: NumberIndex = new Ints();
271 /** Lines' text, when the graph keeps it; without it, it comes from `texts` (#46, text on disk). */
272 #lineText: string[] | undefined = [];
273 get #lineTotal(): number {
274 return this.#lineAtom.length;
275 }
276 /** Where an atom's lines' text is when the graph doesn't keep it: each run's lines, by the atom's seq. */
277 #texts: ((seq: number) => readonly (readonly string[])[]) | undefined;
278 /** Recently read atoms' text, flattened, most recent last, up to TEXT_CACHE characters. */
279 #textCache = new Map<number, readonly string[]>();
280 #textCached = 0;
282 readonly #indexAcceptedAtom?: (atom: Atom, files: readonly string[], storage: GraphStateStorage) => void;
284 /**
285 * `texts`, when given, says where each atom's lines' text can be read back
286 * (#46): the graph then keeps no text, only each line's place, and reads an
287 * atom's text when a line of it is asked for, keeping the most recent.
288 */
289 constructor(
290 options: {
291 texts?: (seq: number) => readonly (readonly string[])[];
292 lists?: (seq: number) => AtomLists;
293 storage?: GraphStateStorage;
294 /** Optional derived indexing inside persistent atom acceptance; must be synchronous. */
295 indexAcceptedAtom?: (atom: Atom, files: readonly string[], storage: GraphStateStorage) => void;
296 } = {},
297 ) {
298 if (options.indexAcceptedAtom && !options.storage)
299 throw Error("accepted atom indexing requires persistent storage");
300 this.#indexAcceptedAtom = options.indexAcceptedAtom;
301 if (options.texts) {
302 this.#texts = options.texts;
303 this.#lineText = undefined;
304 }
305 if (options.lists) this.#lists = options.lists;
306 this.#storage = options.storage;
307 if (options.storage) this.#childCounts = new ChildCounts(options.storage);
308 if (options.storage) {
309 const storage = options.storage;
310 const numbers = (name: string): NumberIndex => storedNumbers(storage, name);
311 const atomText = new StoredText(storage, "atom-text:long");
312 type TextReference = { text: string };
313 const listFields = [
314 "deletes",
315 "writes",
316 "reads",
317 "holds",
318 "needs",
319 "resolves",
320 "deps",
321 "reasons",
322 "attrs",
323 "moves",
324 ] as const;
325 type EncodedAtom = {
326 insertionFormat?: 1;
327 insertionRuns?: string;
328 textFormat?: 1;
329 listFormat?: 1;
330 listCount?: number;
331 lists?: Partial<Record<(typeof listFields)[number], string>>;
332 atom: Atom;
333 };
334 this.#atoms = storedArray<Atom>(
335 storage,
336 "atoms",
337 (value) => {
338 const encoded = value as unknown as Partial<EncodedAtom>;
339 if (encoded.textFormat !== undefined && encoded.textFormat !== 1)
340 throw Error("invalid stored atom text format");
341 if (encoded.listFormat !== undefined && encoded.listFormat !== 1)
342 throw Error("invalid stored atom list format");
343 if (encoded.listFormat === 1) {
344 if (
345 !encoded.lists ||
346 typeof encoded.lists !== "object" ||
347 Array.isArray(encoded.lists) ||
348 !Number.isSafeInteger(encoded.listCount) ||
349 encoded.listCount! < 1 ||
350 Object.keys(encoded.lists).length !== encoded.listCount ||
351 Object.keys(encoded.lists).some((field) => !listFields.includes(field as (typeof listFields)[number]))
352 )
353 throw Error("invalid stored atom list references");
354 }
355 if (encoded.insertionFormat !== undefined && encoded.insertionFormat !== 1)
356 throw Error("invalid stored insertion format");
357 const atom =
358 encoded.textFormat === 1 || encoded.listFormat === 1 || encoded.insertionFormat === 1
359 ? encoded.atom!
360 : value;
361 const text =
362 encoded.textFormat === 1
363 ? (start: number, length: number): readonly string[] => {
364 const result: string[] = [];
365 let index = 0;
366 for (const run of atom.inserts)
367 for (const raw of run.lines) {
368 if (index >= start && index < start + length) {
369 const reference = raw as unknown as TextReference;
370 if (typeof raw === "string") result.push(raw);
371 else if (reference && typeof reference.text === "string")
372 result.push(atomText.read(reference.text));
373 else throw Error("invalid stored atom text reference");
374 }
375 if (++index >= start + length) return result;
376 }
377 throw Error("stored atom text range missing");
378 }
379 : undefined;
380 const frozen = freezeAtom(
381 atom,
382 (id) => id,
383 (author) => author,
384 text,
385 );
386 if (encoded.listFormat !== 1 && encoded.insertionFormat !== 1) return frozen;
387 const result = { ...frozen };
388 if (encoded.insertionFormat === 1) {
389 const collection = `atom-inserts:${atom.seq}`;
390 if (encoded.insertionRuns !== collection) throw Error("invalid stored insertion reference");
391 const inserts = readonlyStoredArray<InsertRun>(storage, collection, (raw, index) => {
392 const run = raw as { file: string; parent: InsertRun["parent"]; lines: string };
393 const lines = `${collection}:lines:${index}`;
394 if (run.lines !== lines || typeof run.file !== "string" || typeof run.parent !== "string")
395 throw Error("invalid stored insertion run");
396 return Object.freeze({
397 file: run.file,
398 parent: run.parent,
399 lines: readonlyStoredArray<string>(storage, lines, (rawLine) => {
400 if (typeof rawLine === "string") return rawLine;
401 const ref = rawLine as TextReference;
402 if (!ref || typeof ref.text !== "string") throw Error("invalid stored insertion text");
403 return atomText.read(ref.text);
404 }),
405 });
406 });
407 Object.defineProperty(result, "inserts", { value: inserts, enumerable: true });
408 }
409 for (const field of listFields) {
410 const collection = encoded.lists?.[field];
411 if (collection === undefined) continue;
412 if (typeof collection !== "string" || collection !== `atom-list:${atom.seq}:${field}`)
413 throw Error("invalid stored atom list reference");
414 Object.defineProperty(result, field, { value: readonlyStoredArray(storage, collection), enumerable: true });
415 }
416 return Object.freeze(result);
417 },
418 (input, key) => {
419 const atom = { ...input };
420 const lists: Partial<Record<(typeof listFields)[number], string>> = {};
421 for (const field of listFields) {
422 const values = input[field];
423 if (!values || values.length <= 256) continue;
424 const collection = `atom-list:${input.seq}:${field}`;
425 const saved = storedArray<unknown>(storage, collection);
426 for (const value of values) saved.push(value);
427 lists[field] = collection;
428 Object.defineProperty(atom, field, { value: [], enumerable: true });
429 }
430 const listCount = Object.keys(lists).length;
431 const hasLists = listCount > 0;
432 if (atom.inserts.length > 256 || atom.inserts.some((run) => run.lines.length > 256)) {
433 const collection = `atom-inserts:${input.seq}`;
434 const runs = storedArray<unknown>(storage, collection);
435 let runIndex = 0;
436 let lineIndex = 0;
437 for (const run of atom.inserts) {
438 const lineCollection = `${collection}:lines:${runIndex++}`;
439 const lines = storedArray<unknown>(storage, lineCollection);
440 for (const line of run.lines) {
441 const text = JSON.stringify([key, lineIndex++]);
442 if (line.length > StoredText.chunkCharacters) {
443 atomText.write(text, line);
444 lines.push({ text });
445 } else lines.push(line);
446 }
447 runs.push({ file: run.file, parent: run.parent, lines: lineCollection });
448 }
449 return {
450 insertionFormat: 1,
451 insertionRuns: collection,
452 ...(hasLists ? { listFormat: 1, listCount, lists } : {}),
453 atom: { ...atom, inserts: [] },
454 };
455 }
456 if (!atom.inserts.some((run) => run.lines.some((line) => line.length > StoredText.chunkCharacters)))
457 return hasLists ? { listFormat: 1, listCount, lists, atom } : atom;
458 let index = 0;
459 const inserts = atom.inserts.map((run) => ({
460 ...run,
461 lines: run.lines.map((line) => {
462 const text = JSON.stringify([key, index++]);
463 if (line.length <= StoredText.chunkCharacters) return line;
464 atomText.write(text, line);
465 return { text };
466 }),
467 }));
468 return {
469 textFormat: 1,
470 ...(hasLists ? { listFormat: 1, listCount, lists } : {}),
471 atom: { ...atom, inserts },
472 };
473 },
474 );
475 this.#lamport = storedArray(storage, "lamport");
476 this.#lineBase = storedArray(storage, "line-base");
477 this.#paths = storedArray(storage, "paths");
478 this.#movers = storedArray(storage, "movers");
479 this.#atomFiles = storedArray(storage, "atom-files");
480 this.#atomDeletes = storedArray(storage, "atom-deletes");
481 this.#lineAtom = numbers("line-atom");
482 this.#lineFile = numbers("line-file");
483 this.#lineParent = numbers("line-parent");
484 this.#deleter = numbers("deleter");
485 this.#replacing = numbers("replacing");
486 const longText = atomText;
487 this.#lineText = storedArray<string>(
488 storage,
489 "line-text",
490 (value) => {
491 if (typeof value === "string") return value;
492 const reference = value as unknown as { format: number; text: string };
493 if (reference?.format !== 1 || typeof reference.text !== "string") throw Error("invalid long line reference");
494 return longText.read(reference.text);
495 },
496 (value, key) => {
497 if (value.length <= StoredText.chunkCharacters) return value;
498 const number = Number(key);
499 const seq = this.#lineAtom.at(number);
500 const text = JSON.stringify([String(seq), number - this.#lineBase[seq]!]);
501 const header = storage.read("atom-text:long", text) as { characters?: number } | undefined;
502 if (header?.characters !== value.length) throw Error("long line atom text is missing");
503 return { format: 1, text };
504 },
505 );
506 this.#pathIndex = storedMap(storage, "path-index");
507 this.#moreDeleterPages = storedLists<number>(storage, "more-deleters", (key) =>
508 JSON.stringify(["number", Number(key)]),
509 );
510 this.#writersPages = storedLists<AtomId>(storage, "writers", (key) => key);
511 this.#readersPages = storedLists<AtomId>(storage, "readers", (key) => key);
512 this.#holdersPages = storedLists<AtomId>(storage, "holders", (key) => key);
513 this.#dependentsPages = storedLists<AtomId>(storage, "dependents");
514 this.#resolversPages = storedLists<AtomId>(storage, "resolvers");
515 this.#togetherPages = storedLists<TogetherLink>(storage, "together");
516 this.#fileAtomPages = storedLists<AtomId>(storage, "file-atoms");
517 this.#runStartPages = storedLists<number>(storage, "run-starts", (key) =>
518 JSON.stringify(["number", Number(key)]),
519 );
520 this.#relocationPages = storedLists<RelocationInfo>(storage, "relocations");
521 this.#relocatedToPages = storedLists<RelocationInfo>(storage, "relocated-to");
522 this.#relocatedToCodePages = storedLists<RelocationInfo>(storage, "relocated-to-code", (key) =>
523 JSON.stringify(["number", Number(key)]),
524 );
525 this.#labels = storedMap(storage, "labels");
526 }
527 }
529 /** Where an atom's key and delete lists are when the graph doesn't keep them (#46): the stored atom. */
530 #lists: ((seq: number) => AtomLists) | undefined;
531 /** Recently read atoms' lists, most recent last, up to LIST_CACHE atoms. */
532 #listCache = new Map<number, AtomLists>();
533 #listCached = 0;
535 /** An atom's deletes, writes, reads and holds, read back from where they are stored. */
536 #listsOf(seq: number): AtomLists {
537 const hit = this.#listCache.get(seq);
538 if (hit) {
539 this.#listCache.delete(seq);
540 this.#listCache.set(seq, hit);
541 return hit;
542 }
543 const got = this.#lists!(seq);
544 const lists: AtomLists = {
545 deletes: frozenList(got.deletes),
546 writes: frozenList(got.writes),
547 reads: frozenList(got.reads),
548 holds: frozenList(got.holds),
549 };
550 this.#listCache.set(seq, lists);
551 this.#listCached += listItems(lists);
552 for (const [old, kept] of this.#listCache) {
553 if (this.#listCached <= LIST_CACHE || old === seq) break;
554 this.#listCache.delete(old);
555 this.#listCached -= listItems(kept);
556 }
557 return lists;
558 }
560 /** The reader an atom's lists use; made apart from add() so it keeps no atom alive (see #reader). */
561 #listReader(seq: number): () => AtomLists {
562 return () => this.#listsOf(seq);
563 }
565 /**
566 * 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
567 * index holds numbers rather than one string per line; start-node and attribute keys stay strings. A key
568 * naming a line the graph doesn't have stays a string, which nothing has claimed.
569 */
570 #code(key: Key): Key | number {
571 const t = key.charCodeAt(0);
572 if (key.charCodeAt(1) !== 58 || key.charCodeAt(2) === 94) return key; // not "X:", or a start node "^"
573 const k = t === 76 ? 0 : t === 80 ? 1 : t === 71 ? 2 : -1; // L, P, G
574 if (k < 0) return key;
575 const n = this.#lineN(key.slice(2));
576 return n < 0 ? key : n * 4 + k;
577 }
579 /** An atom's lines' text, in k order. */
580 #textOf(seq: number): readonly string[] {
581 const hit = this.#textCache.get(seq);
582 if (hit) {
583 this.#textCache.delete(seq);
584 this.#textCache.set(seq, hit);
585 return hit;
586 }
587 const flat = this.#texts!(seq).flat();
588 let chars = 0;
589 for (const t of flat) chars += t.length + 1;
590 this.#textCache.set(seq, flat);
591 this.#textCached += chars;
592 for (const [old, lines] of this.#textCache) {
593 if (this.#textCached <= TEXT_CACHE || old === seq) break;
594 this.#textCache.delete(old);
595 for (const t of lines) this.#textCached -= t.length + 1;
596 }
597 return flat;
598 }
600 /**
601 * The reader an atom's runs use. Made in a function of its own: a closure made inside add() would
602 * keep add()'s whole scope alive, the atom as given with all its text included.
603 */
604 #reader(seq: number): (start: number, length: number) => readonly string[] {
605 return (start, length) => this.#textOf(seq).slice(start, start + length);
606 }
608 /** Line n's text. */
609 #text(n: number): string {
610 if (this.#lineText) return this.#lineText[n]!;
611 const seq = this.#lineAtom.at(n);
612 return this.#textOf(seq)[n - this.#lineBase[seq]!]!;
613 }
614 #paths: string[] = [];
615 #pathIndex: StateMap<string, number> = new Map();
616 /** The first atom that deletes each line (its seq), or -1; a line deleted by more than one has the rest in #moreDeleters. */
617 #deleter: NumberIndex = new Ints();
618 #moreDeleters: StateMap<number, number[]> = new Map();
619 #moreDeleterPages: ReturnType<typeof storedLists<number>> | undefined;
620 #writers: StateMap<Key | number, AtomId | AtomId[]> = new Map();
621 #writersPages: ReturnType<typeof storedLists<AtomId>> | undefined;
622 #readers: StateMap<Key | number, AtomId | AtomId[]> = new Map();
623 #readersPages: ReturnType<typeof storedLists<AtomId>> | undefined;
624 #holders: StateMap<Key | number, AtomId | AtomId[]> = new Map();
625 #holdersPages: ReturnType<typeof storedLists<AtomId>> | undefined;
626 #dependents: StateMap<AtomId, AtomId | AtomId[]> = new Map();
627 #dependentsPages: ReturnType<typeof storedLists<AtomId>> | undefined;
628 #resolvers: StateMap<AtomId, AtomId | AtomId[]> = new Map();
629 #resolversPages: ReturnType<typeof storedLists<AtomId>> | undefined;
630 #together: StateMap<AtomId, TogetherLink[]> = new Map();
631 #togetherPages: ReturnType<typeof storedLists<TogetherLink>> | undefined;
632 #fileAtoms: StateMap<string, AtomId[]> = new Map();
633 #fileAtomPages: ReturnType<typeof storedLists<AtomId>> | undefined;
634 /** First lines of runs (their n), by the node they were written after: a line's n, or -1 - a path's index. */
635 #runStarts: StateMap<number, number | number[]> = new Map();
636 #runStartPages: ReturnType<typeof storedLists<number>> | undefined;
637 /** 1 for the first line of a run whose atom deleted the line it hangs off: the run replaces it. */
638 #replacing: NumberIndex = new Ints(true);
639 #relocations: StateMap<LineId, RelocationInfo[]> = new Map();
640 #relocationPages: ReturnType<typeof storedLists<RelocationInfo>> | undefined;
641 #relocatedTo: StateMap<NodeId, RelocationInfo[]> = new Map();
642 #relocatedToPages: ReturnType<typeof storedLists<RelocationInfo>> | undefined;
643 /** The same relocations by node code (a line's n, or -1 - a path's index), for views laid out by number. */
644 #relocatedToCode: StateMap<number, RelocationInfo[]> = new Map();
645 #relocatedToCodePages: ReturnType<typeof storedLists<RelocationInfo>> | undefined;
646 #movers: AtomId[] = [];
647 #atomFiles: (readonly string[])[] = [];
648 /** Each atom's deleted lines by n, packed (#46), or undefined when it deletes none. */
649 #atomDeletes: (readonly number[] | Int32Array | undefined)[] = [];
650 #labels: StateMap<string, Label> = new Map();
651 /** Each author's name kept once (#46). */
652 #authors = new Map<string, string>();
654 /** Number of atoms (also the seq the next atom gets). */
655 get size(): number {
656 return this.#atoms.length;
657 }
659 /** The id the next accepted atom must have. */
660 nextId(): AtomId {
661 return atomId(this.#atoms.length);
662 }
664 has(id: AtomId): boolean {
665 const seq = this.#seq(id);
666 return seq >= 0 && seq < this.#atoms.length;
667 }
669 atom(id: AtomId): Atom {
670 const seq = this.#seq(id);
671 const atom = seq >= 0 ? this.#atoms[seq] : undefined;
672 if (!atom) throw new EngineError("unknown-atom", `no atom ${id}`);
673 return atom;
674 }
676 /** All atoms in seq order. */
677 atoms(): readonly Atom[] {
678 return this.#atoms;
679 }
681 /** lamport(a) = 1 + max lamport of its deps; 0 for an atom with no deps (such as a0). */
682 lamport(id: AtomId): number {
683 if (!this.has(id)) throw new EngineError("unknown-atom", `no atom ${id}`);
684 return this.#lamport[this.#seq(id)]!;
685 }
687 /** Compare by priority (lamport, then seq). Negative when a comes first (is lower). */
688 comparePriority(a: AtomId, b: AtomId): number {
689 return this.lamport(a) - this.lamport(b) || this.#seq(a) - this.#seq(b);
690 }
692 line(id: LineId): LineInfo | undefined {
693 const n = this.#lineN(id);
694 if (n < 0) return undefined;
695 const seq = this.#lineAtom.at(n);
696 return {
697 id,
698 atom: this.idOfSeq(seq),
699 k: n - this.#lineBase[seq]!,
700 file: this.#paths[this.#lineFile.at(n)]!,
701 parent: this.#nodeName(this.#lineParent.at(n)),
702 text: this.#text(n),
703 };
704 }
706 /** A line's text, or undefined for an unknown line: line(id).text without making the record. */
707 lineText(id: LineId): string | undefined {
708 const n = this.#lineN(id);
709 return n < 0 ? undefined : this.#text(n);
710 }
712 /** The atom that wrote a line, or undefined: line(id).atom without making the record. */
713 lineAtom(id: LineId): AtomId | undefined {
714 const n = this.#lineN(id);
715 return n < 0 ? undefined : this.idOfSeq(this.#lineAtom.at(n));
716 }
718 /** The file a line was written in, or undefined: line(id).file without making the record. */
719 lineFile(id: LineId): string | undefined {
720 const n = this.#lineN(id);
721 return n < 0 ? undefined : this.#paths[this.#lineFile.at(n)];
722 }
724 /** The node a line was written after, or undefined: line(id).parent without making the record. */
725 lineParent(id: LineId): NodeId | undefined {
726 const n = this.#lineN(id);
727 return n < 0 ? undefined : this.#nodeName(this.#lineParent.at(n));
728 }
730 // By number, for views (#46) ------------------------------------------------------
731 // 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
732 // keeps them, so a view can lay files out as arrays of numbers. For the engine's own use.
734 /** A line id's n, or -1 for an unknown line. */
735 lineN(id: LineId): number {
736 return this.#lineN(id);
737 }
739 /** A line's id from its n. */
740 lineIdOf(n: number): LineId {
741 return this.#lineName(n);
742 }
744 /** The lines an atom deletes, from the graph's own packed copy (#46): never a read of the log. */
745 deletedLines(id: AtomId): readonly LineId[] {
746 const seq = this.#seq(id);
747 const count = this.#storage?.read("atom-delete-counts", String(seq));
748 if (count !== undefined) {
749 const out: LineId[] = [];
750 for (const n of storedLists<number>(this.#storage!, "atom-deletes").values(String(seq)))
751 out.push(this.#lineName(n));
752 if (out.length !== count) throw Error("incomplete atom deletion index");
753 return out;
754 }
755 const ns = this.#atomDeletes[this.#seq(id)];
756 if (!ns) return EMPTY;
757 const out: LineId[] = new Array(ns.length);
758 for (let i = 0; i < ns.length; i++) out[i] = this.#lineName(ns[i]!);
759 return out;
760 }
762 /** How many lines an atom deletes, without reading its lists. */
763 deleteCount(id: AtomId): number {
764 const seq = this.#seq(id);
765 const count = this.#storage?.read("atom-delete-counts", String(seq));
766 if (count !== undefined) {
767 if (!Number.isSafeInteger(count) || (count as number) < 0) throw Error("invalid atom deletion count");
768 return count as number;
769 }
770 return this.#atomDeletes[seq]?.length ?? 0;
771 }
773 textOf(n: number): string {
774 return this.#text(n);
775 }
777 /** The seq of the atom that wrote line n. */
778 writerSeqOf(n: number): number {
779 return this.#lineAtom.at(n);
780 }
782 /** Line n's k: its place among its atom's lines. */
783 kOf(n: number): number {
784 return n - this.#lineBase[this.#lineAtom.at(n)]!;
785 }
787 /** The atom id with this seq, as the graph keeps it. */
788 idOfSeq(seq: number): AtomId {
789 if (!Number.isSafeInteger(seq) || seq < 0 || seq >= this.#atoms.length)
790 throw new EngineError("unknown-atom", `no atom at sequence ${seq}`);
791 return atomId(seq);
792 }
794 lamportOfSeq(seq: number): number {
795 return this.#lamport[seq]!;
796 }
798 /** The file line n was written in. */
799 writtenIn(n: number): string {
800 return this.#paths[this.#lineFile.at(n)]!;
801 }
803 /** The code of the node line n was written after. */
804 parentCodeOf(n: number): number {
805 return this.#lineParent.at(n);
806 }
808 /** A node's code, or undefined for a node the graph doesn't know (a start node of a file nothing was written in). */
809 codeOf(node: NodeId): number | undefined {
810 return this.#nodeCode(node);
811 }
813 /** The node a code names. */
814 nodeOf(code: number): NodeId {
815 return this.#nodeName(code);
816 }
818 /** The start node's code for a path, or undefined when nothing was ever written in it. */
819 startCodeOf(path: string): number | undefined {
820 const p = this.#pathIndex.get(path);
821 return p === undefined ? undefined : -1 - p;
822 }
824 /** The lines (their n) written right after a node, as childrenOf, into `out`. */
826 childrenN(code: number, out: number[]): void {
827 for (const n of this.eachChildN(code)) out.push(n);
828 }
829 *eachChildN(code: number): IterableIterator<number> {
830 if (
831 code >= 0 &&
832 code + 1 < this.#lineTotal &&
833 this.#lineAtom.at(code + 1) === this.#lineAtom.at(code) &&
834 this.#lineParent.at(code + 1) === code
835 )
836 yield code + 1;
837 if (this.#runStartPages) yield* this.#runStartPages.values(String(code));
838 else yield* listOf(this.#runStarts.get(code));
839 }
841 get hasOrderedChildren(): boolean {
842 return this.#storage !== undefined;
843 }
844 /** Synchronous derived work against one graph identity. Scratch never commits. */
845 withProjectionScratch<T>(operation: (scratch: GraphStateStorage) => T): T {
846 if (!this.#storage) throw new Error("projection scratch requires persistent graph storage");
847 const size = this.size;
848 const lines = this.lineCount;
849 return withProjectionScratch(
850 this.#storage,
851 () => {
852 if (this.size !== size || this.lineCount !== lines) throw new Error("projection graph identity changed");
853 },
854 operation,
855 );
856 }
857 #childPriority(n: number): string {
858 const seq = this.writerSeqOf(n);
859 return orderedChildKey({
860 n,
861 replaces: this.replacesN(n) ? 1 : 0,
862 lamport: this.lamportOfSeq(seq),
863 seq,
864 k: this.kOf(n),
865 });
866 }
867 /** Persistent layout order with a strict successor cursor; moves are separate. */
868 *orderedChildrenN(code: number, after?: number): IterableIterator<number> {
869 if (!this.#storage) throw new Error("ordered children require indexed storage");
870 const index = new OrderedIndex(this.#storage, "ordered-children", String(code));
871 if (this.#storage.read("ordered-children", "format") !== 2)
872 throw new Error("ordered children require fresh adoption");
873 const count = code >= 0 ? this.#childCounts!.at(code, this.#lineTotal) : index.size;
874 if ((code < 0 || count > 0) && (count !== index.size || count !== this.#runStartPages!.length(String(code))))
875 throw new Error("ordered child index count mismatch");
876 let implicit: number | undefined;
877 if (
878 code >= 0 &&
879 code + 1 < this.#lineTotal &&
880 this.#lineAtom.at(code + 1) === this.#lineAtom.at(code) &&
881 this.#lineParent.at(code + 1) === code
882 )
883 implicit = code + 1;
884 // Most historical run lines have no explicit child. With zero or one
885 // child, traversal needs no priority decoding or radix lookup. Keep the
886 // format/count checks above even on this path.
887 if (count === 0 && (after === undefined || after === implicit)) {
888 if (implicit !== undefined && after !== implicit) yield implicit;
889 return;
890 }
891 const cursor = after === undefined ? undefined : this.#childPriority(after);
892 if (implicit !== undefined && cursor !== undefined && this.#childPriority(implicit) <= cursor) implicit = undefined;
893 for (const n of index.values(cursor)) {
894 if (implicit !== undefined && this.#childPriority(implicit) < this.#childPriority(n)) {
895 yield implicit;
896 implicit = undefined;
897 }
898 yield n;
899 }
900 if (implicit !== undefined) yield implicit;
901 }
903 replacesN(n: number): boolean {
904 return this.#replacing.at(n) === 1;
905 }
907 /** The seqs of every atom that deletes line n (none: an empty list, shared). */
908 deleterSeqsOf(n: number): readonly number[] {
909 return [...this.eachDeleterSeqOf(n)];
910 }
911 *eachDeleterSeqOf(n: number): IterableIterator<number> {
912 const first = this.#deleter.at(n);
913 if (first < 0) return;
914 yield first;
915 if (this.#moreDeleterPages) yield* this.#moreDeleterPages.values(String(n));
916 else yield* this.#moreDeleters.get(n) ?? EMPTY;
917 }
919 /** Every relocation that puts a line right after the node with this code. */
920 relocatedToCode(code: number): readonly RelocationInfo[] {
921 if (this.#relocatedToCodePages) return [...this.eachRelocatedToCode(code)];
922 return this.#relocatedToCode.get(code) ?? EMPTY;
923 }
924 *eachRelocatedToCode(code: number): IterableIterator<RelocationInfo> {
925 if (this.#relocatedToCodePages) yield* this.#relocatedToCodePages.values(String(code));
926 else yield* this.#relocatedToCode.get(code) ?? EMPTY;
927 }
929 /** How many lines every atom together has written. */
930 get lineCount(): number {
931 return this.#lineTotal;
932 }
934 /** A line id's n, or -1 when no accepted atom wrote it. */
935 #lineN(id: LineId): number {
936 const p = parseLineId(id);
937 if (!p || p.seq >= this.#atoms.length) return -1;
938 const base = this.#lineBase[p.seq]!;
939 const end = p.seq + 1 < this.#lineBase.length ? this.#lineBase[p.seq + 1]! : this.#lineTotal;
940 return p.k < end - base ? base + p.k : -1;
941 }
943 /** A line's id from its n. */
944 #lineName(n: number): LineId {
945 const seq = this.#lineAtom.at(n);
946 return `${this.idOfSeq(seq)}.${n - this.#lineBase[seq]!}`;
947 }
949 /** A node's code: a line's n, or -1 - a path's index for a start node; undefined when unknown. */
950 #nodeCode(node: NodeId): number | undefined {
951 if (isStartNode(node)) {
952 const p = this.#pathIndex.get(node.slice(1));
953 return p === undefined ? undefined : -1 - p;
954 }
955 const n = this.#lineN(node);
956 return n < 0 ? undefined : n;
957 }
959 #nodeName(code: number): NodeId {
960 return code >= 0 ? this.#lineName(code) : startNode(this.#paths[-1 - code]!);
961 }
963 #pathOf(file: string): number {
964 let p = this.#pathIndex.get(file);
965 if (p === undefined) {
966 p = this.#paths.push(file) - 1;
967 this.#pathIndex.set(file, p);
968 }
969 return p;
970 }
972 /** The line ids an atom inserted, in k order. */
973 linesOf(id: AtomId): LineId[] {
974 const atom = this.atom(id);
975 const out: LineId[] = [];
976 const seq = atom.seq;
977 const count = (seq + 1 < this.#lineBase.length ? this.#lineBase[seq + 1]! : this.#lineTotal) - this.#lineBase[seq]!;
978 for (let k = 0; k < count; k++) out.push(lineId(id, k));
979 return out;
980 }
982 /** Every atom that deletes this line (across the whole graph). */
983 deletersOf(line: LineId): readonly AtomId[] {
984 const n = this.#lineN(line);
985 if (n < 0) return EMPTY;
986 return [...this.eachDeleterSeqOf(n)].map((seq) => this.idOfSeq(seq));
987 }
989 writersOf(key: Key): readonly AtomId[] {
990 return [...this.eachWriterOf(key)];
991 }
992 *eachWriterOf(key: Key): IterableIterator<AtomId> {
993 const code = this.#code(key);
994 if (this.#writersPages) yield* this.#writersPages.values(JSON.stringify([typeof code, code]));
995 else yield* listOf(this.#writers.get(code));
996 }
998 /** Atoms whose implicit reads include the key. */
999 readersOf(key: Key): readonly AtomId[] {
1000 return [...this.eachReaderOf(key)];
1002 *eachReaderOf(key: Key): IterableIterator<AtomId> {
1003 const code = this.#code(key);
1004 if (this.#readersPages) yield* this.#readersPages.values(JSON.stringify([typeof code, code]));
1005 else yield* listOf(this.#readers.get(code));
1008 /** Atoms whose explicit holds include the key. */
1009 holdersOf(key: Key): readonly AtomId[] {
1010 return [...this.eachHolderOf(key)];
1012 *eachHolderOf(key: Key): IterableIterator<AtomId> {
1013 const code = this.#code(key);
1014 if (this.#holdersPages) yield* this.#holdersPages.values(JSON.stringify([typeof code, code]));
1015 else yield* listOf(this.#holders.get(code));
1018 /** Every atom that inserts or deletes a line of the file, in seq order. */
1019 atomsIn(file: string): readonly AtomId[] {
1020 if (this.#fileAtomPages) return [...this.#fileAtomPages.values(file)];
1021 return this.#fileAtoms.get(file) ?? EMPTY;
1023 *eachAtomIn(file: string): IterableIterator<AtomId> {
1024 if (this.#fileAtomPages) yield* this.#fileAtomPages.values(file);
1025 else yield* this.#fileAtoms.get(file) ?? EMPTY;
1027 hasAtomsIn(file: string): boolean {
1028 return this.#fileAtomPages ? this.#fileAtomPages.length(file) > 0 : this.#fileAtoms.has(file);
1031 /** Unique historical file paths, streamed without collecting their names. */
1032 *knownFiles(): IterableIterator<string> {
1033 yield* this.#fileAtomPages ? this.#fileAtomPages.keys() : this.#fileAtoms.keys();
1036 /**
1037 * The files an atom inserts, deletes or moves lines in, or sets attributes
1038 * of, sorted. For lines, the file each was written in (or, for a move to a
1039 * start node, that file): a set's moves can have taken them elsewhere.
1040 */
1041 filesOf(id: AtomId): readonly string[] {
1042 if (!this.has(id)) throw new EngineError("unknown-atom", `no atom ${id}`);
1043 return this.#atomFiles[this.#seq(id)]!;
1046 /** Lines written right after a node (not counting moves), in seq order. */
1048 childrenOf(node: NodeId): LineId[] {
1049 const code = this.#nodeCode(node);
1050 return code === undefined ? [] : [...this.eachChildN(code)].map((n) => this.#lineName(n));
1053 /** Whether a line starts a run whose atom deleted the line it hangs off. */
1054 replaces(line: LineId): boolean {
1055 const n = this.#lineN(line);
1056 return n >= 0 && this.#replacing.at(n) === 1;
1059 /** Every relocation of a line, in seq order. */
1060 relocationsOf(line: LineId): readonly RelocationInfo[] {
1061 if (this.#relocationPages) return [...this.eachRelocationOf(line)];
1062 return this.#relocations.get(line) ?? EMPTY;
1064 *eachRelocationOf(line: LineId): IterableIterator<RelocationInfo> {
1065 if (this.#relocationPages) yield* this.#relocationPages.values(line);
1066 else yield* this.#relocations.get(line) ?? EMPTY;
1069 /** Every relocation that puts a line right after this node, in seq order. */
1070 relocatedTo(node: NodeId): readonly RelocationInfo[] {
1071 if (this.#relocatedToPages) return [...this.#relocatedToPages.values(node)];
1072 return this.#relocatedTo.get(node) ?? EMPTY;
1075 /** Atoms that move lines, in seq order. */
1076 movers(): readonly AtomId[] {
1077 return this.#movers;
1080 /** Atoms that list this one directly in their deps. */
1081 dependentsOf(id: AtomId): readonly AtomId[] {
1082 return [...this.eachDependentOf(id)];
1084 *eachDependentOf(id: AtomId): IterableIterator<AtomId> {
1085 if (this.#dependentsPages) yield* this.#dependentsPages.values(id);
1086 else yield* listOf(this.#dependents.get(id));
1089 /** Atoms whose `resolves` names this one. */
1090 resolversOf(id: AtomId): readonly AtomId[] {
1091 return [...this.eachResolverOf(id)];
1093 *eachResolverOf(id: AtomId): IterableIterator<AtomId> {
1094 if (this.#resolversPages) yield* this.#resolversPages.values(id);
1095 else yield* listOf(this.#resolvers.get(id));
1098 /** `together` reasons touching this atom, in either direction. */
1099 togetherLinks(id: AtomId): readonly TogetherLink[] {
1100 return [...this.eachTogetherLink(id)];
1102 *eachTogetherLink(id: AtomId): IterableIterator<TogetherLink> {
1103 if (this.#togetherPages) yield* this.#togetherPages.values(id);
1104 else yield* this.#together.get(id) ?? EMPTY;
1107 /**
1108 * The atom plus everything it depends on, transitively. Computed on demand
1109 * and not cached: a cached set per atom costs memory quadratic in the length
1110 * of a dependency chain. Use `dependsOn` to ask about one pair.
1111 */
1112 closure(id: AtomId): Set<AtomId> {
1113 return this.closureOf([id]);
1116 /** The atoms plus everything they depend on, transitively. */
1117 closureOf(ids: Iterable<AtomId>): Set<AtomId> {
1118 const out = new Set<AtomId>();
1119 const stack: AtomId[] = [];
1120 for (const id of ids) {
1121 this.atom(id);
1122 if (!out.has(id)) {
1123 out.add(id);
1124 stack.push(id);
1127 while (stack.length > 0) {
1128 for (const d of this.atom(stack.pop()!).deps) {
1129 if (!out.has(d)) {
1130 out.add(d);
1131 stack.push(d);
1135 return out;
1138 /** Whether `b` is in the closure of `a` (an atom is in its own closure). */
1139 dependsOn(a: AtomId, b: AtomId): boolean {
1140 const atom = this.atom(a);
1141 this.atom(b);
1142 return a === b || this.#reaches(atom.deps, b);
1145 /**
1146 * Whether `target` is reachable along deps from any of `from` (themselves
1147 * included). A dependency always has a lower lamport than its dependent, so
1148 * the search never descends below the target's lamport.
1149 */
1150 #reaches(from: Iterable<AtomId>, target: AtomId): boolean {
1151 const floor = this.#lamport[this.#seq(target)]!;
1152 if (this.#storage) {
1153 return this.withProjectionScratch((scratch) => {
1154 let length = 0;
1155 const push = (id: AtomId): void => {
1156 if (scratch.read("seen", id)) return;
1157 scratch.write("seen", id, true);
1158 scratch.write("stack", String(length++), id);
1159 };
1160 for (const id of from) {
1161 if (id === target) return true;
1162 if (this.#lamport[this.#seq(id)]! > floor) push(id);
1164 while (length > 0) {
1165 const key = String(--length);
1166 const current = scratch.read("stack", key) as AtomId;
1167 scratch.remove("stack", key);
1168 if (this.#lamport[this.#seq(current)]! <= floor) continue;
1169 for (const dependency of this.atom(current).deps) {
1170 if (dependency === target) return true;
1171 push(dependency);
1174 return false;
1175 });
1177 const seen = new Set<AtomId>();
1178 const stack = [...from];
1179 while (stack.length > 0) {
1180 const cur = stack.pop()!;
1181 if (cur === target) return true;
1182 if (seen.has(cur)) continue;
1183 seen.add(cur);
1184 if (this.#lamport[this.#seq(cur)]! <= floor) continue;
1185 for (const d of this.atom(cur).deps) if (!seen.has(d)) stack.push(d);
1187 return false;
1190 /**
1191 * Accept an atom into the graph. It must carry the next id and seq, and
1192 * everything it touches must come from atoms in its dependency closure.
1193 * The atom is frozen. Adding to the graph does not add it to any set.
1194 */
1195 add(atom: Atom): void {
1196 if (this.#storage)
1197 this.#storage.transaction(() => {
1198 this.#add(atom);
1199 const result: unknown = this.#indexAcceptedAtom?.(atom, this.filesOf(atom.id), this.#storage!);
1200 if (result && typeof result === "object" && "then" in result)
1201 throw Error("accepted atom indexing must be synchronous");
1202 });
1203 else this.#add(atom);
1206 #validateAcceptedAtom(atom: Atom, scratch?: GraphStateStorage): void {
1207 const membership = <T extends string>(name: string): { has(key: T): boolean; add(key: T): unknown } => {
1208 if (!scratch) return new Set<T>();
1209 return { has: (key) => scratch.read(name, key) === true, add: (key) => scratch.write(name, key, true) };
1210 };
1211 validateShape(atom);
1212 const seq = this.#atoms.length;
1213 const bad = (why: string): never => {
1214 throw new EngineError("bad-atom", `atom ${atom.id}: ${why}`);
1215 };
1216 if (atom.seq !== seq || atom.id !== atomId(seq)) bad(`expected id ${atomId(seq)} with seq ${seq}`);
1218 const deps = membership<AtomId>("deps");
1219 for (const d of atom.deps) {
1220 if (!this.has(d)) bad(`dependency ${d} is not in the graph`);
1221 if (deps.has(d)) bad(`dependency ${d} listed twice`);
1222 deps.add(d);
1224 for (const list of [atom.needs, atom.resolves])
1225 for (const d of list) {
1226 if (!deps.has(d)) bad(`${d} is in needs/resolves but not in deps`);
1228 for (const r of atom.reasons) if (!this.has(r.to)) bad(`reason points at unknown atom ${r.to}`);
1230 // Everything it touches must come from its closure. Derived deps name the
1231 // writers directly, so this is usually one lookup per writer.
1232 const memoryBelow = scratch ? undefined : new Map<AtomId, boolean>();
1233 const below = {
1234 get: (key: AtomId) => (scratch ? (scratch.read("below", key) as boolean | undefined) : memoryBelow!.get(key)),
1235 set: (key: AtomId, value: boolean) => {
1236 if (scratch) scratch.write("below", key, value);
1237 else memoryBelow!.set(key, value);
1238 },
1239 };
1240 const inClosure = (writer: AtomId): boolean => {
1241 let hit = below.get(writer);
1242 if (hit === undefined) {
1243 hit = deps.has(writer) || this.#reaches(atom.deps, writer);
1244 below.set(writer, hit);
1246 return hit;
1247 };
1248 const checkLine = (line: LineId, what: string): void => {
1249 const writer = this.lineAtom(line);
1250 if (writer === undefined) return bad(`${what} names unknown line ${line}`);
1251 if (!inClosure(writer)) bad(`${what} names line ${line} but ${writer} is not in its closure`);
1252 };
1254 for (const run of atom.inserts) {
1255 if (isStartNode(run.parent)) {
1256 if (run.parent !== startNode(run.file)) bad(`run in ${run.file} starts at ${run.parent}`);
1257 } else {
1258 // The parent may have been moved into run.file, so its own file can differ.
1259 checkLine(run.parent, "an insert");
1262 const writes = membership<Key>("writes");
1263 for (const key of atom.writes) writes.add(key);
1264 const moved = membership<LineId>("moved");
1265 for (const m of atom.moves ?? []) {
1266 checkLine(m.line, "a move");
1267 if (!isStartNode(m.parent)) checkLine(m.parent, "a move");
1268 if (m.line === m.parent) bad(`moves ${m.line} after itself`);
1269 if (moved.has(m.line)) bad(`moves ${m.line} twice`);
1270 moved.add(m.line);
1271 if (!writes.has(posKey(m.line)) || !writes.has(gapKey(m.parent))) {
1272 bad(`moves ${m.line} without writing ${posKey(m.line)} and ${gapKey(m.parent)}`);
1275 const deleted = membership<LineId>("deleted");
1276 for (const line of atom.deletes) {
1277 checkLine(line, "a delete");
1278 if (deleted.has(line)) bad(`deletes ${line} twice`);
1279 deleted.add(line);
1281 for (const line of atom.deletes)
1282 if (!writes.has(lineKey(line))) bad(`deletes ${line} without writing ${lineKey(line)}`);
1283 for (const list of [atom.writes, atom.reads, atom.holds])
1284 for (const key of list) {
1285 const parsed = parseKey(key);
1286 if (parsed.kind === "line") checkLine(parsed.node, `key ${key}`);
1287 else if ((parsed.kind === "gap" || parsed.kind === "pos") && !isStartNode(parsed.node))
1288 checkLine(parsed.node, `key ${key}`);
1292 #add(atom: Atom): void {
1293 if (this.#storage && this.#storage.read("ordered-children", "format") !== 2) {
1294 if (this.#atoms.length !== 0) throw new Error("ordered children require fresh adoption");
1295 this.#storage.write("ordered-children", "format", 2);
1298 if (this.#storage) this.withProjectionScratch((scratch) => this.#validateAcceptedAtom(atom, scratch));
1299 else this.#validateAcceptedAtom(atom);
1300 const seq = this.#atoms.length;
1301 const deps = atom.deps;
1302 const deleted = this.#storage ? undefined : new Set(atom.deletes);
1303 const writes = this.#storage ? atom.writes : new Set(atom.writes);
1305 // Accept.
1306 // Persistent storage copies the accepted atom; a second frozen copy only duplicates its lists.
1307 const frozen = this.#storage
1308 ? atom
1309 : freezeAtom(
1310 atom,
1311 (id) => this.idOfSeq(seqOf(id)),
1312 (author) => {
1313 if (this.#storage) return author;
1314 let a = this.#authors.get(author);
1315 if (a === undefined) this.#authors.set(author, (a = author));
1316 return a;
1317 },
1318 this.#texts ? this.#reader(seq) : undefined,
1319 this.#lists ? this.#listReader(seq) : undefined,
1320 );
1321 this.#atoms.push(this.#storage ? atom : frozen);
1322 let lam = 0;
1323 for (const d of deps) lam = Math.max(lam, this.lamport(d) + 1);
1324 this.#lamport.push(lam);
1326 // The run starts' parents and the deleted lines, as codes, before this atom's own lines exist.
1327 // The atom as given: with lists kept elsewhere, the frozen one reads them back from the log.
1328 const deletes = (line: LineId | NodeId): boolean => {
1329 if (isStartNode(line)) return false;
1330 if (deleted) return deleted.has(line);
1331 const n = this.#lineN(line);
1332 return this.#deleter.at(n) === seq || this.#moreDeleterPages!.last(String(n)) === seq;
1333 };
1334 const deletedN = this.#storage ? undefined : atom.deletes.map((line) => this.#lineN(line));
1335 this.#atomDeletes.push(deletedN?.length ? Int32Array.from(deletedN) : undefined);
1336 if (this.#storage) {
1337 const pages = storedLists<number>(this.#storage, "atom-deletes");
1338 for (const line of atom.deletes) pages.append(String(seq), this.#lineN(line));
1339 this.#storage.write("atom-delete-counts", String(seq), atom.deletes.length);
1341 const deletedNumbers = function* (graph: Graph) {
1342 if (deletedN) yield* deletedN;
1343 else for (const line of atom.deletes) yield graph.#lineN(line);
1344 };
1345 for (const n of deletedNumbers(this)) {
1346 if (this.#deleter.at(n) < 0) this.#deleter.set(n, seq);
1347 else if (this.#moreDeleterPages) this.#moreDeleterPages.append(String(n), seq);
1348 else pushIndex(this.#moreDeleters, n, seq);
1350 this.#lineBase.push(this.#lineTotal);
1351 for (const run of atom.inserts) {
1352 const file = this.#pathOf(run.file);
1353 let parent = isStartNode(run.parent) ? -1 - file : this.#lineN(run.parent);
1354 const first = this.#lineTotal;
1355 if (parent >= 0) this.#childCounts?.increment(parent, first);
1356 if (this.#storage)
1357 new OrderedIndex(this.#storage, "ordered-children", String(parent)).insert(
1358 orderedChildKey({
1359 n: first,
1360 replaces: deletes(run.parent) ? 1 : 0,
1361 lamport: lam,
1362 seq,
1363 k: first - this.#lineBase[seq]!,
1364 }),
1365 first,
1366 );
1368 if (this.#runStartPages) this.#runStartPages.append(String(parent), first);
1369 else pushOne(this.#runStarts, parent, first);
1370 for (let i = 0; i < run.lines.length; i++) {
1371 const n = this.#lineTotal;
1372 this.#childCounts?.append(n);
1373 this.#lineAtom.push(seq);
1374 this.#lineFile.push(file);
1375 this.#lineParent.push(parent);
1376 this.#lineText?.push(run.lines[i]!);
1377 this.#deleter.push(-1);
1378 this.#replacing.push(i === 0 && deletes(run.parent) ? 1 : 0);
1379 parent = n;
1382 (frozen.moves ?? []).forEach((m, i) => {
1383 const info: RelocationInfo = Object.freeze({ atom: frozen.id, line: m.line, parent: m.parent, k: i });
1384 if (this.#relocationPages) this.#relocationPages.append(m.line, info);
1385 else pushIndex(this.#relocations, m.line, info);
1386 if (this.#relocatedToPages) this.#relocatedToPages.append(m.parent, info);
1387 else pushIndex(this.#relocatedTo, m.parent, info);
1388 const parentCode = isStartNode(m.parent) ? -1 - this.#pathOf(m.parent.slice(1)) : this.#lineN(m.parent);
1389 if (this.#relocatedToCodePages) this.#relocatedToCodePages.append(String(parentCode), info);
1390 else pushIndex(this.#relocatedToCode, parentCode, info);
1391 });
1392 if (frozen.moves) this.#movers.push(frozen.id);
1393 for (const key of writes) {
1394 const code = this.#code(key);
1395 if (this.#writersPages) {
1396 const key = JSON.stringify([typeof code, code]);
1397 if (this.#writersPages.last(key) !== frozen.id) this.#writersPages.append(key, frozen.id);
1398 } else pushOne(this.#writers, code, frozen.id);
1400 for (const key of this.#storage ? atom.reads : new Set(atom.reads)) {
1401 const code = this.#code(key);
1402 if (this.#readersPages) {
1403 const key = JSON.stringify([typeof code, code]);
1404 if (this.#readersPages.last(key) !== frozen.id) this.#readersPages.append(key, frozen.id);
1405 } else pushOne(this.#readers, code, frozen.id);
1407 for (const key of this.#storage ? atom.holds : new Set(atom.holds)) {
1408 const code = this.#code(key);
1409 if (this.#holdersPages) {
1410 const key = JSON.stringify([typeof code, code]);
1411 if (this.#holdersPages.last(key) !== frozen.id) this.#holdersPages.append(key, frozen.id);
1412 } else pushOne(this.#holders, code, frozen.id);
1414 for (const d of deps) {
1415 if (this.#dependentsPages) this.#dependentsPages.append(d, frozen.id);
1416 else pushOne(this.#dependents, d, frozen.id);
1418 for (const r of this.#storage ? frozen.resolves : new Set(frozen.resolves)) {
1419 if (this.#resolversPages) {
1420 if (this.#resolversPages.last(r) !== frozen.id) this.#resolversPages.append(r, frozen.id);
1421 } else pushOne(this.#resolvers, r, frozen.id);
1423 const files = new Set<string>();
1424 for (const run of atom.inserts) files.add(run.file);
1425 for (const n of deletedNumbers(this)) files.add(this.#paths[this.#lineFile.at(n)]!);
1426 for (const a of frozen.attrs ?? []) files.add(a.file);
1427 for (const m of frozen.moves ?? []) {
1428 files.add(this.lineFile(m.line)!);
1429 files.add(isStartNode(m.parent) ? m.parent.slice(1) : this.lineFile(m.parent)!);
1431 this.#atomFiles.push(Object.freeze([...files].sort()));
1432 for (const file of files) {
1433 if (this.#fileAtomPages) this.#fileAtomPages.append(file, frozen.id);
1434 else pushIndex(this.#fileAtoms, file, frozen.id);
1436 for (const r of frozen.reasons) {
1437 if (r.kind !== "together" || r.to === frozen.id) continue;
1439 const forward = { other: r.to, text: r.text, from: frozen.id };
1440 const reverse = { other: frozen.id, text: r.text, from: frozen.id };
1441 if (this.#togetherPages) {
1442 this.#togetherPages.append(frozen.id, forward);
1443 this.#togetherPages.append(r.to, reverse);
1444 } else {
1445 pushIndex(this.#together, frozen.id, forward);
1446 pushIndex(this.#together, r.to, reverse);
1451 // Labels -----------------------------------------------------------------
1453 /**
1454 * Add or replace a label. Label names may not look like atom ids. A base is
1455 * resolved to its head only when it is used, never followed further, so
1456 * bases may name each other in any shape.
1457 */
1458 setLabel(label: Label): void {
1459 this.#putLabel(label, (name) => this.#labels.has(name));
1462 #putLabel(label: Label, isLabel: (name: string) => boolean): void {
1463 const bad = (why: string): never => {
1464 throw new EngineError("bad-label", `label ${JSON.stringify(label?.name)}: ${why}`);
1465 };
1466 if (typeof label !== "object" || label === null) bad("not an object");
1467 if (typeof label.name !== "string" || label.name === "") bad("needs a name");
1468 if (isAtomId(label.name)) bad("a label name may not look like an atom id");
1469 if (!this.has(label.head)) bad(`head ${label.head} is not in the graph`);
1470 if (
1471 label.base !== undefined &&
1472 !(typeof label.base === "string" && (isLabel(label.base) || this.has(label.base)))
1473 ) {
1474 bad(`base ${label.base} is neither a label nor an atom`);
1476 if (label.base === label.name) bad("a label cannot be its own base");
1477 if (typeof label.title !== "string" || typeof label.message !== "string") bad("needs a title and message");
1478 if (label.follows !== undefined && !Array.isArray(label.follows)) bad("follows must be a list of label names");
1479 const copy: Label = {
1480 name: label.name,
1481 head: label.head,
1482 ...(label.base !== undefined ? { base: label.base } : {}),
1483 title: label.title,
1484 message: label.message,
1485 ...(label.follows !== undefined ? { follows: Object.freeze([...label.follows]) } : {}),
1486 };
1487 this.#labels.set(label.name, Object.freeze(copy));
1490 label(name: string): Label | undefined {
1491 return this.#labels.get(name);
1494 /** Labels sorted by name. */
1495 labels(): Label[] {
1496 return [...this.#labels.values()].sort((a, b) => (a.name < b.name ? -1 : a.name > b.name ? 1 : 0));
1499 /**
1500 * Remove a label. Labels that used it as their base get its head atom as
1501 * their base instead, so their contents don't change.
1502 */
1503 removeLabel(name: string): boolean {
1504 return this.#storage ? this.#storage.transaction(() => this.#removeLabel(name)) : this.#removeLabel(name);
1507 #removeLabel(name: string): boolean {
1508 const gone = this.#labels.get(name);
1509 if (!gone) return false;
1510 this.#labels.delete(name);
1511 for (const label of [...this.#labels.values()]) {
1512 if (label.base === name) this.#labels.set(label.name, Object.freeze({ ...label, base: gone.head }));
1514 return true;
1517 // JSON -------------------------------------------------------------------
1519 toJSON(): GraphJSON {
1520 return { format: GRAPH_FORMAT, version: 1, atoms: this.#atoms, labels: this.labels() };
1523 /** Load a saved graph. Every atom is re-validated as it is added. */
1524 static fromJSON(data: unknown): Graph {
1525 const bad = (why: string): never => {
1526 throw new EngineError("bad-json", why);
1527 };
1528 if (typeof data !== "object" || data === null) bad("graph JSON must be an object");
1529 const obj = data as Partial<GraphJSON>;
1530 if (obj.format !== GRAPH_FORMAT) bad(`format must be ${GRAPH_FORMAT}`);
1531 if (obj.version !== 1) bad(`unsupported version ${String(obj.version)}`);
1532 if (!Array.isArray(obj.atoms) || !Array.isArray(obj.labels)) bad("atoms and labels must be arrays");
1533 const graph = new Graph();
1534 for (const atom of obj.atoms!) graph.add(atom);
1535 // Labels may name each other as bases, in any order and any shape.
1536 const names = new Set<string>();
1537 for (const label of obj.labels!) {
1538 const name: unknown = (label as Partial<Label> | null)?.name;
1539 if (typeof name !== "string") return bad("every label needs a name");
1540 if (names.has(name)) bad(`label ${name} appears twice`);
1541 names.add(name);
1543 for (const label of obj.labels!) {
1544 try {
1545 graph.#putLabel(label, (name) => names.has(name));
1546 } catch (err) {
1547 if (err instanceof EngineError) bad(err.message);
1548 throw err;
1551 return graph;
1554 #seq(id: AtomId): number {
1555 return typeof id === "string" ? seqOf(id) : -1;
1559function validateShape(atom: Atom): void {
1560 const bad = (why: string): never => {
1561 throw new EngineError("bad-atom", `atom ${String((atom as { id?: unknown }).id)}: ${why}`);
1562 };
1563 if (typeof atom !== "object" || atom === null) bad("not an object");
1564 if (typeof atom.id !== "string" || !Number.isInteger(atom.seq)) bad("needs id and seq");
1565 if (typeof atom.author !== "string" || typeof atom.message !== "string") bad("needs author and message");
1566 if (typeof atom.time !== "number" || !Number.isFinite(atom.time)) bad("time must be a finite number");
1567 const lists = ["inserts", "deletes", "writes", "reads", "holds", "needs", "resolves", "reasons", "deps"] as const;
1568 for (const name of lists) if (!Array.isArray(atom[name])) bad(`${name} must be an array`);
1569 for (const run of atom.inserts as readonly InsertRun[]) {
1570 if (typeof run.file !== "string" || run.file === "" || run.file.includes("\n")) bad("a run needs a file path");
1571 if (typeof run.parent !== "string") bad("a run needs a parent");
1572 if (!Array.isArray(run.lines) || run.lines.length === 0) bad("a run needs at least one line");
1573 for (const text of run.lines) {
1574 if (typeof text !== "string" || text.includes("\n") || text.includes("\r"))
1575 bad("run lines must be strings without line breaks");
1578 if (atom.attrs !== undefined) {
1579 if (!Array.isArray(atom.attrs)) bad("attrs must be an array");
1580 for (const a of atom.attrs) {
1581 if (typeof a?.file !== "string" || a.file === "" || a.file.includes("\n") || !ATTR_NAMES.includes(a.name))
1582 bad("an attr needs a file and a name");
1583 if (a.value !== null && typeof a.value !== "string") bad("an attr value is a string or null");
1584 if (!atom.writes.includes(attrKey(a.file, a.name))) bad(`sets ${a.name} of ${a.file} without writing its key`);
1587 if (atom.moves !== undefined) {
1588 if (!Array.isArray(atom.moves) || atom.moves.length === 0) bad("moves must be a non-empty array");
1589 for (const m of atom.moves) {
1590 if (typeof m?.line !== "string" || typeof m.parent !== "string") bad("a move needs a line and a parent");
1593 for (const name of ["deletes", "writes", "reads", "holds", "needs", "resolves", "deps"] as const) {
1594 for (const x of atom[name]) if (typeof x !== "string") bad(`${name} must hold strings`);
1596 for (const r of atom.reasons as readonly Reason[]) {
1597 if (typeof r.to !== "string" || typeof r.text !== "string" || !REASON_KINDS.includes(r.kind)) {
1598 bad("a reason needs to, kind (together, because-of or supersedes) and text");
1603/**
1604 * A frozen copy of an atom. An empty list is one shared frozen list, and atom
1605 * ids and authors are the graph's own strings (`canon`, `author`), so each is
1606 * kept once however often it's named (#46).
1607 */
1608function freezeAtom(
1609 atom: Atom,
1610 canon: (id: AtomId) => AtomId,
1611 author: (name: string) => string,
1612 text?: (start: number, length: number) => readonly string[],
1613 lists?: () => AtomLists,
1614): Atom {
1615 const list = <T>(xs: readonly T[], f?: (x: T) => T): readonly T[] =>
1616 xs.length === 0 ? EMPTY : Object.freeze(f ? xs.map(f) : [...xs]);
1617 // With text kept elsewhere (#46), a run's lines are read when asked for.
1618 let k = 0;
1619 const run = (r: InsertRun): InsertRun => {
1620 if (!text) return Object.freeze({ file: r.file, parent: r.parent, lines: Object.freeze([...r.lines]) });
1621 const start = k;
1622 const length = r.lines.length;
1623 k += length;
1624 return Object.freeze(new LazyRun(r.file, r.parent, text, start, length));
1625 };
1626 const copy: Atom = {
1627 id: atom.id,
1628 seq: atom.seq,
1629 author: author(atom.author),
1630 message: atom.message,
1631 time: atom.time,
1632 inserts: Object.freeze(atom.inserts.map(run)),
1633 ...(lists
1634 ? {}
1635 : { deletes: list(atom.deletes), writes: list(atom.writes), reads: list(atom.reads), holds: list(atom.holds) }),
1636 needs: list(atom.needs, canon),
1637 resolves: list(atom.resolves, canon),
1638 reasons: list(atom.reasons, (r) => Object.freeze({ to: canon(r.to), kind: r.kind, text: r.text })),
1639 deps: list(atom.deps, canon),
1640 ...(atom.attrs && atom.attrs.length > 0
1641 ? { attrs: Object.freeze(atom.attrs.map((a) => Object.freeze({ file: a.file, name: a.name, value: a.value }))) }
1642 : {}),
1643 ...(atom.moves
1644 ? { moves: Object.freeze(atom.moves.map((m) => Object.freeze({ line: m.line, parent: m.parent }))) }
1645 : {}),
1646 } as Atom;
1647 return Object.freeze(lists ? (new ListedAtom(copy, lists) as unknown as Atom) : copy);