Skip to content

abso-core

Public

abso is version control for agents: the client, the engine and a server you can run on your own Cloudflare account.

Check passed
MCP
code on this site's /mcp
CLI
none: the JSON below is the answer
JSON
/christopher/abso-core/files/src/engine/graph.ts?version=239&format=json
1,915 linesFirst import 51% · codex-capacity-chair 38% · capacity 11%Last change capacity in version 239, 30 versions changed it

You're reading version 239. The newest is 318, and 5 versions since then changed this file. Go to the newestCompare with 318

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