- 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=221&format=json
1,868 linesFirst import 53% · codex-capacity-chair 39% · capacity 8%Last change capacity in version 221, 27 versions changed it
You're reading version 221. The newest is 318, and 8 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}
259/** A line in its file's packed history: [n, parent code, writer seq, k, 1 when it replaces its parent]. */
260export type PackedLine = [number, number, number, number, number];
261/** A delete of a line in a file's packed history: [n, deleter seq]. */
262export type PackedDelete = [number, number];
263/** An attribute set on a file: [seq, name, value]. */
264export type PackedAttr = [number, string, string | null];
265/** A run written in another file under one of a file's lines: [the parent's n, the run's file index]. */
266export type PackedCrossing = [number, number];
267const EMPTY_NUMBERS: readonly number[] = Object.freeze([]);
268/** Lines longer than this aren't packed with their file; their text is read on its own. */
269const PACKED_TEXT = 4096;
271export class Graph {
272 readonly #storage?: GraphStateStorage;
273 readonly #childCounts?: ChildCounts;
274 #atoms: Atom[] = [];
275 #lamport: number[] = [];
276 // Lines, packed (#46): line n is the k-th line atom seq wrote, n = #lineBase[seq] + k. Each holds its
277 // atom's seq, the file it was written in (an index into #paths) and its parent (a line's n, or -1 - a
278 // path's index for a file's start). Its text stays in the atom. Ids and LineInfo objects are made only
279 // when asked for, so a line costs about 16 bytes here instead of a record, its id and its parent's id.
280 #lineBase: number[] = [];
281 #lineAtom: NumberIndex = new Ints();
282 #lineFile: NumberIndex = new Ints();
283 #lineParent: NumberIndex = new Ints();
284 /** Lines' text, when the graph keeps it; without it, it comes from `texts` (#46, text on disk). */
285 #lineText: string[] | undefined = [];
286 get #lineTotal(): number {
287 return this.#lineAtom.length;
288 }
289 /** Where an atom's lines' text is when the graph doesn't keep it: each run's lines, by the atom's seq. */
290 #texts: ((seq: number) => readonly (readonly string[])[]) | undefined;
291 /** Recently read atoms' text, flattened, most recent last, up to TEXT_CACHE characters. */
292 #textCache = new Map<number, readonly string[]>();
293 #textCached = 0;
295 readonly #indexAcceptedAtom?: (atom: Atom, files: readonly string[], storage: GraphStateStorage) => void;
297 /**
298 * `texts`, when given, says where each atom's lines' text can be read back
299 * (#46): the graph then keeps no text, only each line's place, and reads an
300 * atom's text when a line of it is asked for, keeping the most recent.
301 */
302 constructor(
303 options: {
304 texts?: (seq: number) => readonly (readonly string[])[];
305 lists?: (seq: number) => AtomLists;
306 storage?: GraphStateStorage;
307 /** Optional derived indexing inside persistent atom acceptance; must be synchronous. */
308 indexAcceptedAtom?: (atom: Atom, files: readonly string[], storage: GraphStateStorage) => void;
309 /** false: a new stored graph keeps no packed file history, and lays files out line by line (tests of that path). */
310 packFiles?: boolean;
311 } = {},
312 ) {
313 if (options.indexAcceptedAtom && !options.storage)
314 throw Error("accepted atom indexing requires persistent storage");
315 this.#indexAcceptedAtom = options.indexAcceptedAtom;
316 if (options.texts) {
317 this.#texts = options.texts;
318 this.#lineText = undefined;
319 }
320 if (options.lists) this.#lists = options.lists;
321 this.#storage = options.storage;
322 if (options.storage) this.#childCounts = new ChildCounts(options.storage);
323 if (options.storage) {
324 const storage = options.storage;
325 const numbers = (name: string): NumberIndex => storedNumbers(storage, name);
326 const atomText = new StoredText(storage, "atom-text:long");
327 type TextReference = { text: string };
328 const listFields = [
329 "deletes",
330 "writes",
331 "reads",
332 "holds",
333 "needs",
334 "resolves",
335 "deps",
336 "reasons",
337 "attrs",
338 "moves",
339 ] as const;
340 type EncodedAtom = {
341 insertionFormat?: 1;
342 insertionRuns?: string;
343 textFormat?: 1;
344 listFormat?: 1;
345 listCount?: number;
346 lists?: Partial<Record<(typeof listFields)[number], string>>;
347 atom: Atom;
348 };
349 this.#atoms = storedArray<Atom>(
350 storage,
351 "atoms",
352 (value) => {
353 const encoded = value as unknown as Partial<EncodedAtom>;
354 if (encoded.textFormat !== undefined && encoded.textFormat !== 1)
355 throw Error("invalid stored atom text format");
356 if (encoded.listFormat !== undefined && encoded.listFormat !== 1)
357 throw Error("invalid stored atom list format");
358 if (encoded.listFormat === 1) {
359 if (
360 !encoded.lists ||
361 typeof encoded.lists !== "object" ||
362 Array.isArray(encoded.lists) ||
363 !Number.isSafeInteger(encoded.listCount) ||
364 encoded.listCount! < 1 ||
365 Object.keys(encoded.lists).length !== encoded.listCount ||
366 Object.keys(encoded.lists).some((field) => !listFields.includes(field as (typeof listFields)[number]))
367 )
368 throw Error("invalid stored atom list references");
369 }
370 if (encoded.insertionFormat !== undefined && encoded.insertionFormat !== 1)
371 throw Error("invalid stored insertion format");
372 const atom =
373 encoded.textFormat === 1 || encoded.listFormat === 1 || encoded.insertionFormat === 1
374 ? encoded.atom!
375 : value;
376 if (encoded.insertionFormat === 1 && (!Array.isArray(atom.inserts) || atom.inserts.length !== 0))
377 throw Error("invalid stored insertion placeholder");
378 const text =
379 encoded.textFormat === 1
380 ? (start: number, length: number): readonly string[] => {
381 const result: string[] = [];
382 let index = 0;
383 for (const run of atom.inserts)
384 for (const raw of run.lines) {
385 if (index >= start && index < start + length) {
386 const reference = raw as unknown as TextReference;
387 if (typeof raw === "string") result.push(raw);
388 else if (reference && reference.text === JSON.stringify([String(atom.seq), index]))
389 result.push(atomText.read(reference.text));
390 else throw Error("invalid stored atom text reference");
391 }
392 if (++index >= start + length) return result;
393 }
394 throw Error("stored atom text range missing");
395 }
396 : undefined;
397 // Sequential reads advance once per run without retaining a history-sized offset array.
398 let offsetRun = 0;
399 let offsetLine = 0;
400 const insertionStart = (index: number): number => {
401 if (index < offsetRun) {
402 offsetRun = 0;
403 offsetLine = 0;
404 }
405 while (offsetRun < index) {
406 offsetLine += readonlyStoredArray(storage, `atom-inserts:${atom.seq}:lines:${offsetRun}`).length;
407 offsetRun++;
408 }
409 return offsetLine;
410 };
411 const streamed = (target: Atom): Atom => {
412 registerJsonChunkValue(target, () => {
413 const line = (raw: unknown, index: number): unknown => {
414 if (typeof raw === "string") return raw;
415 const reference = raw as TextReference;
416 if (!reference || reference.text !== JSON.stringify([String(atom.seq), index]))
417 throw Error("invalid stored atom text reference");
418 return new JsonStringChunks(() => atomText.chunks(reference.text));
419 };
420 let inserts: readonly unknown[];
421 if (encoded.insertionFormat === 1) {
422 const collection = `atom-inserts:${atom.seq}`;
423 inserts = readonlyStoredArray(storage, collection, (raw, index) => {
424 const run = raw as { file: string; parent: string; lines: string };
425 const lines = `${collection}:lines:${index}`;
426 if (run.lines !== lines || typeof run.file !== "string" || typeof run.parent !== "string")
427 throw Error("invalid stored insertion run");
428 const start = insertionStart(index);
429 return {
430 file: run.file,
431 parent: run.parent,
432 lines: readonlyStoredArray(storage, lines, (raw, i) => line(raw, start + i)),
433 };
434 });
435 } else {
436 let index = 0;
437 inserts = atom.inserts.map((run) => ({
438 file: run.file,
439 parent: run.parent,
440 lines: run.lines.map((raw) => line(raw, index++)),
441 }));
442 }
443 return { ...target, inserts };
444 });
445 return target;
446 };
447 const frozen = freezeAtom(
448 atom,
449 (id) => id,
450 (author) => author,
451 text,
452 );
453 if (encoded.listFormat !== 1 && encoded.insertionFormat !== 1) return streamed(frozen);
454 const result = { ...frozen };
455 if (encoded.insertionFormat === 1) {
456 const collection = `atom-inserts:${atom.seq}`;
457 if (encoded.insertionRuns !== collection) throw Error("invalid stored insertion reference");
458 const inserts = readonlyStoredArray<InsertRun>(storage, collection, (raw, index) => {
459 const run = raw as { file: string; parent: InsertRun["parent"]; lines: string };
460 const lines = `${collection}:lines:${index}`;
461 if (run.lines !== lines || typeof run.file !== "string" || typeof run.parent !== "string")
462 throw Error("invalid stored insertion run");
463 return Object.freeze({
464 file: run.file,
465 parent: run.parent,
466 lines: readonlyStoredArray<string>(storage, lines, (rawLine, lineIndex) => {
467 if (typeof rawLine === "string") return rawLine;
468 const ref = rawLine as TextReference;
469 const atomLine = insertionStart(index) + lineIndex;
470 if (!ref || ref.text !== JSON.stringify([String(atom.seq), atomLine]))
471 throw Error("invalid stored insertion text");
472 return atomText.read(ref.text);
473 }),
474 });
475 });
476 Object.defineProperty(result, "inserts", { value: inserts, enumerable: true });
477 }
478 for (const field of listFields) {
479 const collection = encoded.lists?.[field];
480 if (collection === undefined) continue;
481 if (typeof collection !== "string" || collection !== `atom-list:${atom.seq}:${field}`)
482 throw Error("invalid stored atom list reference");
483 Object.defineProperty(result, field, { value: readonlyStoredArray(storage, collection), enumerable: true });
484 }
485 return streamed(Object.freeze(result));
486 },
487 (input, key) => {
488 const atom = { ...input };
489 const lists: Partial<Record<(typeof listFields)[number], string>> = {};
490 for (const field of listFields) {
491 const values = input[field];
492 if (!values || values.length <= 256) continue;
493 const collection = `atom-list:${input.seq}:${field}`;
494 const saved = storedArray<unknown>(storage, collection);
495 for (const value of values) saved.push(value);
496 lists[field] = collection;
497 Object.defineProperty(atom, field, { value: [], enumerable: true });
498 }
499 const listCount = Object.keys(lists).length;
500 const hasLists = listCount > 0;
501 let insertionCharacters = 0;
502 if (
503 atom.inserts.length > 256 ||
504 atom.inserts.some((run) => run.lines.length > 256) ||
505 atom.inserts.some((run) => run.lines.some((line) => (insertionCharacters += line.length) > 65536))
506 ) {
507 const collection = `atom-inserts:${input.seq}`;
508 const runs = storedArray<unknown>(storage, collection);
509 let runIndex = 0;
510 let lineIndex = 0;
511 for (const run of atom.inserts) {
512 const lineCollection = `${collection}:lines:${runIndex++}`;
513 const lines = storedArray<unknown>(storage, lineCollection);
514 for (const line of run.lines) {
515 const text = JSON.stringify([key, lineIndex++]);
516 if (line.length > StoredText.chunkCharacters) {
517 atomText.write(text, line);
518 lines.push({ text });
519 } else lines.push(line);
520 }
521 runs.push({ file: run.file, parent: run.parent, lines: lineCollection });
522 }
523 return {
524 insertionFormat: 1,
525 insertionRuns: collection,
526 ...(hasLists ? { listFormat: 1, listCount, lists } : {}),
527 atom: { ...atom, inserts: [] },
528 };
529 }
530 if (!atom.inserts.some((run) => run.lines.some((line) => line.length > StoredText.chunkCharacters)))
531 return hasLists ? { listFormat: 1, listCount, lists, atom } : atom;
532 let index = 0;
533 const inserts = atom.inserts.map((run) => ({
534 ...run,
535 lines: run.lines.map((line) => {
536 const text = JSON.stringify([key, index++]);
537 if (line.length <= StoredText.chunkCharacters) return line;
538 atomText.write(text, line);
539 return { text };
540 }),
541 }));
542 return {
543 textFormat: 1,
544 ...(hasLists ? { listFormat: 1, listCount, lists } : {}),
545 atom: { ...atom, inserts },
546 };
547 },
548 );
549 this.#lamport = storedArray(storage, "lamport");
550 this.#lineBase = storedArray(storage, "line-base");
551 this.#paths = storedArray(storage, "paths");
552 this.#movers = storedArray(storage, "movers");
553 this.#atomFiles = storedArray(storage, "atom-files");
554 this.#atomDeletes = storedArray(storage, "atom-deletes");
555 this.#lineAtom = numbers("line-atom");
556 this.#lineFile = numbers("line-file");
557 this.#lineParent = numbers("line-parent");
558 this.#deleter = numbers("deleter");
559 this.#replacing = numbers("replacing");
560 const longText = atomText;
561 this.#lineText = storedArray<string>(
562 storage,
563 "line-text",
564 (value) => {
565 if (typeof value === "string") return value;
566 const reference = value as unknown as { format: number; text: string };
567 if (reference?.format !== 1 || typeof reference.text !== "string") throw Error("invalid long line reference");
568 return longText.read(reference.text);
569 },
570 (value, key) => {
571 if (value.length <= StoredText.chunkCharacters) return value;
572 const number = Number(key);
573 const seq = this.#lineAtom.at(number);
574 const text = JSON.stringify([String(seq), number - this.#lineBase[seq]!]);
575 const header = storage.read("atom-text:long", text) as { characters?: number } | undefined;
576 if (header?.characters !== value.length) throw Error("long line atom text is missing");
577 return { format: 1, text };
578 },
579 );
580 this.#pathIndex = storedMap(storage, "path-index");
581 this.#moreDeleterPages = storedLists<number>(storage, "more-deleters", (key) =>
582 JSON.stringify(["number", Number(key)]),
583 );
584 this.#writersPages = storedLists<AtomId>(storage, "writers", (key) => key);
585 this.#readersPages = storedLists<AtomId>(storage, "readers", (key) => key);
586 this.#holdersPages = storedLists<AtomId>(storage, "holders", (key) => key);
587 this.#dependentsPages = storedLists<AtomId>(storage, "dependents");
588 this.#resolversPages = storedLists<AtomId>(storage, "resolvers");
589 this.#togetherPages = storedLists<TogetherLink>(storage, "together");
590 this.#fileAtomPages = storedLists<AtomId>(storage, "file-atoms");
591 this.#runStartPages = storedLists<number>(storage, "run-starts", (key) =>
592 JSON.stringify(["number", Number(key)]),
593 );
594 this.#relocationPages = storedLists<RelocationInfo>(storage, "relocations");
595 this.#relocatedToPages = storedLists<RelocationInfo>(storage, "relocated-to");
596 this.#relocatedToCodePages = storedLists<RelocationInfo>(storage, "relocated-to-code", (key) =>
597 JSON.stringify(["number", Number(key)]),
598 );
599 this.#labels = storedMap(storage, "labels");
600 this.#fileLines = storedLists<PackedLine>(storage, "file-lines");
601 this.#fileTexts = storedLists<string | null>(storage, "file-texts");
602 this.#fileDeletes = storedLists<PackedDelete>(storage, "file-deletes");
603 this.#fileAttrs = storedLists<PackedAttr>(storage, "file-attrs");
604 this.#fileCrossings = storedLists<PackedCrossing>(storage, "file-crossings");
605 this.#packFiles = options.packFiles ?? true;
606 }
607 }
609 // Each file's line history packed, in pages (abso Capacity) ---------------------------------------------------
610 // For each file, by its path index: every line written in it ([n, parent code, writer seq, k, replaces]) and its
611 // text, every delete of one of those lines ([n, deleter seq]), every attribute set on it ([seq, name, value]), and
612 // every run written in another file under one of its lines ([parent n, the run's file]): a line follows its parent,
613 // so a run written while its parent was moved elsewhere lays out wherever the parent is.
614 // 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
615 // a fresh adoption on; a graph adopted before has none, and views lay out as before.
617 #fileLines: ReturnType<typeof storedLists<PackedLine>> | undefined;
618 #fileTexts: ReturnType<typeof storedLists<string | null>> | undefined;
619 #fileDeletes: ReturnType<typeof storedLists<PackedDelete>> | undefined;
620 #fileAttrs: ReturnType<typeof storedLists<PackedAttr>> | undefined;
621 #fileCrossings: ReturnType<typeof storedLists<PackedCrossing>> | undefined;
622 /** Whether a new stored graph starts packing (GraphOptions.packFiles). */
623 #packFiles = true;
624 /**
625 * How this graph's files are packed, read once when first asked so opening reads nothing: 0 not at all, 1 lines,
626 * deletes and attributes, 2 the runs written across files as well.
627 */
628 #formatKnown: number | undefined;
629 get #format(): number {
630 if (this.#formatKnown === undefined) {
631 const format = this.#storage?.read("file-lines:meta", "format");
632 this.#formatKnown = format === 1 || format === 2 ? format : 0;
633 }
634 return this.#formatKnown;
635 }
636 get #packed(): boolean {
637 return this.#format >= 1;
638 }
639 get #crossings(): boolean {
640 return this.#format >= 2;
641 }
643 /** Whether this graph keeps each file's line history packed. */
644 get packedFiles(): boolean {
645 return this.#packed;
646 }
647 /**
648 * Whether a file can be laid out from packed history alone: it also keeps the runs written across files. A graph
649 * packed before those were kept lays files out line by line.
650 */
651 get packedLayout(): boolean {
652 return this.#crossings;
653 }
654 /** A path's index, or undefined when nothing was ever written or set in it. */
655 pathIndexOf(path: string): number | undefined {
656 return this.#pathIndex.get(path);
657 }
658 /** The index of the path line n was written in. */
659 writtenInIndex(n: number): number {
660 return this.#lineFile.at(n);
661 }
662 *packedLines(file: number): IterableIterator<PackedLine> {
663 yield* this.#fileLines!.values(String(file));
664 }
665 *packedTexts(file: number): IterableIterator<string | null> {
666 yield* this.#fileTexts!.values(String(file));
667 }
668 *packedDeletes(file: number): IterableIterator<PackedDelete> {
669 yield* this.#fileDeletes!.values(String(file));
670 }
671 *packedAttrs(file: number): IterableIterator<PackedAttr> {
672 yield* this.#fileAttrs!.values(String(file));
673 }
674 *packedCrossings(file: number): IterableIterator<PackedCrossing> {
675 yield* this.#fileCrossings!.values(String(file));
676 }
678 /** Where an atom's key and delete lists are when the graph doesn't keep them (#46): the stored atom. */
679 #lists: ((seq: number) => AtomLists) | undefined;
680 /** Recently read atoms' lists, most recent last, up to LIST_CACHE atoms. */
681 #listCache = new Map<number, AtomLists>();
682 #listCached = 0;
684 /** An atom's deletes, writes, reads and holds, read back from where they are stored. */
685 #listsOf(seq: number): AtomLists {
686 const hit = this.#listCache.get(seq);
687 if (hit) {
688 this.#listCache.delete(seq);
689 this.#listCache.set(seq, hit);
690 return hit;
691 }
692 const got = this.#lists!(seq);
693 const lists: AtomLists = {
694 deletes: frozenList(got.deletes),
695 writes: frozenList(got.writes),
696 reads: frozenList(got.reads),
697 holds: frozenList(got.holds),
698 };
699 this.#listCache.set(seq, lists);
700 this.#listCached += listItems(lists);
701 for (const [old, kept] of this.#listCache) {
702 if (this.#listCached <= LIST_CACHE || old === seq) break;
703 this.#listCache.delete(old);
704 this.#listCached -= listItems(kept);
705 }
706 return lists;
707 }
709 /** The reader an atom's lists use; made apart from add() so it keeps no atom alive (see #reader). */
710 #listReader(seq: number): () => AtomLists {
711 return () => this.#listsOf(seq);
712 }
714 /**
715 * 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
716 * index holds numbers rather than one string per line; start-node and attribute keys stay strings. A key
717 * naming a line the graph doesn't have stays a string, which nothing has claimed.
718 */
719 #code(key: Key): Key | number {
720 const t = key.charCodeAt(0);
721 if (key.charCodeAt(1) !== 58 || key.charCodeAt(2) === 94) return key; // not "X:", or a start node "^"
722 const k = t === 76 ? 0 : t === 80 ? 1 : t === 71 ? 2 : -1; // L, P, G
723 if (k < 0) return key;
724 const n = this.#lineN(key.slice(2));
725 return n < 0 ? key : n * 4 + k;
726 }
728 /** An atom's lines' text, in k order. */
729 #textOf(seq: number): readonly string[] {
730 const hit = this.#textCache.get(seq);
731 if (hit) {
732 this.#textCache.delete(seq);
733 this.#textCache.set(seq, hit);
734 return hit;
735 }
736 const flat = this.#texts!(seq).flat();
737 let chars = 0;
738 for (const t of flat) chars += t.length + 1;
739 this.#textCache.set(seq, flat);
740 this.#textCached += chars;
741 for (const [old, lines] of this.#textCache) {
742 if (this.#textCached <= TEXT_CACHE || old === seq) break;
743 this.#textCache.delete(old);
744 for (const t of lines) this.#textCached -= t.length + 1;
745 }
746 return flat;
747 }
749 /**
750 * The reader an atom's runs use. Made in a function of its own: a closure made inside add() would
751 * keep add()'s whole scope alive, the atom as given with all its text included.
752 */
753 #reader(seq: number): (start: number, length: number) => readonly string[] {
754 return (start, length) => this.#textOf(seq).slice(start, start + length);
755 }
757 /** Line n's text. */
758 #text(n: number): string {
759 if (this.#lineText) return this.#lineText[n]!;
760 const seq = this.#lineAtom.at(n);
761 return this.#textOf(seq)[n - this.#lineBase[seq]!]!;
762 }
763 #paths: string[] = [];
764 #pathIndex: StateMap<string, number> = new Map();
765 /** The first atom that deletes each line (its seq), or -1; a line deleted by more than one has the rest in #moreDeleters. */
766 #deleter: NumberIndex = new Ints();
767 #moreDeleters: StateMap<number, number[]> = new Map();
768 #moreDeleterPages: ReturnType<typeof storedLists<number>> | undefined;
769 #writers: StateMap<Key | number, AtomId | AtomId[]> = new Map();
770 #writersPages: ReturnType<typeof storedLists<AtomId>> | undefined;
771 #readers: StateMap<Key | number, AtomId | AtomId[]> = new Map();
772 #readersPages: ReturnType<typeof storedLists<AtomId>> | undefined;
773 #holders: StateMap<Key | number, AtomId | AtomId[]> = new Map();
774 #holdersPages: ReturnType<typeof storedLists<AtomId>> | undefined;
775 #dependents: StateMap<AtomId, AtomId | AtomId[]> = new Map();
776 #dependentsPages: ReturnType<typeof storedLists<AtomId>> | undefined;
777 #resolvers: StateMap<AtomId, AtomId | AtomId[]> = new Map();
778 #resolversPages: ReturnType<typeof storedLists<AtomId>> | undefined;
779 #together: StateMap<AtomId, TogetherLink[]> = new Map();
780 #togetherPages: ReturnType<typeof storedLists<TogetherLink>> | undefined;
781 #fileAtoms: StateMap<string, AtomId[]> = new Map();
782 #fileAtomPages: ReturnType<typeof storedLists<AtomId>> | undefined;
783 /** First lines of runs (their n), by the node they were written after: a line's n, or -1 - a path's index. */
784 #runStarts: StateMap<number, number | number[]> = new Map();
785 #runStartPages: ReturnType<typeof storedLists<number>> | undefined;
786 /** 1 for the first line of a run whose atom deleted the line it hangs off: the run replaces it. */
787 #replacing: NumberIndex = new Ints(true);
788 #relocations: StateMap<LineId, RelocationInfo[]> = new Map();
789 #relocationPages: ReturnType<typeof storedLists<RelocationInfo>> | undefined;
790 #relocatedTo: StateMap<NodeId, RelocationInfo[]> = new Map();
791 #relocatedToPages: ReturnType<typeof storedLists<RelocationInfo>> | undefined;
792 /** The same relocations by node code (a line's n, or -1 - a path's index), for views laid out by number. */
793 #relocatedToCode: StateMap<number, RelocationInfo[]> = new Map();
794 #relocatedToCodePages: ReturnType<typeof storedLists<RelocationInfo>> | undefined;
795 #movers: AtomId[] = [];
796 #atomFiles: (readonly string[])[] = [];
797 /** Each atom's deleted lines by n, packed (#46), or undefined when it deletes none. */
798 #atomDeletes: (readonly number[] | Int32Array | undefined)[] = [];
799 #labels: StateMap<string, Label> = new Map();
800 /** Each author's name kept once (#46). */
801 #authors = new Map<string, string>();
803 /** Number of atoms (also the seq the next atom gets). */
804 get size(): number {
805 return this.#atoms.length;
806 }
808 /** The id the next accepted atom must have. */
809 nextId(): AtomId {
810 return atomId(this.#atoms.length);
811 }
813 has(id: AtomId): boolean {
814 const seq = this.#seq(id);
815 return seq >= 0 && seq < this.#atoms.length;
816 }
818 atom(id: AtomId): Atom {
819 const seq = this.#seq(id);
820 const atom = seq >= 0 ? this.#atoms[seq] : undefined;
821 if (!atom) throw new EngineError("unknown-atom", `no atom ${id}`);
822 return atom;
823 }
825 /** All atoms in seq order. */
826 atoms(): readonly Atom[] {
827 return this.#atoms;
828 }
830 /** lamport(a) = 1 + max lamport of its deps; 0 for an atom with no deps (such as a0). */
831 lamport(id: AtomId): number {
832 if (!this.has(id)) throw new EngineError("unknown-atom", `no atom ${id}`);
833 return this.#lamport[this.#seq(id)]!;
834 }
836 /** Compare by priority (lamport, then seq). Negative when a comes first (is lower). */
837 comparePriority(a: AtomId, b: AtomId): number {
838 return this.lamport(a) - this.lamport(b) || this.#seq(a) - this.#seq(b);
839 }
841 line(id: LineId): LineInfo | undefined {
842 const n = this.#lineN(id);
843 if (n < 0) return undefined;
844 const seq = this.#lineAtom.at(n);
845 return {
846 id,
847 atom: this.idOfSeq(seq),
848 k: n - this.#lineBase[seq]!,
849 file: this.#paths[this.#lineFile.at(n)]!,
850 parent: this.#nodeName(this.#lineParent.at(n)),
851 text: this.#text(n),
852 };
853 }
855 /** A line's text, or undefined for an unknown line: line(id).text without making the record. */
856 lineText(id: LineId): string | undefined {
857 const n = this.#lineN(id);
858 return n < 0 ? undefined : this.#text(n);
859 }
861 /** The atom that wrote a line, or undefined: line(id).atom without making the record. */
862 lineAtom(id: LineId): AtomId | undefined {
863 const n = this.#lineN(id);
864 return n < 0 ? undefined : this.idOfSeq(this.#lineAtom.at(n));
865 }
867 /** The file a line was written in, or undefined: line(id).file without making the record. */
868 lineFile(id: LineId): string | undefined {
869 const n = this.#lineN(id);
870 return n < 0 ? undefined : this.#paths[this.#lineFile.at(n)];
871 }
873 /** The node a line was written after, or undefined: line(id).parent without making the record. */
874 lineParent(id: LineId): NodeId | undefined {
875 const n = this.#lineN(id);
876 return n < 0 ? undefined : this.#nodeName(this.#lineParent.at(n));
877 }
879 // By number, for views (#46) ------------------------------------------------------
880 // 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
881 // keeps them, so a view can lay files out as arrays of numbers. For the engine's own use.
883 /** A line id's n, or -1 for an unknown line. */
884 lineN(id: LineId): number {
885 return this.#lineN(id);
886 }
888 /** A line's id from its n. */
889 lineIdOf(n: number): LineId {
890 return this.#lineName(n);
891 }
893 /** The lines an atom deletes, from the graph's own packed copy (#46): never a read of the log. */
894 deletedLines(id: AtomId): readonly LineId[] {
895 const seq = this.#seq(id);
896 const count = this.#storage?.read("atom-delete-counts", String(seq));
897 if (count !== undefined) {
898 const out: LineId[] = [];
899 for (const n of storedLists<number>(this.#storage!, "atom-deletes").values(String(seq)))
900 out.push(this.#lineName(n));
901 if (out.length !== count) throw Error("incomplete atom deletion index");
902 return out;
903 }
904 const ns = this.#atomDeletes[this.#seq(id)];
905 if (!ns) return EMPTY;
906 const out: LineId[] = new Array(ns.length);
907 for (let i = 0; i < ns.length; i++) out[i] = this.#lineName(ns[i]!);
908 return out;
909 }
911 /** The numbers of the lines an atom deletes, from the graph's packed copy: no lookup per line id. */
912 *deletedNumbers(id: AtomId): IterableIterator<number> {
913 const seq = this.#seq(id);
914 if (this.#storage?.read("atom-delete-counts", String(seq)) !== undefined) {
915 yield* storedLists<number>(this.#storage!, "atom-deletes").values(String(seq));
916 return;
917 }
918 yield* this.#atomDeletes[seq] ?? EMPTY_NUMBERS;
919 }
921 /** How many lines an atom deletes, without reading its lists. */
922 deleteCount(id: AtomId): number {
923 const seq = this.#seq(id);
924 const count = this.#storage?.read("atom-delete-counts", String(seq));
925 if (count !== undefined) {
926 if (!Number.isSafeInteger(count) || (count as number) < 0) throw Error("invalid atom deletion count");
927 return count as number;
928 }
929 return this.#atomDeletes[seq]?.length ?? 0;
930 }
932 textOf(n: number): string {
933 return this.#text(n);
934 }
936 /** Historical text in bounded chunks, without decoding a whole stored line. */
937 *textChunks(n: number): IterableIterator<string> {
938 if (!this.#storage) {
939 const text = this.#text(n);
940 for (let offset = 0; offset < text.length; offset += StoredText.chunkCharacters)
941 yield text.slice(offset, offset + StoredText.chunkCharacters);
942 return;
943 }
944 if (!Number.isSafeInteger(n) || n < 0 || n >= this.#lineText!.length) throw Error("invalid line number");
945 const value = this.#storage.read("line-text", String(n));
946 if (typeof value === "string") {
947 yield value;
948 return;
949 }
950 const reference = value as { format?: number; text?: string } | undefined;
951 if (reference?.format !== 1 || typeof reference.text !== "string") throw Error("invalid long line reference");
952 yield* new StoredText(this.#storage, "atom-text:long").chunks(reference.text);
953 }
955 /** The seq of the atom that wrote line n. */
956 writerSeqOf(n: number): number {
957 return this.#lineAtom.at(n);
958 }
960 /** Line n's k: its place among its atom's lines. */
961 kOf(n: number): number {
962 return n - this.#lineBase[this.#lineAtom.at(n)]!;
963 }
965 /** The atom id with this seq, as the graph keeps it. */
966 idOfSeq(seq: number): AtomId {
967 if (!Number.isSafeInteger(seq) || seq < 0 || seq >= this.#atoms.length)
968 throw new EngineError("unknown-atom", `no atom at sequence ${seq}`);
969 return atomId(seq);
970 }
972 lamportOfSeq(seq: number): number {
973 return this.#lamport[seq]!;
974 }
976 /** The file line n was written in. */
977 writtenIn(n: number): string {
978 return this.#paths[this.#lineFile.at(n)]!;
979 }
981 /** The code of the node line n was written after. */
982 parentCodeOf(n: number): number {
983 return this.#lineParent.at(n);
984 }
986 /** A node's code, or undefined for a node the graph doesn't know (a start node of a file nothing was written in). */
987 codeOf(node: NodeId): number | undefined {
988 return this.#nodeCode(node);
989 }
991 /** The node a code names. */
992 nodeOf(code: number): NodeId {
993 return this.#nodeName(code);
994 }
996 /** The start node's code for a path, or undefined when nothing was ever written in it. */
997 startCodeOf(path: string): number | undefined {
998 const p = this.#pathIndex.get(path);
999 return p === undefined ? undefined : -1 - p;
1000 }
1002 /** The lines (their n) written right after a node, as childrenOf, into `out`. */
1004 childrenN(code: number, out: number[]): void {
1005 for (const n of this.eachChildN(code)) out.push(n);
1006 }
1007 *eachChildN(code: number): IterableIterator<number> {
1008 if (
1009 code >= 0 &&
1010 code + 1 < this.#lineTotal &&
1011 this.#lineAtom.at(code + 1) === this.#lineAtom.at(code) &&
1012 this.#lineParent.at(code + 1) === code
1013 )
1014 yield code + 1;
1015 if (this.#runStartPages) {
1016 // The paged child counts say a line has no other children without a row read per line (abso Capacity).
1017 if (code >= 0 && this.#childCounts && this.#childCounts.at(code, this.#lineTotal) === 0) return;
1018 yield* this.#runStartPages.values(String(code));
1019 } else yield* listOf(this.#runStarts.get(code));
1020 }
1022 get hasOrderedChildren(): boolean {
1023 return this.#storage !== undefined;
1024 }
1025 /** Synchronous derived work against one graph identity. Scratch never commits. */
1026 withProjectionScratch<T>(operation: (scratch: GraphStateStorage) => T): T {
1027 if (!this.#storage) throw new Error("projection scratch requires persistent graph storage");
1028 const size = this.size;
1029 const lines = this.lineCount;
1030 return withProjectionScratch(
1031 this.#storage,
1032 () => {
1033 if (this.size !== size || this.lineCount !== lines) throw new Error("projection graph identity changed");
1034 },
1035 operation,
1036 );
1037 }
1038 #childPriority(n: number): string {
1039 const seq = this.writerSeqOf(n);
1040 return orderedChildKey({
1041 n,
1042 replaces: this.replacesN(n) ? 1 : 0,
1043 lamport: this.lamportOfSeq(seq),
1044 seq,
1045 k: this.kOf(n),
1046 });
1047 }
1048 /** Persistent layout order with a strict successor cursor; moves are separate. */
1049 *orderedChildrenN(code: number, after?: number): IterableIterator<number> {
1050 if (!this.#storage) throw new Error("ordered children require indexed storage");
1051 const index = new OrderedIndex(this.#storage, "ordered-children", String(code));
1052 if (this.#storage.read("ordered-children", "format") !== 2)
1053 throw new Error("ordered children require fresh adoption");
1054 const count = code >= 0 ? this.#childCounts!.at(code, this.#lineTotal) : index.size;
1055 if ((code < 0 || count > 0) && (count !== index.size || count !== this.#runStartPages!.length(String(code))))
1056 throw new Error("ordered child index count mismatch");
1057 let implicit: number | undefined;
1058 if (
1059 code >= 0 &&
1060 code + 1 < this.#lineTotal &&
1061 this.#lineAtom.at(code + 1) === this.#lineAtom.at(code) &&
1062 this.#lineParent.at(code + 1) === code
1063 )
1064 implicit = code + 1;
1065 // Most historical run lines have no explicit child. With zero or one
1066 // child, traversal needs no priority decoding or radix lookup. Keep the
1067 // format/count checks above even on this path.
1068 if (count === 0 && (after === undefined || after === implicit)) {
1069 if (implicit !== undefined && after !== implicit) yield implicit;
1070 return;
1071 }
1072 const cursor = after === undefined ? undefined : this.#childPriority(after);
1073 if (implicit !== undefined && cursor !== undefined && this.#childPriority(implicit) <= cursor) implicit = undefined;
1074 for (const n of index.values(cursor)) {
1075 if (implicit !== undefined && this.#childPriority(implicit) < this.#childPriority(n)) {
1076 yield implicit;
1077 implicit = undefined;
1078 }
1079 yield n;
1080 }
1081 if (implicit !== undefined) yield implicit;
1082 }
1084 replacesN(n: number): boolean {
1085 return this.#replacing.at(n) === 1;
1086 }
1088 /** The seqs of every atom that deletes line n (none: an empty list, shared). */
1089 deleterSeqsOf(n: number): readonly number[] {
1090 return [...this.eachDeleterSeqOf(n)];
1091 }
1092 *eachDeleterSeqOf(n: number): IterableIterator<number> {
1093 const first = this.#deleter.at(n);
1094 if (first < 0) return;
1095 yield first;
1096 if (this.#moreDeleterPages) yield* this.#moreDeleterPages.values(String(n));
1097 else yield* this.#moreDeleters.get(n) ?? EMPTY;
1098 }
1100 /** Every relocation that puts a line right after the node with this code. */
1101 relocatedToCode(code: number): readonly RelocationInfo[] {
1102 if (this.#relocatedToCodePages) return [...this.eachRelocatedToCode(code)];
1103 return this.#relocatedToCode.get(code) ?? EMPTY;
1104 }
1105 *eachRelocatedToCode(code: number): IterableIterator<RelocationInfo> {
1106 if (this.#relocatedToCodePages) yield* this.#relocatedToCodePages.values(String(code));
1107 else yield* this.#relocatedToCode.get(code) ?? EMPTY;
1108 }
1110 /** How many lines every atom together has written. */
1111 get lineCount(): number {
1112 return this.#lineTotal;
1113 }
1115 /** A line id's n, or -1 when no accepted atom wrote it. */
1116 #lineN(id: LineId): number {
1117 const p = parseLineId(id);
1118 if (!p || p.seq >= this.#atoms.length) return -1;
1119 const base = this.#lineBase[p.seq]!;
1120 const end = p.seq + 1 < this.#lineBase.length ? this.#lineBase[p.seq + 1]! : this.#lineTotal;
1121 return p.k < end - base ? base + p.k : -1;
1122 }
1124 /** A line's id from its n. */
1125 #lineName(n: number): LineId {
1126 const seq = this.#lineAtom.at(n);
1127 return `${this.idOfSeq(seq)}.${n - this.#lineBase[seq]!}`;
1128 }
1130 /** A node's code: a line's n, or -1 - a path's index for a start node; undefined when unknown. */
1131 #nodeCode(node: NodeId): number | undefined {
1132 if (isStartNode(node)) {
1133 const p = this.#pathIndex.get(node.slice(1));
1134 return p === undefined ? undefined : -1 - p;
1135 }
1136 const n = this.#lineN(node);
1137 return n < 0 ? undefined : n;
1138 }
1140 #nodeName(code: number): NodeId {
1141 return code >= 0 ? this.#lineName(code) : startNode(this.#paths[-1 - code]!);
1142 }
1144 #pathOf(file: string): number {
1145 let p = this.#pathIndex.get(file);
1146 if (p === undefined) {
1147 p = this.#paths.push(file) - 1;
1148 this.#pathIndex.set(file, p);
1149 }
1150 return p;
1151 }
1153 /** The line ids an atom inserted, in k order. */
1154 linesOf(id: AtomId): LineId[] {
1155 return [...this.eachInsertedLine(id)];
1156 }
1157 /** Inserted identities without decoding or allocating the atom's text. */
1158 *eachInsertedLine(id: AtomId): IterableIterator<LineId> {
1159 const seq = this.atom(id).seq;
1160 const count = (seq + 1 < this.#lineBase.length ? this.#lineBase[seq + 1]! : this.#lineTotal) - this.#lineBase[seq]!;
1161 for (let k = 0; k < count; k++) yield lineId(id, k);
1162 }
1164 /** Every atom that deletes this line (across the whole graph). */
1165 deletersOf(line: LineId): readonly AtomId[] {
1166 const n = this.#lineN(line);
1167 if (n < 0) return EMPTY;
1168 return [...this.eachDeleterSeqOf(n)].map((seq) => this.idOfSeq(seq));
1169 }
1171 writersOf(key: Key): readonly AtomId[] {
1172 return [...this.eachWriterOf(key)];
1173 }
1174 *eachWriterOf(key: Key): IterableIterator<AtomId> {
1175 const code = this.#code(key);
1176 if (this.#writersPages) yield* this.#writersPages.values(JSON.stringify([typeof code, code]));
1177 else yield* listOf(this.#writers.get(code));
1178 }
1180 /** Atoms whose implicit reads include the key. */
1181 readersOf(key: Key): readonly AtomId[] {
1182 return [...this.eachReaderOf(key)];
1183 }
1184 *eachReaderOf(key: Key): IterableIterator<AtomId> {
1185 const code = this.#code(key);
1186 if (this.#readersPages) yield* this.#readersPages.values(JSON.stringify([typeof code, code]));
1187 else yield* listOf(this.#readers.get(code));
1188 }
1190 /** Atoms whose explicit holds include the key. */
1191 holdersOf(key: Key): readonly AtomId[] {
1192 return [...this.eachHolderOf(key)];
1193 }
1194 *eachHolderOf(key: Key): IterableIterator<AtomId> {
1195 const code = this.#code(key);
1196 if (this.#holdersPages) yield* this.#holdersPages.values(JSON.stringify([typeof code, code]));
1197 else yield* listOf(this.#holders.get(code));
1198 }
1200 /** Every atom that inserts or deletes a line of the file, in seq order. */
1201 atomsIn(file: string): readonly AtomId[] {
1202 if (this.#fileAtomPages) return [...this.#fileAtomPages.values(file)];
1203 return this.#fileAtoms.get(file) ?? EMPTY;
1204 }
1205 *eachAtomIn(file: string): IterableIterator<AtomId> {
1206 if (this.#fileAtomPages) yield* this.#fileAtomPages.values(file);
1207 else yield* this.#fileAtoms.get(file) ?? EMPTY;
1208 }
1209 hasAtomsIn(file: string): boolean {
1210 return this.#fileAtomPages ? this.#fileAtomPages.length(file) > 0 : this.#fileAtoms.has(file);
1211 }
1213 /** Unique historical file paths, streamed without collecting their names. */
1214 *knownFiles(): IterableIterator<string> {
1215 yield* this.#fileAtomPages ? this.#fileAtomPages.keys() : this.#fileAtoms.keys();
1216 }
1218 /**
1219 * The files an atom inserts, deletes or moves lines in, or sets attributes
1220 * of, sorted. For lines, the file each was written in (or, for a move to a
1221 * start node, that file): a set's moves can have taken them elsewhere.
1222 */
1223 filesOf(id: AtomId): readonly string[] {
1224 if (!this.has(id)) throw new EngineError("unknown-atom", `no atom ${id}`);
1225 return this.#atomFiles[this.#seq(id)]!;
1226 }
1228 /** Lines written right after a node (not counting moves), in seq order. */
1230 childrenOf(node: NodeId): LineId[] {
1231 const code = this.#nodeCode(node);
1232 return code === undefined ? [] : [...this.eachChildN(code)].map((n) => this.#lineName(n));
1233 }
1235 /** Whether a line starts a run whose atom deleted the line it hangs off. */
1236 replaces(line: LineId): boolean {
1237 const n = this.#lineN(line);
1238 return n >= 0 && this.#replacing.at(n) === 1;
1239 }
1241 /** Every relocation of a line, in seq order. */
1242 relocationsOf(line: LineId): readonly RelocationInfo[] {
1243 if (this.#relocationPages) return [...this.eachRelocationOf(line)];
1244 return this.#relocations.get(line) ?? EMPTY;
1245 }
1246 *eachRelocationOf(line: LineId): IterableIterator<RelocationInfo> {
1247 if (this.#relocationPages) yield* this.#relocationPages.values(line);
1248 else yield* this.#relocations.get(line) ?? EMPTY;
1249 }
1251 /** Every relocation that puts a line right after this node, in seq order. */
1252 relocatedTo(node: NodeId): readonly RelocationInfo[] {
1253 if (this.#relocatedToPages) return [...this.#relocatedToPages.values(node)];
1254 return this.#relocatedTo.get(node) ?? EMPTY;
1255 }
1257 /** Atoms that move lines, in seq order. */
1258 movers(): readonly AtomId[] {
1259 return this.#movers;
1260 }
1262 /** Atoms that list this one directly in their deps. */
1263 dependentsOf(id: AtomId): readonly AtomId[] {
1264 return [...this.eachDependentOf(id)];
1265 }
1266 *eachDependentOf(id: AtomId): IterableIterator<AtomId> {
1267 if (this.#dependentsPages) yield* this.#dependentsPages.values(id);
1268 else yield* listOf(this.#dependents.get(id));
1269 }
1271 /** Atoms whose `resolves` names this one. */
1272 resolversOf(id: AtomId): readonly AtomId[] {
1273 return [...this.eachResolverOf(id)];
1274 }
1275 *eachResolverOf(id: AtomId): IterableIterator<AtomId> {
1276 if (this.#resolversPages) yield* this.#resolversPages.values(id);
1277 else yield* listOf(this.#resolvers.get(id));
1278 }
1280 /** `together` reasons touching this atom, in either direction. */
1281 togetherLinks(id: AtomId): readonly TogetherLink[] {
1282 return [...this.eachTogetherLink(id)];
1283 }
1284 *eachTogetherLink(id: AtomId): IterableIterator<TogetherLink> {
1285 if (this.#togetherPages) yield* this.#togetherPages.values(id);
1286 else yield* this.#together.get(id) ?? EMPTY;
1287 }
1289 /**
1290 * The atom plus everything it depends on, transitively. Computed on demand
1291 * and not cached: a cached set per atom costs memory quadratic in the length
1292 * of a dependency chain. Use `dependsOn` to ask about one pair.
1293 */
1294 closure(id: AtomId): Set<AtomId> {
1295 return this.closureOf([id]);
1296 }
1298 /** The atoms plus everything they depend on, transitively. */
1299 closureOf(ids: Iterable<AtomId>): Set<AtomId> {
1300 const out = new Set<AtomId>();
1301 const stack: AtomId[] = [];
1302 for (const id of ids) {
1303 this.atom(id);
1304 if (!out.has(id)) {
1305 out.add(id);
1306 stack.push(id);
1307 }
1308 }
1309 while (stack.length > 0) {
1310 for (const d of this.atom(stack.pop()!).deps) {
1311 if (!out.has(d)) {
1312 out.add(d);
1313 stack.push(d);
1314 }
1315 }
1316 }
1317 return out;
1318 }
1320 /** Whether `b` is in the closure of `a` (an atom is in its own closure). */
1321 dependsOn(a: AtomId, b: AtomId): boolean {
1322 const atom = this.atom(a);
1323 this.atom(b);
1324 return a === b || this.#reaches(atom.deps, b);
1325 }
1327 /**
1328 * Whether `target` is reachable along deps from any of `from` (themselves
1329 * included). A dependency always has a lower lamport than its dependent, so
1330 * the search never descends below the target's lamport.
1331 */
1332 #reaches(from: Iterable<AtomId>, target: AtomId): boolean {
1333 const floor = this.#lamport[this.#seq(target)]!;
1334 if (this.#storage) {
1335 return this.withProjectionScratch((scratch) => {
1336 let length = 0;
1337 const push = (id: AtomId): void => {
1338 if (scratch.read("seen", id)) return;
1339 scratch.write("seen", id, true);
1340 scratch.write("stack", String(length++), id);
1341 };
1342 for (const id of from) {
1343 if (id === target) return true;
1344 if (this.#lamport[this.#seq(id)]! > floor) push(id);
1345 }
1346 while (length > 0) {
1347 const key = String(--length);
1348 const current = scratch.read("stack", key) as AtomId;
1349 scratch.remove("stack", key);
1350 if (this.#lamport[this.#seq(current)]! <= floor) continue;
1351 for (const dependency of this.atom(current).deps) {
1352 if (dependency === target) return true;
1353 push(dependency);
1354 }
1355 }
1356 return false;
1357 });
1358 }
1359 const seen = new Set<AtomId>();
1360 const stack = [...from];
1361 while (stack.length > 0) {
1362 const cur = stack.pop()!;
1363 if (cur === target) return true;
1364 if (seen.has(cur)) continue;
1365 seen.add(cur);
1366 if (this.#lamport[this.#seq(cur)]! <= floor) continue;
1367 for (const d of this.atom(cur).deps) if (!seen.has(d)) stack.push(d);
1368 }
1369 return false;
1370 }
1372 /**
1373 * Accept an atom into the graph. It must carry the next id and seq, and
1374 * everything it touches must come from atoms in its dependency closure.
1375 * The atom is frozen. Adding to the graph does not add it to any set.
1376 */
1377 add(atom: Atom): void {
1378 if (this.#storage)
1379 this.#storage.transaction(() => {
1380 this.#add(atom);
1381 const result: unknown = this.#indexAcceptedAtom?.(atom, this.filesOf(atom.id), this.#storage!);
1382 if (result && typeof result === "object" && "then" in result)
1383 throw Error("accepted atom indexing must be synchronous");
1384 });
1385 else this.#add(atom);
1386 }
1388 #validateAcceptedAtom(atom: Atom, scratch?: GraphStateStorage): void {
1389 const membership = <T extends string>(name: string): { has(key: T): boolean; add(key: T): unknown } => {
1390 if (!scratch) return new Set<T>();
1391 return { has: (key) => scratch.read(name, key) === true, add: (key) => scratch.write(name, key, true) };
1392 };
1393 validateShape(atom);
1394 const seq = this.#atoms.length;
1395 const bad = (why: string): never => {
1396 throw new EngineError("bad-atom", `atom ${atom.id}: ${why}`);
1397 };
1398 if (atom.seq !== seq || atom.id !== atomId(seq)) bad(`expected id ${atomId(seq)} with seq ${seq}`);
1400 const deps = membership<AtomId>("deps");
1401 for (const d of atom.deps) {
1402 if (!this.has(d)) bad(`dependency ${d} is not in the graph`);
1403 if (deps.has(d)) bad(`dependency ${d} listed twice`);
1404 deps.add(d);
1405 }
1406 for (const list of [atom.needs, atom.resolves])
1407 for (const d of list) {
1408 if (!deps.has(d)) bad(`${d} is in needs/resolves but not in deps`);
1409 }
1410 for (const r of atom.reasons) if (!this.has(r.to)) bad(`reason points at unknown atom ${r.to}`);
1412 // Everything it touches must come from its closure. Derived deps name the
1413 // writers directly, so this is usually one lookup per writer.
1414 const memoryBelow = scratch ? undefined : new Map<AtomId, boolean>();
1415 const below = {
1416 get: (key: AtomId) => (scratch ? (scratch.read("below", key) as boolean | undefined) : memoryBelow!.get(key)),
1417 set: (key: AtomId, value: boolean) => {
1418 if (scratch) scratch.write("below", key, value);
1419 else memoryBelow!.set(key, value);
1420 },
1421 };
1422 const inClosure = (writer: AtomId): boolean => {
1423 let hit = below.get(writer);
1424 if (hit === undefined) {
1425 hit = deps.has(writer) || this.#reaches(atom.deps, writer);
1426 below.set(writer, hit);
1427 }
1428 return hit;
1429 };
1430 const checkLine = (line: LineId, what: string): void => {
1431 const writer = this.lineAtom(line);
1432 if (writer === undefined) return bad(`${what} names unknown line ${line}`);
1433 if (!inClosure(writer)) bad(`${what} names line ${line} but ${writer} is not in its closure`);
1434 };
1436 for (const run of atom.inserts) {
1437 if (isStartNode(run.parent)) {
1438 if (run.parent !== startNode(run.file)) bad(`run in ${run.file} starts at ${run.parent}`);
1439 } else {
1440 // The parent may have been moved into run.file, so its own file can differ.
1441 checkLine(run.parent, "an insert");
1442 }
1443 }
1444 const writes = membership<Key>("writes");
1445 for (const key of atom.writes) writes.add(key);
1446 const moved = membership<LineId>("moved");
1447 for (const m of atom.moves ?? []) {
1448 checkLine(m.line, "a move");
1449 if (!isStartNode(m.parent)) checkLine(m.parent, "a move");
1450 if (m.line === m.parent) bad(`moves ${m.line} after itself`);
1451 if (moved.has(m.line)) bad(`moves ${m.line} twice`);
1452 moved.add(m.line);
1453 if (!writes.has(posKey(m.line)) || !writes.has(gapKey(m.parent))) {
1454 bad(`moves ${m.line} without writing ${posKey(m.line)} and ${gapKey(m.parent)}`);
1455 }
1456 }
1457 const deleted = membership<LineId>("deleted");
1458 for (const line of atom.deletes) {
1459 checkLine(line, "a delete");
1460 if (deleted.has(line)) bad(`deletes ${line} twice`);
1461 deleted.add(line);
1462 }
1463 for (const line of atom.deletes)
1464 if (!writes.has(lineKey(line))) bad(`deletes ${line} without writing ${lineKey(line)}`);
1465 for (const list of [atom.writes, atom.reads, atom.holds])
1466 for (const key of list) {
1467 const parsed = parseKey(key);
1468 if (parsed.kind === "line") checkLine(parsed.node, `key ${key}`);
1469 else if ((parsed.kind === "gap" || parsed.kind === "pos") && !isStartNode(parsed.node))
1470 checkLine(parsed.node, `key ${key}`);
1471 }
1472 }
1474 #add(atom: Atom): void {
1475 if (this.#storage && this.#storage.read("ordered-children", "format") !== 2) {
1476 if (this.#atoms.length !== 0) throw new Error("ordered children require fresh adoption");
1477 this.#storage.write("ordered-children", "format", 2);
1478 }
1479 if (this.#storage && this.#atoms.length === 0 && this.#packFiles) {
1480 this.#storage.write("file-lines:meta", "format", 2);
1481 this.#formatKnown = 2;
1482 }
1484 if (this.#storage) this.withProjectionScratch((scratch) => this.#validateAcceptedAtom(atom, scratch));
1485 else this.#validateAcceptedAtom(atom);
1486 const seq = this.#atoms.length;
1487 const deps = atom.deps;
1488 const deleted = this.#storage ? undefined : new Set(atom.deletes);
1489 const writes = this.#storage ? atom.writes : new Set(atom.writes);
1491 // Accept.
1492 // Persistent storage copies the accepted atom; a second frozen copy only duplicates its lists.
1493 const frozen = this.#storage
1494 ? atom
1495 : freezeAtom(
1496 atom,
1497 (id) => this.idOfSeq(seqOf(id)),
1498 (author) => {
1499 if (this.#storage) return author;
1500 let a = this.#authors.get(author);
1501 if (a === undefined) this.#authors.set(author, (a = author));
1502 return a;
1503 },
1504 this.#texts ? this.#reader(seq) : undefined,
1505 this.#lists ? this.#listReader(seq) : undefined,
1506 );
1507 this.#atoms.push(this.#storage ? atom : frozen);
1508 let lam = 0;
1509 for (const d of deps) lam = Math.max(lam, this.lamport(d) + 1);
1510 this.#lamport.push(lam);
1512 // The run starts' parents and the deleted lines, as codes, before this atom's own lines exist.
1513 // The atom as given: with lists kept elsewhere, the frozen one reads them back from the log.
1514 const deletes = (line: LineId | NodeId): boolean => {
1515 if (isStartNode(line)) return false;
1516 if (deleted) return deleted.has(line);
1517 const n = this.#lineN(line);
1518 return this.#deleter.at(n) === seq || this.#moreDeleterPages!.last(String(n)) === seq;
1519 };
1520 const deletedN = this.#storage ? undefined : atom.deletes.map((line) => this.#lineN(line));
1521 this.#atomDeletes.push(deletedN?.length ? Int32Array.from(deletedN) : undefined);
1522 if (this.#storage) {
1523 const pages = storedLists<number>(this.#storage, "atom-deletes");
1524 for (const line of atom.deletes) pages.append(String(seq), this.#lineN(line));
1525 this.#storage.write("atom-delete-counts", String(seq), atom.deletes.length);
1526 }
1527 const deletedNumbers = function* (graph: Graph) {
1528 if (deletedN) yield* deletedN;
1529 else for (const line of atom.deletes) yield graph.#lineN(line);
1530 };
1531 const packedDeletes = new Map<number, PackedDelete[]>();
1532 for (const n of deletedNumbers(this)) {
1533 if (this.#packed) {
1534 const file = this.#lineFile.at(n);
1535 const list = packedDeletes.get(file);
1536 if (list) list.push([n, seq]);
1537 else packedDeletes.set(file, [[n, seq]]);
1538 }
1539 if (this.#deleter.at(n) < 0) this.#deleter.set(n, seq);
1540 else if (this.#moreDeleterPages) this.#moreDeleterPages.append(String(n), seq);
1541 else pushIndex(this.#moreDeleters, n, seq);
1542 }
1543 for (const [file, list] of packedDeletes) this.#fileDeletes!.appendAll(String(file), list);
1544 this.#lineBase.push(this.#lineTotal);
1545 for (const run of atom.inserts) {
1546 const file = this.#pathOf(run.file);
1547 let parent = isStartNode(run.parent) ? -1 - file : this.#lineN(run.parent);
1548 const first = this.#lineTotal;
1549 if (parent >= 0) this.#childCounts?.increment(parent, first);
1550 if (this.#storage)
1551 new OrderedIndex(this.#storage, "ordered-children", String(parent)).insert(
1552 orderedChildKey({
1553 n: first,
1554 replaces: deletes(run.parent) ? 1 : 0,
1555 lamport: lam,
1556 seq,
1557 k: first - this.#lineBase[seq]!,
1558 }),
1559 first,
1560 );
1562 if (this.#runStartPages) this.#runStartPages.append(String(parent), first);
1563 else pushOne(this.#runStarts, parent, first);
1564 const replacesParent = deletes(run.parent) ? 1 : 0;
1565 if (this.#packed) {
1566 if (this.#crossings && parent >= 0) {
1567 const from = this.#lineFile.at(parent);
1568 if (from !== file) this.#fileCrossings!.append(String(from), [parent, file]);
1569 }
1570 const base = this.#lineBase[seq]!;
1571 this.#fileLines!.appendAll(
1572 String(file),
1573 run.lines.map(
1574 (_, i): PackedLine => [
1575 first + i,
1576 i === 0 ? parent : first + i - 1,
1577 seq,
1578 first + i - base,
1579 i === 0 ? replacesParent : 0,
1580 ],
1581 ),
1582 );
1583 this.#fileTexts!.appendAll(
1584 String(file),
1585 run.lines.map((text) => (typeof text === "string" && text.length <= PACKED_TEXT ? text : null)),
1586 );
1587 }
1588 for (let i = 0; i < run.lines.length; i++) {
1589 const n = this.#lineTotal;
1590 this.#childCounts?.append(n);
1591 this.#lineAtom.push(seq);
1592 this.#lineFile.push(file);
1593 this.#lineParent.push(parent);
1594 this.#lineText?.push(run.lines[i]!);
1595 this.#deleter.push(-1);
1596 this.#replacing.push(i === 0 && deletes(run.parent) ? 1 : 0);
1597 parent = n;
1598 }
1599 }
1600 (frozen.moves ?? []).forEach((m, i) => {
1601 const info: RelocationInfo = Object.freeze({ atom: frozen.id, line: m.line, parent: m.parent, k: i });
1602 if (this.#relocationPages) this.#relocationPages.append(m.line, info);
1603 else pushIndex(this.#relocations, m.line, info);
1604 if (this.#relocatedToPages) this.#relocatedToPages.append(m.parent, info);
1605 else pushIndex(this.#relocatedTo, m.parent, info);
1606 const parentCode = isStartNode(m.parent) ? -1 - this.#pathOf(m.parent.slice(1)) : this.#lineN(m.parent);
1607 if (this.#relocatedToCodePages) this.#relocatedToCodePages.append(String(parentCode), info);
1608 else pushIndex(this.#relocatedToCode, parentCode, info);
1609 });
1610 if (frozen.moves) this.#movers.push(frozen.id);
1611 if (this.#packed)
1612 for (const a of frozen.attrs ?? []) this.#fileAttrs!.append(String(this.#pathOf(a.file)), [seq, a.name, a.value]);
1613 for (const key of writes) {
1614 const code = this.#code(key);
1615 if (this.#writersPages) {
1616 const key = JSON.stringify([typeof code, code]);
1617 if (this.#writersPages.last(key) !== frozen.id) this.#writersPages.append(key, frozen.id);
1618 } else pushOne(this.#writers, code, frozen.id);
1619 }
1620 for (const key of this.#storage ? atom.reads : new Set(atom.reads)) {
1621 const code = this.#code(key);
1622 if (this.#readersPages) {
1623 const key = JSON.stringify([typeof code, code]);
1624 if (this.#readersPages.last(key) !== frozen.id) this.#readersPages.append(key, frozen.id);
1625 } else pushOne(this.#readers, code, frozen.id);
1626 }
1627 for (const key of this.#storage ? atom.holds : new Set(atom.holds)) {
1628 const code = this.#code(key);
1629 if (this.#holdersPages) {
1630 const key = JSON.stringify([typeof code, code]);
1631 if (this.#holdersPages.last(key) !== frozen.id) this.#holdersPages.append(key, frozen.id);
1632 } else pushOne(this.#holders, code, frozen.id);
1633 }
1634 for (const d of deps) {
1635 if (this.#dependentsPages) this.#dependentsPages.append(d, frozen.id);
1636 else pushOne(this.#dependents, d, frozen.id);
1637 }
1638 for (const r of this.#storage ? frozen.resolves : new Set(frozen.resolves)) {
1639 if (this.#resolversPages) {
1640 if (this.#resolversPages.last(r) !== frozen.id) this.#resolversPages.append(r, frozen.id);
1641 } else pushOne(this.#resolvers, r, frozen.id);
1642 }
1643 const files = new Set<string>();
1644 for (const run of atom.inserts) files.add(run.file);
1645 for (const n of deletedNumbers(this)) files.add(this.#paths[this.#lineFile.at(n)]!);
1646 for (const a of frozen.attrs ?? []) files.add(a.file);
1647 for (const m of frozen.moves ?? []) {
1648 files.add(this.lineFile(m.line)!);
1649 files.add(isStartNode(m.parent) ? m.parent.slice(1) : this.lineFile(m.parent)!);
1650 }
1651 this.#atomFiles.push(Object.freeze([...files].sort()));
1652 for (const file of files) {
1653 if (this.#fileAtomPages) this.#fileAtomPages.append(file, frozen.id);
1654 else pushIndex(this.#fileAtoms, file, frozen.id);
1655 }
1656 for (const r of frozen.reasons) {
1657 if (r.kind !== "together" || r.to === frozen.id) continue;
1659 const forward = { other: r.to, text: r.text, from: frozen.id };
1660 const reverse = { other: frozen.id, text: r.text, from: frozen.id };
1661 if (this.#togetherPages) {
1662 this.#togetherPages.append(frozen.id, forward);
1663 this.#togetherPages.append(r.to, reverse);
1664 } else {
1665 pushIndex(this.#together, frozen.id, forward);
1666 pushIndex(this.#together, r.to, reverse);
1667 }
1668 }
1669 }
1671 // Labels -----------------------------------------------------------------
1673 /**
1674 * Add or replace a label. Label names may not look like atom ids. A base is
1675 * resolved to its head only when it is used, never followed further, so
1676 * bases may name each other in any shape.
1677 */
1678 setLabel(label: Label): void {
1679 this.#putLabel(label, (name) => this.#labels.has(name));
1680 }
1682 #putLabel(label: Label, isLabel: (name: string) => boolean): void {
1683 const bad = (why: string): never => {
1684 throw new EngineError("bad-label", `label ${JSON.stringify(label?.name)}: ${why}`);
1685 };
1686 if (typeof label !== "object" || label === null) bad("not an object");
1687 if (typeof label.name !== "string" || label.name === "") bad("needs a name");
1688 if (isAtomId(label.name)) bad("a label name may not look like an atom id");
1689 if (!this.has(label.head)) bad(`head ${label.head} is not in the graph`);
1690 if (
1691 label.base !== undefined &&
1692 !(typeof label.base === "string" && (isLabel(label.base) || this.has(label.base)))
1693 ) {
1694 bad(`base ${label.base} is neither a label nor an atom`);
1695 }
1696 if (label.base === label.name) bad("a label cannot be its own base");
1697 if (typeof label.title !== "string" || typeof label.message !== "string") bad("needs a title and message");
1698 if (label.follows !== undefined && !Array.isArray(label.follows)) bad("follows must be a list of label names");
1699 const copy: Label = {
1700 name: label.name,
1701 head: label.head,
1702 ...(label.base !== undefined ? { base: label.base } : {}),
1703 title: label.title,
1704 message: label.message,
1705 ...(label.follows !== undefined ? { follows: Object.freeze([...label.follows]) } : {}),
1706 };
1707 this.#labels.set(label.name, Object.freeze(copy));
1708 }
1710 label(name: string): Label | undefined {
1711 return this.#labels.get(name);
1712 }
1714 /** Labels sorted by name. */
1715 labels(): Label[] {
1716 return [...this.#labels.values()].sort((a, b) => (a.name < b.name ? -1 : a.name > b.name ? 1 : 0));
1717 }
1719 /**
1720 * Remove a label. Labels that used it as their base get its head atom as
1721 * their base instead, so their contents don't change.
1722 */
1723 removeLabel(name: string): boolean {
1724 return this.#storage ? this.#storage.transaction(() => this.#removeLabel(name)) : this.#removeLabel(name);
1725 }
1727 #removeLabel(name: string): boolean {
1728 const gone = this.#labels.get(name);
1729 if (!gone) return false;
1730 this.#labels.delete(name);
1731 for (const label of [...this.#labels.values()]) {
1732 if (label.base === name) this.#labels.set(label.name, Object.freeze({ ...label, base: gone.head }));
1733 }
1734 return true;
1735 }
1737 // JSON -------------------------------------------------------------------
1739 toJSON(): GraphJSON {
1740 return { format: GRAPH_FORMAT, version: 1, atoms: this.#atoms, labels: this.labels() };
1741 }
1743 /** Load a saved graph. Every atom is re-validated as it is added. */
1744 static fromJSON(data: unknown): Graph {
1745 const bad = (why: string): never => {
1746 throw new EngineError("bad-json", why);
1747 };
1748 if (typeof data !== "object" || data === null) bad("graph JSON must be an object");
1749 const obj = data as Partial<GraphJSON>;
1750 if (obj.format !== GRAPH_FORMAT) bad(`format must be ${GRAPH_FORMAT}`);
1751 if (obj.version !== 1) bad(`unsupported version ${String(obj.version)}`);
1752 if (!Array.isArray(obj.atoms) || !Array.isArray(obj.labels)) bad("atoms and labels must be arrays");
1753 const graph = new Graph();
1754 for (const atom of obj.atoms!) graph.add(atom);
1755 // Labels may name each other as bases, in any order and any shape.
1756 const names = new Set<string>();
1757 for (const label of obj.labels!) {
1758 const name: unknown = (label as Partial<Label> | null)?.name;
1759 if (typeof name !== "string") return bad("every label needs a name");
1760 if (names.has(name)) bad(`label ${name} appears twice`);
1761 names.add(name);
1762 }
1763 for (const label of obj.labels!) {
1764 try {
1765 graph.#putLabel(label, (name) => names.has(name));
1766 } catch (err) {
1767 if (err instanceof EngineError) bad(err.message);
1768 throw err;
1769 }
1770 }
1771 return graph;
1772 }
1774 #seq(id: AtomId): number {
1775 return typeof id === "string" ? seqOf(id) : -1;
1776 }
1777}
1779function validateShape(atom: Atom): void {
1780 const bad = (why: string): never => {
1781 throw new EngineError("bad-atom", `atom ${String((atom as { id?: unknown }).id)}: ${why}`);
1782 };
1783 if (typeof atom !== "object" || atom === null) bad("not an object");
1784 if (typeof atom.id !== "string" || !Number.isInteger(atom.seq)) bad("needs id and seq");
1785 if (typeof atom.author !== "string" || typeof atom.message !== "string") bad("needs author and message");
1786 if (typeof atom.time !== "number" || !Number.isFinite(atom.time)) bad("time must be a finite number");
1787 const lists = ["inserts", "deletes", "writes", "reads", "holds", "needs", "resolves", "reasons", "deps"] as const;
1788 for (const name of lists) if (!Array.isArray(atom[name])) bad(`${name} must be an array`);
1789 for (const run of atom.inserts as readonly InsertRun[]) {
1790 if (typeof run.file !== "string" || run.file === "" || run.file.includes("\n")) bad("a run needs a file path");
1791 if (typeof run.parent !== "string") bad("a run needs a parent");
1792 if (!Array.isArray(run.lines) || run.lines.length === 0) bad("a run needs at least one line");
1793 for (const text of run.lines) {
1794 if (typeof text !== "string" || text.includes("\n") || text.includes("\r"))
1795 bad("run lines must be strings without line breaks");
1796 }
1797 }
1798 if (atom.attrs !== undefined) {
1799 if (!Array.isArray(atom.attrs)) bad("attrs must be an array");
1800 for (const a of atom.attrs) {
1801 if (typeof a?.file !== "string" || a.file === "" || a.file.includes("\n") || !ATTR_NAMES.includes(a.name))
1802 bad("an attr needs a file and a name");
1803 if (a.value !== null && typeof a.value !== "string") bad("an attr value is a string or null");
1804 if (!atom.writes.includes(attrKey(a.file, a.name))) bad(`sets ${a.name} of ${a.file} without writing its key`);
1805 }
1806 }
1807 if (atom.moves !== undefined) {
1808 if (!Array.isArray(atom.moves) || atom.moves.length === 0) bad("moves must be a non-empty array");
1809 for (const m of atom.moves) {
1810 if (typeof m?.line !== "string" || typeof m.parent !== "string") bad("a move needs a line and a parent");
1811 }
1812 }
1813 for (const name of ["deletes", "writes", "reads", "holds", "needs", "resolves", "deps"] as const) {
1814 for (const x of atom[name]) if (typeof x !== "string") bad(`${name} must hold strings`);
1815 }
1816 for (const r of atom.reasons as readonly Reason[]) {
1817 if (typeof r.to !== "string" || typeof r.text !== "string" || !REASON_KINDS.includes(r.kind)) {
1818 bad("a reason needs to, kind (together, because-of or supersedes) and text");
1819 }
1820 }
1821}
1823/**
1824 * A frozen copy of an atom. An empty list is one shared frozen list, and atom
1825 * ids and authors are the graph's own strings (`canon`, `author`), so each is
1826 * kept once however often it's named (#46).
1827 */
1828function freezeAtom(
1829 atom: Atom,
1830 canon: (id: AtomId) => AtomId,
1831 author: (name: string) => string,
1832 text?: (start: number, length: number) => readonly string[],
1833 lists?: () => AtomLists,
1834): Atom {
1835 const list = <T>(xs: readonly T[], f?: (x: T) => T): readonly T[] =>
1836 xs.length === 0 ? EMPTY : Object.freeze(f ? xs.map(f) : [...xs]);
1837 // With text kept elsewhere (#46), a run's lines are read when asked for.
1838 let k = 0;
1839 const run = (r: InsertRun): InsertRun => {
1840 if (!text) return Object.freeze({ file: r.file, parent: r.parent, lines: Object.freeze([...r.lines]) });
1841 const start = k;
1842 const length = r.lines.length;
1843 k += length;
1844 return Object.freeze(new LazyRun(r.file, r.parent, text, start, length));
1845 };
1846 const copy: Atom = {
1847 id: atom.id,
1848 seq: atom.seq,
1849 author: author(atom.author),
1850 message: atom.message,
1851 time: atom.time,
1852 inserts: Object.freeze(atom.inserts.map(run)),
1853 ...(lists
1854 ? {}
1855 : { deletes: list(atom.deletes), writes: list(atom.writes), reads: list(atom.reads), holds: list(atom.holds) }),
1856 needs: list(atom.needs, canon),
1857 resolves: list(atom.resolves, canon),
1858 reasons: list(atom.reasons, (r) => Object.freeze({ to: canon(r.to), kind: r.kind, text: r.text })),
1859 deps: list(atom.deps, canon),
1860 ...(atom.attrs && atom.attrs.length > 0
1861 ? { attrs: Object.freeze(atom.attrs.map((a) => Object.freeze({ file: a.file, name: a.name, value: a.value }))) }
1862 : {}),
1863 ...(atom.moves
1864 ? { moves: Object.freeze(atom.moves.map((m) => Object.freeze({ line: m.line, parent: m.parent }))) }
1865 : {}),
1866 } as Atom;
1867 return Object.freeze(lists ? (new ListedAtom(copy, lists) as unknown as Atom) : copy);
1868}