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

Versions 23 to 318

Compare

+1148 −159 in 26 places
Lines 2–9 at 318 (were 2–7 at 23)
22// the codebase) are separate values; the graph only answers questions about
33// atoms and keeps indexes so those questions are cheap.
44
5+import { ChildCounts } from "./child-counts.ts";
6+import { JsonStringChunks, registerJsonChunkValue } from "./json-value-chunks.ts";
57import {
68 atomId,
79 attrKey,
Lines 17–37 at 318 (were 15–21 at 23)
1517 seqOf,
1618 startNode,
1719} from "./keys.ts";
20+import { OrderedIndex, orderedChildKey } from "./ordered-index.ts";
21+import { withProjectionScratch } from "./projection-scratch.ts";
1822import {
23+ type GraphStateStorage,
24+ readonlyPagedArray,
25+ readonlyStoredArray,
26+ type StateMap,
27+ storedArray,
28+ storedLists,
29+ storedMap,
30+ storedNumbers,
31+ writePagedArray,
32+} from "./state-source.ts";
33+import { StoredText } from "./stored-text.ts";
34+import {
1935 ATTR_NAMES,
2036 type Atom,
2137 type AtomId,
Lines 92–116 at 318 (were 76–96 at 23)
7692 * are two (#46): most keys name one atom, and a list for each costs more than
7793 * the value.
7894 */
79−function pushOne<K, V>(map: Map<K, V | V[]>, key: K, value: V): void {
95+function pushOne<K, V>(map: StateMap<K, V | V[]>, key: K, value: V): void {
8096 const had = map.get(key);
8197 if (had === undefined) map.set(key, value);
82− else if (Array.isArray(had)) had.push(value);
83− else map.set(key, [had, value]);
98+ else if (Array.isArray(had)) {
99+ had.push(value);
100+ map.set(key, had);
101+ } else map.set(key, [had, value]);
84102}
85103
86104function listOf<V>(had: V | V[] | undefined): readonly V[] {
87105 return had === undefined ? EMPTY : Array.isArray(had) ? had : [had];
88106}
89107
90−function pushIndex<K, V>(map: Map<K, V[]>, key: K, value: V): void {
108+function pushIndex<K, V>(map: StateMap<K, V[]>, key: K, value: V): void {
91109 const list = map.get(key);
92− if (list) list.push(value);
93− else map.set(key, [value]);
110+ if (list) {
111+ list.push(value);
112+ map.set(key, list);
113+ } else map.set(key, [value]);
94114}
95115
96116const EMPTY: readonly never[] = Object.freeze([]);
Lines 196–209 at 318 (were 176–182 at 23)
176196}
177197
178198/** A growable array of 32-bit integers: a line's fields cost 4 bytes each, not an object and its strings (#46). */
179−class Ints {
199+interface NumberIndex {
200+ readonly length: number;
201+ push(n: number): void;
202+ at(i: number): number;
203+ set(i: number, n: number): void;
204+}
206+class Ints implements NumberIndex {
180207 #buf: Int32Array | Uint8Array;
181208 /** bytes: values 0-255 only, one byte each. */
182209 constructor(bytes = false) {
Lines 258–811 at 318 (were 231–271 at 23)
231258 return { seq, k };
232259}
233260
261+/** A line in its file's packed history: [n, parent code, writer seq, k, 1 when it replaces its parent]. */
262+export type PackedLine = [number, number, number, number, number];
263+/** A delete of a line in a file's packed history: [n, deleter seq]. */
264+export type PackedDelete = [number, number];
265+/** An attribute set on a file: [seq, name, value]. */
266+export type PackedAttr = [number, string, string | null];
267+/** A run written in another file under one of a file's lines: [the parent's n, the run's file index]. */
268+export type PackedCrossing = [number, number];
270+/**
271+ * A file's packed history decoded, without texts (Graph.packedHistory): PackedLine's five numbers per line, then
272+ * PackedDelete's two per delete and PackedCrossing's two per crossing, each list flat.
273+ */
274+export interface PackedHistory {
275+ readonly lines: ArrayLike<number>;
276+ readonly deletes: ArrayLike<number>;
277+ readonly crossings: ArrayLike<number>;
278+}
280+/**
281+ * Bytes of decoded file histories a stored graph keeps between layouts (abso Capacity). Every view of a file read its
282+ * whole history from pages: compare lays each file out once per side, collisions once per draft touching it, and a
283+ * file whose lines moved in from another read that one's history too (abso's worker files, split out of index.ts).
284+ * abso's index.ts, 46,000 lines of history, takes about 1 MB.
285+ */
286+export const PACKED_HISTORY_BUDGET = 4_000_000;
288+/** Numbers packed flat: 4 bytes each while they fit in 32 bits, else 8. */
289+function packNumbers(rows: Iterable<readonly number[]>): Int32Array | Float64Array {
290+ const flat: number[] = [];
291+ let small = true;
292+ for (const row of rows)
293+ for (const value of row) {
294+ if ((value | 0) !== value) small = false;
295+ flat.push(value);
296+ }
297+ return small ? Int32Array.from(flat) : Float64Array.from(flat);
298+}
299+const EMPTY_NUMBERS: readonly number[] = Object.freeze([]);
300+/** At most this many path names kept in memory (Graph.#pathName). */
301+const PATH_NAMES = 4096;
302+/** Lines longer than this aren't packed with their file; their text is read on its own. */
303+const PACKED_TEXT = 4096;
234305export class Graph {
306+ readonly #storage?: GraphStateStorage;
307+ readonly #childCounts?: ChildCounts;
235308 #atoms: Atom[] = [];
236309 #lamport: number[] = [];
310+ /**
311+ * A stored graph's lamport numbers, 256 to a row (abso Capacity). A graph that already has them a row each (#lamport)
312+ * keeps that; the choice is made when first needed, so opening reads nothing.
313+ */
314+ #lamportPaged: ReturnType<typeof storedNumbers> | undefined;
315+ #lamportPagesKnown: ReturnType<typeof storedNumbers> | null | undefined;
316+ get #lamportPages(): ReturnType<typeof storedNumbers> | null {
317+ if (this.#lamportPagesKnown === undefined)
318+ this.#lamportPagesKnown =
319+ this.#lamportPaged && this.#storage!.read("lamport:meta", "length") === undefined ? this.#lamportPaged : null;
320+ return this.#lamportPagesKnown;
321+ }
237322 // Lines, packed (#46): line n is the k-th line atom seq wrote, n = #lineBase[seq] + k. Each holds its
238323 // atom's seq, the file it was written in (an index into #paths) and its parent (a line's n, or -1 - a
239324 // path's index for a file's start). Its text stays in the atom. Ids and LineInfo objects are made only
240325 // when asked for, so a line costs about 16 bytes here instead of a record, its id and its parent's id.
241326 #lineBase: number[] = [];
242− #lineAtom = new Ints();
243− #lineFile = new Ints();
244− #lineParent = new Ints();
327+ #lineAtom: NumberIndex = new Ints();
328+ #lineFile: NumberIndex = new Ints();
329+ #lineParent: NumberIndex = new Ints();
245330 /** Lines' text, when the graph keeps it; without it, it comes from `texts` (#46, text on disk). */
246331 #lineText: string[] | undefined = [];
247− #lineTotal = 0;
332+ get #lineTotal(): number {
333+ return this.#lineAtom.length;
334+ }
248335 /** Where an atom's lines' text is when the graph doesn't keep it: each run's lines, by the atom's seq. */
249336 #texts: ((seq: number) => readonly (readonly string[])[]) | undefined;
250337 /** Recently read atoms' text, flattened, most recent last, up to TEXT_CACHE characters. */
251338 #textCache = new Map<number, readonly string[]>();
252339 #textCached = 0;
253340
341+ readonly #indexAcceptedAtom?: (atom: Atom, files: readonly string[], storage: GraphStateStorage) => void;
254343 /**
255344 * `texts`, when given, says where each atom's lines' text can be read back
256345 * (#46): the graph then keeps no text, only each line's place, and reads an
257346 * atom's text when a line of it is asked for, keeping the most recent.
258347 */
259348 constructor(
260− options: { texts?: (seq: number) => readonly (readonly string[])[]; lists?: (seq: number) => AtomLists } = {},
349+ options: {
350+ texts?: (seq: number) => readonly (readonly string[])[];
351+ lists?: (seq: number) => AtomLists;
352+ storage?: GraphStateStorage;
353+ /** Optional derived indexing inside persistent atom acceptance; must be synchronous. */
354+ indexAcceptedAtom?: (atom: Atom, files: readonly string[], storage: GraphStateStorage) => void;
355+ /** false: a new stored graph keeps no packed file history, and lays files out line by line (tests of that path). */
356+ packFiles?: boolean;
357+ } = {},
261358 ) {
359+ if (options.indexAcceptedAtom && !options.storage)
360+ throw Error("accepted atom indexing requires persistent storage");
361+ this.#indexAcceptedAtom = options.indexAcceptedAtom;
262362 if (options.texts) {
263363 this.#texts = options.texts;
264364 this.#lineText = undefined;
265365 }
266366 if (options.lists) this.#lists = options.lists;
367+ this.#storage = options.storage;
368+ if (options.storage) this.#childCounts = new ChildCounts(options.storage);
369+ if (options.storage) {
370+ const storage = options.storage;
371+ const numbers = (name: string): NumberIndex => storedNumbers(storage, name);
372+ const atomText = new StoredText(storage, "atom-text:long");
373+ type TextReference = { text: string };
374+ const listFields = [
375+ "deletes",
376+ "writes",
377+ "reads",
378+ "holds",
379+ "needs",
380+ "resolves",
381+ "deps",
382+ "reasons",
383+ "attrs",
384+ "moves",
385+ ] as const;
386+ type EncodedAtom = {
387+ insertionFormat?: 1;
388+ insertionRuns?: string;
389+ textFormat?: 1;
390+ listFormat?: 1 | 2;
391+ listCount?: number;
392+ lists?: Partial<Record<(typeof listFields)[number], string>>;
393+ atom: Atom;
394+ };
395+ this.#atoms = storedArray<Atom>(
396+ storage,
397+ "atoms",
398+ (value) => {
399+ const encoded = value as unknown as Partial<EncodedAtom>;
400+ if (encoded.textFormat !== undefined && encoded.textFormat !== 1)
401+ throw Error("invalid stored atom text format");
402+ if (encoded.listFormat !== undefined && encoded.listFormat !== 1 && encoded.listFormat !== 2)
403+ throw Error("invalid stored atom list format");
404+ if (encoded.listFormat === 1 || encoded.listFormat === 2) {
405+ if (
406+ !encoded.lists ||
407+ typeof encoded.lists !== "object" ||
408+ Array.isArray(encoded.lists) ||
409+ !Number.isSafeInteger(encoded.listCount) ||
410+ encoded.listCount! < 1 ||
411+ Object.keys(encoded.lists).length !== encoded.listCount ||
412+ Object.keys(encoded.lists).some((field) => !listFields.includes(field as (typeof listFields)[number]))
413+ )
414+ throw Error("invalid stored atom list references");
415+ }
416+ if (encoded.insertionFormat !== undefined && encoded.insertionFormat !== 1)
417+ throw Error("invalid stored insertion format");
418+ const atom =
419+ encoded.textFormat === 1 ||
420+ encoded.listFormat === 1 ||
421+ encoded.listFormat === 2 ||
422+ encoded.insertionFormat === 1
423+ ? encoded.atom!
424+ : value;
425+ if (encoded.insertionFormat === 1 && (!Array.isArray(atom.inserts) || atom.inserts.length !== 0))
426+ throw Error("invalid stored insertion placeholder");
427+ const text =
428+ encoded.textFormat === 1
429+ ? (start: number, length: number): readonly string[] => {
430+ const result: string[] = [];
431+ let index = 0;
432+ for (const run of atom.inserts)
433+ for (const raw of run.lines) {
434+ if (index >= start && index < start + length) {
435+ const reference = raw as unknown as TextReference;
436+ if (typeof raw === "string") result.push(raw);
437+ else if (reference && reference.text === JSON.stringify([String(atom.seq), index]))
438+ result.push(atomText.read(reference.text));
439+ else throw Error("invalid stored atom text reference");
440+ }
441+ if (++index >= start + length) return result;
442+ }
443+ throw Error("stored atom text range missing");
444+ }
445+ : undefined;
446+ // Sequential reads advance once per run without retaining a history-sized offset array.
447+ let offsetRun = 0;
448+ let offsetLine = 0;
449+ const insertionStart = (index: number): number => {
450+ if (index < offsetRun) {
451+ offsetRun = 0;
452+ offsetLine = 0;
453+ }
454+ while (offsetRun < index) {
455+ offsetLine += readonlyStoredArray(storage, `atom-inserts:${atom.seq}:lines:${offsetRun}`).length;
456+ offsetRun++;
457+ }
458+ return offsetLine;
459+ };
460+ const streamed = (target: Atom): Atom => {
461+ registerJsonChunkValue(target, () => {
462+ const line = (raw: unknown, index: number): unknown => {
463+ if (typeof raw === "string") return raw;
464+ const reference = raw as TextReference;
465+ if (!reference || reference.text !== JSON.stringify([String(atom.seq), index]))
466+ throw Error("invalid stored atom text reference");
467+ return new JsonStringChunks(() => atomText.chunks(reference.text));
468+ };
469+ let inserts: readonly unknown[];
470+ if (encoded.insertionFormat === 1) {
471+ const collection = `atom-inserts:${atom.seq}`;
472+ inserts = readonlyStoredArray(storage, collection, (raw, index) => {
473+ const run = raw as {
474+ file: string;
475+ parent: string;
476+ lines: string;
477+ };
478+ const lines = `${collection}:lines:${index}`;
479+ if (run.lines !== lines || typeof run.file !== "string" || typeof run.parent !== "string")
480+ throw Error("invalid stored insertion run");
481+ const start = insertionStart(index);
482+ return {
483+ file: run.file,
484+ parent: run.parent,
485+ lines: readonlyStoredArray(storage, lines, (raw, i) => line(raw, start + i)),
486+ };
487+ });
488+ } else {
489+ let index = 0;
490+ inserts = atom.inserts.map((run) => ({
491+ file: run.file,
492+ parent: run.parent,
493+ lines: run.lines.map((raw) => line(raw, index++)),
494+ }));
495+ }
496+ return { ...target, inserts };
497+ });
498+ return target;
499+ };
500+ const frozen = freezeAtom(
501+ atom,
502+ (id) => id,
503+ (author) => author,
504+ text,
505+ );
506+ if (encoded.listFormat !== 1 && encoded.listFormat !== 2 && encoded.insertionFormat !== 1)
507+ return streamed(frozen);
508+ const result = { ...frozen };
509+ if (encoded.insertionFormat === 1) {
510+ const collection = `atom-inserts:${atom.seq}`;
511+ if (encoded.insertionRuns !== collection) throw Error("invalid stored insertion reference");
512+ const inserts = readonlyStoredArray<InsertRun>(storage, collection, (raw, index) => {
513+ const run = raw as {
514+ file: string;
515+ parent: InsertRun["parent"];
516+ lines: string;
517+ };
518+ const lines = `${collection}:lines:${index}`;
519+ if (run.lines !== lines || typeof run.file !== "string" || typeof run.parent !== "string")
520+ throw Error("invalid stored insertion run");
521+ return Object.freeze({
522+ file: run.file,
523+ parent: run.parent,
524+ lines: readonlyStoredArray<string>(storage, lines, (rawLine, lineIndex) => {
525+ if (typeof rawLine === "string") return rawLine;
526+ const ref = rawLine as TextReference;
527+ const atomLine = insertionStart(index) + lineIndex;
528+ if (!ref || ref.text !== JSON.stringify([String(atom.seq), atomLine]))
529+ throw Error("invalid stored insertion text");
530+ return atomText.read(ref.text);
531+ }),
532+ });
533+ });
534+ Object.defineProperty(result, "inserts", {
535+ value: inserts,
536+ enumerable: true,
537+ });
538+ }
539+ for (const field of listFields) {
540+ const collection = encoded.lists?.[field];
541+ if (collection === undefined) continue;
542+ if (typeof collection !== "string" || collection !== `atom-list:${atom.seq}:${field}`)
543+ throw Error("invalid stored atom list reference");
544+ const list =
545+ encoded.listFormat === 2
546+ ? readonlyPagedArray(storage, collection)
547+ : readonlyStoredArray(storage, collection);
548+ Object.defineProperty(result, field, {
549+ value: list,
550+ enumerable: true,
551+ });
552+ }
553+ return streamed(Object.freeze(result));
554+ },
555+ (input, key) => {
556+ const atom = { ...input };
557+ const lists: Partial<Record<(typeof listFields)[number], string>> = {};
558+ for (const field of listFields) {
559+ const values = input[field];
560+ if (!values || values.length <= 256) continue;
561+ // 256 to a row from list format 2 on (abso Capacity); an atom stored before keeps a row per value.
562+ const collection = `atom-list:${input.seq}:${field}`;
563+ writePagedArray(storage, collection, values);
564+ lists[field] = collection;
565+ Object.defineProperty(atom, field, { value: [], enumerable: true });
566+ }
567+ const listCount = Object.keys(lists).length;
568+ const hasLists = listCount > 0;
569+ let insertionCharacters = 0;
570+ if (
571+ atom.inserts.length > 256 ||
572+ atom.inserts.some((run) => run.lines.length > 256) ||
573+ atom.inserts.some((run) => run.lines.some((line) => (insertionCharacters += line.length) > 65536))
574+ ) {
575+ const collection = `atom-inserts:${input.seq}`;
576+ const runs = storedArray<unknown>(storage, collection);
577+ let runIndex = 0;
578+ let lineIndex = 0;
579+ for (const run of atom.inserts) {
580+ const lineCollection = `${collection}:lines:${runIndex++}`;
581+ const lines = storedArray<unknown>(storage, lineCollection);
582+ for (const line of run.lines) {
583+ const text = JSON.stringify([key, lineIndex++]);
584+ if (line.length > StoredText.chunkCharacters) {
585+ atomText.write(text, line);
586+ lines.push({ text });
587+ } else lines.push(line);
588+ }
589+ runs.push({
590+ file: run.file,
591+ parent: run.parent,
592+ lines: lineCollection,
593+ });
594+ }
595+ return {
596+ insertionFormat: 1,
597+ insertionRuns: collection,
598+ ...(hasLists ? { listFormat: 2, listCount, lists } : {}),
599+ atom: { ...atom, inserts: [] },
600+ };
601+ }
602+ if (!atom.inserts.some((run) => run.lines.some((line) => line.length > StoredText.chunkCharacters)))
603+ return hasLists ? { listFormat: 2, listCount, lists, atom } : atom;
604+ let index = 0;
605+ const inserts = atom.inserts.map((run) => ({
606+ ...run,
607+ lines: run.lines.map((line) => {
608+ const text = JSON.stringify([key, index++]);
609+ if (line.length <= StoredText.chunkCharacters) return line;
610+ atomText.write(text, line);
611+ return { text };
612+ }),
613+ }));
614+ return {
615+ textFormat: 1,
616+ ...(hasLists ? { listFormat: 2, listCount, lists } : {}),
617+ atom: { ...atom, inserts },
618+ };
619+ },
620+ );
621+ this.#lamport = storedArray(storage, "lamport");
622+ this.#lamportPaged = storedNumbers(storage, "lamport-pages");
623+ this.#lineBase = storedArray(storage, "line-base");
624+ this.#paths = storedArray(storage, "paths");
625+ this.#movers = storedArray(storage, "movers");
626+ this.#atomFiles = storedArray(storage, "atom-files");
627+ this.#atomDeletes = storedArray(storage, "atom-deletes");
628+ this.#lineAtom = numbers("line-atom");
629+ this.#lineFile = numbers("line-file");
630+ this.#lineParent = numbers("line-parent");
631+ this.#deleter = numbers("deleter");
632+ this.#replacing = numbers("replacing");
633+ const longText = atomText;
634+ this.#lineText = storedArray<string>(
635+ storage,
636+ "line-text",
637+ (value) => {
638+ if (typeof value === "string") return value;
639+ const reference = value as unknown as {
640+ format: number;
641+ text: string;
642+ };
643+ if (reference?.format !== 1 || typeof reference.text !== "string") throw Error("invalid long line reference");
644+ return longText.read(reference.text);
645+ },
646+ (value, key) => {
647+ if (value.length <= StoredText.chunkCharacters) return value;
648+ const number = Number(key);
649+ const seq = this.#lineAtom.at(number);
650+ const text = JSON.stringify([String(seq), number - this.#lineBase[seq]!]);
651+ const header = storage.read("atom-text:long", text) as { characters?: number } | undefined;
652+ if (header?.characters !== value.length) throw Error("long line atom text is missing");
653+ return { format: 1, text };
654+ },
655+ );
656+ this.#pathIndex = storedMap(storage, "path-index");
657+ this.#moreDeleterPages = storedLists<number>(storage, "more-deleters", (key) =>
658+ JSON.stringify(["number", Number(key)]),
659+ );
660+ this.#writersPages = storedLists<AtomId>(storage, "writers", (key) => key);
661+ this.#readersPages = storedLists<AtomId>(storage, "readers", (key) => key);
662+ this.#holdersPages = storedLists<AtomId>(storage, "holders", (key) => key);
663+ this.#dependentsPages = storedLists<AtomId>(storage, "dependents");
664+ this.#resolversPages = storedLists<AtomId>(storage, "resolvers");
665+ this.#togetherPages = storedLists<TogetherLink>(storage, "together");
666+ this.#reasonsInPages = storedLists<AtomId>(storage, "reasons-in");
667+ this.#fileAtomPages = storedLists<AtomId>(storage, "file-atoms");
668+ this.#runStartPages = storedLists<number>(storage, "run-starts", (key) =>
669+ JSON.stringify(["number", Number(key)]),
670+ );
671+ this.#relocationPages = storedLists<RelocationInfo>(storage, "relocations");
672+ this.#relocatedToPages = storedLists<RelocationInfo>(storage, "relocated-to");
673+ this.#relocatedToCodePages = storedLists<RelocationInfo>(storage, "relocated-to-code", (key) =>
674+ JSON.stringify(["number", Number(key)]),
675+ );
676+ this.#labels = storedMap(storage, "labels");
677+ this.#fileLines = storedLists<PackedLine>(storage, "file-lines");
678+ this.#fileTexts = storedLists<string | null>(storage, "file-texts");
679+ this.#fileDeletes = storedLists<PackedDelete>(storage, "file-deletes");
680+ this.#fileAttrs = storedLists<PackedAttr>(storage, "file-attrs");
681+ this.#fileCrossings = storedLists<PackedCrossing>(storage, "file-crossings");
682+ this.#packFiles = options.packFiles ?? true;
683+ }
267684 }
268685
686+ // Each file's line history packed, in pages (abso Capacity) ---------------------------------------------------
687+ // For each file, by its path index: every line written in it ([n, parent code, writer seq, k, replaces]) and its
688+ // text, every delete of one of those lines ([n, deleter seq]), every attribute set on it ([seq, name, value]), and
689+ // every run written in another file under one of its lines ([parent n, the run's file]): a line follows its parent,
690+ // so a run written while its parent was moved elsewhere lays out wherever the parent is.
691+ // 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
692+ // a fresh adoption on; a graph adopted before has none, and views lay out as before.
694+ #fileLines: ReturnType<typeof storedLists<PackedLine>> | undefined;
695+ #fileTexts: ReturnType<typeof storedLists<string | null>> | undefined;
696+ #fileDeletes: ReturnType<typeof storedLists<PackedDelete>> | undefined;
697+ #fileAttrs: ReturnType<typeof storedLists<PackedAttr>> | undefined;
698+ #fileCrossings: ReturnType<typeof storedLists<PackedCrossing>> | undefined;
699+ /** Whether a new stored graph starts packing (GraphOptions.packFiles). */
700+ #packFiles = true;
701+ /**
702+ * How this graph's files are packed, read once when first asked so opening reads nothing: 0 not at all, 1 lines,
703+ * deletes and attributes, 2 the runs written across files as well.
704+ */
705+ #formatKnown: number | undefined;
706+ get #format(): number {
707+ if (this.#formatKnown === undefined) {
708+ const format = this.#storage?.read("file-lines:meta", "format");
709+ this.#formatKnown = format === 1 || format === 2 ? format : 0;
710+ }
711+ return this.#formatKnown;
712+ }
713+ get #packed(): boolean {
714+ return this.#format >= 1;
715+ }
716+ get #crossings(): boolean {
717+ return this.#format >= 2;
718+ }
720+ /** Whether this graph keeps each file's line history packed. */
721+ get packedFiles(): boolean {
722+ return this.#packed;
723+ }
724+ /**
725+ * Whether a file can be laid out from packed history alone: it also keeps the runs written across files. A graph
726+ * packed before those were kept lays files out line by line.
727+ */
728+ get packedLayout(): boolean {
729+ return this.#crossings;
730+ }
731+ /** A path's index, or undefined when nothing was ever written or set in it. */
732+ pathIndexOf(path: string): number | undefined {
733+ return this.#pathIndex.get(path);
734+ }
735+ /** The index of the path line n was written in. */
736+ writtenInIndex(n: number): number {
737+ return this.#lineFile.at(n);
738+ }
739+ *packedLines(file: number): IterableIterator<PackedLine> {
740+ yield* this.#fileLines!.values(String(file));
741+ }
742+ *packedTexts(file: number): IterableIterator<string | null> {
743+ yield* this.#fileTexts!.values(String(file));
744+ }
745+ /**
746+ * The texts at positions [page * 256, (page + 1) * 256) of packedTexts(file) (abso Capacity): a layout reads only the
747+ * pages holding a line it shows.
748+ */
749+ packedTextPage(file: number, page: number): readonly (string | null)[] {
750+ return this.#fileTexts!.pageAt(String(file), page);
751+ }
752+ *packedDeletes(file: number): IterableIterator<PackedDelete> {
753+ yield* this.#fileDeletes!.values(String(file));
754+ }
755+ *packedAttrs(file: number): IterableIterator<PackedAttr> {
756+ yield* this.#fileAttrs!.values(String(file));
757+ }
758+ *packedCrossings(file: number): IterableIterator<PackedCrossing> {
759+ yield* this.#fileCrossings!.values(String(file));
760+ }
762+ /** Decoded file histories by path index, most recently used last, under PACKED_HISTORY_BUDGET bytes. */
763+ readonly #histories = new Map<number, { counts: string; history: PackedHistory; bytes: number }>();
764+ #historyBytes = 0;
766+ /**
767+ * A file's line, delete and crossing history, decoded once and kept while it fits (abso Capacity). Kept under its
768+ * three lists' lengths: the lists only grow, and add() lets every kept history go, so a kept one is always whole.
769+ */
770+ packedHistory(file: number): PackedHistory {
771+ const key = String(file);
772+ const counts = `${this.#fileLines!.length(key)} ${this.#fileDeletes!.length(key)} ${this.#fileCrossings!.length(key)}`;
773+ const kept = this.#histories.get(file);
774+ if (kept) {
775+ this.#histories.delete(file);
776+ if (kept.counts === counts) {
777+ this.#histories.set(file, kept);
778+ return kept.history;
779+ }
780+ this.#historyBytes -= kept.bytes;
781+ }
782+ const history: PackedHistory = {
783+ lines: packNumbers(this.#fileLines!.values(key)),
784+ deletes: packNumbers(this.#fileDeletes!.values(key)),
785+ crossings: packNumbers(this.#fileCrossings!.values(key)),
786+ };
787+ const bytes =
788+ (history.lines as Int32Array).byteLength +
789+ (history.deletes as Int32Array).byteLength +
790+ (history.crossings as Int32Array).byteLength +
791+ 200;
792+ if (bytes <= PACKED_HISTORY_BUDGET) {
793+ this.#histories.set(file, { counts, history, bytes });
794+ this.#historyBytes += bytes;
795+ for (const [old, entry] of this.#histories) {
796+ if (this.#historyBytes <= PACKED_HISTORY_BUDGET) break;
797+ this.#histories.delete(old);
798+ this.#historyBytes -= entry.bytes;
799+ }
800+ }
801+ return history;
802+ }
804+ /** Bytes of decoded file histories kept (packedHistory). */
805+ get historyBytes(): number {
806+ return this.#historyBytes;
807+ }
269809 /** Where an atom's key and delete lists are when the graph doesn't keep them (#46): the stored atom. */
270810 #lists: ((seq: number) => AtomLists) | undefined;
271811 /** Recently read atoms' lists, most recent last, up to LIST_CACHE atoms. */
Lines 892–945 at 318 (were 352–381 at 23)
352892 return this.#textOf(seq)[n - this.#lineBase[seq]!]!;
353893 }
354894 #paths: string[] = [];
355− #pathIndex = new Map<string, number>();
895+ #pathIndex: StateMap<string, number> = new Map();
356896 /** The first atom that deletes each line (its seq), or -1; a line deleted by more than one has the rest in #moreDeleters. */
357− #deleter = new Ints();
358− #moreDeleters = new Map<number, number[]>();
359− #writers = new Map<Key | number, AtomId | AtomId[]>();
360− #readers = new Map<Key | number, AtomId | AtomId[]>();
361− #holders = new Map<Key | number, AtomId | AtomId[]>();
362− #dependents = new Map<AtomId, AtomId | AtomId[]>();
363− #resolvers = new Map<AtomId, AtomId | AtomId[]>();
364− #together = new Map<AtomId, TogetherLink[]>();
365− #fileAtoms = new Map<string, AtomId[]>();
897+ #deleter: NumberIndex = new Ints();
898+ #moreDeleters: StateMap<number, number[]> = new Map();
899+ #moreDeleterPages: ReturnType<typeof storedLists<number>> | undefined;
900+ #writers: StateMap<Key | number, AtomId | AtomId[]> = new Map();
901+ #writersPages: ReturnType<typeof storedLists<AtomId>> | undefined;
902+ #readers: StateMap<Key | number, AtomId | AtomId[]> = new Map();
903+ #readersPages: ReturnType<typeof storedLists<AtomId>> | undefined;
904+ #holders: StateMap<Key | number, AtomId | AtomId[]> = new Map();
905+ #holdersPages: ReturnType<typeof storedLists<AtomId>> | undefined;
906+ #dependents: StateMap<AtomId, AtomId | AtomId[]> = new Map();
907+ #dependentsPages: ReturnType<typeof storedLists<AtomId>> | undefined;
908+ #resolvers: StateMap<AtomId, AtomId | AtomId[]> = new Map();
909+ #resolversPages: ReturnType<typeof storedLists<AtomId>> | undefined;
910+ #together: StateMap<AtomId, TogetherLink[]> = new Map();
911+ #togetherPages: ReturnType<typeof storedLists<TogetherLink>> | undefined;
912+ /** The atoms whose reasons point at each atom, in seq order, once each (abso Capacity). */
913+ #reasonsIn = new Map<AtomId, AtomId[]>();
914+ #reasonsInPages: ReturnType<typeof storedLists<AtomId>> | undefined;
915+ /** Whether a stored graph keeps reasons-in: from a fresh graph on, worked out when first needed. */
916+ #reasonsInKnown: boolean | undefined;
917+ get #reasonsInKept(): boolean {
918+ if (!this.#storage) return true;
919+ this.#reasonsInKnown ??= this.#storage.read("reasons-in:meta", "kept") === 1;
920+ return this.#reasonsInKnown;
921+ }
922+ #fileAtoms: StateMap<string, AtomId[]> = new Map();
923+ #fileAtomPages: ReturnType<typeof storedLists<AtomId>> | undefined;
366924 /** First lines of runs (their n), by the node they were written after: a line's n, or -1 - a path's index. */
367− #runStarts = new Map<number, number | number[]>();
925+ #runStarts: StateMap<number, number | number[]> = new Map();
926+ #runStartPages: ReturnType<typeof storedLists<number>> | undefined;
368927 /** 1 for the first line of a run whose atom deleted the line it hangs off: the run replaces it. */
369− #replacing = new Ints(true);
370− #relocations = new Map<LineId, RelocationInfo[]>();
371− #relocatedTo = new Map<NodeId, RelocationInfo[]>();
928+ #replacing: NumberIndex = new Ints(true);
929+ #relocations: StateMap<LineId, RelocationInfo[]> = new Map();
930+ #relocationPages: ReturnType<typeof storedLists<RelocationInfo>> | undefined;
931+ #relocatedTo: StateMap<NodeId, RelocationInfo[]> = new Map();
932+ #relocatedToPages: ReturnType<typeof storedLists<RelocationInfo>> | undefined;
372933 /** The same relocations by node code (a line's n, or -1 - a path's index), for views laid out by number. */
373− #relocatedToCode = new Map<number, RelocationInfo[]>();
934+ #relocatedToCode: StateMap<number, RelocationInfo[]> = new Map();
935+ #relocatedToCodePages: ReturnType<typeof storedLists<RelocationInfo>> | undefined;
374936 #movers: AtomId[] = [];
937+ /** A stored graph's movers, read once (abso Capacity): every view walks them, a row each. */
938+ #moverList: AtomId[] | undefined;
375939 #atomFiles: (readonly string[])[] = [];
376940 /** Each atom's deleted lines by n, packed (#46), or undefined when it deletes none. */
377− #atomDeletes: (Int32Array | undefined)[] = [];
378− #labels = new Map<string, Label>();
941+ #atomDeletes: (readonly number[] | Int32Array | undefined)[] = [];
942+ #labels: StateMap<string, Label> = new Map();
379943 /** Each author's name kept once (#46). */
380944 #authors = new Map<string, string>();
381945
Lines 948–963 at 318 (were 384–389 at 23)
384948 return this.#atoms.length;
385949 }
386950
951+ /**
952+ * How many atoms this graph object has accepted since it was made (abso Capacity): in memory, so a cache over the
953+ * graph can tell nothing was added without reading storage. A rolled-back add still counts, which only makes such a
954+ * cache look again.
955+ */
956+ get accepted(): number {
957+ return this.#accepted;
958+ }
959+ #accepted = 0;
387961 /** The id the next accepted atom must have. */
388962 nextId(): AtomId {
389963 return atomId(this.#atoms.length);
Lines 982–989 at 318 (were 408–415 at 23)
408982
409983 /** lamport(a) = 1 + max lamport of its deps; 0 for an atom with no deps (such as a0). */
410984 lamport(id: AtomId): number {
411− this.atom(id);
412− return this.#lamport[this.#seq(id)]!;
985+ if (!this.has(id)) throw new EngineError("unknown-atom", `no atom ${id}`);
986+ return this.#lamportAt(this.#seq(id));
413987 }
414988
415989 /** Compare by priority (lamport, then seq). Negative when a comes first (is lower). */
Lines 997–1005 at 318 (were 423–431 at 23)
423997 const seq = this.#lineAtom.at(n);
424998 return {
425999 id,
426− atom: this.#atoms[seq]!.id,
1000+ atom: this.idOfSeq(seq),
4271001 k: n - this.#lineBase[seq]!,
428− file: this.#paths[this.#lineFile.at(n)]!,
1002+ file: this.#pathName(this.#lineFile.at(n)),
4291003 parent: this.#nodeName(this.#lineParent.at(n)),
4301004 text: this.#text(n),
4311005 };
Lines 1014–1026 at 318 (were 440–452 at 23)
4401014 /** The atom that wrote a line, or undefined: line(id).atom without making the record. */
4411015 lineAtom(id: LineId): AtomId | undefined {
4421016 const n = this.#lineN(id);
443− return n < 0 ? undefined : this.#atoms[this.#lineAtom.at(n)]!.id;
1017+ return n < 0 ? undefined : this.idOfSeq(this.#lineAtom.at(n));
4441018 }
4451019
4461020 /** The file a line was written in, or undefined: line(id).file without making the record. */
4471021 lineFile(id: LineId): string | undefined {
4481022 const n = this.#lineN(id);
449− return n < 0 ? undefined : this.#paths[this.#lineFile.at(n)];
1023+ return n < 0 ? undefined : this.#pathName(this.#lineFile.at(n));
4501024 }
4511025
4521026 /** The node a line was written after, or undefined: line(id).parent without making the record. */
Lines 1045–1059 at 318 (were 471–476 at 23)
4711045
4721046 /** The lines an atom deletes, from the graph's own packed copy (#46): never a read of the log. */
4731047 deletedLines(id: AtomId): readonly LineId[] {
1048+ const seq = this.#seq(id);
1049+ const count = this.#storage?.read("atom-delete-counts", String(seq));
1050+ if (count !== undefined) {
1051+ const out: LineId[] = [];
1052+ for (const n of storedLists<number>(this.#storage!, "atom-deletes").values(String(seq)))
1053+ out.push(this.#lineName(n));
1054+ if (out.length !== count) throw Error("incomplete atom deletion index");
1055+ return out;
1056+ }
4741057 const ns = this.#atomDeletes[this.#seq(id)];
4751058 if (!ns) return EMPTY;
4761059 const out: LineId[] = new Array(ns.length);
Lines 1061–1110 at 318 (were 478–492 at 23)
4781061 return out;
4791062 }
4801063
1064+ /** The numbers of the lines an atom deletes, from the graph's packed copy: no lookup per line id. */
1065+ *deletedNumbers(id: AtomId): IterableIterator<number> {
1066+ const seq = this.#seq(id);
1067+ if (this.#storage?.read("atom-delete-counts", String(seq)) !== undefined) {
1068+ yield* storedLists<number>(this.#storage!, "atom-deletes").values(String(seq));
1069+ return;
1070+ }
1071+ yield* this.#atomDeletes[seq] ?? EMPTY_NUMBERS;
1072+ }
4811074 /** How many lines an atom deletes, without reading its lists. */
4821075 deleteCount(id: AtomId): number {
483− return this.#atomDeletes[this.#seq(id)]?.length ?? 0;
1076+ const seq = this.#seq(id);
1077+ const count = this.#storage?.read("atom-delete-counts", String(seq));
1078+ if (count !== undefined) {
1079+ if (!Number.isSafeInteger(count) || (count as number) < 0) throw Error("invalid atom deletion count");
1080+ return count as number;
1081+ }
1082+ return this.#atomDeletes[seq]?.length ?? 0;
4841083 }
4851084
4861085 textOf(n: number): string {
4871086 return this.#text(n);
4881087 }
4891088
1089+ /** Historical text in bounded chunks, without decoding a whole stored line. */
1090+ *textChunks(n: number): IterableIterator<string> {
1091+ if (!this.#storage) {
1092+ const text = this.#text(n);
1093+ for (let offset = 0; offset < text.length; offset += StoredText.chunkCharacters)
1094+ yield text.slice(offset, offset + StoredText.chunkCharacters);
1095+ return;
1096+ }
1097+ if (!Number.isSafeInteger(n) || n < 0 || n >= this.#lineText!.length) throw Error("invalid line number");
1098+ const value = this.#storage.read("line-text", String(n));
1099+ if (typeof value === "string") {
1100+ yield value;
1101+ return;
1102+ }
1103+ const reference = value as { format?: number; text?: string } | undefined;
1104+ if (reference?.format !== 1 || typeof reference.text !== "string") throw Error("invalid long line reference");
1105+ yield* new StoredText(this.#storage, "atom-text:long").chunks(reference.text);
1106+ }
4901108 /** The seq of the atom that wrote line n. */
4911109 writerSeqOf(n: number): number {
4921110 return this.#lineAtom.at(n);
Lines 1117–1138 at 318 (were 499–514 at 23)
4991117
5001118 /** The atom id with this seq, as the graph keeps it. */
5011119 idOfSeq(seq: number): AtomId {
502− return this.#atoms[seq]!.id;
1120+ if (!Number.isSafeInteger(seq) || seq < 0 || seq >= this.#atoms.length)
1121+ throw new EngineError("unknown-atom", `no atom at sequence ${seq}`);
1122+ return atomId(seq);
5031123 }
5041124
1125+ #lamportAt(seq: number): number {
1126+ return this.#lamportPages ? this.#lamportPages.at(seq) : this.#lamport[seq]!;
1127+ }
5051129 lamportOfSeq(seq: number): number {
506− return this.#lamport[seq]!;
1130+ return this.#lamportAt(seq);
5071131 }
5081132
5091133 /** The file line n was written in. */
5101134 writtenIn(n: number): string {
511− return this.#paths[this.#lineFile.at(n)]!;
1135+ return this.#pathName(this.#lineFile.at(n));
5121136 }
5131137
5141138 /** The code of the node line n was written after. */
Lines 1157–1268 at 318 (were 533–568 at 23)
5331157 }
5341158
5351159 /** The lines (their n) written right after a node, as childrenOf, into `out`. */
5361161 childrenN(code: number, out: number[]): void {
1162+ for (const n of this.eachChildN(code)) out.push(n);
1163+ }
1164+ *eachChildN(code: number): IterableIterator<number> {
5371165 if (
5381166 code >= 0 &&
5391167 code + 1 < this.#lineTotal &&
5401168 this.#lineAtom.at(code + 1) === this.#lineAtom.at(code) &&
5411169 this.#lineParent.at(code + 1) === code
5421170 )
543− out.push(code + 1);
544− const starts = this.#runStarts.get(code);
545− if (starts === undefined) return;
546− if (Array.isArray(starts)) out.push(...starts);
547− else out.push(starts);
1171+ yield code + 1;
1172+ if (this.#runStartPages) {
1173+ // The paged child counts say a line has no other children without a row read per line (abso Capacity).
1174+ if (code >= 0 && this.#childCounts && this.#childCounts.at(code, this.#lineTotal) === 0) return;
1175+ yield* this.#runStartPages.values(String(code));
1176+ } else yield* listOf(this.#runStarts.get(code));
5481177 }
5491178
1179+ get hasOrderedChildren(): boolean {
1180+ return this.#storage !== undefined;
1181+ }
1182+ /** Synchronous derived work against one graph identity. Scratch never commits. */
1183+ withProjectionScratch<T>(operation: (scratch: GraphStateStorage) => T): T {
1184+ if (!this.#storage) throw new Error("projection scratch requires persistent graph storage");
1185+ const size = this.size;
1186+ const lines = this.lineCount;
1187+ return withProjectionScratch(
1188+ this.#storage,
1189+ () => {
1190+ if (this.size !== size || this.lineCount !== lines) throw new Error("projection graph identity changed");
1191+ },
1192+ operation,
1193+ );
1194+ }
1195+ #childPriority(n: number): string {
1196+ const seq = this.writerSeqOf(n);
1197+ return orderedChildKey({
1198+ n,
1199+ replaces: this.replacesN(n) ? 1 : 0,
1200+ lamport: this.lamportOfSeq(seq),
1201+ seq,
1202+ k: this.kOf(n),
1203+ });
1204+ }
1205+ /** Persistent layout order with a strict successor cursor; moves are separate. */
1206+ *orderedChildrenN(code: number, after?: number): IterableIterator<number> {
1207+ if (!this.#storage) throw new Error("ordered children require indexed storage");
1208+ const index = new OrderedIndex(this.#storage, "ordered-children", String(code));
1209+ if (this.#storage.read("ordered-children", "format") !== 2)
1210+ throw new Error("ordered children require fresh adoption");
1211+ const count = code >= 0 ? this.#childCounts!.at(code, this.#lineTotal) : index.size;
1212+ if ((code < 0 || count > 0) && (count !== index.size || count !== this.#runStartPages!.length(String(code))))
1213+ throw new Error("ordered child index count mismatch");
1214+ let implicit: number | undefined;
1215+ if (
1216+ code >= 0 &&
1217+ code + 1 < this.#lineTotal &&
1218+ this.#lineAtom.at(code + 1) === this.#lineAtom.at(code) &&
1219+ this.#lineParent.at(code + 1) === code
1220+ )
1221+ implicit = code + 1;
1222+ // Most historical run lines have no explicit child. With zero or one
1223+ // child, traversal needs no priority decoding or radix lookup. Keep the
1224+ // format/count checks above even on this path.
1225+ if (count === 0 && (after === undefined || after === implicit)) {
1226+ if (implicit !== undefined && after !== implicit) yield implicit;
1227+ return;
1228+ }
1229+ const cursor = after === undefined ? undefined : this.#childPriority(after);
1230+ if (implicit !== undefined && cursor !== undefined && this.#childPriority(implicit) <= cursor) implicit = undefined;
1231+ for (const n of index.values(cursor)) {
1232+ if (implicit !== undefined && this.#childPriority(implicit) < this.#childPriority(n)) {
1233+ yield implicit;
1234+ implicit = undefined;
1235+ }
1236+ yield n;
1237+ }
1238+ if (implicit !== undefined) yield implicit;
1239+ }
5501241 replacesN(n: number): boolean {
5511242 return this.#replacing.at(n) === 1;
5521243 }
5531244
5541245 /** The seqs of every atom that deletes line n (none: an empty list, shared). */
5551246 deleterSeqsOf(n: number): readonly number[] {
1247+ return [...this.eachDeleterSeqOf(n)];
1248+ }
1249+ *eachDeleterSeqOf(n: number): IterableIterator<number> {
5561250 const first = this.#deleter.at(n);
557− if (first < 0) return EMPTY;
558− const more = this.#moreDeleters.get(n);
559− return more ? [first, ...more] : [first];
1251+ if (first < 0) return;
1252+ yield first;
1253+ if (this.#moreDeleterPages) yield* this.#moreDeleterPages.values(String(n));
1254+ else yield* this.#moreDeleters.get(n) ?? EMPTY;
5601255 }
5611256
5621257 /** Every relocation that puts a line right after the node with this code. */
5631258 relocatedToCode(code: number): readonly RelocationInfo[] {
1259+ if (this.#relocatedToCodePages) return [...this.eachRelocatedToCode(code)];
5641260 return this.#relocatedToCode.get(code) ?? EMPTY;
5651261 }
1262+ *eachRelocatedToCode(code: number): IterableIterator<RelocationInfo> {
1263+ if (this.#relocatedToCodePages) yield* this.#relocatedToCodePages.values(String(code));
1264+ else yield* this.#relocatedToCode.get(code) ?? EMPTY;
1265+ }
5661266
5671267 /** How many lines every atom together has written. */
5681268 get lineCount(): number {
Lines 1281–1287 at 318 (were 581–587 at 23)
5811281 /** A line's id from its n. */
5821282 #lineName(n: number): LineId {
5831283 const seq = this.#lineAtom.at(n);
584− return `${this.#atoms[seq]!.id}.${n - this.#lineBase[seq]!}`;
1284+ return `${this.idOfSeq(seq)}.${n - this.#lineBase[seq]!}`;
5851285 }
5861286
5871287 /** A node's code: a line's n, or -1 - a path's index for a start node; undefined when unknown. */
Lines 1295–1324 at 318 (were 595–603 at 23)
5951295 }
5961296
5971297 #nodeName(code: number): NodeId {
598− return code >= 0 ? this.#lineName(code) : startNode(this.#paths[-1 - code]!);
1298+ return code >= 0 ? this.#lineName(code) : startNode(this.#pathName(-1 - code));
5991299 }
6001300
1301+ /**
1302+ * A path's name by its index, kept in memory once read (abso Capacity): finding a deleted line's file names the file
1303+ * it reaches, and a stored graph read the path list each time. Cleared when the graph accepts an atom, so a name a
1304+ * rolled-back add made never stays.
1305+ */
1306+ #pathName(index: number): string {
1307+ if (this.#pathNamesAt !== this.#accepted) {
1308+ this.#pathNames.clear();
1309+ this.#pathNamesAt = this.#accepted;
1310+ }
1311+ let name = this.#pathNames.get(index);
1312+ if (name === undefined) {
1313+ name = this.#paths[index]!;
1314+ if (this.#pathNames.size >= PATH_NAMES) this.#pathNames.clear();
1315+ this.#pathNames.set(index, name);
1316+ }
1317+ return name;
1318+ }
1319+ readonly #pathNames = new Map<number, string>();
1320+ #pathNamesAt = -1;
6011322 #pathOf(file: string): number {
6021323 let p = this.#pathIndex.get(file);
6031324 if (p === undefined) {
Lines 1330–1413 at 318 (were 609–679 at 23)
6091330
6101331 /** The line ids an atom inserted, in k order. */
6111332 linesOf(id: AtomId): LineId[] {
612− const atom = this.atom(id);
613− const out: LineId[] = [];
614− const seq = atom.seq;
1333+ return [...this.eachInsertedLine(id)];
1334+ }
1335+ /** Inserted identities without decoding or allocating the atom's text. */
1336+ *eachInsertedLine(id: AtomId): IterableIterator<LineId> {
1337+ const seq = this.atom(id).seq;
6151338 const count = (seq + 1 < this.#lineBase.length ? this.#lineBase[seq + 1]! : this.#lineTotal) - this.#lineBase[seq]!;
616− for (let k = 0; k < count; k++) out.push(lineId(id, k));
617− return out;
1339+ for (let k = 0; k < count; k++) yield lineId(id, k);
6181340 }
6191341
6201342 /** Every atom that deletes this line (across the whole graph). */
6211343 deletersOf(line: LineId): readonly AtomId[] {
6221344 const n = this.#lineN(line);
6231345 if (n < 0) return EMPTY;
624− const first = this.#deleter.at(n);
625− if (first < 0) return EMPTY;
626− const more = this.#moreDeleters.get(n);
627− const out = [this.#atoms[first]!.id];
628− if (more) for (const seq of more) out.push(this.#atoms[seq]!.id);
629− return out;
1346+ return [...this.eachDeleterSeqOf(n)].map((seq) => this.idOfSeq(seq));
6301347 }
6311348
6321349 writersOf(key: Key): readonly AtomId[] {
633− return listOf(this.#writers.get(this.#code(key)));
1350+ return [...this.eachWriterOf(key)];
6341351 }
1352+ *eachWriterOf(key: Key): IterableIterator<AtomId> {
1353+ const code = this.#code(key);
1354+ if (this.#writersPages) yield* this.#writersPages.values(JSON.stringify([typeof code, code]));
1355+ else yield* listOf(this.#writers.get(code));
1356+ }
6351357
6361358 /** Atoms whose implicit reads include the key. */
6371359 readersOf(key: Key): readonly AtomId[] {
638− return listOf(this.#readers.get(this.#code(key)));
1360+ return [...this.eachReaderOf(key)];
6391361 }
1362+ *eachReaderOf(key: Key): IterableIterator<AtomId> {
1363+ const code = this.#code(key);
1364+ if (this.#readersPages) yield* this.#readersPages.values(JSON.stringify([typeof code, code]));
1365+ else yield* listOf(this.#readers.get(code));
1366+ }
6401367
6411368 /** Atoms whose explicit holds include the key. */
6421369 holdersOf(key: Key): readonly AtomId[] {
643− return listOf(this.#holders.get(this.#code(key)));
1370+ return [...this.eachHolderOf(key)];
6441371 }
1372+ *eachHolderOf(key: Key): IterableIterator<AtomId> {
1373+ const code = this.#code(key);
1374+ if (this.#holdersPages) yield* this.#holdersPages.values(JSON.stringify([typeof code, code]));
1375+ else yield* listOf(this.#holders.get(code));
1376+ }
6451377
6461378 /** Every atom that inserts or deletes a line of the file, in seq order. */
6471379 atomsIn(file: string): readonly AtomId[] {
1380+ if (this.#fileAtomPages) return [...this.#fileAtomPages.values(file)];
6481381 return this.#fileAtoms.get(file) ?? EMPTY;
6491382 }
1383+ *eachAtomIn(file: string): IterableIterator<AtomId> {
1384+ if (this.#fileAtomPages) yield* this.#fileAtomPages.values(file);
1385+ else yield* this.#fileAtoms.get(file) ?? EMPTY;
1386+ }
1387+ hasAtomsIn(file: string): boolean {
1388+ return this.#fileAtomPages ? this.#fileAtomPages.length(file) > 0 : this.#fileAtoms.has(file);
1389+ }
6501390
1391+ /** Unique historical file paths, streamed without collecting their names. */
1392+ *knownFiles(): IterableIterator<string> {
1393+ yield* this.#fileAtomPages ? this.#fileAtomPages.keys() : this.#fileAtoms.keys();
1394+ }
6511396 /**
6521397 * The files an atom inserts, deletes or moves lines in, or sets attributes
6531398 * of, sorted. For lines, the file each was written in (or, for a move to a
6541399 * start node, that file): a set's moves can have taken them elsewhere.
6551400 */
6561401 filesOf(id: AtomId): readonly string[] {
657− this.atom(id);
1402+ if (!this.has(id)) throw new EngineError("unknown-atom", `no atom ${id}`);
6581403 return this.#atomFiles[this.#seq(id)]!;
6591404 }
6601405
6611406 /** Lines written right after a node (not counting moves), in seq order. */
6621408 childrenOf(node: NodeId): LineId[] {
663− const out: LineId[] = [];
6641409 const code = this.#nodeCode(node);
665− if (code === undefined) return out;
666− // The next line of the same run hangs off this one.
667− if (
668− code >= 0 &&
669− code + 1 < this.#lineTotal &&
670− this.#lineAtom.at(code + 1) === this.#lineAtom.at(code) &&
671− this.#lineParent.at(code + 1) === code
672− ) {
673− out.push(this.#lineName(code + 1));
674− }
675− for (const n of listOf(this.#runStarts.get(code))) out.push(this.#lineName(n));
676− return out;
1410+ return code === undefined ? [] : [...this.eachChildN(code)].map((n) => this.#lineName(n));
6771411 }
6781412
6791413 /** Whether a line starts a run whose atom deleted the line it hangs off. */
Lines 1418–1484 at 318 (were 684–716 at 23)
6841418
6851419 /** Every relocation of a line, in seq order. */
6861420 relocationsOf(line: LineId): readonly RelocationInfo[] {
1421+ if (this.#relocationPages) return [...this.eachRelocationOf(line)];
6871422 return this.#relocations.get(line) ?? EMPTY;
6881423 }
1424+ *eachRelocationOf(line: LineId): IterableIterator<RelocationInfo> {
1425+ if (this.#relocationPages) yield* this.#relocationPages.values(line);
1426+ else yield* this.#relocations.get(line) ?? EMPTY;
1427+ }
6891428
6901429 /** Every relocation that puts a line right after this node, in seq order. */
6911430 relocatedTo(node: NodeId): readonly RelocationInfo[] {
1431+ if (this.#relocatedToPages) return [...this.#relocatedToPages.values(node)];
6921432 return this.#relocatedTo.get(node) ?? EMPTY;
6931433 }
6941434
6951435 /** Atoms that move lines, in seq order. */
6961436 movers(): readonly AtomId[] {
697− return this.#movers;
1437+ if (!this.#storage) return this.#movers;
1438+ // Checked against the stored list's length and last mover, so a rolled-back add can't leave one behind.
1439+ const length = this.#movers.length;
1440+ const list = this.#moverList;
1441+ if (list && list.length === length && (length === 0 || list[length - 1] === this.#movers[length - 1])) return list;
1442+ this.#moverList = [...this.#movers];
1443+ return this.#moverList;
6981444 }
6991445
7001446 /** Atoms that list this one directly in their deps. */
7011447 dependentsOf(id: AtomId): readonly AtomId[] {
702− return listOf(this.#dependents.get(id));
1448+ return [...this.eachDependentOf(id)];
7031449 }
1450+ *eachDependentOf(id: AtomId): IterableIterator<AtomId> {
1451+ if (this.#dependentsPages) yield* this.#dependentsPages.values(id);
1452+ else yield* listOf(this.#dependents.get(id));
1453+ }
7041454
7051455 /** Atoms whose `resolves` names this one. */
7061456 resolversOf(id: AtomId): readonly AtomId[] {
707− return listOf(this.#resolvers.get(id));
1457+ return [...this.eachResolverOf(id)];
7081458 }
1459+ *eachResolverOf(id: AtomId): IterableIterator<AtomId> {
1460+ if (this.#resolversPages) yield* this.#resolversPages.values(id);
1461+ else yield* listOf(this.#resolvers.get(id));
1462+ }
7091463
1464+ /**
1465+ * The atoms whose reasons point at this one, in seq order, once each; or undefined when a stored graph made before
1466+ * this index keeps none, and the caller looks at every atom (abso Capacity).
1467+ */
1468+ reasonsTo(id: AtomId): readonly AtomId[] | undefined {
1469+ if (!this.#reasonsInKept) return undefined;
1470+ if (this.#reasonsInPages) return [...this.#reasonsInPages.values(id)];
1471+ return this.#reasonsIn.get(id) ?? [];
1472+ }
7101474 /** `together` reasons touching this atom, in either direction. */
7111475 togetherLinks(id: AtomId): readonly TogetherLink[] {
712− return this.#together.get(id) ?? EMPTY;
1476+ return [...this.eachTogetherLink(id)];
7131477 }
1478+ *eachTogetherLink(id: AtomId): IterableIterator<TogetherLink> {
1479+ if (this.#togetherPages) yield* this.#togetherPages.values(id);
1480+ else yield* this.#together.get(id) ?? EMPTY;
1481+ }
7141482
7151483 /**
7161484 * The atom plus everything it depends on, transitively. Computed on demand
Lines 1524–1562 at 318 (were 756–773 at 23)
7561524 * the search never descends below the target's lamport.
7571525 */
7581526 #reaches(from: Iterable<AtomId>, target: AtomId): boolean {
759− const floor = this.#lamport[this.#seq(target)]!;
760− const seen = new Set<AtomId>();
761− const stack = [...from];
762− while (stack.length > 0) {
763− const cur = stack.pop()!;
764− if (cur === target) return true;
765− if (seen.has(cur)) continue;
766− seen.add(cur);
767− if (this.#lamport[this.#seq(cur)]! <= floor) continue;
768− for (const d of this.atom(cur).deps) if (!seen.has(d)) stack.push(d);
1527+ return this.#reachable(from, new Set([target])).has(target);
1528+ }
1530+ /**
1531+ * Which of `targets` are reachable along deps from any of `from` (themselves included), in one walk: it never
1532+ * descends below the lowest target's lamport, and stops once every target is found (abso 714, piece 4: record
1533+ * walked once per line writer).
1534+ * The walk's seen marks and stack are in memory, by atom number: one byte and four bytes an atom at most, so about
1535+ * 62 KB on abso's 12,454 atoms and 50 MB at 10 million, under a Worker's 128 MB. They were scratch rows in storage
1536+ * (abso-core 139, bounding memory with the graph), which cost a read and a write per atom visited: on abso's Oct 14
1537+ * tables, 41,000 of a 1470-shaped record's 77,767 statements.
1538+ */
1539+ #reachable(from: Iterable<AtomId>, targets: ReadonlySet<AtomId>): Set<AtomId> {
1540+ const found = new Set<AtomId>();
1541+ let floor = Number.POSITIVE_INFINITY;
1542+ for (const target of targets) floor = Math.min(floor, this.#lamportAt(this.#seq(target)));
1543+ const seen = new Uint8Array(this.#atoms.length);
1544+ const stack = new Int32Array(this.#atoms.length);
1545+ let length = 0;
1546+ const visit = (id: AtomId): void => {
1547+ if (targets.has(id)) found.add(id);
1548+ const seq = this.#seq(id);
1549+ if (seen[seq]) return;
1550+ seen[seq] = 1;
1551+ stack[length++] = seq;
1552+ };
1553+ for (const id of from) visit(id);
1554+ while (length > 0 && found.size < targets.size) {
1555+ const seq = stack[--length]!;
1556+ if (this.#lamportAt(seq) <= floor) continue;
1557+ for (const dependency of this.atom(atomId(seq)).deps) visit(dependency);
7691558 }
770− return false;
1559+ return found;
7711560 }
7721561
7731562 /**
Lines 1565–1591 at 318 (were 776–781 at 23)
7761565 * The atom is frozen. Adding to the graph does not add it to any set.
7771566 */
7781567 add(atom: Atom): void {
1568+ // A new atom appends to its files' histories; a failed one may leave a kept history longer than the lists.
1569+ this.#histories.clear();
1570+ this.#historyBytes = 0;
1571+ if (this.#storage)
1572+ this.#storage.transaction(() => {
1573+ this.#add(atom);
1574+ const result: unknown = this.#indexAcceptedAtom?.(atom, this.filesOf(atom.id), this.#storage!);
1575+ if (result && typeof result === "object" && "then" in result)
1576+ throw Error("accepted atom indexing must be synchronous");
1577+ });
1578+ else this.#add(atom);
1579+ }
1581+ #validateAcceptedAtom(atom: Atom, scratch?: GraphStateStorage): void {
1582+ const membership = <T extends string>(name: string): { has(key: T): boolean; add(key: T): unknown } => {
1583+ if (!scratch) return new Set<T>();
1584+ return {
1585+ has: (key) => scratch.read(name, key) === true,
1586+ add: (key) => scratch.write(name, key, true),
1587+ };
1588+ };
7791589 validateShape(atom);
7801590 const seq = this.#atoms.length;
7811591 const bad = (why: string): never => {
Lines 1593–1633 at 318 (were 783–810 at 23)
7831593 };
7841594 if (atom.seq !== seq || atom.id !== atomId(seq)) bad(`expected id ${atomId(seq)} with seq ${seq}`);
7851595
786− const deps = new Set<AtomId>();
1596+ const deps = membership<AtomId>("deps");
7871597 for (const d of atom.deps) {
7881598 if (!this.has(d)) bad(`dependency ${d} is not in the graph`);
7891599 if (deps.has(d)) bad(`dependency ${d} listed twice`);
7901600 deps.add(d);
7911601 }
792− for (const d of [...atom.needs, ...atom.resolves]) {
793− if (!deps.has(d)) bad(`${d} is in needs/resolves but not in deps`);
794− }
1602+ for (const list of [atom.needs, atom.resolves])
1603+ for (const d of list) {
1604+ if (!deps.has(d)) bad(`${d} is in needs/resolves but not in deps`);
1605+ }
7951606 for (const r of atom.reasons) if (!this.has(r.to)) bad(`reason points at unknown atom ${r.to}`);
7961607
7971608 // Everything it touches must come from its closure. Derived deps name the
798− // writers directly, so this is usually one lookup per writer.
799− const below = new Map<AtomId, boolean>();
800− const inClosure = (writer: AtomId): boolean => {
801− let hit = below.get(writer);
802− if (hit === undefined) {
803− hit = deps.has(writer) || this.#reaches(deps, writer);
804− below.set(writer, hit);
1609+ // writers directly, so this is usually one lookup per writer. The writers
1610+ // that aren't deps are walked for together, once (abso 714, piece 4).
1611+ const touched: LineId[] = [];
1612+ for (const run of atom.inserts) if (!isStartNode(run.parent)) touched.push(run.parent);
1613+ for (const m of atom.moves ?? []) {
1614+ touched.push(m.line);
1615+ if (!isStartNode(m.parent)) touched.push(m.parent);
1616+ }
1617+ touched.push(...atom.deletes);
1618+ for (const list of [atom.writes, atom.reads, atom.holds])
1619+ for (const key of list) {
1620+ const parsed = parseKey(key);
1621+ if (parsed.kind === "line" || ((parsed.kind === "gap" || parsed.kind === "pos") && !isStartNode(parsed.node)))
1622+ touched.push(parsed.node);
8051623 }
806− return hit;
807− };
1624+ const beyond = new Set<AtomId>();
1625+ for (const line of touched) {
1626+ const writer = this.lineAtom(line);
1627+ if (writer !== undefined && !deps.has(writer)) beyond.add(writer);
1628+ }
1629+ const reached = beyond.size > 0 ? this.#reachable(atom.deps, beyond) : beyond;
1630+ const inClosure = (writer: AtomId): boolean => deps.has(writer) || reached.has(writer);
8081631 const checkLine = (line: LineId, what: string): void => {
8091632 const writer = this.lineAtom(line);
8101633 if (writer === undefined) return bad(`${what} names unknown line ${line}`);
Lines 1642–1889 at 318 (were 819–923 at 23)
8191642 checkLine(run.parent, "an insert");
8201643 }
8211644 }
822− const moved = new Set<LineId>();
1645+ const writes = membership<Key>("writes");
1646+ for (const key of atom.writes) writes.add(key);
1647+ const moved = membership<LineId>("moved");
8231648 for (const m of atom.moves ?? []) {
8241649 checkLine(m.line, "a move");
8251650 if (!isStartNode(m.parent)) checkLine(m.parent, "a move");
8261651 if (m.line === m.parent) bad(`moves ${m.line} after itself`);
8271652 if (moved.has(m.line)) bad(`moves ${m.line} twice`);
8281653 moved.add(m.line);
829− if (!atom.writes.includes(posKey(m.line)) || !atom.writes.includes(gapKey(m.parent))) {
1654+ if (!writes.has(posKey(m.line)) || !writes.has(gapKey(m.parent))) {
8301655 bad(`moves ${m.line} without writing ${posKey(m.line)} and ${gapKey(m.parent)}`);
8311656 }
8321657 }
833− const deleted = new Set<LineId>();
1658+ const deleted = membership<LineId>("deleted");
8341659 for (const line of atom.deletes) {
8351660 checkLine(line, "a delete");
8361661 if (deleted.has(line)) bad(`deletes ${line} twice`);
8371662 deleted.add(line);
8381663 }
839− const writes = new Set(atom.writes);
840− for (const line of deleted) if (!writes.has(lineKey(line))) bad(`deletes ${line} without writing ${lineKey(line)}`);
841− for (const key of [...atom.writes, ...atom.reads, ...atom.holds]) {
842− const parsed = parseKey(key);
843− if (parsed.kind === "line") checkLine(parsed.node, `key ${key}`);
844− else if ((parsed.kind === "gap" || parsed.kind === "pos") && !isStartNode(parsed.node))
845− checkLine(parsed.node, `key ${key}`);
1664+ for (const line of atom.deletes)
1665+ if (!writes.has(lineKey(line))) bad(`deletes ${line} without writing ${lineKey(line)}`);
1666+ for (const list of [atom.writes, atom.reads, atom.holds])
1667+ for (const key of list) {
1668+ const parsed = parseKey(key);
1669+ if (parsed.kind === "line") checkLine(parsed.node, `key ${key}`);
1670+ else if ((parsed.kind === "gap" || parsed.kind === "pos") && !isStartNode(parsed.node))
1671+ checkLine(parsed.node, `key ${key}`);
1672+ }
1673+ }
1675+ #add(atom: Atom): void {
1676+ if (this.#storage && this.#storage.read("ordered-children", "format") !== 2) {
1677+ if (this.#atoms.length !== 0) throw new Error("ordered children require fresh adoption");
1678+ this.#storage.write("ordered-children", "format", 2);
8461679 }
1680+ if (this.#storage && this.#atoms.length === 0 && this.#packFiles) {
1681+ this.#storage.write("file-lines:meta", "format", 2);
1682+ this.#storage.write("reasons-in:meta", "kept", 1);
1683+ this.#reasonsInKnown = true;
1684+ this.#formatKnown = 2;
1685+ }
8471686
1687+ if (this.#storage) this.withProjectionScratch((scratch) => this.#validateAcceptedAtom(atom, scratch));
1688+ else this.#validateAcceptedAtom(atom);
1689+ const seq = this.#atoms.length;
1690+ const deps = atom.deps;
1691+ const deleted = this.#storage ? undefined : new Set(atom.deletes);
1692+ const writes = this.#storage ? atom.writes : new Set(atom.writes);
8481694 // Accept.
849− const frozen = freezeAtom(
850− atom,
851− (id) => this.#atoms[seqOf(id)]!.id,
852− (author) => {
853− let a = this.#authors.get(author);
854− if (a === undefined) this.#authors.set(author, (a = author));
855− return a;
856− },
857− this.#texts ? this.#reader(seq) : undefined,
858− this.#lists ? this.#listReader(seq) : undefined,
859− );
860− this.#atoms.push(frozen);
1695+ // Persistent storage copies the accepted atom; a second frozen copy only duplicates its lists.
1696+ const frozen = this.#storage
1697+ ? atom
1698+ : freezeAtom(
1699+ atom,
1700+ (id) => this.idOfSeq(seqOf(id)),
1701+ (author) => {
1702+ if (this.#storage) return author;
1703+ let a = this.#authors.get(author);
1704+ if (a === undefined) this.#authors.set(author, (a = author));
1705+ return a;
1706+ },
1707+ this.#texts ? this.#reader(seq) : undefined,
1708+ this.#lists ? this.#listReader(seq) : undefined,
1709+ );
1710+ this.#atoms.push(this.#storage ? atom : frozen);
1711+ this.#accepted++;
8611712 let lam = 0;
8621713 for (const d of deps) lam = Math.max(lam, this.lamport(d) + 1);
863− this.#lamport.push(lam);
1714+ if (this.#lamportPages) this.#lamportPages.push(lam);
1715+ else this.#lamport.push(lam);
8641716
8651717 // The run starts' parents and the deleted lines, as codes, before this atom's own lines exist.
8661718 // The atom as given: with lists kept elsewhere, the frozen one reads them back from the log.
867− const deletes = atom.deletes.length > 0 ? new Set(atom.deletes) : undefined;
868− const deletedN = atom.deletes.map((line) => this.#lineN(line));
869− this.#atomDeletes.push(deletedN.length > 0 ? Int32Array.from(deletedN) : undefined);
1719+ const deletes = (line: LineId | NodeId): boolean => {
1720+ if (isStartNode(line)) return false;
1721+ if (deleted) return deleted.has(line);
1722+ const n = this.#lineN(line);
1723+ return this.#deleter.at(n) === seq || this.#moreDeleterPages!.last(String(n)) === seq;
1724+ };
1725+ const deletedN = this.#storage ? undefined : atom.deletes.map((line) => this.#lineN(line));
1726+ this.#atomDeletes.push(deletedN?.length ? Int32Array.from(deletedN) : undefined);
1727+ if (this.#storage) {
1728+ const pages = storedLists<number>(this.#storage, "atom-deletes");
1729+ for (const line of atom.deletes) pages.append(String(seq), this.#lineN(line));
1730+ this.#storage.write("atom-delete-counts", String(seq), atom.deletes.length);
1731+ }
1732+ const deletedNumbers = function* (graph: Graph) {
1733+ if (deletedN) yield* deletedN;
1734+ else for (const line of atom.deletes) yield graph.#lineN(line);
1735+ };
1736+ const packedDeletes = new Map<number, PackedDelete[]>();
1737+ for (const n of deletedNumbers(this)) {
1738+ if (this.#packed) {
1739+ const file = this.#lineFile.at(n);
1740+ const list = packedDeletes.get(file);
1741+ if (list) list.push([n, seq]);
1742+ else packedDeletes.set(file, [[n, seq]]);
1743+ }
1744+ if (this.#deleter.at(n) < 0) this.#deleter.set(n, seq);
1745+ else if (this.#moreDeleterPages) this.#moreDeleterPages.append(String(n), seq);
1746+ else pushIndex(this.#moreDeleters, n, seq);
1747+ }
1748+ for (const [file, list] of packedDeletes) this.#fileDeletes!.appendAll(String(file), list);
8701749 this.#lineBase.push(this.#lineTotal);
8711750 for (const run of atom.inserts) {
8721751 const file = this.#pathOf(run.file);
8731752 let parent = isStartNode(run.parent) ? -1 - file : this.#lineN(run.parent);
8741753 const first = this.#lineTotal;
875− pushOne(this.#runStarts, parent, first);
1754+ if (parent >= 0) this.#childCounts?.increment(parent, first);
1755+ if (this.#storage)
1756+ new OrderedIndex(this.#storage, "ordered-children", String(parent)).insert(
1757+ orderedChildKey({
1758+ n: first,
1759+ replaces: deletes(run.parent) ? 1 : 0,
1760+ lamport: lam,
1761+ seq,
1762+ k: first - this.#lineBase[seq]!,
1763+ }),
1764+ first,
1765+ );
1767+ if (this.#runStartPages) this.#runStartPages.append(String(parent), first);
1768+ else pushOne(this.#runStarts, parent, first);
1769+ const replacesParent = deletes(run.parent) ? 1 : 0;
1770+ if (this.#packed) {
1771+ if (this.#crossings && parent >= 0) {
1772+ const from = this.#lineFile.at(parent);
1773+ if (from !== file) this.#fileCrossings!.append(String(from), [parent, file]);
1774+ }
1775+ const base = this.#lineBase[seq]!;
1776+ this.#fileLines!.appendAll(
1777+ String(file),
1778+ run.lines.map(
1779+ (_, i): PackedLine => [
1780+ first + i,
1781+ i === 0 ? parent : first + i - 1,
1782+ seq,
1783+ first + i - base,
1784+ i === 0 ? replacesParent : 0,
1785+ ],
1786+ ),
1787+ );
1788+ this.#fileTexts!.appendAll(
1789+ String(file),
1790+ run.lines.map((text) => (typeof text === "string" && text.length <= PACKED_TEXT ? text : null)),
1791+ );
1792+ }
8761793 for (let i = 0; i < run.lines.length; i++) {
877− const n = this.#lineTotal++;
1794+ const n = this.#lineTotal;
1795+ this.#childCounts?.append(n);
8781796 this.#lineAtom.push(seq);
8791797 this.#lineFile.push(file);
8801798 this.#lineParent.push(parent);
8811799 this.#lineText?.push(run.lines[i]!);
8821800 this.#deleter.push(-1);
883− this.#replacing.push(i === 0 && deletes?.has(run.parent) ? 1 : 0);
1801+ this.#replacing.push(i === 0 && deletes(run.parent) ? 1 : 0);
8841802 parent = n;
8851803 }
8861804 }
8871805 (frozen.moves ?? []).forEach((m, i) => {
888− const info: RelocationInfo = Object.freeze({ atom: frozen.id, line: m.line, parent: m.parent, k: i });
889− pushIndex(this.#relocations, m.line, info);
890− pushIndex(this.#relocatedTo, m.parent, info);
891− pushIndex(
892− this.#relocatedToCode,
893− isStartNode(m.parent) ? -1 - this.#pathOf(m.parent.slice(1)) : this.#lineN(m.parent),
894− info,
895− );
1806+ const info: RelocationInfo = Object.freeze({
1807+ atom: frozen.id,
1808+ line: m.line,
1809+ parent: m.parent,
1810+ k: i,
1811+ });
1812+ if (this.#relocationPages) this.#relocationPages.append(m.line, info);
1813+ else pushIndex(this.#relocations, m.line, info);
1814+ if (this.#relocatedToPages) this.#relocatedToPages.append(m.parent, info);
1815+ else pushIndex(this.#relocatedTo, m.parent, info);
1816+ const parentCode = isStartNode(m.parent) ? -1 - this.#pathOf(m.parent.slice(1)) : this.#lineN(m.parent);
1817+ if (this.#relocatedToCodePages) this.#relocatedToCodePages.append(String(parentCode), info);
1818+ else pushIndex(this.#relocatedToCode, parentCode, info);
8961819 });
8971820 if (frozen.moves) this.#movers.push(frozen.id);
898− for (const n of deletedN) {
899− if (this.#deleter.at(n) < 0) this.#deleter.set(n, seq);
900− else pushIndex(this.#moreDeleters, n, seq);
1821+ if (this.#packed)
1822+ for (const a of frozen.attrs ?? []) this.#fileAttrs!.append(String(this.#pathOf(a.file)), [seq, a.name, a.value]);
1823+ for (const key of writes) {
1824+ const code = this.#code(key);
1825+ if (this.#writersPages) {
1826+ const key = JSON.stringify([typeof code, code]);
1827+ if (this.#writersPages.last(key) !== frozen.id) this.#writersPages.append(key, frozen.id);
1828+ } else pushOne(this.#writers, code, frozen.id);
9011829 }
902− for (const key of new Set(atom.writes)) pushOne(this.#writers, this.#code(key), frozen.id);
903− for (const key of new Set(atom.reads)) pushOne(this.#readers, this.#code(key), frozen.id);
904− for (const key of new Set(atom.holds)) pushOne(this.#holders, this.#code(key), frozen.id);
905− for (const d of deps) pushOne(this.#dependents, d, frozen.id);
906− for (const r of new Set(frozen.resolves)) pushOne(this.#resolvers, r, frozen.id);
1830+ for (const key of this.#storage ? atom.reads : new Set(atom.reads)) {
1831+ const code = this.#code(key);
1832+ if (this.#readersPages) {
1833+ const key = JSON.stringify([typeof code, code]);
1834+ if (this.#readersPages.last(key) !== frozen.id) this.#readersPages.append(key, frozen.id);
1835+ } else pushOne(this.#readers, code, frozen.id);
1836+ }
1837+ for (const key of this.#storage ? atom.holds : new Set(atom.holds)) {
1838+ const code = this.#code(key);
1839+ if (this.#holdersPages) {
1840+ const key = JSON.stringify([typeof code, code]);
1841+ if (this.#holdersPages.last(key) !== frozen.id) this.#holdersPages.append(key, frozen.id);
1842+ } else pushOne(this.#holders, code, frozen.id);
1843+ }
1844+ for (const d of deps) {
1845+ if (this.#dependentsPages) this.#dependentsPages.append(d, frozen.id);
1846+ else pushOne(this.#dependents, d, frozen.id);
1847+ }
1848+ for (const r of this.#storage ? frozen.resolves : new Set(frozen.resolves)) {
1849+ if (this.#resolversPages) {
1850+ if (this.#resolversPages.last(r) !== frozen.id) this.#resolversPages.append(r, frozen.id);
1851+ } else pushOne(this.#resolvers, r, frozen.id);
1852+ }
9071853 const files = new Set<string>();
9081854 for (const run of atom.inserts) files.add(run.file);
909− for (const n of deletedN) files.add(this.#paths[this.#lineFile.at(n)]!);
1855+ for (const n of deletedNumbers(this)) files.add(this.#pathName(this.#lineFile.at(n)));
9101856 for (const a of frozen.attrs ?? []) files.add(a.file);
9111857 for (const m of frozen.moves ?? []) {
9121858 files.add(this.lineFile(m.line)!);
9131859 files.add(isStartNode(m.parent) ? m.parent.slice(1) : this.lineFile(m.parent)!);
9141860 }
9151861 this.#atomFiles.push(Object.freeze([...files].sort()));
916− for (const file of files) pushIndex(this.#fileAtoms, file, frozen.id);
1862+ for (const file of files) {
1863+ if (this.#fileAtomPages) this.#fileAtomPages.append(file, frozen.id);
1864+ else pushIndex(this.#fileAtoms, file, frozen.id);
1865+ }
1866+ if (this.#reasonsInKept) {
1867+ const pointed = new Set<AtomId>();
1868+ for (const r of frozen.reasons) {
1869+ if (pointed.has(r.to)) continue;
1870+ pointed.add(r.to);
1871+ if (this.#reasonsInPages) this.#reasonsInPages.append(r.to, frozen.id);
1872+ else pushIndex(this.#reasonsIn, r.to, frozen.id);
1873+ }
1874+ }
9171875 for (const r of frozen.reasons) {
9181876 if (r.kind !== "together" || r.to === frozen.id) continue;
919− pushIndex(this.#together, frozen.id, { other: r.to, text: r.text, from: frozen.id });
920− pushIndex(this.#together, r.to, { other: frozen.id, text: r.text, from: frozen.id });
1878+ const forward = { other: r.to, text: r.text, from: frozen.id };
1879+ const reverse = { other: frozen.id, text: r.text, from: frozen.id };
1880+ if (this.#togetherPages) {
1881+ this.#togetherPages.append(frozen.id, forward);
1882+ this.#togetherPages.append(r.to, reverse);
1883+ } else {
1884+ pushIndex(this.#together, frozen.id, forward);
1885+ pushIndex(this.#together, r.to, reverse);
1886+ }
9211887 }
9221888 }
9231889
Lines 1940–1949 at 318 (were 974–979 at 23)
9741940 * their base instead, so their contents don't change.
9751941 */
9761942 removeLabel(name: string): boolean {
1943+ return this.#storage ? this.#storage.transaction(() => this.#removeLabel(name)) : this.#removeLabel(name);
1944+ }
1946+ #removeLabel(name: string): boolean {
9771947 const gone = this.#labels.get(name);
9781948 if (!gone) return false;
9791949 this.#labels.delete(name);
Lines 1956–1967 at 318 (were 986–992 at 23)
9861956 // JSON -------------------------------------------------------------------
9871957
9881958 toJSON(): GraphJSON {
989− return { format: GRAPH_FORMAT, version: 1, atoms: this.#atoms, labels: this.labels() };
1959+ return {
1960+ format: GRAPH_FORMAT,
1961+ version: 1,
1962+ atoms: this.#atoms,
1963+ labels: this.labels(),
1964+ };
9901965 }
9911966
9921967 /** Load a saved graph. Every atom is re-validated as it is added. */
Lines 2061–2072 at 318 (were 1086–1092 at 23)
10862061 // With text kept elsewhere (#46), a run's lines are read when asked for.
10872062 let k = 0;
10882063 const run = (r: InsertRun): InsertRun => {
1089− if (!text) return Object.freeze({ file: r.file, parent: r.parent, lines: Object.freeze([...r.lines]) });
2064+ if (!text)
2065+ return Object.freeze({
2066+ file: r.file,
2067+ parent: r.parent,
2068+ lines: Object.freeze([...r.lines]),
2069+ });
10902070 const start = k;
10912071 const length = r.lines.length;
10922072 k += length;
Lines 2081–2105 at 318 (were 1101–1116 at 23)
11012081 inserts: Object.freeze(atom.inserts.map(run)),
11022082 ...(lists
11032083 ? {}
1104− : { deletes: list(atom.deletes), writes: list(atom.writes), reads: list(atom.reads), holds: list(atom.holds) }),
2084+ : {
2085+ deletes: list(atom.deletes),
2086+ writes: list(atom.writes),
2087+ reads: list(atom.reads),
2088+ holds: list(atom.holds),
2089+ }),
11052090 needs: list(atom.needs, canon),
11062091 resolves: list(atom.resolves, canon),
11072092 reasons: list(atom.reasons, (r) => Object.freeze({ to: canon(r.to), kind: r.kind, text: r.text })),
11082093 deps: list(atom.deps, canon),
11092094 ...(atom.attrs && atom.attrs.length > 0
1110− ? { attrs: Object.freeze(atom.attrs.map((a) => Object.freeze({ file: a.file, name: a.name, value: a.value }))) }
2095+ ? {
2096+ attrs: Object.freeze(atom.attrs.map((a) => Object.freeze({ file: a.file, name: a.name, value: a.value }))),
2097+ }
11112098 : {}),
11122099 ...(atom.moves
1113− ? { moves: Object.freeze(atom.moves.map((m) => Object.freeze({ line: m.line, parent: m.parent }))) }
2100+ ? {
2101+ moves: Object.freeze(atom.moves.map((m) => Object.freeze({ line: m.line, parent: m.parent }))),
2102+ }
11142103 : {}),
11152104 } as Atom;
11162105 return Object.freeze(lists ? (new ListedAtom(copy, lists) as unknown as Atom) : copy);
MCP
compare on this site's /mcp
CLI
abso diff 23 318 src/engine/graph.ts --json
JSON
/christopher/abso-core/compare/23..318?file=src%2Fengine%2Fgraph.ts&format=json