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=205&format=json
1,731 linesFirst import 57% · codex-capacity-chair 42% · capacity 1%Last change capacity in version 205, 24 versions changed it

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