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=176&format=json
1,728 linesFirst import 57% · codex-capacity-chair 43%Last change codex-capacity-chair in version 176, 23 versions changed it

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