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=215&format=json
1,836 linesFirst import 54% · codex-capacity-chair 40% · capacity 6%Last change capacity in version 212, 26 versions changed it

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