- 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=274&format=json
1,977 linesFirst import 50% · codex-capacity-chair 36% · capacity 14%Last change capacity in version 274, 33 versions changed it
You're reading version 274. The newest is 318, and 2 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 readonlyPagedArray,
25 readonlyStoredArray,
26 type StateMap,
27 storedArray,
28 storedLists,
29 storedMap,
30 storedNumbers,
31 writePagedArray,
32} from "./state-source.ts";
33import { StoredText } from "./stored-text.ts";
34import {
35 ATTR_NAMES,
36 type Atom,
37 type AtomId,
38 EngineError,
39 type InsertRun,
40 type Key,
41 type Label,
42 type LineId,
43 type NodeId,
44 REASON_KINDS,
45 type Reason,
46} from "./types.ts";
48/**
49 * Where a line was written and what it says. Its text never changes. A move
50 * can give it another parent in a set, even in another file: `view.parentOf`
51 * and `view.fileOf` say where it is in a set.
52 */
53export interface LineInfo {
54 readonly id: LineId;
55 readonly atom: AtomId;
56 readonly k: number;
57 /** The file it was written in. */
58 readonly file: string;
59 /** The node it was written after. */
60 readonly parent: NodeId;
61 readonly text: string;
62}
64/** One relocation of a line, by the atom that made it; `k` is its place in that atom's moves. */
65export interface RelocationInfo {
66 readonly atom: AtomId;
67 readonly line: LineId;
68 readonly parent: NodeId;
69 readonly k: number;
70}
72/** A `together` reason seen from one end: `other` is the atom at the far end. */
73export interface TogetherLink {
74 readonly other: AtomId;
75 readonly text: string;
76 /** The atom that carries the reason. */
77 readonly from: AtomId;
78}
80export const GRAPH_FORMAT = "ai-first-vcs.graph";
82/** The saved form of a graph. Atoms are in seq order. */
83export interface GraphJSON {
84 readonly format: typeof GRAPH_FORMAT;
85 readonly version: 1;
86 readonly atoms: readonly Atom[];
87 readonly labels: readonly Label[];
88}
90/**
91 * An index entry that holds a lone value as itself, and a list only once there
92 * are two (#46): most keys name one atom, and a list for each costs more than
93 * the value.
94 */
95function pushOne<K, V>(map: StateMap<K, V | V[]>, key: K, value: V): void {
96 const had = map.get(key);
97 if (had === undefined) map.set(key, value);
98 else if (Array.isArray(had)) {
99 had.push(value);
100 map.set(key, had);
101 } else map.set(key, [had, value]);
102}
104function listOf<V>(had: V | V[] | undefined): readonly V[] {
105 return had === undefined ? EMPTY : Array.isArray(had) ? had : [had];
106}
108function pushIndex<K, V>(map: StateMap<K, V[]>, key: K, value: V): void {
109 const list = map.get(key);
110 if (list) {
111 list.push(value);
112 map.set(key, list);
113 } else map.set(key, [value]);
114}
116const EMPTY: readonly never[] = Object.freeze([]);
118/**
119 * A run whose lines are read when asked for (#46, text on disk): a few fields
120 * and a shared reader, where an object with its own accessor cost about 400
121 * bytes a run.
122 */
123class LazyRun implements InsertRun {
124 readonly file: string;
125 readonly parent: NodeId;
126 readonly #text: (start: number, length: number) => readonly string[];
127 readonly #start: number;
128 readonly #length: number;
129 constructor(
130 file: string,
131 parent: NodeId,
132 text: (start: number, length: number) => readonly string[],
133 start: number,
134 length: number,
135 ) {
136 this.file = file;
137 this.parent = parent;
138 this.#text = text;
139 this.#start = start;
140 this.#length = length;
141 }
142 get lines(): readonly string[] {
143 return this.#text(this.#start, this.#length);
144 }
145 toJSON(): InsertRun {
146 return { file: this.file, parent: this.parent, lines: this.lines };
147 }
148}
150/** Characters of atoms' text a graph that keeps text elsewhere holds at most (#46): about 8 MB. */
151const TEXT_CACHE = 4_000_000;
152/** 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. */
153const LIST_CACHE = 50_000;
155/** An atom's deletes and claim keys: kept in the log rather than in memory when the graph has a `lists` reader (#46). */
156export interface AtomLists {
157 readonly deletes: readonly LineId[];
158 readonly writes: readonly Key[];
159 readonly reads: readonly Key[];
160 readonly holds: readonly Key[];
161}
163function listItems(l: AtomLists): number {
164 return l.deletes.length + l.writes.length + l.reads.length + l.holds.length;
165}
167function frozenList<T>(xs: readonly T[]): readonly T[] {
168 return xs.length === 0 ? (EMPTY as readonly T[]) : Object.freeze([...xs]);
169}
171/**
172 * An atom whose deletes, writes, reads and holds are read back through `read` (#46). The getters live on the
173 * prototype, so each atom keeps one reader and a fixed shape, not four closures in a dictionary-mode object.
174 */
175class ListedAtom {
176 readonly #read: () => AtomLists;
177 constructor(fields: object, read: () => AtomLists) {
178 Object.assign(this, fields);
179 this.#read = read;
180 }
181 get deletes(): readonly LineId[] {
182 return this.#read().deletes;
183 }
184 get writes(): readonly Key[] {
185 return this.#read().writes;
186 }
187 get reads(): readonly Key[] {
188 return this.#read().reads;
189 }
190 get holds(): readonly Key[] {
191 return this.#read().holds;
192 }
193 toJSON(): object {
194 return { ...this, ...this.#read() };
195 }
196}
198/** A growable array of 32-bit integers: a line's fields cost 4 bytes each, not an object and its strings (#46). */
199interface NumberIndex {
200 readonly length: number;
201 push(n: number): void;
202 at(i: number): number;
203 set(i: number, n: number): void;
204}
206class Ints implements NumberIndex {
207 #buf: Int32Array | Uint8Array;
208 /** bytes: values 0-255 only, one byte each. */
209 constructor(bytes = false) {
210 this.#buf = bytes ? new Uint8Array(1024) : new Int32Array(1024);
211 }
212 length = 0;
213 push(n: number): void {
214 if (this.length === this.#buf.length) {
215 const bigger =
216 this.#buf instanceof Uint8Array ? new Uint8Array(this.#buf.length * 2) : new Int32Array(this.#buf.length * 2);
217 bigger.set(this.#buf);
218 this.#buf = bigger;
219 }
220 this.#buf[this.length++] = n;
221 }
222 at(i: number): number {
223 return this.#buf[i]!;
224 }
225 set(i: number, n: number): void {
226 this.#buf[i] = n;
227 }
228}
230/**
231 * A line id's place in the graph's line arrays, or -1: "a<seq>.<k>" is line
232 * `base[seq] + k`. Hand-parsed, as seqOf is, with the same rules: no leading
233 * zeros, and k within the lines its atom wrote.
234 */
235function parseLineId(id: string): { seq: number; k: number } | undefined {
236 if (typeof id !== "string") return undefined;
237 const n = id.length;
238 if (n < 4 || id.charCodeAt(0) !== 97 /* a */) return undefined;
239 let i = 1;
240 let seq = 0;
241 const seqStart = i;
242 for (; i < n; i++) {
243 const c = id.charCodeAt(i);
244 if (c === 46 /* . */) break;
245 if (c < 48 || c > 57) return undefined;
246 seq = seq * 10 + (c - 48);
247 }
248 if (i === seqStart || i >= n - 1 || i - seqStart > 15 || (i - seqStart > 1 && id.charCodeAt(seqStart) === 48))
249 return undefined;
250 const kStart = ++i;
251 let k = 0;
252 for (; i < n; i++) {
253 const c = id.charCodeAt(i);
254 if (c < 48 || c > 57) return undefined;
255 k = k * 10 + (c - 48);
256 }
257 if (i - kStart > 15 || (i - kStart > 1 && id.charCodeAt(kStart) === 48)) return undefined;
258 return { seq, k };
259}
261/** A line in its file's packed history: [n, parent code, writer seq, k, 1 when it replaces its parent]. */
262export type PackedLine = [number, number, number, number, number];
263/** A delete of a line in a file's packed history: [n, deleter seq]. */
264export type PackedDelete = [number, number];
265/** An attribute set on a file: [seq, name, value]. */
266export type PackedAttr = [number, string, string | null];
267/** A run written in another file under one of a file's lines: [the parent's n, the run's file index]. */
268export type PackedCrossing = [number, number];
269const EMPTY_NUMBERS: readonly number[] = Object.freeze([]);
270/** At most this many path names kept in memory (Graph.#pathName). */
271const PATH_NAMES = 4096;
272/** Lines longer than this aren't packed with their file; their text is read on its own. */
273const PACKED_TEXT = 4096;
275export class Graph {
276 readonly #storage?: GraphStateStorage;
277 readonly #childCounts?: ChildCounts;
278 #atoms: Atom[] = [];
279 #lamport: number[] = [];
280 /**
281 * A stored graph's lamport numbers, 256 to a row (abso Capacity). A graph that already has them a row each (#lamport)
282 * keeps that; the choice is made when first needed, so opening reads nothing.
283 */
284 #lamportPaged: ReturnType<typeof storedNumbers> | undefined;
285 #lamportPagesKnown: ReturnType<typeof storedNumbers> | null | undefined;
286 get #lamportPages(): ReturnType<typeof storedNumbers> | null {
287 if (this.#lamportPagesKnown === undefined)
288 this.#lamportPagesKnown =
289 this.#lamportPaged && this.#storage!.read("lamport:meta", "length") === undefined ? this.#lamportPaged : null;
290 return this.#lamportPagesKnown;
291 }
292 // Lines, packed (#46): line n is the k-th line atom seq wrote, n = #lineBase[seq] + k. Each holds its
293 // atom's seq, the file it was written in (an index into #paths) and its parent (a line's n, or -1 - a
294 // path's index for a file's start). Its text stays in the atom. Ids and LineInfo objects are made only
295 // when asked for, so a line costs about 16 bytes here instead of a record, its id and its parent's id.
296 #lineBase: number[] = [];
297 #lineAtom: NumberIndex = new Ints();
298 #lineFile: NumberIndex = new Ints();
299 #lineParent: NumberIndex = new Ints();
300 /** Lines' text, when the graph keeps it; without it, it comes from `texts` (#46, text on disk). */
301 #lineText: string[] | undefined = [];
302 get #lineTotal(): number {
303 return this.#lineAtom.length;
304 }
305 /** Where an atom's lines' text is when the graph doesn't keep it: each run's lines, by the atom's seq. */
306 #texts: ((seq: number) => readonly (readonly string[])[]) | undefined;
307 /** Recently read atoms' text, flattened, most recent last, up to TEXT_CACHE characters. */
308 #textCache = new Map<number, readonly string[]>();
309 #textCached = 0;
311 readonly #indexAcceptedAtom?: (atom: Atom, files: readonly string[], storage: GraphStateStorage) => void;
313 /**
314 * `texts`, when given, says where each atom's lines' text can be read back
315 * (#46): the graph then keeps no text, only each line's place, and reads an
316 * atom's text when a line of it is asked for, keeping the most recent.
317 */
318 constructor(
319 options: {
320 texts?: (seq: number) => readonly (readonly string[])[];
321 lists?: (seq: number) => AtomLists;
322 storage?: GraphStateStorage;
323 /** Optional derived indexing inside persistent atom acceptance; must be synchronous. */
324 indexAcceptedAtom?: (atom: Atom, files: readonly string[], storage: GraphStateStorage) => void;
325 /** false: a new stored graph keeps no packed file history, and lays files out line by line (tests of that path). */
326 packFiles?: boolean;
327 } = {},
328 ) {
329 if (options.indexAcceptedAtom && !options.storage)
330 throw Error("accepted atom indexing requires persistent storage");
331 this.#indexAcceptedAtom = options.indexAcceptedAtom;
332 if (options.texts) {
333 this.#texts = options.texts;
334 this.#lineText = undefined;
335 }
336 if (options.lists) this.#lists = options.lists;
337 this.#storage = options.storage;
338 if (options.storage) this.#childCounts = new ChildCounts(options.storage);
339 if (options.storage) {
340 const storage = options.storage;
341 const numbers = (name: string): NumberIndex => storedNumbers(storage, name);
342 const atomText = new StoredText(storage, "atom-text:long");
343 type TextReference = { text: string };
344 const listFields = [
345 "deletes",
346 "writes",
347 "reads",
348 "holds",
349 "needs",
350 "resolves",
351 "deps",
352 "reasons",
353 "attrs",
354 "moves",
355 ] as const;
356 type EncodedAtom = {
357 insertionFormat?: 1;
358 insertionRuns?: string;
359 textFormat?: 1;
360 listFormat?: 1 | 2;
361 listCount?: number;
362 lists?: Partial<Record<(typeof listFields)[number], string>>;
363 atom: Atom;
364 };
365 this.#atoms = storedArray<Atom>(
366 storage,
367 "atoms",
368 (value) => {
369 const encoded = value as unknown as Partial<EncodedAtom>;
370 if (encoded.textFormat !== undefined && encoded.textFormat !== 1)
371 throw Error("invalid stored atom text format");
372 if (encoded.listFormat !== undefined && encoded.listFormat !== 1 && encoded.listFormat !== 2)
373 throw Error("invalid stored atom list format");
374 if (encoded.listFormat === 1 || encoded.listFormat === 2) {
375 if (
376 !encoded.lists ||
377 typeof encoded.lists !== "object" ||
378 Array.isArray(encoded.lists) ||
379 !Number.isSafeInteger(encoded.listCount) ||
380 encoded.listCount! < 1 ||
381 Object.keys(encoded.lists).length !== encoded.listCount ||
382 Object.keys(encoded.lists).some((field) => !listFields.includes(field as (typeof listFields)[number]))
383 )
384 throw Error("invalid stored atom list references");
385 }
386 if (encoded.insertionFormat !== undefined && encoded.insertionFormat !== 1)
387 throw Error("invalid stored insertion format");
388 const atom =
389 encoded.textFormat === 1 ||
390 encoded.listFormat === 1 ||
391 encoded.listFormat === 2 ||
392 encoded.insertionFormat === 1
393 ? encoded.atom!
394 : value;
395 if (encoded.insertionFormat === 1 && (!Array.isArray(atom.inserts) || atom.inserts.length !== 0))
396 throw Error("invalid stored insertion placeholder");
397 const text =
398 encoded.textFormat === 1
399 ? (start: number, length: number): readonly string[] => {
400 const result: string[] = [];
401 let index = 0;
402 for (const run of atom.inserts)
403 for (const raw of run.lines) {
404 if (index >= start && index < start + length) {
405 const reference = raw as unknown as TextReference;
406 if (typeof raw === "string") result.push(raw);
407 else if (reference && reference.text === JSON.stringify([String(atom.seq), index]))
408 result.push(atomText.read(reference.text));
409 else throw Error("invalid stored atom text reference");
410 }
411 if (++index >= start + length) return result;
412 }
413 throw Error("stored atom text range missing");
414 }
415 : undefined;
416 // Sequential reads advance once per run without retaining a history-sized offset array.
417 let offsetRun = 0;
418 let offsetLine = 0;
419 const insertionStart = (index: number): number => {
420 if (index < offsetRun) {
421 offsetRun = 0;
422 offsetLine = 0;
423 }
424 while (offsetRun < index) {
425 offsetLine += readonlyStoredArray(storage, `atom-inserts:${atom.seq}:lines:${offsetRun}`).length;
426 offsetRun++;
427 }
428 return offsetLine;
429 };
430 const streamed = (target: Atom): Atom => {
431 registerJsonChunkValue(target, () => {
432 const line = (raw: unknown, index: number): unknown => {
433 if (typeof raw === "string") return raw;
434 const reference = raw as TextReference;
435 if (!reference || reference.text !== JSON.stringify([String(atom.seq), index]))
436 throw Error("invalid stored atom text reference");
437 return new JsonStringChunks(() => atomText.chunks(reference.text));
438 };
439 let inserts: readonly unknown[];
440 if (encoded.insertionFormat === 1) {
441 const collection = `atom-inserts:${atom.seq}`;
442 inserts = readonlyStoredArray(storage, collection, (raw, index) => {
443 const run = raw as { file: string; parent: string; lines: string };
444 const lines = `${collection}:lines:${index}`;
445 if (run.lines !== lines || typeof run.file !== "string" || typeof run.parent !== "string")
446 throw Error("invalid stored insertion run");
447 const start = insertionStart(index);
448 return {
449 file: run.file,
450 parent: run.parent,
451 lines: readonlyStoredArray(storage, lines, (raw, i) => line(raw, start + i)),
452 };
453 });
454 } else {
455 let index = 0;
456 inserts = atom.inserts.map((run) => ({
457 file: run.file,
458 parent: run.parent,
459 lines: run.lines.map((raw) => line(raw, index++)),
460 }));
461 }
462 return { ...target, inserts };
463 });
464 return target;
465 };
466 const frozen = freezeAtom(
467 atom,
468 (id) => id,
469 (author) => author,
470 text,
471 );
472 if (encoded.listFormat !== 1 && encoded.listFormat !== 2 && encoded.insertionFormat !== 1)
473 return streamed(frozen);
474 const result = { ...frozen };
475 if (encoded.insertionFormat === 1) {
476 const collection = `atom-inserts:${atom.seq}`;
477 if (encoded.insertionRuns !== collection) throw Error("invalid stored insertion reference");
478 const inserts = readonlyStoredArray<InsertRun>(storage, collection, (raw, index) => {
479 const run = raw as { file: string; parent: InsertRun["parent"]; lines: string };
480 const lines = `${collection}:lines:${index}`;
481 if (run.lines !== lines || typeof run.file !== "string" || typeof run.parent !== "string")
482 throw Error("invalid stored insertion run");
483 return Object.freeze({
484 file: run.file,
485 parent: run.parent,
486 lines: readonlyStoredArray<string>(storage, lines, (rawLine, lineIndex) => {
487 if (typeof rawLine === "string") return rawLine;
488 const ref = rawLine as TextReference;
489 const atomLine = insertionStart(index) + lineIndex;
490 if (!ref || ref.text !== JSON.stringify([String(atom.seq), atomLine]))
491 throw Error("invalid stored insertion text");
492 return atomText.read(ref.text);
493 }),
494 });
495 });
496 Object.defineProperty(result, "inserts", { value: inserts, enumerable: true });
497 }
498 for (const field of listFields) {
499 const collection = encoded.lists?.[field];
500 if (collection === undefined) continue;
501 if (typeof collection !== "string" || collection !== `atom-list:${atom.seq}:${field}`)
502 throw Error("invalid stored atom list reference");
503 const list =
504 encoded.listFormat === 2
505 ? readonlyPagedArray(storage, collection)
506 : readonlyStoredArray(storage, collection);
507 Object.defineProperty(result, field, { value: list, enumerable: true });
508 }
509 return streamed(Object.freeze(result));
510 },
511 (input, key) => {
512 const atom = { ...input };
513 const lists: Partial<Record<(typeof listFields)[number], string>> = {};
514 for (const field of listFields) {
515 const values = input[field];
516 if (!values || values.length <= 256) continue;
517 // 256 to a row from list format 2 on (abso Capacity); an atom stored before keeps a row per value.
518 const collection = `atom-list:${input.seq}:${field}`;
519 writePagedArray(storage, collection, values);
520 lists[field] = collection;
521 Object.defineProperty(atom, field, { value: [], enumerable: true });
522 }
523 const listCount = Object.keys(lists).length;
524 const hasLists = listCount > 0;
525 let insertionCharacters = 0;
526 if (
527 atom.inserts.length > 256 ||
528 atom.inserts.some((run) => run.lines.length > 256) ||
529 atom.inserts.some((run) => run.lines.some((line) => (insertionCharacters += line.length) > 65536))
530 ) {
531 const collection = `atom-inserts:${input.seq}`;
532 const runs = storedArray<unknown>(storage, collection);
533 let runIndex = 0;
534 let lineIndex = 0;
535 for (const run of atom.inserts) {
536 const lineCollection = `${collection}:lines:${runIndex++}`;
537 const lines = storedArray<unknown>(storage, lineCollection);
538 for (const line of run.lines) {
539 const text = JSON.stringify([key, lineIndex++]);
540 if (line.length > StoredText.chunkCharacters) {
541 atomText.write(text, line);
542 lines.push({ text });
543 } else lines.push(line);
544 }
545 runs.push({ file: run.file, parent: run.parent, lines: lineCollection });
546 }
547 return {
548 insertionFormat: 1,
549 insertionRuns: collection,
550 ...(hasLists ? { listFormat: 2, listCount, lists } : {}),
551 atom: { ...atom, inserts: [] },
552 };
553 }
554 if (!atom.inserts.some((run) => run.lines.some((line) => line.length > StoredText.chunkCharacters)))
555 return hasLists ? { listFormat: 2, listCount, lists, atom } : atom;
556 let index = 0;
557 const inserts = atom.inserts.map((run) => ({
558 ...run,
559 lines: run.lines.map((line) => {
560 const text = JSON.stringify([key, index++]);
561 if (line.length <= StoredText.chunkCharacters) return line;
562 atomText.write(text, line);
563 return { text };
564 }),
565 }));
566 return {
567 textFormat: 1,
568 ...(hasLists ? { listFormat: 2, listCount, lists } : {}),
569 atom: { ...atom, inserts },
570 };
571 },
572 );
573 this.#lamport = storedArray(storage, "lamport");
574 this.#lamportPaged = storedNumbers(storage, "lamport-pages");
575 this.#lineBase = storedArray(storage, "line-base");
576 this.#paths = storedArray(storage, "paths");
577 this.#movers = storedArray(storage, "movers");
578 this.#atomFiles = storedArray(storage, "atom-files");
579 this.#atomDeletes = storedArray(storage, "atom-deletes");
580 this.#lineAtom = numbers("line-atom");
581 this.#lineFile = numbers("line-file");
582 this.#lineParent = numbers("line-parent");
583 this.#deleter = numbers("deleter");
584 this.#replacing = numbers("replacing");
585 const longText = atomText;
586 this.#lineText = storedArray<string>(
587 storage,
588 "line-text",
589 (value) => {
590 if (typeof value === "string") return value;
591 const reference = value as unknown as { format: number; text: string };
592 if (reference?.format !== 1 || typeof reference.text !== "string") throw Error("invalid long line reference");
593 return longText.read(reference.text);
594 },
595 (value, key) => {
596 if (value.length <= StoredText.chunkCharacters) return value;
597 const number = Number(key);
598 const seq = this.#lineAtom.at(number);
599 const text = JSON.stringify([String(seq), number - this.#lineBase[seq]!]);
600 const header = storage.read("atom-text:long", text) as { characters?: number } | undefined;
601 if (header?.characters !== value.length) throw Error("long line atom text is missing");
602 return { format: 1, text };
603 },
604 );
605 this.#pathIndex = storedMap(storage, "path-index");
606 this.#moreDeleterPages = storedLists<number>(storage, "more-deleters", (key) =>
607 JSON.stringify(["number", Number(key)]),
608 );
609 this.#writersPages = storedLists<AtomId>(storage, "writers", (key) => key);
610 this.#readersPages = storedLists<AtomId>(storage, "readers", (key) => key);
611 this.#holdersPages = storedLists<AtomId>(storage, "holders", (key) => key);
612 this.#dependentsPages = storedLists<AtomId>(storage, "dependents");
613 this.#resolversPages = storedLists<AtomId>(storage, "resolvers");
614 this.#togetherPages = storedLists<TogetherLink>(storage, "together");
615 this.#reasonsInPages = storedLists<AtomId>(storage, "reasons-in");
616 this.#fileAtomPages = storedLists<AtomId>(storage, "file-atoms");
617 this.#runStartPages = storedLists<number>(storage, "run-starts", (key) =>
618 JSON.stringify(["number", Number(key)]),
619 );
620 this.#relocationPages = storedLists<RelocationInfo>(storage, "relocations");
621 this.#relocatedToPages = storedLists<RelocationInfo>(storage, "relocated-to");
622 this.#relocatedToCodePages = storedLists<RelocationInfo>(storage, "relocated-to-code", (key) =>
623 JSON.stringify(["number", Number(key)]),
624 );
625 this.#labels = storedMap(storage, "labels");
626 this.#fileLines = storedLists<PackedLine>(storage, "file-lines");
627 this.#fileTexts = storedLists<string | null>(storage, "file-texts");
628 this.#fileDeletes = storedLists<PackedDelete>(storage, "file-deletes");
629 this.#fileAttrs = storedLists<PackedAttr>(storage, "file-attrs");
630 this.#fileCrossings = storedLists<PackedCrossing>(storage, "file-crossings");
631 this.#packFiles = options.packFiles ?? true;
632 }
633 }
635 // Each file's line history packed, in pages (abso Capacity) ---------------------------------------------------
636 // For each file, by its path index: every line written in it ([n, parent code, writer seq, k, replaces]) and its
637 // text, every delete of one of those lines ([n, deleter seq]), every attribute set on it ([seq, name, value]), and
638 // every run written in another file under one of its lines ([parent n, the run's file]): a line follows its parent,
639 // so a run written while its parent was moved elsewhere lays out wherever the parent is.
640 // Appended as atoms are added, so a view lays a file out from a few pages instead of a row read per line. Kept from
641 // a fresh adoption on; a graph adopted before has none, and views lay out as before.
643 #fileLines: ReturnType<typeof storedLists<PackedLine>> | undefined;
644 #fileTexts: ReturnType<typeof storedLists<string | null>> | undefined;
645 #fileDeletes: ReturnType<typeof storedLists<PackedDelete>> | undefined;
646 #fileAttrs: ReturnType<typeof storedLists<PackedAttr>> | undefined;
647 #fileCrossings: ReturnType<typeof storedLists<PackedCrossing>> | undefined;
648 /** Whether a new stored graph starts packing (GraphOptions.packFiles). */
649 #packFiles = true;
650 /**
651 * How this graph's files are packed, read once when first asked so opening reads nothing: 0 not at all, 1 lines,
652 * deletes and attributes, 2 the runs written across files as well.
653 */
654 #formatKnown: number | undefined;
655 get #format(): number {
656 if (this.#formatKnown === undefined) {
657 const format = this.#storage?.read("file-lines:meta", "format");
658 this.#formatKnown = format === 1 || format === 2 ? format : 0;
659 }
660 return this.#formatKnown;
661 }
662 get #packed(): boolean {
663 return this.#format >= 1;
664 }
665 get #crossings(): boolean {
666 return this.#format >= 2;
667 }
669 /** Whether this graph keeps each file's line history packed. */
670 get packedFiles(): boolean {
671 return this.#packed;
672 }
673 /**
674 * Whether a file can be laid out from packed history alone: it also keeps the runs written across files. A graph
675 * packed before those were kept lays files out line by line.
676 */
677 get packedLayout(): boolean {
678 return this.#crossings;
679 }
680 /** A path's index, or undefined when nothing was ever written or set in it. */
681 pathIndexOf(path: string): number | undefined {
682 return this.#pathIndex.get(path);
683 }
684 /** The index of the path line n was written in. */
685 writtenInIndex(n: number): number {
686 return this.#lineFile.at(n);
687 }
688 *packedLines(file: number): IterableIterator<PackedLine> {
689 yield* this.#fileLines!.values(String(file));
690 }
691 *packedTexts(file: number): IterableIterator<string | null> {
692 yield* this.#fileTexts!.values(String(file));
693 }
694 /**
695 * The texts at positions [page * 256, (page + 1) * 256) of packedTexts(file) (abso Capacity): a layout reads only the
696 * pages holding a line it shows.
697 */
698 packedTextPage(file: number, page: number): readonly (string | null)[] {
699 return this.#fileTexts!.pageAt(String(file), page);
700 }
701 *packedDeletes(file: number): IterableIterator<PackedDelete> {
702 yield* this.#fileDeletes!.values(String(file));
703 }
704 *packedAttrs(file: number): IterableIterator<PackedAttr> {
705 yield* this.#fileAttrs!.values(String(file));
706 }
707 *packedCrossings(file: number): IterableIterator<PackedCrossing> {
708 yield* this.#fileCrossings!.values(String(file));
709 }
711 /** Where an atom's key and delete lists are when the graph doesn't keep them (#46): the stored atom. */
712 #lists: ((seq: number) => AtomLists) | undefined;
713 /** Recently read atoms' lists, most recent last, up to LIST_CACHE atoms. */
714 #listCache = new Map<number, AtomLists>();
715 #listCached = 0;
717 /** An atom's deletes, writes, reads and holds, read back from where they are stored. */
718 #listsOf(seq: number): AtomLists {
719 const hit = this.#listCache.get(seq);
720 if (hit) {
721 this.#listCache.delete(seq);
722 this.#listCache.set(seq, hit);
723 return hit;
724 }
725 const got = this.#lists!(seq);
726 const lists: AtomLists = {
727 deletes: frozenList(got.deletes),
728 writes: frozenList(got.writes),
729 reads: frozenList(got.reads),
730 holds: frozenList(got.holds),
731 };
732 this.#listCache.set(seq, lists);
733 this.#listCached += listItems(lists);
734 for (const [old, kept] of this.#listCache) {
735 if (this.#listCached <= LIST_CACHE || old === seq) break;
736 this.#listCache.delete(old);
737 this.#listCached -= listItems(kept);
738 }
739 return lists;
740 }
742 /** The reader an atom's lists use; made apart from add() so it keeps no atom alive (see #reader). */
743 #listReader(seq: number): () => AtomLists {
744 return () => this.#listsOf(seq);
745 }
747 /**
748 * 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
749 * index holds numbers rather than one string per line; start-node and attribute keys stay strings. A key
750 * naming a line the graph doesn't have stays a string, which nothing has claimed.
751 */
752 #code(key: Key): Key | number {
753 const t = key.charCodeAt(0);
754 if (key.charCodeAt(1) !== 58 || key.charCodeAt(2) === 94) return key; // not "X:", or a start node "^"
755 const k = t === 76 ? 0 : t === 80 ? 1 : t === 71 ? 2 : -1; // L, P, G
756 if (k < 0) return key;
757 const n = this.#lineN(key.slice(2));
758 return n < 0 ? key : n * 4 + k;
759 }
761 /** An atom's lines' text, in k order. */
762 #textOf(seq: number): readonly string[] {
763 const hit = this.#textCache.get(seq);
764 if (hit) {
765 this.#textCache.delete(seq);
766 this.#textCache.set(seq, hit);
767 return hit;
768 }
769 const flat = this.#texts!(seq).flat();
770 let chars = 0;
771 for (const t of flat) chars += t.length + 1;
772 this.#textCache.set(seq, flat);
773 this.#textCached += chars;
774 for (const [old, lines] of this.#textCache) {
775 if (this.#textCached <= TEXT_CACHE || old === seq) break;
776 this.#textCache.delete(old);
777 for (const t of lines) this.#textCached -= t.length + 1;
778 }
779 return flat;
780 }
782 /**
783 * The reader an atom's runs use. Made in a function of its own: a closure made inside add() would
784 * keep add()'s whole scope alive, the atom as given with all its text included.
785 */
786 #reader(seq: number): (start: number, length: number) => readonly string[] {
787 return (start, length) => this.#textOf(seq).slice(start, start + length);
788 }
790 /** Line n's text. */
791 #text(n: number): string {
792 if (this.#lineText) return this.#lineText[n]!;
793 const seq = this.#lineAtom.at(n);
794 return this.#textOf(seq)[n - this.#lineBase[seq]!]!;
795 }
796 #paths: string[] = [];
797 #pathIndex: StateMap<string, number> = new Map();
798 /** The first atom that deletes each line (its seq), or -1; a line deleted by more than one has the rest in #moreDeleters. */
799 #deleter: NumberIndex = new Ints();
800 #moreDeleters: StateMap<number, number[]> = new Map();
801 #moreDeleterPages: ReturnType<typeof storedLists<number>> | undefined;
802 #writers: StateMap<Key | number, AtomId | AtomId[]> = new Map();
803 #writersPages: ReturnType<typeof storedLists<AtomId>> | undefined;
804 #readers: StateMap<Key | number, AtomId | AtomId[]> = new Map();
805 #readersPages: ReturnType<typeof storedLists<AtomId>> | undefined;
806 #holders: StateMap<Key | number, AtomId | AtomId[]> = new Map();
807 #holdersPages: ReturnType<typeof storedLists<AtomId>> | undefined;
808 #dependents: StateMap<AtomId, AtomId | AtomId[]> = new Map();
809 #dependentsPages: ReturnType<typeof storedLists<AtomId>> | undefined;
810 #resolvers: StateMap<AtomId, AtomId | AtomId[]> = new Map();
811 #resolversPages: ReturnType<typeof storedLists<AtomId>> | undefined;
812 #together: StateMap<AtomId, TogetherLink[]> = new Map();
813 #togetherPages: ReturnType<typeof storedLists<TogetherLink>> | undefined;
814 /** The atoms whose reasons point at each atom, in seq order, once each (abso Capacity). */
815 #reasonsIn = new Map<AtomId, AtomId[]>();
816 #reasonsInPages: ReturnType<typeof storedLists<AtomId>> | undefined;
817 /** Whether a stored graph keeps reasons-in: from a fresh graph on, worked out when first needed. */
818 #reasonsInKnown: boolean | undefined;
819 get #reasonsInKept(): boolean {
820 if (!this.#storage) return true;
821 this.#reasonsInKnown ??= this.#storage.read("reasons-in:meta", "kept") === 1;
822 return this.#reasonsInKnown;
823 }
824 #fileAtoms: StateMap<string, AtomId[]> = new Map();
825 #fileAtomPages: ReturnType<typeof storedLists<AtomId>> | undefined;
826 /** First lines of runs (their n), by the node they were written after: a line's n, or -1 - a path's index. */
827 #runStarts: StateMap<number, number | number[]> = new Map();
828 #runStartPages: ReturnType<typeof storedLists<number>> | undefined;
829 /** 1 for the first line of a run whose atom deleted the line it hangs off: the run replaces it. */
830 #replacing: NumberIndex = new Ints(true);
831 #relocations: StateMap<LineId, RelocationInfo[]> = new Map();
832 #relocationPages: ReturnType<typeof storedLists<RelocationInfo>> | undefined;
833 #relocatedTo: StateMap<NodeId, RelocationInfo[]> = new Map();
834 #relocatedToPages: ReturnType<typeof storedLists<RelocationInfo>> | undefined;
835 /** The same relocations by node code (a line's n, or -1 - a path's index), for views laid out by number. */
836 #relocatedToCode: StateMap<number, RelocationInfo[]> = new Map();
837 #relocatedToCodePages: ReturnType<typeof storedLists<RelocationInfo>> | undefined;
838 #movers: AtomId[] = [];
839 /** A stored graph's movers, read once (abso Capacity): every view walks them, a row each. */
840 #moverList: AtomId[] | undefined;
841 #atomFiles: (readonly string[])[] = [];
842 /** Each atom's deleted lines by n, packed (#46), or undefined when it deletes none. */
843 #atomDeletes: (readonly number[] | Int32Array | undefined)[] = [];
844 #labels: StateMap<string, Label> = new Map();
845 /** Each author's name kept once (#46). */
846 #authors = new Map<string, string>();
848 /** Number of atoms (also the seq the next atom gets). */
849 get size(): number {
850 return this.#atoms.length;
851 }
853 /**
854 * How many atoms this graph object has accepted since it was made (abso Capacity): in memory, so a cache over the
855 * graph can tell nothing was added without reading storage. A rolled-back add still counts, which only makes such a
856 * cache look again.
857 */
858 get accepted(): number {
859 return this.#accepted;
860 }
861 #accepted = 0;
863 /** The id the next accepted atom must have. */
864 nextId(): AtomId {
865 return atomId(this.#atoms.length);
866 }
868 has(id: AtomId): boolean {
869 const seq = this.#seq(id);
870 return seq >= 0 && seq < this.#atoms.length;
871 }
873 atom(id: AtomId): Atom {
874 const seq = this.#seq(id);
875 const atom = seq >= 0 ? this.#atoms[seq] : undefined;
876 if (!atom) throw new EngineError("unknown-atom", `no atom ${id}`);
877 return atom;
878 }
880 /** All atoms in seq order. */
881 atoms(): readonly Atom[] {
882 return this.#atoms;
883 }
885 /** lamport(a) = 1 + max lamport of its deps; 0 for an atom with no deps (such as a0). */
886 lamport(id: AtomId): number {
887 if (!this.has(id)) throw new EngineError("unknown-atom", `no atom ${id}`);
888 return this.#lamportAt(this.#seq(id));
889 }
891 /** Compare by priority (lamport, then seq). Negative when a comes first (is lower). */
892 comparePriority(a: AtomId, b: AtomId): number {
893 return this.lamport(a) - this.lamport(b) || this.#seq(a) - this.#seq(b);
894 }
896 line(id: LineId): LineInfo | undefined {
897 const n = this.#lineN(id);
898 if (n < 0) return undefined;
899 const seq = this.#lineAtom.at(n);
900 return {
901 id,
902 atom: this.idOfSeq(seq),
903 k: n - this.#lineBase[seq]!,
904 file: this.#pathName(this.#lineFile.at(n)),
905 parent: this.#nodeName(this.#lineParent.at(n)),
906 text: this.#text(n),
907 };
908 }
910 /** A line's text, or undefined for an unknown line: line(id).text without making the record. */
911 lineText(id: LineId): string | undefined {
912 const n = this.#lineN(id);
913 return n < 0 ? undefined : this.#text(n);
914 }
916 /** The atom that wrote a line, or undefined: line(id).atom without making the record. */
917 lineAtom(id: LineId): AtomId | undefined {
918 const n = this.#lineN(id);
919 return n < 0 ? undefined : this.idOfSeq(this.#lineAtom.at(n));
920 }
922 /** The file a line was written in, or undefined: line(id).file without making the record. */
923 lineFile(id: LineId): string | undefined {
924 const n = this.#lineN(id);
925 return n < 0 ? undefined : this.#pathName(this.#lineFile.at(n));
926 }
928 /** The node a line was written after, or undefined: line(id).parent without making the record. */
929 lineParent(id: LineId): NodeId | undefined {
930 const n = this.#lineN(id);
931 return n < 0 ? undefined : this.#nodeName(this.#lineParent.at(n));
932 }
934 // By number, for views (#46) ------------------------------------------------------
935 // 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
936 // keeps them, so a view can lay files out as arrays of numbers. For the engine's own use.
938 /** A line id's n, or -1 for an unknown line. */
939 lineN(id: LineId): number {
940 return this.#lineN(id);
941 }
943 /** A line's id from its n. */
944 lineIdOf(n: number): LineId {
945 return this.#lineName(n);
946 }
948 /** The lines an atom deletes, from the graph's own packed copy (#46): never a read of the log. */
949 deletedLines(id: AtomId): readonly LineId[] {
950 const seq = this.#seq(id);
951 const count = this.#storage?.read("atom-delete-counts", String(seq));
952 if (count !== undefined) {
953 const out: LineId[] = [];
954 for (const n of storedLists<number>(this.#storage!, "atom-deletes").values(String(seq)))
955 out.push(this.#lineName(n));
956 if (out.length !== count) throw Error("incomplete atom deletion index");
957 return out;
958 }
959 const ns = this.#atomDeletes[this.#seq(id)];
960 if (!ns) return EMPTY;
961 const out: LineId[] = new Array(ns.length);
962 for (let i = 0; i < ns.length; i++) out[i] = this.#lineName(ns[i]!);
963 return out;
964 }
966 /** The numbers of the lines an atom deletes, from the graph's packed copy: no lookup per line id. */
967 *deletedNumbers(id: AtomId): IterableIterator<number> {
968 const seq = this.#seq(id);
969 if (this.#storage?.read("atom-delete-counts", String(seq)) !== undefined) {
970 yield* storedLists<number>(this.#storage!, "atom-deletes").values(String(seq));
971 return;
972 }
973 yield* this.#atomDeletes[seq] ?? EMPTY_NUMBERS;
974 }
976 /** How many lines an atom deletes, without reading its lists. */
977 deleteCount(id: AtomId): number {
978 const seq = this.#seq(id);
979 const count = this.#storage?.read("atom-delete-counts", String(seq));
980 if (count !== undefined) {
981 if (!Number.isSafeInteger(count) || (count as number) < 0) throw Error("invalid atom deletion count");
982 return count as number;
983 }
984 return this.#atomDeletes[seq]?.length ?? 0;
985 }
987 textOf(n: number): string {
988 return this.#text(n);
989 }
991 /** Historical text in bounded chunks, without decoding a whole stored line. */
992 *textChunks(n: number): IterableIterator<string> {
993 if (!this.#storage) {
994 const text = this.#text(n);
995 for (let offset = 0; offset < text.length; offset += StoredText.chunkCharacters)
996 yield text.slice(offset, offset + StoredText.chunkCharacters);
997 return;
998 }
999 if (!Number.isSafeInteger(n) || n < 0 || n >= this.#lineText!.length) throw Error("invalid line number");
1000 const value = this.#storage.read("line-text", String(n));
1001 if (typeof value === "string") {
1002 yield value;
1003 return;
1004 }
1005 const reference = value as { format?: number; text?: string } | undefined;
1006 if (reference?.format !== 1 || typeof reference.text !== "string") throw Error("invalid long line reference");
1007 yield* new StoredText(this.#storage, "atom-text:long").chunks(reference.text);
1008 }
1010 /** The seq of the atom that wrote line n. */
1011 writerSeqOf(n: number): number {
1012 return this.#lineAtom.at(n);
1013 }
1015 /** Line n's k: its place among its atom's lines. */
1016 kOf(n: number): number {
1017 return n - this.#lineBase[this.#lineAtom.at(n)]!;
1018 }
1020 /** The atom id with this seq, as the graph keeps it. */
1021 idOfSeq(seq: number): AtomId {
1022 if (!Number.isSafeInteger(seq) || seq < 0 || seq >= this.#atoms.length)
1023 throw new EngineError("unknown-atom", `no atom at sequence ${seq}`);
1024 return atomId(seq);
1025 }
1027 #lamportAt(seq: number): number {
1028 return this.#lamportPages ? this.#lamportPages.at(seq) : this.#lamport[seq]!;
1029 }
1031 lamportOfSeq(seq: number): number {
1032 return this.#lamportAt(seq);
1033 }
1035 /** The file line n was written in. */
1036 writtenIn(n: number): string {
1037 return this.#pathName(this.#lineFile.at(n));
1038 }
1040 /** The code of the node line n was written after. */
1041 parentCodeOf(n: number): number {
1042 return this.#lineParent.at(n);
1043 }
1045 /** A node's code, or undefined for a node the graph doesn't know (a start node of a file nothing was written in). */
1046 codeOf(node: NodeId): number | undefined {
1047 return this.#nodeCode(node);
1048 }
1050 /** The node a code names. */
1051 nodeOf(code: number): NodeId {
1052 return this.#nodeName(code);
1053 }
1055 /** The start node's code for a path, or undefined when nothing was ever written in it. */
1056 startCodeOf(path: string): number | undefined {
1057 const p = this.#pathIndex.get(path);
1058 return p === undefined ? undefined : -1 - p;
1059 }
1061 /** The lines (their n) written right after a node, as childrenOf, into `out`. */
1063 childrenN(code: number, out: number[]): void {
1064 for (const n of this.eachChildN(code)) out.push(n);
1065 }
1066 *eachChildN(code: number): IterableIterator<number> {
1067 if (
1068 code >= 0 &&
1069 code + 1 < this.#lineTotal &&
1070 this.#lineAtom.at(code + 1) === this.#lineAtom.at(code) &&
1071 this.#lineParent.at(code + 1) === code
1072 )
1073 yield code + 1;
1074 if (this.#runStartPages) {
1075 // The paged child counts say a line has no other children without a row read per line (abso Capacity).
1076 if (code >= 0 && this.#childCounts && this.#childCounts.at(code, this.#lineTotal) === 0) return;
1077 yield* this.#runStartPages.values(String(code));
1078 } else yield* listOf(this.#runStarts.get(code));
1079 }
1081 get hasOrderedChildren(): boolean {
1082 return this.#storage !== undefined;
1083 }
1084 /** Synchronous derived work against one graph identity. Scratch never commits. */
1085 withProjectionScratch<T>(operation: (scratch: GraphStateStorage) => T): T {
1086 if (!this.#storage) throw new Error("projection scratch requires persistent graph storage");
1087 const size = this.size;
1088 const lines = this.lineCount;
1089 return withProjectionScratch(
1090 this.#storage,
1091 () => {
1092 if (this.size !== size || this.lineCount !== lines) throw new Error("projection graph identity changed");
1093 },
1094 operation,
1095 );
1096 }
1097 #childPriority(n: number): string {
1098 const seq = this.writerSeqOf(n);
1099 return orderedChildKey({
1100 n,
1101 replaces: this.replacesN(n) ? 1 : 0,
1102 lamport: this.lamportOfSeq(seq),
1103 seq,
1104 k: this.kOf(n),
1105 });
1106 }
1107 /** Persistent layout order with a strict successor cursor; moves are separate. */
1108 *orderedChildrenN(code: number, after?: number): IterableIterator<number> {
1109 if (!this.#storage) throw new Error("ordered children require indexed storage");
1110 const index = new OrderedIndex(this.#storage, "ordered-children", String(code));
1111 if (this.#storage.read("ordered-children", "format") !== 2)
1112 throw new Error("ordered children require fresh adoption");
1113 const count = code >= 0 ? this.#childCounts!.at(code, this.#lineTotal) : index.size;
1114 if ((code < 0 || count > 0) && (count !== index.size || count !== this.#runStartPages!.length(String(code))))
1115 throw new Error("ordered child index count mismatch");
1116 let implicit: number | undefined;
1117 if (
1118 code >= 0 &&
1119 code + 1 < this.#lineTotal &&
1120 this.#lineAtom.at(code + 1) === this.#lineAtom.at(code) &&
1121 this.#lineParent.at(code + 1) === code
1122 )
1123 implicit = code + 1;
1124 // Most historical run lines have no explicit child. With zero or one
1125 // child, traversal needs no priority decoding or radix lookup. Keep the
1126 // format/count checks above even on this path.
1127 if (count === 0 && (after === undefined || after === implicit)) {
1128 if (implicit !== undefined && after !== implicit) yield implicit;
1129 return;
1130 }
1131 const cursor = after === undefined ? undefined : this.#childPriority(after);
1132 if (implicit !== undefined && cursor !== undefined && this.#childPriority(implicit) <= cursor) implicit = undefined;
1133 for (const n of index.values(cursor)) {
1134 if (implicit !== undefined && this.#childPriority(implicit) < this.#childPriority(n)) {
1135 yield implicit;
1136 implicit = undefined;
1137 }
1138 yield n;
1139 }
1140 if (implicit !== undefined) yield implicit;
1141 }
1143 replacesN(n: number): boolean {
1144 return this.#replacing.at(n) === 1;
1145 }
1147 /** The seqs of every atom that deletes line n (none: an empty list, shared). */
1148 deleterSeqsOf(n: number): readonly number[] {
1149 return [...this.eachDeleterSeqOf(n)];
1150 }
1151 *eachDeleterSeqOf(n: number): IterableIterator<number> {
1152 const first = this.#deleter.at(n);
1153 if (first < 0) return;
1154 yield first;
1155 if (this.#moreDeleterPages) yield* this.#moreDeleterPages.values(String(n));
1156 else yield* this.#moreDeleters.get(n) ?? EMPTY;
1157 }
1159 /** Every relocation that puts a line right after the node with this code. */
1160 relocatedToCode(code: number): readonly RelocationInfo[] {
1161 if (this.#relocatedToCodePages) return [...this.eachRelocatedToCode(code)];
1162 return this.#relocatedToCode.get(code) ?? EMPTY;
1163 }
1164 *eachRelocatedToCode(code: number): IterableIterator<RelocationInfo> {
1165 if (this.#relocatedToCodePages) yield* this.#relocatedToCodePages.values(String(code));
1166 else yield* this.#relocatedToCode.get(code) ?? EMPTY;
1167 }
1169 /** How many lines every atom together has written. */
1170 get lineCount(): number {
1171 return this.#lineTotal;
1172 }
1174 /** A line id's n, or -1 when no accepted atom wrote it. */
1175 #lineN(id: LineId): number {
1176 const p = parseLineId(id);
1177 if (!p || p.seq >= this.#atoms.length) return -1;
1178 const base = this.#lineBase[p.seq]!;
1179 const end = p.seq + 1 < this.#lineBase.length ? this.#lineBase[p.seq + 1]! : this.#lineTotal;
1180 return p.k < end - base ? base + p.k : -1;
1181 }
1183 /** A line's id from its n. */
1184 #lineName(n: number): LineId {
1185 const seq = this.#lineAtom.at(n);
1186 return `${this.idOfSeq(seq)}.${n - this.#lineBase[seq]!}`;
1187 }
1189 /** A node's code: a line's n, or -1 - a path's index for a start node; undefined when unknown. */
1190 #nodeCode(node: NodeId): number | undefined {
1191 if (isStartNode(node)) {
1192 const p = this.#pathIndex.get(node.slice(1));
1193 return p === undefined ? undefined : -1 - p;
1194 }
1195 const n = this.#lineN(node);
1196 return n < 0 ? undefined : n;
1197 }
1199 #nodeName(code: number): NodeId {
1200 return code >= 0 ? this.#lineName(code) : startNode(this.#pathName(-1 - code));
1201 }
1203 /**
1204 * A path's name by its index, kept in memory once read (abso Capacity): finding a deleted line's file names the file
1205 * it reaches, and a stored graph read the path list each time. Cleared when the graph accepts an atom, so a name a
1206 * rolled-back add made never stays.
1207 */
1208 #pathName(index: number): string {
1209 if (this.#pathNamesAt !== this.#accepted) {
1210 this.#pathNames.clear();
1211 this.#pathNamesAt = this.#accepted;
1212 }
1213 let name = this.#pathNames.get(index);
1214 if (name === undefined) {
1215 name = this.#paths[index]!;
1216 if (this.#pathNames.size >= PATH_NAMES) this.#pathNames.clear();
1217 this.#pathNames.set(index, name);
1218 }
1219 return name;
1220 }
1221 readonly #pathNames = new Map<number, string>();
1222 #pathNamesAt = -1;
1224 #pathOf(file: string): number {
1225 let p = this.#pathIndex.get(file);
1226 if (p === undefined) {
1227 p = this.#paths.push(file) - 1;
1228 this.#pathIndex.set(file, p);
1229 }
1230 return p;
1231 }
1233 /** The line ids an atom inserted, in k order. */
1234 linesOf(id: AtomId): LineId[] {
1235 return [...this.eachInsertedLine(id)];
1236 }
1237 /** Inserted identities without decoding or allocating the atom's text. */
1238 *eachInsertedLine(id: AtomId): IterableIterator<LineId> {
1239 const seq = this.atom(id).seq;
1240 const count = (seq + 1 < this.#lineBase.length ? this.#lineBase[seq + 1]! : this.#lineTotal) - this.#lineBase[seq]!;
1241 for (let k = 0; k < count; k++) yield lineId(id, k);
1242 }
1244 /** Every atom that deletes this line (across the whole graph). */
1245 deletersOf(line: LineId): readonly AtomId[] {
1246 const n = this.#lineN(line);
1247 if (n < 0) return EMPTY;
1248 return [...this.eachDeleterSeqOf(n)].map((seq) => this.idOfSeq(seq));
1249 }
1251 writersOf(key: Key): readonly AtomId[] {
1252 return [...this.eachWriterOf(key)];
1253 }
1254 *eachWriterOf(key: Key): IterableIterator<AtomId> {
1255 const code = this.#code(key);
1256 if (this.#writersPages) yield* this.#writersPages.values(JSON.stringify([typeof code, code]));
1257 else yield* listOf(this.#writers.get(code));
1258 }
1260 /** Atoms whose implicit reads include the key. */
1261 readersOf(key: Key): readonly AtomId[] {
1262 return [...this.eachReaderOf(key)];
1263 }
1264 *eachReaderOf(key: Key): IterableIterator<AtomId> {
1265 const code = this.#code(key);
1266 if (this.#readersPages) yield* this.#readersPages.values(JSON.stringify([typeof code, code]));
1267 else yield* listOf(this.#readers.get(code));
1268 }
1270 /** Atoms whose explicit holds include the key. */
1271 holdersOf(key: Key): readonly AtomId[] {
1272 return [...this.eachHolderOf(key)];
1273 }
1274 *eachHolderOf(key: Key): IterableIterator<AtomId> {
1275 const code = this.#code(key);
1276 if (this.#holdersPages) yield* this.#holdersPages.values(JSON.stringify([typeof code, code]));
1277 else yield* listOf(this.#holders.get(code));
1278 }
1280 /** Every atom that inserts or deletes a line of the file, in seq order. */
1281 atomsIn(file: string): readonly AtomId[] {
1282 if (this.#fileAtomPages) return [...this.#fileAtomPages.values(file)];
1283 return this.#fileAtoms.get(file) ?? EMPTY;
1284 }
1285 *eachAtomIn(file: string): IterableIterator<AtomId> {
1286 if (this.#fileAtomPages) yield* this.#fileAtomPages.values(file);
1287 else yield* this.#fileAtoms.get(file) ?? EMPTY;
1288 }
1289 hasAtomsIn(file: string): boolean {
1290 return this.#fileAtomPages ? this.#fileAtomPages.length(file) > 0 : this.#fileAtoms.has(file);
1291 }
1293 /** Unique historical file paths, streamed without collecting their names. */
1294 *knownFiles(): IterableIterator<string> {
1295 yield* this.#fileAtomPages ? this.#fileAtomPages.keys() : this.#fileAtoms.keys();
1296 }
1298 /**
1299 * The files an atom inserts, deletes or moves lines in, or sets attributes
1300 * of, sorted. For lines, the file each was written in (or, for a move to a
1301 * start node, that file): a set's moves can have taken them elsewhere.
1302 */
1303 filesOf(id: AtomId): readonly string[] {
1304 if (!this.has(id)) throw new EngineError("unknown-atom", `no atom ${id}`);
1305 return this.#atomFiles[this.#seq(id)]!;
1306 }
1308 /** Lines written right after a node (not counting moves), in seq order. */
1310 childrenOf(node: NodeId): LineId[] {
1311 const code = this.#nodeCode(node);
1312 return code === undefined ? [] : [...this.eachChildN(code)].map((n) => this.#lineName(n));
1313 }
1315 /** Whether a line starts a run whose atom deleted the line it hangs off. */
1316 replaces(line: LineId): boolean {
1317 const n = this.#lineN(line);
1318 return n >= 0 && this.#replacing.at(n) === 1;
1319 }
1321 /** Every relocation of a line, in seq order. */
1322 relocationsOf(line: LineId): readonly RelocationInfo[] {
1323 if (this.#relocationPages) return [...this.eachRelocationOf(line)];
1324 return this.#relocations.get(line) ?? EMPTY;
1325 }
1326 *eachRelocationOf(line: LineId): IterableIterator<RelocationInfo> {
1327 if (this.#relocationPages) yield* this.#relocationPages.values(line);
1328 else yield* this.#relocations.get(line) ?? EMPTY;
1329 }
1331 /** Every relocation that puts a line right after this node, in seq order. */
1332 relocatedTo(node: NodeId): readonly RelocationInfo[] {
1333 if (this.#relocatedToPages) return [...this.#relocatedToPages.values(node)];
1334 return this.#relocatedTo.get(node) ?? EMPTY;
1335 }
1337 /** Atoms that move lines, in seq order. */
1338 movers(): readonly AtomId[] {
1339 if (!this.#storage) return this.#movers;
1340 // Checked against the stored list's length and last mover, so a rolled-back add can't leave one behind.
1341 const length = this.#movers.length;
1342 const list = this.#moverList;
1343 if (list && list.length === length && (length === 0 || list[length - 1] === this.#movers[length - 1])) return list;
1344 this.#moverList = [...this.#movers];
1345 return this.#moverList;
1346 }
1348 /** Atoms that list this one directly in their deps. */
1349 dependentsOf(id: AtomId): readonly AtomId[] {
1350 return [...this.eachDependentOf(id)];
1351 }
1352 *eachDependentOf(id: AtomId): IterableIterator<AtomId> {
1353 if (this.#dependentsPages) yield* this.#dependentsPages.values(id);
1354 else yield* listOf(this.#dependents.get(id));
1355 }
1357 /** Atoms whose `resolves` names this one. */
1358 resolversOf(id: AtomId): readonly AtomId[] {
1359 return [...this.eachResolverOf(id)];
1360 }
1361 *eachResolverOf(id: AtomId): IterableIterator<AtomId> {
1362 if (this.#resolversPages) yield* this.#resolversPages.values(id);
1363 else yield* listOf(this.#resolvers.get(id));
1364 }
1366 /**
1367 * The atoms whose reasons point at this one, in seq order, once each; or undefined when a stored graph made before
1368 * this index keeps none, and the caller looks at every atom (abso Capacity).
1369 */
1370 reasonsTo(id: AtomId): readonly AtomId[] | undefined {
1371 if (!this.#reasonsInKept) return undefined;
1372 if (this.#reasonsInPages) return [...this.#reasonsInPages.values(id)];
1373 return this.#reasonsIn.get(id) ?? [];
1374 }
1376 /** `together` reasons touching this atom, in either direction. */
1377 togetherLinks(id: AtomId): readonly TogetherLink[] {
1378 return [...this.eachTogetherLink(id)];
1379 }
1380 *eachTogetherLink(id: AtomId): IterableIterator<TogetherLink> {
1381 if (this.#togetherPages) yield* this.#togetherPages.values(id);
1382 else yield* this.#together.get(id) ?? EMPTY;
1383 }
1385 /**
1386 * The atom plus everything it depends on, transitively. Computed on demand
1387 * and not cached: a cached set per atom costs memory quadratic in the length
1388 * of a dependency chain. Use `dependsOn` to ask about one pair.
1389 */
1390 closure(id: AtomId): Set<AtomId> {
1391 return this.closureOf([id]);
1392 }
1394 /** The atoms plus everything they depend on, transitively. */
1395 closureOf(ids: Iterable<AtomId>): Set<AtomId> {
1396 const out = new Set<AtomId>();
1397 const stack: AtomId[] = [];
1398 for (const id of ids) {
1399 this.atom(id);
1400 if (!out.has(id)) {
1401 out.add(id);
1402 stack.push(id);
1403 }
1404 }
1405 while (stack.length > 0) {
1406 for (const d of this.atom(stack.pop()!).deps) {
1407 if (!out.has(d)) {
1408 out.add(d);
1409 stack.push(d);
1410 }
1411 }
1412 }
1413 return out;
1414 }
1416 /** Whether `b` is in the closure of `a` (an atom is in its own closure). */
1417 dependsOn(a: AtomId, b: AtomId): boolean {
1418 const atom = this.atom(a);
1419 this.atom(b);
1420 return a === b || this.#reaches(atom.deps, b);
1421 }
1423 /**
1424 * Whether `target` is reachable along deps from any of `from` (themselves
1425 * included). A dependency always has a lower lamport than its dependent, so
1426 * the search never descends below the target's lamport.
1427 */
1428 #reaches(from: Iterable<AtomId>, target: AtomId): boolean {
1429 const floor = this.#lamportAt(this.#seq(target));
1430 if (this.#storage) {
1431 return this.withProjectionScratch((scratch) => {
1432 let length = 0;
1433 const push = (id: AtomId): void => {
1434 if (scratch.read("seen", id)) return;
1435 scratch.write("seen", id, true);
1436 scratch.write("stack", String(length++), id);
1437 };
1438 for (const id of from) {
1439 if (id === target) return true;
1440 if (this.#lamportAt(this.#seq(id)) > floor) push(id);
1441 }
1442 while (length > 0) {
1443 const key = String(--length);
1444 const current = scratch.read("stack", key) as AtomId;
1445 scratch.remove("stack", key);
1446 if (this.#lamportAt(this.#seq(current)) <= floor) continue;
1447 for (const dependency of this.atom(current).deps) {
1448 if (dependency === target) return true;
1449 push(dependency);
1450 }
1451 }
1452 return false;
1453 });
1454 }
1455 const seen = new Set<AtomId>();
1456 const stack = [...from];
1457 while (stack.length > 0) {
1458 const cur = stack.pop()!;
1459 if (cur === target) return true;
1460 if (seen.has(cur)) continue;
1461 seen.add(cur);
1462 if (this.#lamportAt(this.#seq(cur)) <= floor) continue;
1463 for (const d of this.atom(cur).deps) if (!seen.has(d)) stack.push(d);
1464 }
1465 return false;
1466 }
1468 /**
1469 * Accept an atom into the graph. It must carry the next id and seq, and
1470 * everything it touches must come from atoms in its dependency closure.
1471 * The atom is frozen. Adding to the graph does not add it to any set.
1472 */
1473 add(atom: Atom): void {
1474 if (this.#storage)
1475 this.#storage.transaction(() => {
1476 this.#add(atom);
1477 const result: unknown = this.#indexAcceptedAtom?.(atom, this.filesOf(atom.id), this.#storage!);
1478 if (result && typeof result === "object" && "then" in result)
1479 throw Error("accepted atom indexing must be synchronous");
1480 });
1481 else this.#add(atom);
1482 }
1484 #validateAcceptedAtom(atom: Atom, scratch?: GraphStateStorage): void {
1485 const membership = <T extends string>(name: string): { has(key: T): boolean; add(key: T): unknown } => {
1486 if (!scratch) return new Set<T>();
1487 return { has: (key) => scratch.read(name, key) === true, add: (key) => scratch.write(name, key, true) };
1488 };
1489 validateShape(atom);
1490 const seq = this.#atoms.length;
1491 const bad = (why: string): never => {
1492 throw new EngineError("bad-atom", `atom ${atom.id}: ${why}`);
1493 };
1494 if (atom.seq !== seq || atom.id !== atomId(seq)) bad(`expected id ${atomId(seq)} with seq ${seq}`);
1496 const deps = membership<AtomId>("deps");
1497 for (const d of atom.deps) {
1498 if (!this.has(d)) bad(`dependency ${d} is not in the graph`);
1499 if (deps.has(d)) bad(`dependency ${d} listed twice`);
1500 deps.add(d);
1501 }
1502 for (const list of [atom.needs, atom.resolves])
1503 for (const d of list) {
1504 if (!deps.has(d)) bad(`${d} is in needs/resolves but not in deps`);
1505 }
1506 for (const r of atom.reasons) if (!this.has(r.to)) bad(`reason points at unknown atom ${r.to}`);
1508 // Everything it touches must come from its closure. Derived deps name the
1509 // writers directly, so this is usually one lookup per writer.
1510 const memoryBelow = scratch ? undefined : new Map<AtomId, boolean>();
1511 const below = {
1512 get: (key: AtomId) => (scratch ? (scratch.read("below", key) as boolean | undefined) : memoryBelow!.get(key)),
1513 set: (key: AtomId, value: boolean) => {
1514 if (scratch) scratch.write("below", key, value);
1515 else memoryBelow!.set(key, value);
1516 },
1517 };
1518 const inClosure = (writer: AtomId): boolean => {
1519 let hit = below.get(writer);
1520 if (hit === undefined) {
1521 hit = deps.has(writer) || this.#reaches(atom.deps, writer);
1522 below.set(writer, hit);
1523 }
1524 return hit;
1525 };
1526 const checkLine = (line: LineId, what: string): void => {
1527 const writer = this.lineAtom(line);
1528 if (writer === undefined) return bad(`${what} names unknown line ${line}`);
1529 if (!inClosure(writer)) bad(`${what} names line ${line} but ${writer} is not in its closure`);
1530 };
1532 for (const run of atom.inserts) {
1533 if (isStartNode(run.parent)) {
1534 if (run.parent !== startNode(run.file)) bad(`run in ${run.file} starts at ${run.parent}`);
1535 } else {
1536 // The parent may have been moved into run.file, so its own file can differ.
1537 checkLine(run.parent, "an insert");
1538 }
1539 }
1540 const writes = membership<Key>("writes");
1541 for (const key of atom.writes) writes.add(key);
1542 const moved = membership<LineId>("moved");
1543 for (const m of atom.moves ?? []) {
1544 checkLine(m.line, "a move");
1545 if (!isStartNode(m.parent)) checkLine(m.parent, "a move");
1546 if (m.line === m.parent) bad(`moves ${m.line} after itself`);
1547 if (moved.has(m.line)) bad(`moves ${m.line} twice`);
1548 moved.add(m.line);
1549 if (!writes.has(posKey(m.line)) || !writes.has(gapKey(m.parent))) {
1550 bad(`moves ${m.line} without writing ${posKey(m.line)} and ${gapKey(m.parent)}`);
1551 }
1552 }
1553 const deleted = membership<LineId>("deleted");
1554 for (const line of atom.deletes) {
1555 checkLine(line, "a delete");
1556 if (deleted.has(line)) bad(`deletes ${line} twice`);
1557 deleted.add(line);
1558 }
1559 for (const line of atom.deletes)
1560 if (!writes.has(lineKey(line))) bad(`deletes ${line} without writing ${lineKey(line)}`);
1561 for (const list of [atom.writes, atom.reads, atom.holds])
1562 for (const key of list) {
1563 const parsed = parseKey(key);
1564 if (parsed.kind === "line") checkLine(parsed.node, `key ${key}`);
1565 else if ((parsed.kind === "gap" || parsed.kind === "pos") && !isStartNode(parsed.node))
1566 checkLine(parsed.node, `key ${key}`);
1567 }
1568 }
1570 #add(atom: Atom): void {
1571 if (this.#storage && this.#storage.read("ordered-children", "format") !== 2) {
1572 if (this.#atoms.length !== 0) throw new Error("ordered children require fresh adoption");
1573 this.#storage.write("ordered-children", "format", 2);
1574 }
1575 if (this.#storage && this.#atoms.length === 0 && this.#packFiles) {
1576 this.#storage.write("file-lines:meta", "format", 2);
1577 this.#storage.write("reasons-in:meta", "kept", 1);
1578 this.#reasonsInKnown = true;
1579 this.#formatKnown = 2;
1580 }
1582 if (this.#storage) this.withProjectionScratch((scratch) => this.#validateAcceptedAtom(atom, scratch));
1583 else this.#validateAcceptedAtom(atom);
1584 const seq = this.#atoms.length;
1585 const deps = atom.deps;
1586 const deleted = this.#storage ? undefined : new Set(atom.deletes);
1587 const writes = this.#storage ? atom.writes : new Set(atom.writes);
1589 // Accept.
1590 // Persistent storage copies the accepted atom; a second frozen copy only duplicates its lists.
1591 const frozen = this.#storage
1592 ? atom
1593 : freezeAtom(
1594 atom,
1595 (id) => this.idOfSeq(seqOf(id)),
1596 (author) => {
1597 if (this.#storage) return author;
1598 let a = this.#authors.get(author);
1599 if (a === undefined) this.#authors.set(author, (a = author));
1600 return a;
1601 },
1602 this.#texts ? this.#reader(seq) : undefined,
1603 this.#lists ? this.#listReader(seq) : undefined,
1604 );
1605 this.#atoms.push(this.#storage ? atom : frozen);
1606 this.#accepted++;
1607 let lam = 0;
1608 for (const d of deps) lam = Math.max(lam, this.lamport(d) + 1);
1609 if (this.#lamportPages) this.#lamportPages.push(lam);
1610 else this.#lamport.push(lam);
1612 // The run starts' parents and the deleted lines, as codes, before this atom's own lines exist.
1613 // The atom as given: with lists kept elsewhere, the frozen one reads them back from the log.
1614 const deletes = (line: LineId | NodeId): boolean => {
1615 if (isStartNode(line)) return false;
1616 if (deleted) return deleted.has(line);
1617 const n = this.#lineN(line);
1618 return this.#deleter.at(n) === seq || this.#moreDeleterPages!.last(String(n)) === seq;
1619 };
1620 const deletedN = this.#storage ? undefined : atom.deletes.map((line) => this.#lineN(line));
1621 this.#atomDeletes.push(deletedN?.length ? Int32Array.from(deletedN) : undefined);
1622 if (this.#storage) {
1623 const pages = storedLists<number>(this.#storage, "atom-deletes");
1624 for (const line of atom.deletes) pages.append(String(seq), this.#lineN(line));
1625 this.#storage.write("atom-delete-counts", String(seq), atom.deletes.length);
1626 }
1627 const deletedNumbers = function* (graph: Graph) {
1628 if (deletedN) yield* deletedN;
1629 else for (const line of atom.deletes) yield graph.#lineN(line);
1630 };
1631 const packedDeletes = new Map<number, PackedDelete[]>();
1632 for (const n of deletedNumbers(this)) {
1633 if (this.#packed) {
1634 const file = this.#lineFile.at(n);
1635 const list = packedDeletes.get(file);
1636 if (list) list.push([n, seq]);
1637 else packedDeletes.set(file, [[n, seq]]);
1638 }
1639 if (this.#deleter.at(n) < 0) this.#deleter.set(n, seq);
1640 else if (this.#moreDeleterPages) this.#moreDeleterPages.append(String(n), seq);
1641 else pushIndex(this.#moreDeleters, n, seq);
1642 }
1643 for (const [file, list] of packedDeletes) this.#fileDeletes!.appendAll(String(file), list);
1644 this.#lineBase.push(this.#lineTotal);
1645 for (const run of atom.inserts) {
1646 const file = this.#pathOf(run.file);
1647 let parent = isStartNode(run.parent) ? -1 - file : this.#lineN(run.parent);
1648 const first = this.#lineTotal;
1649 if (parent >= 0) this.#childCounts?.increment(parent, first);
1650 if (this.#storage)
1651 new OrderedIndex(this.#storage, "ordered-children", String(parent)).insert(
1652 orderedChildKey({
1653 n: first,
1654 replaces: deletes(run.parent) ? 1 : 0,
1655 lamport: lam,
1656 seq,
1657 k: first - this.#lineBase[seq]!,
1658 }),
1659 first,
1660 );
1662 if (this.#runStartPages) this.#runStartPages.append(String(parent), first);
1663 else pushOne(this.#runStarts, parent, first);
1664 const replacesParent = deletes(run.parent) ? 1 : 0;
1665 if (this.#packed) {
1666 if (this.#crossings && parent >= 0) {
1667 const from = this.#lineFile.at(parent);
1668 if (from !== file) this.#fileCrossings!.append(String(from), [parent, file]);
1669 }
1670 const base = this.#lineBase[seq]!;
1671 this.#fileLines!.appendAll(
1672 String(file),
1673 run.lines.map(
1674 (_, i): PackedLine => [
1675 first + i,
1676 i === 0 ? parent : first + i - 1,
1677 seq,
1678 first + i - base,
1679 i === 0 ? replacesParent : 0,
1680 ],
1681 ),
1682 );
1683 this.#fileTexts!.appendAll(
1684 String(file),
1685 run.lines.map((text) => (typeof text === "string" && text.length <= PACKED_TEXT ? text : null)),
1686 );
1687 }
1688 for (let i = 0; i < run.lines.length; i++) {
1689 const n = this.#lineTotal;
1690 this.#childCounts?.append(n);
1691 this.#lineAtom.push(seq);
1692 this.#lineFile.push(file);
1693 this.#lineParent.push(parent);
1694 this.#lineText?.push(run.lines[i]!);
1695 this.#deleter.push(-1);
1696 this.#replacing.push(i === 0 && deletes(run.parent) ? 1 : 0);
1697 parent = n;
1698 }
1699 }
1700 (frozen.moves ?? []).forEach((m, i) => {
1701 const info: RelocationInfo = Object.freeze({ atom: frozen.id, line: m.line, parent: m.parent, k: i });
1702 if (this.#relocationPages) this.#relocationPages.append(m.line, info);
1703 else pushIndex(this.#relocations, m.line, info);
1704 if (this.#relocatedToPages) this.#relocatedToPages.append(m.parent, info);
1705 else pushIndex(this.#relocatedTo, m.parent, info);
1706 const parentCode = isStartNode(m.parent) ? -1 - this.#pathOf(m.parent.slice(1)) : this.#lineN(m.parent);
1707 if (this.#relocatedToCodePages) this.#relocatedToCodePages.append(String(parentCode), info);
1708 else pushIndex(this.#relocatedToCode, parentCode, info);
1709 });
1710 if (frozen.moves) this.#movers.push(frozen.id);
1711 if (this.#packed)
1712 for (const a of frozen.attrs ?? []) this.#fileAttrs!.append(String(this.#pathOf(a.file)), [seq, a.name, a.value]);
1713 for (const key of writes) {
1714 const code = this.#code(key);
1715 if (this.#writersPages) {
1716 const key = JSON.stringify([typeof code, code]);
1717 if (this.#writersPages.last(key) !== frozen.id) this.#writersPages.append(key, frozen.id);
1718 } else pushOne(this.#writers, code, frozen.id);
1719 }
1720 for (const key of this.#storage ? atom.reads : new Set(atom.reads)) {
1721 const code = this.#code(key);
1722 if (this.#readersPages) {
1723 const key = JSON.stringify([typeof code, code]);
1724 if (this.#readersPages.last(key) !== frozen.id) this.#readersPages.append(key, frozen.id);
1725 } else pushOne(this.#readers, code, frozen.id);
1726 }
1727 for (const key of this.#storage ? atom.holds : new Set(atom.holds)) {
1728 const code = this.#code(key);
1729 if (this.#holdersPages) {
1730 const key = JSON.stringify([typeof code, code]);
1731 if (this.#holdersPages.last(key) !== frozen.id) this.#holdersPages.append(key, frozen.id);
1732 } else pushOne(this.#holders, code, frozen.id);
1733 }
1734 for (const d of deps) {
1735 if (this.#dependentsPages) this.#dependentsPages.append(d, frozen.id);
1736 else pushOne(this.#dependents, d, frozen.id);
1737 }
1738 for (const r of this.#storage ? frozen.resolves : new Set(frozen.resolves)) {
1739 if (this.#resolversPages) {
1740 if (this.#resolversPages.last(r) !== frozen.id) this.#resolversPages.append(r, frozen.id);
1741 } else pushOne(this.#resolvers, r, frozen.id);
1742 }
1743 const files = new Set<string>();
1744 for (const run of atom.inserts) files.add(run.file);
1745 for (const n of deletedNumbers(this)) files.add(this.#pathName(this.#lineFile.at(n)));
1746 for (const a of frozen.attrs ?? []) files.add(a.file);
1747 for (const m of frozen.moves ?? []) {
1748 files.add(this.lineFile(m.line)!);
1749 files.add(isStartNode(m.parent) ? m.parent.slice(1) : this.lineFile(m.parent)!);
1750 }
1751 this.#atomFiles.push(Object.freeze([...files].sort()));
1752 for (const file of files) {
1753 if (this.#fileAtomPages) this.#fileAtomPages.append(file, frozen.id);
1754 else pushIndex(this.#fileAtoms, file, frozen.id);
1755 }
1756 if (this.#reasonsInKept) {
1757 const pointed = new Set<AtomId>();
1758 for (const r of frozen.reasons) {
1759 if (pointed.has(r.to)) continue;
1760 pointed.add(r.to);
1761 if (this.#reasonsInPages) this.#reasonsInPages.append(r.to, frozen.id);
1762 else pushIndex(this.#reasonsIn, r.to, frozen.id);
1763 }
1764 }
1765 for (const r of frozen.reasons) {
1766 if (r.kind !== "together" || r.to === frozen.id) continue;
1768 const forward = { other: r.to, text: r.text, from: frozen.id };
1769 const reverse = { other: frozen.id, text: r.text, from: frozen.id };
1770 if (this.#togetherPages) {
1771 this.#togetherPages.append(frozen.id, forward);
1772 this.#togetherPages.append(r.to, reverse);
1773 } else {
1774 pushIndex(this.#together, frozen.id, forward);
1775 pushIndex(this.#together, r.to, reverse);
1776 }
1777 }
1778 }
1780 // Labels -----------------------------------------------------------------
1782 /**
1783 * Add or replace a label. Label names may not look like atom ids. A base is
1784 * resolved to its head only when it is used, never followed further, so
1785 * bases may name each other in any shape.
1786 */
1787 setLabel(label: Label): void {
1788 this.#putLabel(label, (name) => this.#labels.has(name));
1789 }
1791 #putLabel(label: Label, isLabel: (name: string) => boolean): void {
1792 const bad = (why: string): never => {
1793 throw new EngineError("bad-label", `label ${JSON.stringify(label?.name)}: ${why}`);
1794 };
1795 if (typeof label !== "object" || label === null) bad("not an object");
1796 if (typeof label.name !== "string" || label.name === "") bad("needs a name");
1797 if (isAtomId(label.name)) bad("a label name may not look like an atom id");
1798 if (!this.has(label.head)) bad(`head ${label.head} is not in the graph`);
1799 if (
1800 label.base !== undefined &&
1801 !(typeof label.base === "string" && (isLabel(label.base) || this.has(label.base)))
1802 ) {
1803 bad(`base ${label.base} is neither a label nor an atom`);
1804 }
1805 if (label.base === label.name) bad("a label cannot be its own base");
1806 if (typeof label.title !== "string" || typeof label.message !== "string") bad("needs a title and message");
1807 if (label.follows !== undefined && !Array.isArray(label.follows)) bad("follows must be a list of label names");
1808 const copy: Label = {
1809 name: label.name,
1810 head: label.head,
1811 ...(label.base !== undefined ? { base: label.base } : {}),
1812 title: label.title,
1813 message: label.message,
1814 ...(label.follows !== undefined ? { follows: Object.freeze([...label.follows]) } : {}),
1815 };
1816 this.#labels.set(label.name, Object.freeze(copy));
1817 }
1819 label(name: string): Label | undefined {
1820 return this.#labels.get(name);
1821 }
1823 /** Labels sorted by name. */
1824 labels(): Label[] {
1825 return [...this.#labels.values()].sort((a, b) => (a.name < b.name ? -1 : a.name > b.name ? 1 : 0));
1826 }
1828 /**
1829 * Remove a label. Labels that used it as their base get its head atom as
1830 * their base instead, so their contents don't change.
1831 */
1832 removeLabel(name: string): boolean {
1833 return this.#storage ? this.#storage.transaction(() => this.#removeLabel(name)) : this.#removeLabel(name);
1834 }
1836 #removeLabel(name: string): boolean {
1837 const gone = this.#labels.get(name);
1838 if (!gone) return false;
1839 this.#labels.delete(name);
1840 for (const label of [...this.#labels.values()]) {
1841 if (label.base === name) this.#labels.set(label.name, Object.freeze({ ...label, base: gone.head }));
1842 }
1843 return true;
1844 }
1846 // JSON -------------------------------------------------------------------
1848 toJSON(): GraphJSON {
1849 return { format: GRAPH_FORMAT, version: 1, atoms: this.#atoms, labels: this.labels() };
1850 }
1852 /** Load a saved graph. Every atom is re-validated as it is added. */
1853 static fromJSON(data: unknown): Graph {
1854 const bad = (why: string): never => {
1855 throw new EngineError("bad-json", why);
1856 };
1857 if (typeof data !== "object" || data === null) bad("graph JSON must be an object");
1858 const obj = data as Partial<GraphJSON>;
1859 if (obj.format !== GRAPH_FORMAT) bad(`format must be ${GRAPH_FORMAT}`);
1860 if (obj.version !== 1) bad(`unsupported version ${String(obj.version)}`);
1861 if (!Array.isArray(obj.atoms) || !Array.isArray(obj.labels)) bad("atoms and labels must be arrays");
1862 const graph = new Graph();
1863 for (const atom of obj.atoms!) graph.add(atom);
1864 // Labels may name each other as bases, in any order and any shape.
1865 const names = new Set<string>();
1866 for (const label of obj.labels!) {
1867 const name: unknown = (label as Partial<Label> | null)?.name;
1868 if (typeof name !== "string") return bad("every label needs a name");
1869 if (names.has(name)) bad(`label ${name} appears twice`);
1870 names.add(name);
1871 }
1872 for (const label of obj.labels!) {
1873 try {
1874 graph.#putLabel(label, (name) => names.has(name));
1875 } catch (err) {
1876 if (err instanceof EngineError) bad(err.message);
1877 throw err;
1878 }
1879 }
1880 return graph;
1881 }
1883 #seq(id: AtomId): number {
1884 return typeof id === "string" ? seqOf(id) : -1;
1885 }
1886}
1888function validateShape(atom: Atom): void {
1889 const bad = (why: string): never => {
1890 throw new EngineError("bad-atom", `atom ${String((atom as { id?: unknown }).id)}: ${why}`);
1891 };
1892 if (typeof atom !== "object" || atom === null) bad("not an object");
1893 if (typeof atom.id !== "string" || !Number.isInteger(atom.seq)) bad("needs id and seq");
1894 if (typeof atom.author !== "string" || typeof atom.message !== "string") bad("needs author and message");
1895 if (typeof atom.time !== "number" || !Number.isFinite(atom.time)) bad("time must be a finite number");
1896 const lists = ["inserts", "deletes", "writes", "reads", "holds", "needs", "resolves", "reasons", "deps"] as const;
1897 for (const name of lists) if (!Array.isArray(atom[name])) bad(`${name} must be an array`);
1898 for (const run of atom.inserts as readonly InsertRun[]) {
1899 if (typeof run.file !== "string" || run.file === "" || run.file.includes("\n")) bad("a run needs a file path");
1900 if (typeof run.parent !== "string") bad("a run needs a parent");
1901 if (!Array.isArray(run.lines) || run.lines.length === 0) bad("a run needs at least one line");
1902 for (const text of run.lines) {
1903 if (typeof text !== "string" || text.includes("\n") || text.includes("\r"))
1904 bad("run lines must be strings without line breaks");
1905 }
1906 }
1907 if (atom.attrs !== undefined) {
1908 if (!Array.isArray(atom.attrs)) bad("attrs must be an array");
1909 for (const a of atom.attrs) {
1910 if (typeof a?.file !== "string" || a.file === "" || a.file.includes("\n") || !ATTR_NAMES.includes(a.name))
1911 bad("an attr needs a file and a name");
1912 if (a.value !== null && typeof a.value !== "string") bad("an attr value is a string or null");
1913 if (!atom.writes.includes(attrKey(a.file, a.name))) bad(`sets ${a.name} of ${a.file} without writing its key`);
1914 }
1915 }
1916 if (atom.moves !== undefined) {
1917 if (!Array.isArray(atom.moves) || atom.moves.length === 0) bad("moves must be a non-empty array");
1918 for (const m of atom.moves) {
1919 if (typeof m?.line !== "string" || typeof m.parent !== "string") bad("a move needs a line and a parent");
1920 }
1921 }
1922 for (const name of ["deletes", "writes", "reads", "holds", "needs", "resolves", "deps"] as const) {
1923 for (const x of atom[name]) if (typeof x !== "string") bad(`${name} must hold strings`);
1924 }
1925 for (const r of atom.reasons as readonly Reason[]) {
1926 if (typeof r.to !== "string" || typeof r.text !== "string" || !REASON_KINDS.includes(r.kind)) {
1927 bad("a reason needs to, kind (together, because-of or supersedes) and text");
1928 }
1929 }
1930}
1932/**
1933 * A frozen copy of an atom. An empty list is one shared frozen list, and atom
1934 * ids and authors are the graph's own strings (`canon`, `author`), so each is
1935 * kept once however often it's named (#46).
1936 */
1937function freezeAtom(
1938 atom: Atom,
1939 canon: (id: AtomId) => AtomId,
1940 author: (name: string) => string,
1941 text?: (start: number, length: number) => readonly string[],
1942 lists?: () => AtomLists,
1943): Atom {
1944 const list = <T>(xs: readonly T[], f?: (x: T) => T): readonly T[] =>
1945 xs.length === 0 ? EMPTY : Object.freeze(f ? xs.map(f) : [...xs]);
1946 // With text kept elsewhere (#46), a run's lines are read when asked for.
1947 let k = 0;
1948 const run = (r: InsertRun): InsertRun => {
1949 if (!text) return Object.freeze({ file: r.file, parent: r.parent, lines: Object.freeze([...r.lines]) });
1950 const start = k;
1951 const length = r.lines.length;
1952 k += length;
1953 return Object.freeze(new LazyRun(r.file, r.parent, text, start, length));
1954 };
1955 const copy: Atom = {
1956 id: atom.id,
1957 seq: atom.seq,
1958 author: author(atom.author),
1959 message: atom.message,
1960 time: atom.time,
1961 inserts: Object.freeze(atom.inserts.map(run)),
1962 ...(lists
1963 ? {}
1964 : { deletes: list(atom.deletes), writes: list(atom.writes), reads: list(atom.reads), holds: list(atom.holds) }),
1965 needs: list(atom.needs, canon),
1966 resolves: list(atom.resolves, canon),
1967 reasons: list(atom.reasons, (r) => Object.freeze({ to: canon(r.to), kind: r.kind, text: r.text })),
1968 deps: list(atom.deps, canon),
1969 ...(atom.attrs && atom.attrs.length > 0
1970 ? { attrs: Object.freeze(atom.attrs.map((a) => Object.freeze({ file: a.file, name: a.name, value: a.value }))) }
1971 : {}),
1972 ...(atom.moves
1973 ? { moves: Object.freeze(atom.moves.map((m) => Object.freeze({ line: m.line, parent: m.parent }))) }
1974 : {}),
1975 } as Atom;
1976 return Object.freeze(lists ? (new ListedAtom(copy, lists) as unknown as Atom) : copy);
1977}