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=211&format=json
1,825 linesFirst import 54% · codex-capacity-chair 40% · capacity 5%Last change capacity in version 206, 25 versions changed it

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