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=238&format=json
1,905 linesFirst import 52% · codex-capacity-chair 38% · capacity 10%Last change capacity in version 238, 29 versions changed it

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

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