- 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=175&format=json
1,718 linesFirst import 58% · codex-capacity-chair 42%Last change codex-capacity-chair in version 175, 22 versions changed it
You're reading version 175. The newest is 318, and 13 versions since then changed this file.
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.
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;
60}
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;
68}
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;
76}
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[];
86}
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]);
100}
102function listOf<V>(had: V | V[] | undefined): readonly V[] {
103 return had === undefined ? EMPTY : Array.isArray(had) ? had : [had];
104}
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]);
112}
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 }
146}
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[];
159}
161function listItems(l: AtomLists): number {
162 return l.deletes.length + l.writes.length + l.reads.length + l.holds.length;
163}
165function frozenList<T>(xs: readonly T[]): readonly T[] {
166 return xs.length === 0 ? (EMPTY as readonly T[]) : Object.freeze([...xs]);
167}
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 }
194}
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;
202}
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 }
226}
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 };
257}
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 const streamed = (target: Atom): Atom => {
384 registerJsonChunkValue(target, () => {
385 const line = (raw: unknown, index: number): unknown => {
386 if (typeof raw === "string") return raw;
387 const reference = raw as TextReference;
388 if (!reference || reference.text !== JSON.stringify([String(atom.seq), index]))
389 throw Error("invalid stored atom text reference");
390 return new JsonStringChunks(() => atomText.chunks(reference.text));
391 };
392 let inserts: readonly unknown[];
393 if (encoded.insertionFormat === 1) {
394 const collection = `atom-inserts:${atom.seq}`;
395 inserts = readonlyStoredArray(storage, collection, (raw, index) => {
396 const run = raw as { file: string; parent: string; lines: string };
397 const lines = `${collection}:lines:${index}`;
398 if (run.lines !== lines || typeof run.file !== "string" || typeof run.parent !== "string")
399 throw Error("invalid stored insertion run");
400 let start = 0;
401 for (let prior = 0; prior < index; prior++)
402 start += readonlyStoredArray(storage, `${collection}:lines:${prior}`).length;
403 return {
404 file: run.file,
405 parent: run.parent,
406 lines: readonlyStoredArray(storage, lines, (raw, i) => line(raw, start + i)),
407 };
408 });
409 } else {
410 let index = 0;
411 inserts = atom.inserts.map((run) => ({
412 file: run.file,
413 parent: run.parent,
414 lines: run.lines.map((raw) => line(raw, index++)),
415 }));
416 }
417 return { ...target, inserts };
418 });
419 return target;
420 };
421 const frozen = freezeAtom(
422 atom,
423 (id) => id,
424 (author) => author,
425 text,
426 );
427 if (encoded.listFormat !== 1 && encoded.insertionFormat !== 1) return streamed(frozen);
428 const result = { ...frozen };
429 if (encoded.insertionFormat === 1) {
430 const collection = `atom-inserts:${atom.seq}`;
431 if (encoded.insertionRuns !== collection) throw Error("invalid stored insertion reference");
432 const inserts = readonlyStoredArray<InsertRun>(storage, collection, (raw, index) => {
433 const run = raw as { file: string; parent: InsertRun["parent"]; lines: string };
434 const lines = `${collection}:lines:${index}`;
435 if (run.lines !== lines || typeof run.file !== "string" || typeof run.parent !== "string")
436 throw Error("invalid stored insertion run");
437 return Object.freeze({
438 file: run.file,
439 parent: run.parent,
440 lines: readonlyStoredArray<string>(storage, lines, (rawLine, lineIndex) => {
441 if (typeof rawLine === "string") return rawLine;
442 const ref = rawLine as TextReference;
443 let atomLine = lineIndex;
444 for (let prior = 0; prior < index; prior++)
445 atomLine += readonlyStoredArray(storage, `${collection}:lines:${prior}`).length;
446 if (!ref || ref.text !== JSON.stringify([String(atom.seq), atomLine]))
447 throw Error("invalid stored insertion text");
448 return atomText.read(ref.text);
449 }),
450 });
451 });
452 Object.defineProperty(result, "inserts", { value: inserts, enumerable: true });
453 }
454 for (const field of listFields) {
455 const collection = encoded.lists?.[field];
456 if (collection === undefined) continue;
457 if (typeof collection !== "string" || collection !== `atom-list:${atom.seq}:${field}`)
458 throw Error("invalid stored atom list reference");
459 Object.defineProperty(result, field, { value: readonlyStoredArray(storage, collection), enumerable: true });
460 }
461 return streamed(Object.freeze(result));
462 },
463 (input, key) => {
464 const atom = { ...input };
465 const lists: Partial<Record<(typeof listFields)[number], string>> = {};
466 for (const field of listFields) {
467 const values = input[field];
468 if (!values || values.length <= 256) continue;
469 const collection = `atom-list:${input.seq}:${field}`;
470 const saved = storedArray<unknown>(storage, collection);
471 for (const value of values) saved.push(value);
472 lists[field] = collection;
473 Object.defineProperty(atom, field, { value: [], enumerable: true });
474 }
475 const listCount = Object.keys(lists).length;
476 const hasLists = listCount > 0;
477 let insertionCharacters = 0;
478 if (
479 atom.inserts.length > 256 ||
480 atom.inserts.some((run) => run.lines.length > 256) ||
481 atom.inserts.some((run) => run.lines.some((line) => (insertionCharacters += line.length) > 65536))
482 ) {
483 const collection = `atom-inserts:${input.seq}`;
484 const runs = storedArray<unknown>(storage, collection);
485 let runIndex = 0;
486 let lineIndex = 0;
487 for (const run of atom.inserts) {
488 const lineCollection = `${collection}:lines:${runIndex++}`;
489 const lines = storedArray<unknown>(storage, lineCollection);
490 for (const line of run.lines) {
491 const text = JSON.stringify([key, lineIndex++]);
492 if (line.length > StoredText.chunkCharacters) {
493 atomText.write(text, line);
494 lines.push({ text });
495 } else lines.push(line);
496 }
497 runs.push({ file: run.file, parent: run.parent, lines: lineCollection });
498 }
499 return {
500 insertionFormat: 1,
501 insertionRuns: collection,
502 ...(hasLists ? { listFormat: 1, listCount, lists } : {}),
503 atom: { ...atom, inserts: [] },
504 };
505 }
506 if (!atom.inserts.some((run) => run.lines.some((line) => line.length > StoredText.chunkCharacters)))
507 return hasLists ? { listFormat: 1, listCount, lists, atom } : atom;
508 let index = 0;
509 const inserts = atom.inserts.map((run) => ({
510 ...run,
511 lines: run.lines.map((line) => {
512 const text = JSON.stringify([key, index++]);
513 if (line.length <= StoredText.chunkCharacters) return line;
514 atomText.write(text, line);
515 return { text };
516 }),
517 }));
518 return {
519 textFormat: 1,
520 ...(hasLists ? { listFormat: 1, listCount, lists } : {}),
521 atom: { ...atom, inserts },
522 };
523 },
524 );
525 this.#lamport = storedArray(storage, "lamport");
526 this.#lineBase = storedArray(storage, "line-base");
527 this.#paths = storedArray(storage, "paths");
528 this.#movers = storedArray(storage, "movers");
529 this.#atomFiles = storedArray(storage, "atom-files");
530 this.#atomDeletes = storedArray(storage, "atom-deletes");
531 this.#lineAtom = numbers("line-atom");
532 this.#lineFile = numbers("line-file");
533 this.#lineParent = numbers("line-parent");
534 this.#deleter = numbers("deleter");
535 this.#replacing = numbers("replacing");
536 const longText = atomText;
537 this.#lineText = storedArray<string>(
538 storage,
539 "line-text",
540 (value) => {
541 if (typeof value === "string") return value;
542 const reference = value as unknown as { format: number; text: string };
543 if (reference?.format !== 1 || typeof reference.text !== "string") throw Error("invalid long line reference");
544 return longText.read(reference.text);
545 },
546 (value, key) => {
547 if (value.length <= StoredText.chunkCharacters) return value;
548 const number = Number(key);
549 const seq = this.#lineAtom.at(number);
550 const text = JSON.stringify([String(seq), number - this.#lineBase[seq]!]);
551 const header = storage.read("atom-text:long", text) as { characters?: number } | undefined;
552 if (header?.characters !== value.length) throw Error("long line atom text is missing");
553 return { format: 1, text };
554 },
555 );
556 this.#pathIndex = storedMap(storage, "path-index");
557 this.#moreDeleterPages = storedLists<number>(storage, "more-deleters", (key) =>
558 JSON.stringify(["number", Number(key)]),
559 );
560 this.#writersPages = storedLists<AtomId>(storage, "writers", (key) => key);
561 this.#readersPages = storedLists<AtomId>(storage, "readers", (key) => key);
562 this.#holdersPages = storedLists<AtomId>(storage, "holders", (key) => key);
563 this.#dependentsPages = storedLists<AtomId>(storage, "dependents");
564 this.#resolversPages = storedLists<AtomId>(storage, "resolvers");
565 this.#togetherPages = storedLists<TogetherLink>(storage, "together");
566 this.#fileAtomPages = storedLists<AtomId>(storage, "file-atoms");
567 this.#runStartPages = storedLists<number>(storage, "run-starts", (key) =>
568 JSON.stringify(["number", Number(key)]),
569 );
570 this.#relocationPages = storedLists<RelocationInfo>(storage, "relocations");
571 this.#relocatedToPages = storedLists<RelocationInfo>(storage, "relocated-to");
572 this.#relocatedToCodePages = storedLists<RelocationInfo>(storage, "relocated-to-code", (key) =>
573 JSON.stringify(["number", Number(key)]),
574 );
575 this.#labels = storedMap(storage, "labels");
576 }
577 }
579 /** Where an atom's key and delete lists are when the graph doesn't keep them (#46): the stored atom. */
580 #lists: ((seq: number) => AtomLists) | undefined;
581 /** Recently read atoms' lists, most recent last, up to LIST_CACHE atoms. */
582 #listCache = new Map<number, AtomLists>();
583 #listCached = 0;
585 /** An atom's deletes, writes, reads and holds, read back from where they are stored. */
586 #listsOf(seq: number): AtomLists {
587 const hit = this.#listCache.get(seq);
588 if (hit) {
589 this.#listCache.delete(seq);
590 this.#listCache.set(seq, hit);
591 return hit;
592 }
593 const got = this.#lists!(seq);
594 const lists: AtomLists = {
595 deletes: frozenList(got.deletes),
596 writes: frozenList(got.writes),
597 reads: frozenList(got.reads),
598 holds: frozenList(got.holds),
599 };
600 this.#listCache.set(seq, lists);
601 this.#listCached += listItems(lists);
602 for (const [old, kept] of this.#listCache) {
603 if (this.#listCached <= LIST_CACHE || old === seq) break;
604 this.#listCache.delete(old);
605 this.#listCached -= listItems(kept);
606 }
607 return lists;
608 }
610 /** The reader an atom's lists use; made apart from add() so it keeps no atom alive (see #reader). */
611 #listReader(seq: number): () => AtomLists {
612 return () => this.#listsOf(seq);
613 }
615 /**
616 * 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
617 * index holds numbers rather than one string per line; start-node and attribute keys stay strings. A key
618 * naming a line the graph doesn't have stays a string, which nothing has claimed.
619 */
620 #code(key: Key): Key | number {
621 const t = key.charCodeAt(0);
622 if (key.charCodeAt(1) !== 58 || key.charCodeAt(2) === 94) return key; // not "X:", or a start node "^"
623 const k = t === 76 ? 0 : t === 80 ? 1 : t === 71 ? 2 : -1; // L, P, G
624 if (k < 0) return key;
625 const n = this.#lineN(key.slice(2));
626 return n < 0 ? key : n * 4 + k;
627 }
629 /** An atom's lines' text, in k order. */
630 #textOf(seq: number): readonly string[] {
631 const hit = this.#textCache.get(seq);
632 if (hit) {
633 this.#textCache.delete(seq);
634 this.#textCache.set(seq, hit);
635 return hit;
636 }
637 const flat = this.#texts!(seq).flat();
638 let chars = 0;
639 for (const t of flat) chars += t.length + 1;
640 this.#textCache.set(seq, flat);
641 this.#textCached += chars;
642 for (const [old, lines] of this.#textCache) {
643 if (this.#textCached <= TEXT_CACHE || old === seq) break;
644 this.#textCache.delete(old);
645 for (const t of lines) this.#textCached -= t.length + 1;
646 }
647 return flat;
648 }
650 /**
651 * The reader an atom's runs use. Made in a function of its own: a closure made inside add() would
652 * keep add()'s whole scope alive, the atom as given with all its text included.
653 */
654 #reader(seq: number): (start: number, length: number) => readonly string[] {
655 return (start, length) => this.#textOf(seq).slice(start, start + length);
656 }
658 /** Line n's text. */
659 #text(n: number): string {
660 if (this.#lineText) return this.#lineText[n]!;
661 const seq = this.#lineAtom.at(n);
662 return this.#textOf(seq)[n - this.#lineBase[seq]!]!;
663 }
664 #paths: string[] = [];
665 #pathIndex: StateMap<string, number> = new Map();
666 /** The first atom that deletes each line (its seq), or -1; a line deleted by more than one has the rest in #moreDeleters. */
667 #deleter: NumberIndex = new Ints();
668 #moreDeleters: StateMap<number, number[]> = new Map();
669 #moreDeleterPages: ReturnType<typeof storedLists<number>> | undefined;
670 #writers: StateMap<Key | number, AtomId | AtomId[]> = new Map();
671 #writersPages: ReturnType<typeof storedLists<AtomId>> | undefined;
672 #readers: StateMap<Key | number, AtomId | AtomId[]> = new Map();
673 #readersPages: ReturnType<typeof storedLists<AtomId>> | undefined;
674 #holders: StateMap<Key | number, AtomId | AtomId[]> = new Map();
675 #holdersPages: ReturnType<typeof storedLists<AtomId>> | undefined;
676 #dependents: StateMap<AtomId, AtomId | AtomId[]> = new Map();
677 #dependentsPages: ReturnType<typeof storedLists<AtomId>> | undefined;
678 #resolvers: StateMap<AtomId, AtomId | AtomId[]> = new Map();
679 #resolversPages: ReturnType<typeof storedLists<AtomId>> | undefined;
680 #together: StateMap<AtomId, TogetherLink[]> = new Map();
681 #togetherPages: ReturnType<typeof storedLists<TogetherLink>> | undefined;
682 #fileAtoms: StateMap<string, AtomId[]> = new Map();
683 #fileAtomPages: ReturnType<typeof storedLists<AtomId>> | undefined;
684 /** First lines of runs (their n), by the node they were written after: a line's n, or -1 - a path's index. */
685 #runStarts: StateMap<number, number | number[]> = new Map();
686 #runStartPages: ReturnType<typeof storedLists<number>> | undefined;
687 /** 1 for the first line of a run whose atom deleted the line it hangs off: the run replaces it. */
688 #replacing: NumberIndex = new Ints(true);
689 #relocations: StateMap<LineId, RelocationInfo[]> = new Map();
690 #relocationPages: ReturnType<typeof storedLists<RelocationInfo>> | undefined;
691 #relocatedTo: StateMap<NodeId, RelocationInfo[]> = new Map();
692 #relocatedToPages: ReturnType<typeof storedLists<RelocationInfo>> | undefined;
693 /** The same relocations by node code (a line's n, or -1 - a path's index), for views laid out by number. */
694 #relocatedToCode: StateMap<number, RelocationInfo[]> = new Map();
695 #relocatedToCodePages: ReturnType<typeof storedLists<RelocationInfo>> | undefined;
696 #movers: AtomId[] = [];
697 #atomFiles: (readonly string[])[] = [];
698 /** Each atom's deleted lines by n, packed (#46), or undefined when it deletes none. */
699 #atomDeletes: (readonly number[] | Int32Array | undefined)[] = [];
700 #labels: StateMap<string, Label> = new Map();
701 /** Each author's name kept once (#46). */
702 #authors = new Map<string, string>();
704 /** Number of atoms (also the seq the next atom gets). */
705 get size(): number {
706 return this.#atoms.length;
707 }
709 /** The id the next accepted atom must have. */
710 nextId(): AtomId {
711 return atomId(this.#atoms.length);
712 }
714 has(id: AtomId): boolean {
715 const seq = this.#seq(id);
716 return seq >= 0 && seq < this.#atoms.length;
717 }
719 atom(id: AtomId): Atom {
720 const seq = this.#seq(id);
721 const atom = seq >= 0 ? this.#atoms[seq] : undefined;
722 if (!atom) throw new EngineError("unknown-atom", `no atom ${id}`);
723 return atom;
724 }
726 /** All atoms in seq order. */
727 atoms(): readonly Atom[] {
728 return this.#atoms;
729 }
731 /** lamport(a) = 1 + max lamport of its deps; 0 for an atom with no deps (such as a0). */
732 lamport(id: AtomId): number {
733 if (!this.has(id)) throw new EngineError("unknown-atom", `no atom ${id}`);
734 return this.#lamport[this.#seq(id)]!;
735 }
737 /** Compare by priority (lamport, then seq). Negative when a comes first (is lower). */
738 comparePriority(a: AtomId, b: AtomId): number {
739 return this.lamport(a) - this.lamport(b) || this.#seq(a) - this.#seq(b);
740 }
742 line(id: LineId): LineInfo | undefined {
743 const n = this.#lineN(id);
744 if (n < 0) return undefined;
745 const seq = this.#lineAtom.at(n);
746 return {
747 id,
748 atom: this.idOfSeq(seq),
749 k: n - this.#lineBase[seq]!,
750 file: this.#paths[this.#lineFile.at(n)]!,
751 parent: this.#nodeName(this.#lineParent.at(n)),
752 text: this.#text(n),
753 };
754 }
756 /** A line's text, or undefined for an unknown line: line(id).text without making the record. */
757 lineText(id: LineId): string | undefined {
758 const n = this.#lineN(id);
759 return n < 0 ? undefined : this.#text(n);
760 }
762 /** The atom that wrote a line, or undefined: line(id).atom without making the record. */
763 lineAtom(id: LineId): AtomId | undefined {
764 const n = this.#lineN(id);
765 return n < 0 ? undefined : this.idOfSeq(this.#lineAtom.at(n));
766 }
768 /** The file a line was written in, or undefined: line(id).file without making the record. */
769 lineFile(id: LineId): string | undefined {
770 const n = this.#lineN(id);
771 return n < 0 ? undefined : this.#paths[this.#lineFile.at(n)];
772 }
774 /** The node a line was written after, or undefined: line(id).parent without making the record. */
775 lineParent(id: LineId): NodeId | undefined {
776 const n = this.#lineN(id);
777 return n < 0 ? undefined : this.#nodeName(this.#lineParent.at(n));
778 }
780 // By number, for views (#46) ------------------------------------------------------
781 // 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
782 // keeps them, so a view can lay files out as arrays of numbers. For the engine's own use.
784 /** A line id's n, or -1 for an unknown line. */
785 lineN(id: LineId): number {
786 return this.#lineN(id);
787 }
789 /** A line's id from its n. */
790 lineIdOf(n: number): LineId {
791 return this.#lineName(n);
792 }
794 /** The lines an atom deletes, from the graph's own packed copy (#46): never a read of the log. */
795 deletedLines(id: AtomId): readonly LineId[] {
796 const seq = this.#seq(id);
797 const count = this.#storage?.read("atom-delete-counts", String(seq));
798 if (count !== undefined) {
799 const out: LineId[] = [];
800 for (const n of storedLists<number>(this.#storage!, "atom-deletes").values(String(seq)))
801 out.push(this.#lineName(n));
802 if (out.length !== count) throw Error("incomplete atom deletion index");
803 return out;
804 }
805 const ns = this.#atomDeletes[this.#seq(id)];
806 if (!ns) return EMPTY;
807 const out: LineId[] = new Array(ns.length);
808 for (let i = 0; i < ns.length; i++) out[i] = this.#lineName(ns[i]!);
809 return out;
810 }
812 /** How many lines an atom deletes, without reading its lists. */
813 deleteCount(id: AtomId): number {
814 const seq = this.#seq(id);
815 const count = this.#storage?.read("atom-delete-counts", String(seq));
816 if (count !== undefined) {
817 if (!Number.isSafeInteger(count) || (count as number) < 0) throw Error("invalid atom deletion count");
818 return count as number;
819 }
820 return this.#atomDeletes[seq]?.length ?? 0;
821 }
823 textOf(n: number): string {
824 return this.#text(n);
825 }
827 /** Historical text in bounded chunks, without decoding a whole stored line. */
828 *textChunks(n: number): IterableIterator<string> {
829 if (!this.#storage) {
830 const text = this.#text(n);
831 for (let offset = 0; offset < text.length; offset += StoredText.chunkCharacters)
832 yield text.slice(offset, offset + StoredText.chunkCharacters);
833 return;
834 }
835 if (!Number.isSafeInteger(n) || n < 0 || n >= this.#lineText!.length) throw Error("invalid line number");
836 const value = this.#storage.read("line-text", String(n));
837 if (typeof value === "string") {
838 yield value;
839 return;
840 }
841 const reference = value as { format?: number; text?: string } | undefined;
842 if (reference?.format !== 1 || typeof reference.text !== "string") throw Error("invalid long line reference");
843 yield* new StoredText(this.#storage, "atom-text:long").chunks(reference.text);
844 }
846 /** The seq of the atom that wrote line n. */
847 writerSeqOf(n: number): number {
848 return this.#lineAtom.at(n);
849 }
851 /** Line n's k: its place among its atom's lines. */
852 kOf(n: number): number {
853 return n - this.#lineBase[this.#lineAtom.at(n)]!;
854 }
856 /** The atom id with this seq, as the graph keeps it. */
857 idOfSeq(seq: number): AtomId {
858 if (!Number.isSafeInteger(seq) || seq < 0 || seq >= this.#atoms.length)
859 throw new EngineError("unknown-atom", `no atom at sequence ${seq}`);
860 return atomId(seq);
861 }
863 lamportOfSeq(seq: number): number {
864 return this.#lamport[seq]!;
865 }
867 /** The file line n was written in. */
868 writtenIn(n: number): string {
869 return this.#paths[this.#lineFile.at(n)]!;
870 }
872 /** The code of the node line n was written after. */
873 parentCodeOf(n: number): number {
874 return this.#lineParent.at(n);
875 }
877 /** A node's code, or undefined for a node the graph doesn't know (a start node of a file nothing was written in). */
878 codeOf(node: NodeId): number | undefined {
879 return this.#nodeCode(node);
880 }
882 /** The node a code names. */
883 nodeOf(code: number): NodeId {
884 return this.#nodeName(code);
885 }
887 /** The start node's code for a path, or undefined when nothing was ever written in it. */
888 startCodeOf(path: string): number | undefined {
889 const p = this.#pathIndex.get(path);
890 return p === undefined ? undefined : -1 - p;
891 }
893 /** The lines (their n) written right after a node, as childrenOf, into `out`. */
895 childrenN(code: number, out: number[]): void {
896 for (const n of this.eachChildN(code)) out.push(n);
897 }
898 *eachChildN(code: number): IterableIterator<number> {
899 if (
900 code >= 0 &&
901 code + 1 < this.#lineTotal &&
902 this.#lineAtom.at(code + 1) === this.#lineAtom.at(code) &&
903 this.#lineParent.at(code + 1) === code
904 )
905 yield code + 1;
906 if (this.#runStartPages) yield* this.#runStartPages.values(String(code));
907 else yield* listOf(this.#runStarts.get(code));
908 }
910 get hasOrderedChildren(): boolean {
911 return this.#storage !== undefined;
912 }
913 /** Synchronous derived work against one graph identity. Scratch never commits. */
914 withProjectionScratch<T>(operation: (scratch: GraphStateStorage) => T): T {
915 if (!this.#storage) throw new Error("projection scratch requires persistent graph storage");
916 const size = this.size;
917 const lines = this.lineCount;
918 return withProjectionScratch(
919 this.#storage,
920 () => {
921 if (this.size !== size || this.lineCount !== lines) throw new Error("projection graph identity changed");
922 },
923 operation,
924 );
925 }
926 #childPriority(n: number): string {
927 const seq = this.writerSeqOf(n);
928 return orderedChildKey({
929 n,
930 replaces: this.replacesN(n) ? 1 : 0,
931 lamport: this.lamportOfSeq(seq),
932 seq,
933 k: this.kOf(n),
934 });
935 }
936 /** Persistent layout order with a strict successor cursor; moves are separate. */
937 *orderedChildrenN(code: number, after?: number): IterableIterator<number> {
938 if (!this.#storage) throw new Error("ordered children require indexed storage");
939 const index = new OrderedIndex(this.#storage, "ordered-children", String(code));
940 if (this.#storage.read("ordered-children", "format") !== 2)
941 throw new Error("ordered children require fresh adoption");
942 const count = code >= 0 ? this.#childCounts!.at(code, this.#lineTotal) : index.size;
943 if ((code < 0 || count > 0) && (count !== index.size || count !== this.#runStartPages!.length(String(code))))
944 throw new Error("ordered child index count mismatch");
945 let implicit: number | undefined;
946 if (
947 code >= 0 &&
948 code + 1 < this.#lineTotal &&
949 this.#lineAtom.at(code + 1) === this.#lineAtom.at(code) &&
950 this.#lineParent.at(code + 1) === code
951 )
952 implicit = code + 1;
953 // Most historical run lines have no explicit child. With zero or one
954 // child, traversal needs no priority decoding or radix lookup. Keep the
955 // format/count checks above even on this path.
956 if (count === 0 && (after === undefined || after === implicit)) {
957 if (implicit !== undefined && after !== implicit) yield implicit;
958 return;
959 }
960 const cursor = after === undefined ? undefined : this.#childPriority(after);
961 if (implicit !== undefined && cursor !== undefined && this.#childPriority(implicit) <= cursor) implicit = undefined;
962 for (const n of index.values(cursor)) {
963 if (implicit !== undefined && this.#childPriority(implicit) < this.#childPriority(n)) {
964 yield implicit;
965 implicit = undefined;
966 }
967 yield n;
968 }
969 if (implicit !== undefined) yield implicit;
970 }
972 replacesN(n: number): boolean {
973 return this.#replacing.at(n) === 1;
974 }
976 /** The seqs of every atom that deletes line n (none: an empty list, shared). */
977 deleterSeqsOf(n: number): readonly number[] {
978 return [...this.eachDeleterSeqOf(n)];
979 }
980 *eachDeleterSeqOf(n: number): IterableIterator<number> {
981 const first = this.#deleter.at(n);
982 if (first < 0) return;
983 yield first;
984 if (this.#moreDeleterPages) yield* this.#moreDeleterPages.values(String(n));
985 else yield* this.#moreDeleters.get(n) ?? EMPTY;
986 }
988 /** Every relocation that puts a line right after the node with this code. */
989 relocatedToCode(code: number): readonly RelocationInfo[] {
990 if (this.#relocatedToCodePages) return [...this.eachRelocatedToCode(code)];
991 return this.#relocatedToCode.get(code) ?? EMPTY;
992 }
993 *eachRelocatedToCode(code: number): IterableIterator<RelocationInfo> {
994 if (this.#relocatedToCodePages) yield* this.#relocatedToCodePages.values(String(code));
995 else yield* this.#relocatedToCode.get(code) ?? EMPTY;
996 }
998 /** How many lines every atom together has written. */
999 get lineCount(): number {
1000 return this.#lineTotal;
1001 }
1003 /** A line id's n, or -1 when no accepted atom wrote it. */
1004 #lineN(id: LineId): number {
1005 const p = parseLineId(id);
1006 if (!p || p.seq >= this.#atoms.length) return -1;
1007 const base = this.#lineBase[p.seq]!;
1008 const end = p.seq + 1 < this.#lineBase.length ? this.#lineBase[p.seq + 1]! : this.#lineTotal;
1009 return p.k < end - base ? base + p.k : -1;
1010 }
1012 /** A line's id from its n. */
1013 #lineName(n: number): LineId {
1014 const seq = this.#lineAtom.at(n);
1015 return `${this.idOfSeq(seq)}.${n - this.#lineBase[seq]!}`;
1016 }
1018 /** A node's code: a line's n, or -1 - a path's index for a start node; undefined when unknown. */
1019 #nodeCode(node: NodeId): number | undefined {
1020 if (isStartNode(node)) {
1021 const p = this.#pathIndex.get(node.slice(1));
1022 return p === undefined ? undefined : -1 - p;
1023 }
1024 const n = this.#lineN(node);
1025 return n < 0 ? undefined : n;
1026 }
1028 #nodeName(code: number): NodeId {
1029 return code >= 0 ? this.#lineName(code) : startNode(this.#paths[-1 - code]!);
1030 }
1032 #pathOf(file: string): number {
1033 let p = this.#pathIndex.get(file);
1034 if (p === undefined) {
1035 p = this.#paths.push(file) - 1;
1036 this.#pathIndex.set(file, p);
1037 }
1038 return p;
1039 }
1041 /** The line ids an atom inserted, in k order. */
1042 linesOf(id: AtomId): LineId[] {
1043 return [...this.eachInsertedLine(id)];
1044 }
1045 /** Inserted identities without decoding or allocating the atom's text. */
1046 *eachInsertedLine(id: AtomId): IterableIterator<LineId> {
1047 const seq = this.atom(id).seq;
1048 const count = (seq + 1 < this.#lineBase.length ? this.#lineBase[seq + 1]! : this.#lineTotal) - this.#lineBase[seq]!;
1049 for (let k = 0; k < count; k++) yield lineId(id, k);
1050 }
1052 /** Every atom that deletes this line (across the whole graph). */
1053 deletersOf(line: LineId): readonly AtomId[] {
1054 const n = this.#lineN(line);
1055 if (n < 0) return EMPTY;
1056 return [...this.eachDeleterSeqOf(n)].map((seq) => this.idOfSeq(seq));
1057 }
1059 writersOf(key: Key): readonly AtomId[] {
1060 return [...this.eachWriterOf(key)];
1061 }
1062 *eachWriterOf(key: Key): IterableIterator<AtomId> {
1063 const code = this.#code(key);
1064 if (this.#writersPages) yield* this.#writersPages.values(JSON.stringify([typeof code, code]));
1065 else yield* listOf(this.#writers.get(code));
1066 }
1068 /** Atoms whose implicit reads include the key. */
1069 readersOf(key: Key): readonly AtomId[] {
1070 return [...this.eachReaderOf(key)];
1071 }
1072 *eachReaderOf(key: Key): IterableIterator<AtomId> {
1073 const code = this.#code(key);
1074 if (this.#readersPages) yield* this.#readersPages.values(JSON.stringify([typeof code, code]));
1075 else yield* listOf(this.#readers.get(code));
1076 }
1078 /** Atoms whose explicit holds include the key. */
1079 holdersOf(key: Key): readonly AtomId[] {
1080 return [...this.eachHolderOf(key)];
1081 }
1082 *eachHolderOf(key: Key): IterableIterator<AtomId> {
1083 const code = this.#code(key);
1084 if (this.#holdersPages) yield* this.#holdersPages.values(JSON.stringify([typeof code, code]));
1085 else yield* listOf(this.#holders.get(code));
1086 }
1088 /** Every atom that inserts or deletes a line of the file, in seq order. */
1089 atomsIn(file: string): readonly AtomId[] {
1090 if (this.#fileAtomPages) return [...this.#fileAtomPages.values(file)];
1091 return this.#fileAtoms.get(file) ?? EMPTY;
1092 }
1093 *eachAtomIn(file: string): IterableIterator<AtomId> {
1094 if (this.#fileAtomPages) yield* this.#fileAtomPages.values(file);
1095 else yield* this.#fileAtoms.get(file) ?? EMPTY;
1096 }
1097 hasAtomsIn(file: string): boolean {
1098 return this.#fileAtomPages ? this.#fileAtomPages.length(file) > 0 : this.#fileAtoms.has(file);
1099 }
1101 /** Unique historical file paths, streamed without collecting their names. */
1102 *knownFiles(): IterableIterator<string> {
1103 yield* this.#fileAtomPages ? this.#fileAtomPages.keys() : this.#fileAtoms.keys();
1104 }
1106 /**
1107 * The files an atom inserts, deletes or moves lines in, or sets attributes
1108 * of, sorted. For lines, the file each was written in (or, for a move to a
1109 * start node, that file): a set's moves can have taken them elsewhere.
1110 */
1111 filesOf(id: AtomId): readonly string[] {
1112 if (!this.has(id)) throw new EngineError("unknown-atom", `no atom ${id}`);
1113 return this.#atomFiles[this.#seq(id)]!;
1114 }
1116 /** Lines written right after a node (not counting moves), in seq order. */
1118 childrenOf(node: NodeId): LineId[] {
1119 const code = this.#nodeCode(node);
1120 return code === undefined ? [] : [...this.eachChildN(code)].map((n) => this.#lineName(n));
1121 }
1123 /** Whether a line starts a run whose atom deleted the line it hangs off. */
1124 replaces(line: LineId): boolean {
1125 const n = this.#lineN(line);
1126 return n >= 0 && this.#replacing.at(n) === 1;
1127 }
1129 /** Every relocation of a line, in seq order. */
1130 relocationsOf(line: LineId): readonly RelocationInfo[] {
1131 if (this.#relocationPages) return [...this.eachRelocationOf(line)];
1132 return this.#relocations.get(line) ?? EMPTY;
1133 }
1134 *eachRelocationOf(line: LineId): IterableIterator<RelocationInfo> {
1135 if (this.#relocationPages) yield* this.#relocationPages.values(line);
1136 else yield* this.#relocations.get(line) ?? EMPTY;
1137 }
1139 /** Every relocation that puts a line right after this node, in seq order. */
1140 relocatedTo(node: NodeId): readonly RelocationInfo[] {
1141 if (this.#relocatedToPages) return [...this.#relocatedToPages.values(node)];
1142 return this.#relocatedTo.get(node) ?? EMPTY;
1143 }
1145 /** Atoms that move lines, in seq order. */
1146 movers(): readonly AtomId[] {
1147 return this.#movers;
1148 }
1150 /** Atoms that list this one directly in their deps. */
1151 dependentsOf(id: AtomId): readonly AtomId[] {
1152 return [...this.eachDependentOf(id)];
1153 }
1154 *eachDependentOf(id: AtomId): IterableIterator<AtomId> {
1155 if (this.#dependentsPages) yield* this.#dependentsPages.values(id);
1156 else yield* listOf(this.#dependents.get(id));
1157 }
1159 /** Atoms whose `resolves` names this one. */
1160 resolversOf(id: AtomId): readonly AtomId[] {
1161 return [...this.eachResolverOf(id)];
1162 }
1163 *eachResolverOf(id: AtomId): IterableIterator<AtomId> {
1164 if (this.#resolversPages) yield* this.#resolversPages.values(id);
1165 else yield* listOf(this.#resolvers.get(id));
1166 }
1168 /** `together` reasons touching this atom, in either direction. */
1169 togetherLinks(id: AtomId): readonly TogetherLink[] {
1170 return [...this.eachTogetherLink(id)];
1171 }
1172 *eachTogetherLink(id: AtomId): IterableIterator<TogetherLink> {
1173 if (this.#togetherPages) yield* this.#togetherPages.values(id);
1174 else yield* this.#together.get(id) ?? EMPTY;
1175 }
1177 /**
1178 * The atom plus everything it depends on, transitively. Computed on demand
1179 * and not cached: a cached set per atom costs memory quadratic in the length
1180 * of a dependency chain. Use `dependsOn` to ask about one pair.
1181 */
1182 closure(id: AtomId): Set<AtomId> {
1183 return this.closureOf([id]);
1184 }
1186 /** The atoms plus everything they depend on, transitively. */
1187 closureOf(ids: Iterable<AtomId>): Set<AtomId> {
1188 const out = new Set<AtomId>();
1189 const stack: AtomId[] = [];
1190 for (const id of ids) {
1191 this.atom(id);
1192 if (!out.has(id)) {
1193 out.add(id);
1194 stack.push(id);
1195 }
1196 }
1197 while (stack.length > 0) {
1198 for (const d of this.atom(stack.pop()!).deps) {
1199 if (!out.has(d)) {
1200 out.add(d);
1201 stack.push(d);
1202 }
1203 }
1204 }
1205 return out;
1206 }
1208 /** Whether `b` is in the closure of `a` (an atom is in its own closure). */
1209 dependsOn(a: AtomId, b: AtomId): boolean {
1210 const atom = this.atom(a);
1211 this.atom(b);
1212 return a === b || this.#reaches(atom.deps, b);
1213 }
1215 /**
1216 * Whether `target` is reachable along deps from any of `from` (themselves
1217 * included). A dependency always has a lower lamport than its dependent, so
1218 * the search never descends below the target's lamport.
1219 */
1220 #reaches(from: Iterable<AtomId>, target: AtomId): boolean {
1221 const floor = this.#lamport[this.#seq(target)]!;
1222 if (this.#storage) {
1223 return this.withProjectionScratch((scratch) => {
1224 let length = 0;
1225 const push = (id: AtomId): void => {
1226 if (scratch.read("seen", id)) return;
1227 scratch.write("seen", id, true);
1228 scratch.write("stack", String(length++), id);
1229 };
1230 for (const id of from) {
1231 if (id === target) return true;
1232 if (this.#lamport[this.#seq(id)]! > floor) push(id);
1233 }
1234 while (length > 0) {
1235 const key = String(--length);
1236 const current = scratch.read("stack", key) as AtomId;
1237 scratch.remove("stack", key);
1238 if (this.#lamport[this.#seq(current)]! <= floor) continue;
1239 for (const dependency of this.atom(current).deps) {
1240 if (dependency === target) return true;
1241 push(dependency);
1242 }
1243 }
1244 return false;
1245 });
1246 }
1247 const seen = new Set<AtomId>();
1248 const stack = [...from];
1249 while (stack.length > 0) {
1250 const cur = stack.pop()!;
1251 if (cur === target) return true;
1252 if (seen.has(cur)) continue;
1253 seen.add(cur);
1254 if (this.#lamport[this.#seq(cur)]! <= floor) continue;
1255 for (const d of this.atom(cur).deps) if (!seen.has(d)) stack.push(d);
1256 }
1257 return false;
1258 }
1260 /**
1261 * Accept an atom into the graph. It must carry the next id and seq, and
1262 * everything it touches must come from atoms in its dependency closure.
1263 * The atom is frozen. Adding to the graph does not add it to any set.
1264 */
1265 add(atom: Atom): void {
1266 if (this.#storage)
1267 this.#storage.transaction(() => {
1268 this.#add(atom);
1269 const result: unknown = this.#indexAcceptedAtom?.(atom, this.filesOf(atom.id), this.#storage!);
1270 if (result && typeof result === "object" && "then" in result)
1271 throw Error("accepted atom indexing must be synchronous");
1272 });
1273 else this.#add(atom);
1274 }
1276 #validateAcceptedAtom(atom: Atom, scratch?: GraphStateStorage): void {
1277 const membership = <T extends string>(name: string): { has(key: T): boolean; add(key: T): unknown } => {
1278 if (!scratch) return new Set<T>();
1279 return { has: (key) => scratch.read(name, key) === true, add: (key) => scratch.write(name, key, true) };
1280 };
1281 validateShape(atom);
1282 const seq = this.#atoms.length;
1283 const bad = (why: string): never => {
1284 throw new EngineError("bad-atom", `atom ${atom.id}: ${why}`);
1285 };
1286 if (atom.seq !== seq || atom.id !== atomId(seq)) bad(`expected id ${atomId(seq)} with seq ${seq}`);
1288 const deps = membership<AtomId>("deps");
1289 for (const d of atom.deps) {
1290 if (!this.has(d)) bad(`dependency ${d} is not in the graph`);
1291 if (deps.has(d)) bad(`dependency ${d} listed twice`);
1292 deps.add(d);
1293 }
1294 for (const list of [atom.needs, atom.resolves])
1295 for (const d of list) {
1296 if (!deps.has(d)) bad(`${d} is in needs/resolves but not in deps`);
1297 }
1298 for (const r of atom.reasons) if (!this.has(r.to)) bad(`reason points at unknown atom ${r.to}`);
1300 // Everything it touches must come from its closure. Derived deps name the
1301 // writers directly, so this is usually one lookup per writer.
1302 const memoryBelow = scratch ? undefined : new Map<AtomId, boolean>();
1303 const below = {
1304 get: (key: AtomId) => (scratch ? (scratch.read("below", key) as boolean | undefined) : memoryBelow!.get(key)),
1305 set: (key: AtomId, value: boolean) => {
1306 if (scratch) scratch.write("below", key, value);
1307 else memoryBelow!.set(key, value);
1308 },
1309 };
1310 const inClosure = (writer: AtomId): boolean => {
1311 let hit = below.get(writer);
1312 if (hit === undefined) {
1313 hit = deps.has(writer) || this.#reaches(atom.deps, writer);
1314 below.set(writer, hit);
1315 }
1316 return hit;
1317 };
1318 const checkLine = (line: LineId, what: string): void => {
1319 const writer = this.lineAtom(line);
1320 if (writer === undefined) return bad(`${what} names unknown line ${line}`);
1321 if (!inClosure(writer)) bad(`${what} names line ${line} but ${writer} is not in its closure`);
1322 };
1324 for (const run of atom.inserts) {
1325 if (isStartNode(run.parent)) {
1326 if (run.parent !== startNode(run.file)) bad(`run in ${run.file} starts at ${run.parent}`);
1327 } else {
1328 // The parent may have been moved into run.file, so its own file can differ.
1329 checkLine(run.parent, "an insert");
1330 }
1331 }
1332 const writes = membership<Key>("writes");
1333 for (const key of atom.writes) writes.add(key);
1334 const moved = membership<LineId>("moved");
1335 for (const m of atom.moves ?? []) {
1336 checkLine(m.line, "a move");
1337 if (!isStartNode(m.parent)) checkLine(m.parent, "a move");
1338 if (m.line === m.parent) bad(`moves ${m.line} after itself`);
1339 if (moved.has(m.line)) bad(`moves ${m.line} twice`);
1340 moved.add(m.line);
1341 if (!writes.has(posKey(m.line)) || !writes.has(gapKey(m.parent))) {
1342 bad(`moves ${m.line} without writing ${posKey(m.line)} and ${gapKey(m.parent)}`);
1343 }
1344 }
1345 const deleted = membership<LineId>("deleted");
1346 for (const line of atom.deletes) {
1347 checkLine(line, "a delete");
1348 if (deleted.has(line)) bad(`deletes ${line} twice`);
1349 deleted.add(line);
1350 }
1351 for (const line of atom.deletes)
1352 if (!writes.has(lineKey(line))) bad(`deletes ${line} without writing ${lineKey(line)}`);
1353 for (const list of [atom.writes, atom.reads, atom.holds])
1354 for (const key of list) {
1355 const parsed = parseKey(key);
1356 if (parsed.kind === "line") checkLine(parsed.node, `key ${key}`);
1357 else if ((parsed.kind === "gap" || parsed.kind === "pos") && !isStartNode(parsed.node))
1358 checkLine(parsed.node, `key ${key}`);
1359 }
1360 }
1362 #add(atom: Atom): void {
1363 if (this.#storage && this.#storage.read("ordered-children", "format") !== 2) {
1364 if (this.#atoms.length !== 0) throw new Error("ordered children require fresh adoption");
1365 this.#storage.write("ordered-children", "format", 2);
1366 }
1368 if (this.#storage) this.withProjectionScratch((scratch) => this.#validateAcceptedAtom(atom, scratch));
1369 else this.#validateAcceptedAtom(atom);
1370 const seq = this.#atoms.length;
1371 const deps = atom.deps;
1372 const deleted = this.#storage ? undefined : new Set(atom.deletes);
1373 const writes = this.#storage ? atom.writes : new Set(atom.writes);
1375 // Accept.
1376 // Persistent storage copies the accepted atom; a second frozen copy only duplicates its lists.
1377 const frozen = this.#storage
1378 ? atom
1379 : freezeAtom(
1380 atom,
1381 (id) => this.idOfSeq(seqOf(id)),
1382 (author) => {
1383 if (this.#storage) return author;
1384 let a = this.#authors.get(author);
1385 if (a === undefined) this.#authors.set(author, (a = author));
1386 return a;
1387 },
1388 this.#texts ? this.#reader(seq) : undefined,
1389 this.#lists ? this.#listReader(seq) : undefined,
1390 );
1391 this.#atoms.push(this.#storage ? atom : frozen);
1392 let lam = 0;
1393 for (const d of deps) lam = Math.max(lam, this.lamport(d) + 1);
1394 this.#lamport.push(lam);
1396 // The run starts' parents and the deleted lines, as codes, before this atom's own lines exist.
1397 // The atom as given: with lists kept elsewhere, the frozen one reads them back from the log.
1398 const deletes = (line: LineId | NodeId): boolean => {
1399 if (isStartNode(line)) return false;
1400 if (deleted) return deleted.has(line);
1401 const n = this.#lineN(line);
1402 return this.#deleter.at(n) === seq || this.#moreDeleterPages!.last(String(n)) === seq;
1403 };
1404 const deletedN = this.#storage ? undefined : atom.deletes.map((line) => this.#lineN(line));
1405 this.#atomDeletes.push(deletedN?.length ? Int32Array.from(deletedN) : undefined);
1406 if (this.#storage) {
1407 const pages = storedLists<number>(this.#storage, "atom-deletes");
1408 for (const line of atom.deletes) pages.append(String(seq), this.#lineN(line));
1409 this.#storage.write("atom-delete-counts", String(seq), atom.deletes.length);
1410 }
1411 const deletedNumbers = function* (graph: Graph) {
1412 if (deletedN) yield* deletedN;
1413 else for (const line of atom.deletes) yield graph.#lineN(line);
1414 };
1415 for (const n of deletedNumbers(this)) {
1416 if (this.#deleter.at(n) < 0) this.#deleter.set(n, seq);
1417 else if (this.#moreDeleterPages) this.#moreDeleterPages.append(String(n), seq);
1418 else pushIndex(this.#moreDeleters, n, seq);
1419 }
1420 this.#lineBase.push(this.#lineTotal);
1421 for (const run of atom.inserts) {
1422 const file = this.#pathOf(run.file);
1423 let parent = isStartNode(run.parent) ? -1 - file : this.#lineN(run.parent);
1424 const first = this.#lineTotal;
1425 if (parent >= 0) this.#childCounts?.increment(parent, first);
1426 if (this.#storage)
1427 new OrderedIndex(this.#storage, "ordered-children", String(parent)).insert(
1428 orderedChildKey({
1429 n: first,
1430 replaces: deletes(run.parent) ? 1 : 0,
1431 lamport: lam,
1432 seq,
1433 k: first - this.#lineBase[seq]!,
1434 }),
1435 first,
1436 );
1438 if (this.#runStartPages) this.#runStartPages.append(String(parent), first);
1439 else pushOne(this.#runStarts, parent, first);
1440 for (let i = 0; i < run.lines.length; i++) {
1441 const n = this.#lineTotal;
1442 this.#childCounts?.append(n);
1443 this.#lineAtom.push(seq);
1444 this.#lineFile.push(file);
1445 this.#lineParent.push(parent);
1446 this.#lineText?.push(run.lines[i]!);
1447 this.#deleter.push(-1);
1448 this.#replacing.push(i === 0 && deletes(run.parent) ? 1 : 0);
1449 parent = n;
1450 }
1451 }
1452 (frozen.moves ?? []).forEach((m, i) => {
1453 const info: RelocationInfo = Object.freeze({ atom: frozen.id, line: m.line, parent: m.parent, k: i });
1454 if (this.#relocationPages) this.#relocationPages.append(m.line, info);
1455 else pushIndex(this.#relocations, m.line, info);
1456 if (this.#relocatedToPages) this.#relocatedToPages.append(m.parent, info);
1457 else pushIndex(this.#relocatedTo, m.parent, info);
1458 const parentCode = isStartNode(m.parent) ? -1 - this.#pathOf(m.parent.slice(1)) : this.#lineN(m.parent);
1459 if (this.#relocatedToCodePages) this.#relocatedToCodePages.append(String(parentCode), info);
1460 else pushIndex(this.#relocatedToCode, parentCode, info);
1461 });
1462 if (frozen.moves) this.#movers.push(frozen.id);
1463 for (const key of writes) {
1464 const code = this.#code(key);
1465 if (this.#writersPages) {
1466 const key = JSON.stringify([typeof code, code]);
1467 if (this.#writersPages.last(key) !== frozen.id) this.#writersPages.append(key, frozen.id);
1468 } else pushOne(this.#writers, code, frozen.id);
1469 }
1470 for (const key of this.#storage ? atom.reads : new Set(atom.reads)) {
1471 const code = this.#code(key);
1472 if (this.#readersPages) {
1473 const key = JSON.stringify([typeof code, code]);
1474 if (this.#readersPages.last(key) !== frozen.id) this.#readersPages.append(key, frozen.id);
1475 } else pushOne(this.#readers, code, frozen.id);
1476 }
1477 for (const key of this.#storage ? atom.holds : new Set(atom.holds)) {
1478 const code = this.#code(key);
1479 if (this.#holdersPages) {
1480 const key = JSON.stringify([typeof code, code]);
1481 if (this.#holdersPages.last(key) !== frozen.id) this.#holdersPages.append(key, frozen.id);
1482 } else pushOne(this.#holders, code, frozen.id);
1483 }
1484 for (const d of deps) {
1485 if (this.#dependentsPages) this.#dependentsPages.append(d, frozen.id);
1486 else pushOne(this.#dependents, d, frozen.id);
1487 }
1488 for (const r of this.#storage ? frozen.resolves : new Set(frozen.resolves)) {
1489 if (this.#resolversPages) {
1490 if (this.#resolversPages.last(r) !== frozen.id) this.#resolversPages.append(r, frozen.id);
1491 } else pushOne(this.#resolvers, r, frozen.id);
1492 }
1493 const files = new Set<string>();
1494 for (const run of atom.inserts) files.add(run.file);
1495 for (const n of deletedNumbers(this)) files.add(this.#paths[this.#lineFile.at(n)]!);
1496 for (const a of frozen.attrs ?? []) files.add(a.file);
1497 for (const m of frozen.moves ?? []) {
1498 files.add(this.lineFile(m.line)!);
1499 files.add(isStartNode(m.parent) ? m.parent.slice(1) : this.lineFile(m.parent)!);
1500 }
1501 this.#atomFiles.push(Object.freeze([...files].sort()));
1502 for (const file of files) {
1503 if (this.#fileAtomPages) this.#fileAtomPages.append(file, frozen.id);
1504 else pushIndex(this.#fileAtoms, file, frozen.id);
1505 }
1506 for (const r of frozen.reasons) {
1507 if (r.kind !== "together" || r.to === frozen.id) continue;
1509 const forward = { other: r.to, text: r.text, from: frozen.id };
1510 const reverse = { other: frozen.id, text: r.text, from: frozen.id };
1511 if (this.#togetherPages) {
1512 this.#togetherPages.append(frozen.id, forward);
1513 this.#togetherPages.append(r.to, reverse);
1514 } else {
1515 pushIndex(this.#together, frozen.id, forward);
1516 pushIndex(this.#together, r.to, reverse);
1517 }
1518 }
1519 }
1521 // Labels -----------------------------------------------------------------
1523 /**
1524 * Add or replace a label. Label names may not look like atom ids. A base is
1525 * resolved to its head only when it is used, never followed further, so
1526 * bases may name each other in any shape.
1527 */
1528 setLabel(label: Label): void {
1529 this.#putLabel(label, (name) => this.#labels.has(name));
1530 }
1532 #putLabel(label: Label, isLabel: (name: string) => boolean): void {
1533 const bad = (why: string): never => {
1534 throw new EngineError("bad-label", `label ${JSON.stringify(label?.name)}: ${why}`);
1535 };
1536 if (typeof label !== "object" || label === null) bad("not an object");
1537 if (typeof label.name !== "string" || label.name === "") bad("needs a name");
1538 if (isAtomId(label.name)) bad("a label name may not look like an atom id");
1539 if (!this.has(label.head)) bad(`head ${label.head} is not in the graph`);
1540 if (
1541 label.base !== undefined &&
1542 !(typeof label.base === "string" && (isLabel(label.base) || this.has(label.base)))
1543 ) {
1544 bad(`base ${label.base} is neither a label nor an atom`);
1545 }
1546 if (label.base === label.name) bad("a label cannot be its own base");
1547 if (typeof label.title !== "string" || typeof label.message !== "string") bad("needs a title and message");
1548 if (label.follows !== undefined && !Array.isArray(label.follows)) bad("follows must be a list of label names");
1549 const copy: Label = {
1550 name: label.name,
1551 head: label.head,
1552 ...(label.base !== undefined ? { base: label.base } : {}),
1553 title: label.title,
1554 message: label.message,
1555 ...(label.follows !== undefined ? { follows: Object.freeze([...label.follows]) } : {}),
1556 };
1557 this.#labels.set(label.name, Object.freeze(copy));
1558 }
1560 label(name: string): Label | undefined {
1561 return this.#labels.get(name);
1562 }
1564 /** Labels sorted by name. */
1565 labels(): Label[] {
1566 return [...this.#labels.values()].sort((a, b) => (a.name < b.name ? -1 : a.name > b.name ? 1 : 0));
1567 }
1569 /**
1570 * Remove a label. Labels that used it as their base get its head atom as
1571 * their base instead, so their contents don't change.
1572 */
1573 removeLabel(name: string): boolean {
1574 return this.#storage ? this.#storage.transaction(() => this.#removeLabel(name)) : this.#removeLabel(name);
1575 }
1577 #removeLabel(name: string): boolean {
1578 const gone = this.#labels.get(name);
1579 if (!gone) return false;
1580 this.#labels.delete(name);
1581 for (const label of [...this.#labels.values()]) {
1582 if (label.base === name) this.#labels.set(label.name, Object.freeze({ ...label, base: gone.head }));
1583 }
1584 return true;
1585 }
1587 // JSON -------------------------------------------------------------------
1589 toJSON(): GraphJSON {
1590 return { format: GRAPH_FORMAT, version: 1, atoms: this.#atoms, labels: this.labels() };
1591 }
1593 /** Load a saved graph. Every atom is re-validated as it is added. */
1594 static fromJSON(data: unknown): Graph {
1595 const bad = (why: string): never => {
1596 throw new EngineError("bad-json", why);
1597 };
1598 if (typeof data !== "object" || data === null) bad("graph JSON must be an object");
1599 const obj = data as Partial<GraphJSON>;
1600 if (obj.format !== GRAPH_FORMAT) bad(`format must be ${GRAPH_FORMAT}`);
1601 if (obj.version !== 1) bad(`unsupported version ${String(obj.version)}`);
1602 if (!Array.isArray(obj.atoms) || !Array.isArray(obj.labels)) bad("atoms and labels must be arrays");
1603 const graph = new Graph();
1604 for (const atom of obj.atoms!) graph.add(atom);
1605 // Labels may name each other as bases, in any order and any shape.
1606 const names = new Set<string>();
1607 for (const label of obj.labels!) {
1608 const name: unknown = (label as Partial<Label> | null)?.name;
1609 if (typeof name !== "string") return bad("every label needs a name");
1610 if (names.has(name)) bad(`label ${name} appears twice`);
1611 names.add(name);
1612 }
1613 for (const label of obj.labels!) {
1614 try {
1615 graph.#putLabel(label, (name) => names.has(name));
1616 } catch (err) {
1617 if (err instanceof EngineError) bad(err.message);
1618 throw err;
1619 }
1620 }
1621 return graph;
1622 }
1624 #seq(id: AtomId): number {
1625 return typeof id === "string" ? seqOf(id) : -1;
1626 }
1627}
1629function validateShape(atom: Atom): void {
1630 const bad = (why: string): never => {
1631 throw new EngineError("bad-atom", `atom ${String((atom as { id?: unknown }).id)}: ${why}`);
1632 };
1633 if (typeof atom !== "object" || atom === null) bad("not an object");
1634 if (typeof atom.id !== "string" || !Number.isInteger(atom.seq)) bad("needs id and seq");
1635 if (typeof atom.author !== "string" || typeof atom.message !== "string") bad("needs author and message");
1636 if (typeof atom.time !== "number" || !Number.isFinite(atom.time)) bad("time must be a finite number");
1637 const lists = ["inserts", "deletes", "writes", "reads", "holds", "needs", "resolves", "reasons", "deps"] as const;
1638 for (const name of lists) if (!Array.isArray(atom[name])) bad(`${name} must be an array`);
1639 for (const run of atom.inserts as readonly InsertRun[]) {
1640 if (typeof run.file !== "string" || run.file === "" || run.file.includes("\n")) bad("a run needs a file path");
1641 if (typeof run.parent !== "string") bad("a run needs a parent");
1642 if (!Array.isArray(run.lines) || run.lines.length === 0) bad("a run needs at least one line");
1643 for (const text of run.lines) {
1644 if (typeof text !== "string" || text.includes("\n") || text.includes("\r"))
1645 bad("run lines must be strings without line breaks");
1646 }
1647 }
1648 if (atom.attrs !== undefined) {
1649 if (!Array.isArray(atom.attrs)) bad("attrs must be an array");
1650 for (const a of atom.attrs) {
1651 if (typeof a?.file !== "string" || a.file === "" || a.file.includes("\n") || !ATTR_NAMES.includes(a.name))
1652 bad("an attr needs a file and a name");
1653 if (a.value !== null && typeof a.value !== "string") bad("an attr value is a string or null");
1654 if (!atom.writes.includes(attrKey(a.file, a.name))) bad(`sets ${a.name} of ${a.file} without writing its key`);
1655 }
1656 }
1657 if (atom.moves !== undefined) {
1658 if (!Array.isArray(atom.moves) || atom.moves.length === 0) bad("moves must be a non-empty array");
1659 for (const m of atom.moves) {
1660 if (typeof m?.line !== "string" || typeof m.parent !== "string") bad("a move needs a line and a parent");
1661 }
1662 }
1663 for (const name of ["deletes", "writes", "reads", "holds", "needs", "resolves", "deps"] as const) {
1664 for (const x of atom[name]) if (typeof x !== "string") bad(`${name} must hold strings`);
1665 }
1666 for (const r of atom.reasons as readonly Reason[]) {
1667 if (typeof r.to !== "string" || typeof r.text !== "string" || !REASON_KINDS.includes(r.kind)) {
1668 bad("a reason needs to, kind (together, because-of or supersedes) and text");
1669 }
1670 }
1671}
1673/**
1674 * A frozen copy of an atom. An empty list is one shared frozen list, and atom
1675 * ids and authors are the graph's own strings (`canon`, `author`), so each is
1676 * kept once however often it's named (#46).
1677 */
1678function freezeAtom(
1679 atom: Atom,
1680 canon: (id: AtomId) => AtomId,
1681 author: (name: string) => string,
1682 text?: (start: number, length: number) => readonly string[],
1683 lists?: () => AtomLists,
1684): Atom {
1685 const list = <T>(xs: readonly T[], f?: (x: T) => T): readonly T[] =>
1686 xs.length === 0 ? EMPTY : Object.freeze(f ? xs.map(f) : [...xs]);
1687 // With text kept elsewhere (#46), a run's lines are read when asked for.
1688 let k = 0;
1689 const run = (r: InsertRun): InsertRun => {
1690 if (!text) return Object.freeze({ file: r.file, parent: r.parent, lines: Object.freeze([...r.lines]) });
1691 const start = k;
1692 const length = r.lines.length;
1693 k += length;
1694 return Object.freeze(new LazyRun(r.file, r.parent, text, start, length));
1695 };
1696 const copy: Atom = {
1697 id: atom.id,
1698 seq: atom.seq,
1699 author: author(atom.author),
1700 message: atom.message,
1701 time: atom.time,
1702 inserts: Object.freeze(atom.inserts.map(run)),
1703 ...(lists
1704 ? {}
1705 : { deletes: list(atom.deletes), writes: list(atom.writes), reads: list(atom.reads), holds: list(atom.holds) }),
1706 needs: list(atom.needs, canon),
1707 resolves: list(atom.resolves, canon),
1708 reasons: list(atom.reasons, (r) => Object.freeze({ to: canon(r.to), kind: r.kind, text: r.text })),
1709 deps: list(atom.deps, canon),
1710 ...(atom.attrs && atom.attrs.length > 0
1711 ? { attrs: Object.freeze(atom.attrs.map((a) => Object.freeze({ file: a.file, name: a.name, value: a.value }))) }
1712 : {}),
1713 ...(atom.moves
1714 ? { moves: Object.freeze(atom.moves.map((m) => Object.freeze({ line: m.line, parent: m.parent }))) }
1715 : {}),
1716 } as Atom;
1717 return Object.freeze(lists ? (new ListedAtom(copy, lists) as unknown as Atom) : copy);
1718}