- MCP
- blame on this site's /mcp
- CLI
- abso blame src/engine/graph.ts --version 229 --json
- JSON
- /christopher/abso-core/blame/src/engine/graph.ts?version=229&format=json
1,894 linesFirst import 52% · codex-capacity-chair 39% · capacity 9%Last change capacity in version 228,
1,894 lines from 28 changes in 27 versions.
init0Start the project1// 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.
codex-capacity-chair137Page explicit child counts with bounded corruption checksCompare5import { ChildCounts } from "./child-counts.ts";
codex-capacity-chair175Reduce disk-backed record and publish allocations; reviewed in core ask 52 with parsed-code budget and exact aligned-line follow-ups. Keep disk-first activation off.Compare6import { JsonStringChunks, registerJsonChunkValue } from "./json-value-chunks.ts";
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";
codex-capacity-chair131Bound persisted no-move layout with ordered successor traversalCompare20import { OrderedIndex, orderedChildKey } from "./ordered-index.ts";
codex-capacity-chair132Bound persistent relocation projection memory with rollback-only scratchCompare21import { withProjectionScratch } from "./projection-scratch.ts";
codex-capacity-chair119Page per-file atom indexes and stream current-view attribute scansCompare23 type GraphStateStorage,
codex-capacity-chair162Add reviewed disk-first history and indexed graph storage for core issue 16; retain runtime activation gateCompare24 readonlyStoredArray,
codex-capacity-chair119Page per-file atom indexes and stream current-view attribute scansCompare25 type StateMap,
26 storedArray,
27 storedLists,
28 storedMap,
29 storedNumbers,
30} from "./state-source.ts";
codex-capacity-chair162Add reviewed disk-first history and indexed graph storage for core issue 16; retain runtime activation gateCompare31import { StoredText } from "./stored-text.ts";
codex-capacity-chair119Page per-file atom indexes and stream current-view attribute scansCompare32import {
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;
60}
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;
68}
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;
76}
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[];
86}
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 */
codex-capacity-chair109Add opt-in persistent writer state, checked reopen and bounded adoptionCompare93function pushOne<K, V>(map: StateMap<K, V | V[]>, key: K, value: V): void {
95 if (had === undefined) map.set(key, value);
codex-capacity-chair109Add opt-in persistent writer state, checked reopen and bounded adoptionCompare96 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];
104}
codex-capacity-chair109Add opt-in persistent writer state, checked reopen and bounded adoptionCompare106function pushIndex<K, V>(map: StateMap<K, V[]>, key: K, value: V): void {
codex-capacity-chair109Add opt-in persistent writer state, checked reopen and bounded adoptionCompare108 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 }
146}
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[];
159}
161function listItems(l: AtomLists): number {
162 return l.deletes.length + l.writes.length + l.reads.length + l.holds.length;
163}
165function frozenList<T>(xs: readonly T[]): readonly T[] {
166 return xs.length === 0 ? (EMPTY as readonly T[]) : Object.freeze([...xs]);
167}
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 }
194}
196/** A growable array of 32-bit integers: a line's fields cost 4 bytes each, not an object and its strings (#46). */
codex-capacity-chair109Add opt-in persistent writer state, checked reopen and bounded adoptionCompare197interface NumberIndex {
198 readonly length: number;
199 push(n: number): void;
200 at(i: number): number;
201 set(i: number, n: number): void;
202}
204class Ints implements NumberIndex {
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 }
226}
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 };
257}
capacity206Each file's line history packed (disk-first 2, lines by file; abso Capacity). A stored graph appends every line written in a file ([n, parent code, writer seq, k, replaces]) and its text, every delete of one of its lines, and every attribute set on it to that file's pages as atoms are added, a run at a time (storedLists appendAll). A view lays a file out from those pages in memory: membership checked once per atom, moves followed from the ones it already resolved, lines moved in from other files read from theirs. Same tree and order as before (packed-files.test.ts checks it against the in-memory graph through edits, deletes and moves). Graphs adopted before have no packs and lay out line by line as before; packFiles: false keeps that path for its tests. On game's export: first shared() 13 s to 2-3.6 s at 20,000 queries, warm 56-82 ms, pathsAt(head) 29-119 ms; files at a version 14 s to 3 s, compare 26 s to 11 s, a path's log 27 s to 4.5 s; every answer the harness finished matches Project.load.Compare259/** A line in its file's packed history: [n, parent code, writer seq, k, 1 when it replaces its parent]. */
260export type PackedLine = [number, number, number, number, number];
261/** A delete of a line in a file's packed history: [n, deleter seq]. */
262export type PackedDelete = [number, number];
263/** An attribute set on a file: [seq, name, value]. */
264export type PackedAttr = [number, string, string | null];
capacity221Packed layout follows lines written in another file (disk-first 2; abso Capacity).
where {} on typescript-rs left 11 lines out of erasable_syntax.rs in cloud-ts-12's draft. cloud-ts-12 moved one block between files several times, wrote lines under its last line while it sat in uninitialized_props_forms.rs, then moved the block on. Those lines followed their parent with no move of their own. The packed layout read only the file's own lines and the files its moved-in lines were written in, so it never read them.
- Each file's packed history also keeps the runs written in another file under one of its lines (file-crossings). The packed layout follows them until no new file turns up.
- New adoptions write packed format 2. A graph packed at format 1 has no such list, so it lays files out line by line: correct, but slower until it is adopted again.
- packed-crossings.test.ts moves c.ts to d.ts, adds a line in d.ts, moves d.ts to e.ts, and checks files, where and every draft's text against the in-memory project.
Named tests: packed-crossings, packed-files, state-source, draft-reads-stored, version-files, project-writer-storage, writer-adoption, moves, queued-moves, files-reads, move-reconstruction (60 of 60); tsc and biome clean.Compare265/** A run written in another file under one of a file's lines: [the parent's n, the run's file index]. */
266export type PackedCrossing = [number, number];
capacity212Draft reads on a stored writer (disk-first 2; abso Capacity): where, drafts, status and collisions on website's export.
- where looks deleted lines up by number (graph.deletedNumbers, View.fileOfNumber, View.lineNumberOf). It takes the agent's view once instead of once per line, since each read weighed every cached view. It finds the draft's lines by writer (View.visibleWriters), with no text or id read per line.
- Draft files (overlaps.ts) go by number the same way.
- An agent's view takes its base's resolved moves when both hold the same atoms that move lines (View.shareMoves checks this).
- Draft collisions:
- build the union view only when two drafts share a file;
- work out each agent's touched files and its "shared now plus draft" view once;
- find claimants among the drafts from the drafts' own keys (collisions.ts claimantsAmong) instead of walking each key's history;
- have the definition rule keep a draft's uses, and the newer work's definitions, across partners.
- A stored list read in order reads its length once, not before every element.
draft-reads-stored.test.ts checks where and collisions against the in-memory project. It covers edits, a whole file deleted, a line collision, one name defined twice, and bases before and after a move. 135 of 136 related tests pass; none fail.
On website's export (1,387 entries) the answers match Project.load:
- status: 17 s to 4.5 s
- where: over 60 s to 8.8 s
- drafts: 14 s to 5.3 s
- collisions: over 60 s to 54 s, measured under the profiler before the last two changesCompare267const EMPTY_NUMBERS: readonly number[] = Object.freeze([]);
capacity206Each file's line history packed (disk-first 2, lines by file; abso Capacity). A stored graph appends every line written in a file ([n, parent code, writer seq, k, replaces]) and its text, every delete of one of its lines, and every attribute set on it to that file's pages as atoms are added, a run at a time (storedLists appendAll). A view lays a file out from those pages in memory: membership checked once per atom, moves followed from the ones it already resolved, lines moved in from other files read from theirs. Same tree and order as before (packed-files.test.ts checks it against the in-memory graph through edits, deletes and moves). Graphs adopted before have no packs and lay out line by line as before; packFiles: false keeps that path for its tests. On game's export: first shared() 13 s to 2-3.6 s at 20,000 queries, warm 56-82 ms, pathsAt(head) 29-119 ms; files at a version 14 s to 3 s, compare 26 s to 11 s, a path's log 27 s to 4.5 s; every answer the harness finished matches Project.load.Compare268/** Lines longer than this aren't packed with their file; their text is read on its own. */
269const PACKED_TEXT = 4096;
codex-capacity-chair109Add opt-in persistent writer state, checked reopen and bounded adoptionCompare272 readonly #storage?: GraphStateStorage;
codex-capacity-chair137Page explicit child counts with bounded corruption checksCompare273 readonly #childCounts?: ChildCounts;
275 #lamport: number[] = [];
capacity228Lamport numbers 256 to a row, and movers read once per graph (disk-first 2; abso Capacity).
After 226, where on typescript-rs still read about 12,000 lamport rows (one per atom, for ordering a file's lines) and the movers list (1,024 rows, one per atom that moves lines) nine times over.
- A stored graph keeps its atoms' lamport numbers in pages of 256 (lamport-pages), from a fresh graph on. A graph that already keeps them a row each goes on doing so. The choice is made when a number is first needed, so opening still reads nothing.
- A stored graph reads its movers once and keeps them, checked against the stored list's length and last mover on each use so a rolled-back add can't leave one behind.
On typescript-rs adopted fresh, cold: where 59,000 reads to 39,000. Its time locally is now mostly work, not reads (5.2 s). 26 of 27 answers match replay; collisions still runs past 60 s.
New test lamport-pages: a fresh graph keeps pages and reopens with them; a graph with a row each reads them and writes the next atom as a row. Named tests: every engine test (288 of 288), membership-pages, stored-closure, draft-reads-stored, version-files, packed-crossings, project-writer-storage, writer-adoption, moves, view-cache (36 of 36); tsc and biome clean.Compare276 /**
277 * A stored graph's lamport numbers, 256 to a row (abso Capacity). A graph that already has them a row each (#lamport)
278 * keeps that; the choice is made when first needed, so opening reads nothing.
279 */
280 #lamportPaged: ReturnType<typeof storedNumbers> | undefined;
281 #lamportPagesKnown: ReturnType<typeof storedNumbers> | null | undefined;
282 get #lamportPages(): ReturnType<typeof storedNumbers> | null {
283 if (this.#lamportPagesKnown === undefined)
284 this.#lamportPagesKnown =
285 this.#lamportPaged && this.#storage!.read("lamport:meta", "length") === undefined ? this.#lamportPaged : null;
286 return this.#lamportPagesKnown;
287 }
init0Start the project288 // Lines, packed (#46): line n is the k-th line atom seq wrote, n = #lineBase[seq] + k. Each holds its
289 // atom's seq, the file it was written in (an index into #paths) and its parent (a line's n, or -1 - a
290 // path's index for a file's start). Its text stays in the atom. Ids and LineInfo objects are made only
291 // when asked for, so a line costs about 16 bytes here instead of a record, its id and its parent's id.
292 #lineBase: number[] = [];
codex-capacity-chair109Add opt-in persistent writer state, checked reopen and bounded adoptionCompare293 #lineAtom: NumberIndex = new Ints();
294 #lineFile: NumberIndex = new Ints();
295 #lineParent: NumberIndex = new Ints();
init0Start the project296 /** Lines' text, when the graph keeps it; without it, it comes from `texts` (#46, text on disk). */
297 #lineText: string[] | undefined = [];
codex-capacity-chair109Add opt-in persistent writer state, checked reopen and bounded adoptionCompare298 get #lineTotal(): number {
299 return this.#lineAtom.length;
300 }
init0Start the project301 /** Where an atom's lines' text is when the graph doesn't keep it: each run's lines, by the atom's seq. */
302 #texts: ((seq: number) => readonly (readonly string[])[]) | undefined;
303 /** Recently read atoms' text, flattened, most recent last, up to TEXT_CACHE characters. */
304 #textCache = new Map<number, readonly string[]>();
305 #textCached = 0;
codex-capacity-chair149Index atom metadata for resumable projection adoptionCompare307 readonly #indexAcceptedAtom?: (atom: Atom, files: readonly string[], storage: GraphStateStorage) => void;
310 * `texts`, when given, says where each atom's lines' text can be read back
311 * (#46): the graph then keeps no text, only each line's place, and reads an
312 * atom's text when a line of it is asked for, keeping the most recent.
313 */
314 constructor(
codex-capacity-chair109Add opt-in persistent writer state, checked reopen and bounded adoptionCompare315 options: {
316 texts?: (seq: number) => readonly (readonly string[])[];
317 lists?: (seq: number) => AtomLists;
318 storage?: GraphStateStorage;
codex-capacity-chair149Index atom metadata for resumable projection adoptionCompare319 /** Optional derived indexing inside persistent atom acceptance; must be synchronous. */
320 indexAcceptedAtom?: (atom: Atom, files: readonly string[], storage: GraphStateStorage) => void;
capacity206Each file's line history packed (disk-first 2, lines by file; abso Capacity). A stored graph appends every line written in a file ([n, parent code, writer seq, k, replaces]) and its text, every delete of one of its lines, and every attribute set on it to that file's pages as atoms are added, a run at a time (storedLists appendAll). A view lays a file out from those pages in memory: membership checked once per atom, moves followed from the ones it already resolved, lines moved in from other files read from theirs. Same tree and order as before (packed-files.test.ts checks it against the in-memory graph through edits, deletes and moves). Graphs adopted before have no packs and lay out line by line as before; packFiles: false keeps that path for its tests. On game's export: first shared() 13 s to 2-3.6 s at 20,000 queries, warm 56-82 ms, pathsAt(head) 29-119 ms; files at a version 14 s to 3 s, compare 26 s to 11 s, a path's log 27 s to 4.5 s; every answer the harness finished matches Project.load.Compare321 /** false: a new stored graph keeps no packed file history, and lays files out line by line (tests of that path). */
322 packFiles?: boolean;
codex-capacity-chair109Add opt-in persistent writer state, checked reopen and bounded adoptionCompare323 } = {},
codex-capacity-chair149Index atom metadata for resumable projection adoptionCompare325 if (options.indexAcceptedAtom && !options.storage)
326 throw Error("accepted atom indexing requires persistent storage");
327 this.#indexAcceptedAtom = options.indexAcceptedAtom;
329 this.#texts = options.texts;
330 this.#lineText = undefined;
331 }
332 if (options.lists) this.#lists = options.lists;
codex-capacity-chair109Add opt-in persistent writer state, checked reopen and bounded adoptionCompare333 this.#storage = options.storage;
codex-capacity-chair137Page explicit child counts with bounded corruption checksCompare334 if (options.storage) this.#childCounts = new ChildCounts(options.storage);
codex-capacity-chair109Add opt-in persistent writer state, checked reopen and bounded adoptionCompare335 if (options.storage) {
336 const storage = options.storage;
codex-capacity-chair113Page disk-first numeric graph indexes under bounded storage cacheCompare337 const numbers = (name: string): NumberIndex => storedNumbers(storage, name);
codex-capacity-chair162Add reviewed disk-first history and indexed graph storage for core issue 16; retain runtime activation gateCompare338 const atomText = new StoredText(storage, "atom-text:long");
339 type TextReference = { text: string };
340 const listFields = [
341 "deletes",
342 "writes",
343 "reads",
344 "holds",
345 "needs",
346 "resolves",
347 "deps",
348 "reasons",
349 "attrs",
350 "moves",
351 ] as const;
352 type EncodedAtom = {
353 insertionFormat?: 1;
354 insertionRuns?: string;
355 textFormat?: 1;
356 listFormat?: 1;
357 listCount?: number;
358 lists?: Partial<Record<(typeof listFields)[number], string>>;
359 atom: Atom;
360 };
361 this.#atoms = storedArray<Atom>(
362 storage,
363 "atoms",
364 (value) => {
365 const encoded = value as unknown as Partial<EncodedAtom>;
366 if (encoded.textFormat !== undefined && encoded.textFormat !== 1)
367 throw Error("invalid stored atom text format");
368 if (encoded.listFormat !== undefined && encoded.listFormat !== 1)
369 throw Error("invalid stored atom list format");
370 if (encoded.listFormat === 1) {
371 if (
372 !encoded.lists ||
373 typeof encoded.lists !== "object" ||
374 Array.isArray(encoded.lists) ||
375 !Number.isSafeInteger(encoded.listCount) ||
376 encoded.listCount! < 1 ||
377 Object.keys(encoded.lists).length !== encoded.listCount ||
378 Object.keys(encoded.lists).some((field) => !listFields.includes(field as (typeof listFields)[number]))
379 )
380 throw Error("invalid stored atom list references");
381 }
382 if (encoded.insertionFormat !== undefined && encoded.insertionFormat !== 1)
383 throw Error("invalid stored insertion format");
384 const atom =
385 encoded.textFormat === 1 || encoded.listFormat === 1 || encoded.insertionFormat === 1
386 ? encoded.atom!
387 : value;
codex-capacity-chair175Reduce disk-backed record and publish allocations; reviewed in core ask 52 with parsed-code budget and exact aligned-line follow-ups. Keep disk-first activation off.Compare388 if (encoded.insertionFormat === 1 && (!Array.isArray(atom.inserts) || atom.inserts.length !== 0))
389 throw Error("invalid stored insertion placeholder");
codex-capacity-chair162Add reviewed disk-first history and indexed graph storage for core issue 16; retain runtime activation gateCompare390 const text =
391 encoded.textFormat === 1
392 ? (start: number, length: number): readonly string[] => {
393 const result: string[] = [];
394 let index = 0;
395 for (const run of atom.inserts)
396 for (const raw of run.lines) {
397 if (index >= start && index < start + length) {
398 const reference = raw as unknown as TextReference;
399 if (typeof raw === "string") result.push(raw);
codex-capacity-chair175Reduce disk-backed record and publish allocations; reviewed in core ask 52 with parsed-code budget and exact aligned-line follow-ups. Keep disk-first activation off.Compare400 else if (reference && reference.text === JSON.stringify([String(atom.seq), index]))
codex-capacity-chair162Add reviewed disk-first history and indexed graph storage for core issue 16; retain runtime activation gateCompare401 result.push(atomText.read(reference.text));
402 else throw Error("invalid stored atom text reference");
403 }
404 if (++index >= start + length) return result;
405 }
406 throw Error("stored atom text range missing");
407 }
408 : undefined;
codex-capacity-chair176Avoid quadratic insertion-run offsets; cleared in review ask 52Compare409 // Sequential reads advance once per run without retaining a history-sized offset array.
410 let offsetRun = 0;
411 let offsetLine = 0;
412 const insertionStart = (index: number): number => {
413 if (index < offsetRun) {
414 offsetRun = 0;
415 offsetLine = 0;
416 }
417 while (offsetRun < index) {
418 offsetLine += readonlyStoredArray(storage, `atom-inserts:${atom.seq}:lines:${offsetRun}`).length;
419 offsetRun++;
420 }
421 return offsetLine;
422 };
codex-capacity-chair175Reduce disk-backed record and publish allocations; reviewed in core ask 52 with parsed-code budget and exact aligned-line follow-ups. Keep disk-first activation off.Compare423 const streamed = (target: Atom): Atom => {
424 registerJsonChunkValue(target, () => {
425 const line = (raw: unknown, index: number): unknown => {
426 if (typeof raw === "string") return raw;
427 const reference = raw as TextReference;
428 if (!reference || reference.text !== JSON.stringify([String(atom.seq), index]))
429 throw Error("invalid stored atom text reference");
430 return new JsonStringChunks(() => atomText.chunks(reference.text));
431 };
432 let inserts: readonly unknown[];
433 if (encoded.insertionFormat === 1) {
434 const collection = `atom-inserts:${atom.seq}`;
435 inserts = readonlyStoredArray(storage, collection, (raw, index) => {
436 const run = raw as { file: string; parent: string; lines: string };
437 const lines = `${collection}:lines:${index}`;
438 if (run.lines !== lines || typeof run.file !== "string" || typeof run.parent !== "string")
439 throw Error("invalid stored insertion run");
codex-capacity-chair176Avoid quadratic insertion-run offsets; cleared in review ask 52Compare440 const start = insertionStart(index);
codex-capacity-chair175Reduce disk-backed record and publish allocations; reviewed in core ask 52 with parsed-code budget and exact aligned-line follow-ups. Keep disk-first activation off.Compare441 return {
442 file: run.file,
443 parent: run.parent,
444 lines: readonlyStoredArray(storage, lines, (raw, i) => line(raw, start + i)),
445 };
446 });
447 } else {
448 let index = 0;
449 inserts = atom.inserts.map((run) => ({
450 file: run.file,
451 parent: run.parent,
452 lines: run.lines.map((raw) => line(raw, index++)),
453 }));
454 }
455 return { ...target, inserts };
456 });
457 return target;
458 };
codex-capacity-chair162Add reviewed disk-first history and indexed graph storage for core issue 16; retain runtime activation gateCompare459 const frozen = freezeAtom(
460 atom,
461 (id) => id,
462 (author) => author,
463 text,
464 );
codex-capacity-chair175Reduce disk-backed record and publish allocations; reviewed in core ask 52 with parsed-code budget and exact aligned-line follow-ups. Keep disk-first activation off.Compare465 if (encoded.listFormat !== 1 && encoded.insertionFormat !== 1) return streamed(frozen);
codex-capacity-chair162Add reviewed disk-first history and indexed graph storage for core issue 16; retain runtime activation gateCompare466 const result = { ...frozen };
467 if (encoded.insertionFormat === 1) {
468 const collection = `atom-inserts:${atom.seq}`;
469 if (encoded.insertionRuns !== collection) throw Error("invalid stored insertion reference");
470 const inserts = readonlyStoredArray<InsertRun>(storage, collection, (raw, index) => {
471 const run = raw as { file: string; parent: InsertRun["parent"]; lines: string };
472 const lines = `${collection}:lines:${index}`;
473 if (run.lines !== lines || typeof run.file !== "string" || typeof run.parent !== "string")
474 throw Error("invalid stored insertion run");
475 return Object.freeze({
476 file: run.file,
477 parent: run.parent,
codex-capacity-chair175Reduce disk-backed record and publish allocations; reviewed in core ask 52 with parsed-code budget and exact aligned-line follow-ups. Keep disk-first activation off.Compare478 lines: readonlyStoredArray<string>(storage, lines, (rawLine, lineIndex) => {
codex-capacity-chair162Add reviewed disk-first history and indexed graph storage for core issue 16; retain runtime activation gateCompare479 if (typeof rawLine === "string") return rawLine;
480 const ref = rawLine as TextReference;
codex-capacity-chair176Avoid quadratic insertion-run offsets; cleared in review ask 52Compare481 const atomLine = insertionStart(index) + lineIndex;
codex-capacity-chair175Reduce disk-backed record and publish allocations; reviewed in core ask 52 with parsed-code budget and exact aligned-line follow-ups. Keep disk-first activation off.Compare482 if (!ref || ref.text !== JSON.stringify([String(atom.seq), atomLine]))
483 throw Error("invalid stored insertion text");
codex-capacity-chair162Add reviewed disk-first history and indexed graph storage for core issue 16; retain runtime activation gateCompare484 return atomText.read(ref.text);
485 }),
486 });
487 });
488 Object.defineProperty(result, "inserts", { value: inserts, enumerable: true });
489 }
490 for (const field of listFields) {
491 const collection = encoded.lists?.[field];
492 if (collection === undefined) continue;
493 if (typeof collection !== "string" || collection !== `atom-list:${atom.seq}:${field}`)
494 throw Error("invalid stored atom list reference");
495 Object.defineProperty(result, field, { value: readonlyStoredArray(storage, collection), enumerable: true });
496 }
codex-capacity-chair175Reduce disk-backed record and publish allocations; reviewed in core ask 52 with parsed-code budget and exact aligned-line follow-ups. Keep disk-first activation off.Compare497 return streamed(Object.freeze(result));
codex-capacity-chair162Add reviewed disk-first history and indexed graph storage for core issue 16; retain runtime activation gateCompare498 },
499 (input, key) => {
500 const atom = { ...input };
501 const lists: Partial<Record<(typeof listFields)[number], string>> = {};
502 for (const field of listFields) {
503 const values = input[field];
504 if (!values || values.length <= 256) continue;
505 const collection = `atom-list:${input.seq}:${field}`;
506 const saved = storedArray<unknown>(storage, collection);
507 for (const value of values) saved.push(value);
508 lists[field] = collection;
509 Object.defineProperty(atom, field, { value: [], enumerable: true });
510 }
511 const listCount = Object.keys(lists).length;
512 const hasLists = listCount > 0;
codex-capacity-chair166Read long insertion text lazily and stream files through Git commit constructionCompare513 let insertionCharacters = 0;
514 if (
515 atom.inserts.length > 256 ||
516 atom.inserts.some((run) => run.lines.length > 256) ||
517 atom.inserts.some((run) => run.lines.some((line) => (insertionCharacters += line.length) > 65536))
518 ) {
codex-capacity-chair162Add reviewed disk-first history and indexed graph storage for core issue 16; retain runtime activation gateCompare519 const collection = `atom-inserts:${input.seq}`;
520 const runs = storedArray<unknown>(storage, collection);
521 let runIndex = 0;
522 let lineIndex = 0;
523 for (const run of atom.inserts) {
524 const lineCollection = `${collection}:lines:${runIndex++}`;
525 const lines = storedArray<unknown>(storage, lineCollection);
526 for (const line of run.lines) {
527 const text = JSON.stringify([key, lineIndex++]);
528 if (line.length > StoredText.chunkCharacters) {
529 atomText.write(text, line);
530 lines.push({ text });
531 } else lines.push(line);
532 }
533 runs.push({ file: run.file, parent: run.parent, lines: lineCollection });
534 }
535 return {
536 insertionFormat: 1,
537 insertionRuns: collection,
538 ...(hasLists ? { listFormat: 1, listCount, lists } : {}),
539 atom: { ...atom, inserts: [] },
540 };
541 }
542 if (!atom.inserts.some((run) => run.lines.some((line) => line.length > StoredText.chunkCharacters)))
543 return hasLists ? { listFormat: 1, listCount, lists, atom } : atom;
544 let index = 0;
545 const inserts = atom.inserts.map((run) => ({
546 ...run,
547 lines: run.lines.map((line) => {
548 const text = JSON.stringify([key, index++]);
549 if (line.length <= StoredText.chunkCharacters) return line;
550 atomText.write(text, line);
551 return { text };
552 }),
553 }));
554 return {
555 textFormat: 1,
556 ...(hasLists ? { listFormat: 1, listCount, lists } : {}),
557 atom: { ...atom, inserts },
558 };
559 },
codex-capacity-chair109Add opt-in persistent writer state, checked reopen and bounded adoptionCompare560 );
561 this.#lamport = storedArray(storage, "lamport");
capacity228Lamport numbers 256 to a row, and movers read once per graph (disk-first 2; abso Capacity).
After 226, where on typescript-rs still read about 12,000 lamport rows (one per atom, for ordering a file's lines) and the movers list (1,024 rows, one per atom that moves lines) nine times over.
- A stored graph keeps its atoms' lamport numbers in pages of 256 (lamport-pages), from a fresh graph on. A graph that already keeps them a row each goes on doing so. The choice is made when a number is first needed, so opening still reads nothing.
- A stored graph reads its movers once and keeps them, checked against the stored list's length and last mover on each use so a rolled-back add can't leave one behind.
On typescript-rs adopted fresh, cold: where 59,000 reads to 39,000. Its time locally is now mostly work, not reads (5.2 s). 26 of 27 answers match replay; collisions still runs past 60 s.
New test lamport-pages: a fresh graph keeps pages and reopens with them; a graph with a row each reads them and writes the next atom as a row. Named tests: every engine test (288 of 288), membership-pages, stored-closure, draft-reads-stored, version-files, packed-crossings, project-writer-storage, writer-adoption, moves, view-cache (36 of 36); tsc and biome clean.Compare562 this.#lamportPaged = storedNumbers(storage, "lamport-pages");
codex-capacity-chair109Add opt-in persistent writer state, checked reopen and bounded adoptionCompare563 this.#lineBase = storedArray(storage, "line-base");
564 this.#paths = storedArray(storage, "paths");
565 this.#movers = storedArray(storage, "movers");
566 this.#atomFiles = storedArray(storage, "atom-files");
567 this.#atomDeletes = storedArray(storage, "atom-deletes");
568 this.#lineAtom = numbers("line-atom");
569 this.#lineFile = numbers("line-file");
570 this.#lineParent = numbers("line-parent");
571 this.#deleter = numbers("deleter");
572 this.#replacing = numbers("replacing");
codex-capacity-chair162Add reviewed disk-first history and indexed graph storage for core issue 16; retain runtime activation gateCompare573 const longText = atomText;
574 this.#lineText = storedArray<string>(
575 storage,
576 "line-text",
577 (value) => {
578 if (typeof value === "string") return value;
579 const reference = value as unknown as { format: number; text: string };
580 if (reference?.format !== 1 || typeof reference.text !== "string") throw Error("invalid long line reference");
581 return longText.read(reference.text);
582 },
583 (value, key) => {
584 if (value.length <= StoredText.chunkCharacters) return value;
585 const number = Number(key);
586 const seq = this.#lineAtom.at(number);
587 const text = JSON.stringify([String(seq), number - this.#lineBase[seq]!]);
588 const header = storage.read("atom-text:long", text) as { characters?: number } | undefined;
589 if (header?.characters !== value.length) throw Error("long line atom text is missing");
590 return { format: 1, text };
591 },
592 );
codex-capacity-chair109Add opt-in persistent writer state, checked reopen and bounded adoptionCompare593 this.#pathIndex = storedMap(storage, "path-index");
codex-capacity-chair128Page deletion history and short-circuit current visibilityCompare594 this.#moreDeleterPages = storedLists<number>(storage, "more-deleters", (key) =>
595 JSON.stringify(["number", Number(key)]),
596 );
codex-capacity-chair120Page persistent claim indexes and stream dependency queriesCompare597 this.#writersPages = storedLists<AtomId>(storage, "writers", (key) => key);
598 this.#readersPages = storedLists<AtomId>(storage, "readers", (key) => key);
599 this.#holdersPages = storedLists<AtomId>(storage, "holders", (key) => key);
codex-capacity-chair122Page dependency and resolver indexes with streamed intersectionCompare600 this.#dependentsPages = storedLists<AtomId>(storage, "dependents");
601 this.#resolversPages = storedLists<AtomId>(storage, "resolvers");
codex-capacity-chair129Page together relationship history for bounded traversalCompare602 this.#togetherPages = storedLists<TogetherLink>(storage, "together");
codex-capacity-chair119Page per-file atom indexes and stream current-view attribute scansCompare603 this.#fileAtomPages = storedLists<AtomId>(storage, "file-atoms");
codex-capacity-chair130Stream paged child history into layout filteringCompare604 this.#runStartPages = storedLists<number>(storage, "run-starts", (key) =>
605 JSON.stringify(["number", Number(key)]),
606 );
codex-capacity-chair127Page persistent relocation indexes and stream projection readsCompare607 this.#relocationPages = storedLists<RelocationInfo>(storage, "relocations");
608 this.#relocatedToPages = storedLists<RelocationInfo>(storage, "relocated-to");
609 this.#relocatedToCodePages = storedLists<RelocationInfo>(storage, "relocated-to-code", (key) =>
610 JSON.stringify(["number", Number(key)]),
611 );
codex-capacity-chair109Add opt-in persistent writer state, checked reopen and bounded adoptionCompare612 this.#labels = storedMap(storage, "labels");
capacity206Each file's line history packed (disk-first 2, lines by file; abso Capacity). A stored graph appends every line written in a file ([n, parent code, writer seq, k, replaces]) and its text, every delete of one of its lines, and every attribute set on it to that file's pages as atoms are added, a run at a time (storedLists appendAll). A view lays a file out from those pages in memory: membership checked once per atom, moves followed from the ones it already resolved, lines moved in from other files read from theirs. Same tree and order as before (packed-files.test.ts checks it against the in-memory graph through edits, deletes and moves). Graphs adopted before have no packs and lay out line by line as before; packFiles: false keeps that path for its tests. On game's export: first shared() 13 s to 2-3.6 s at 20,000 queries, warm 56-82 ms, pathsAt(head) 29-119 ms; files at a version 14 s to 3 s, compare 26 s to 11 s, a path's log 27 s to 4.5 s; every answer the harness finished matches Project.load.Compare613 this.#fileLines = storedLists<PackedLine>(storage, "file-lines");
614 this.#fileTexts = storedLists<string | null>(storage, "file-texts");
615 this.#fileDeletes = storedLists<PackedDelete>(storage, "file-deletes");
616 this.#fileAttrs = storedLists<PackedAttr>(storage, "file-attrs");
capacity221Packed layout follows lines written in another file (disk-first 2; abso Capacity).
where {} on typescript-rs left 11 lines out of erasable_syntax.rs in cloud-ts-12's draft. cloud-ts-12 moved one block between files several times, wrote lines under its last line while it sat in uninitialized_props_forms.rs, then moved the block on. Those lines followed their parent with no move of their own. The packed layout read only the file's own lines and the files its moved-in lines were written in, so it never read them.
- Each file's packed history also keeps the runs written in another file under one of its lines (file-crossings). The packed layout follows them until no new file turns up.
- New adoptions write packed format 2. A graph packed at format 1 has no such list, so it lays files out line by line: correct, but slower until it is adopted again.
- packed-crossings.test.ts moves c.ts to d.ts, adds a line in d.ts, moves d.ts to e.ts, and checks files, where and every draft's text against the in-memory project.
Named tests: packed-crossings, packed-files, state-source, draft-reads-stored, version-files, project-writer-storage, writer-adoption, moves, queued-moves, files-reads, move-reconstruction (60 of 60); tsc and biome clean.Compare617 this.#fileCrossings = storedLists<PackedCrossing>(storage, "file-crossings");
capacity206Each file's line history packed (disk-first 2, lines by file; abso Capacity). A stored graph appends every line written in a file ([n, parent code, writer seq, k, replaces]) and its text, every delete of one of its lines, and every attribute set on it to that file's pages as atoms are added, a run at a time (storedLists appendAll). A view lays a file out from those pages in memory: membership checked once per atom, moves followed from the ones it already resolved, lines moved in from other files read from theirs. Same tree and order as before (packed-files.test.ts checks it against the in-memory graph through edits, deletes and moves). Graphs adopted before have no packs and lay out line by line as before; packFiles: false keeps that path for its tests. On game's export: first shared() 13 s to 2-3.6 s at 20,000 queries, warm 56-82 ms, pathsAt(head) 29-119 ms; files at a version 14 s to 3 s, compare 26 s to 11 s, a path's log 27 s to 4.5 s; every answer the harness finished matches Project.load.Compare618 this.#packFiles = options.packFiles ?? true;
codex-capacity-chair109Add opt-in persistent writer state, checked reopen and bounded adoptionCompare619 }
capacity206Each file's line history packed (disk-first 2, lines by file; abso Capacity). A stored graph appends every line written in a file ([n, parent code, writer seq, k, replaces]) and its text, every delete of one of its lines, and every attribute set on it to that file's pages as atoms are added, a run at a time (storedLists appendAll). A view lays a file out from those pages in memory: membership checked once per atom, moves followed from the ones it already resolved, lines moved in from other files read from theirs. Same tree and order as before (packed-files.test.ts checks it against the in-memory graph through edits, deletes and moves). Graphs adopted before have no packs and lay out line by line as before; packFiles: false keeps that path for its tests. On game's export: first shared() 13 s to 2-3.6 s at 20,000 queries, warm 56-82 ms, pathsAt(head) 29-119 ms; files at a version 14 s to 3 s, compare 26 s to 11 s, a path's log 27 s to 4.5 s; every answer the harness finished matches Project.load.Compare621
622 // Each file's line history packed, in pages (abso Capacity) ---------------------------------------------------
623 // For each file, by its path index: every line written in it ([n, parent code, writer seq, k, replaces]) and its
capacity221Packed layout follows lines written in another file (disk-first 2; abso Capacity).
where {} on typescript-rs left 11 lines out of erasable_syntax.rs in cloud-ts-12's draft. cloud-ts-12 moved one block between files several times, wrote lines under its last line while it sat in uninitialized_props_forms.rs, then moved the block on. Those lines followed their parent with no move of their own. The packed layout read only the file's own lines and the files its moved-in lines were written in, so it never read them.
- Each file's packed history also keeps the runs written in another file under one of its lines (file-crossings). The packed layout follows them until no new file turns up.
- New adoptions write packed format 2. A graph packed at format 1 has no such list, so it lays files out line by line: correct, but slower until it is adopted again.
- packed-crossings.test.ts moves c.ts to d.ts, adds a line in d.ts, moves d.ts to e.ts, and checks files, where and every draft's text against the in-memory project.
Named tests: packed-crossings, packed-files, state-source, draft-reads-stored, version-files, project-writer-storage, writer-adoption, moves, queued-moves, files-reads, move-reconstruction (60 of 60); tsc and biome clean.Compare624 // text, every delete of one of those lines ([n, deleter seq]), every attribute set on it ([seq, name, value]), and
625 // every run written in another file under one of its lines ([parent n, the run's file]): a line follows its parent,
626 // so a run written while its parent was moved elsewhere lays out wherever the parent is.
capacity206Each file's line history packed (disk-first 2, lines by file; abso Capacity). A stored graph appends every line written in a file ([n, parent code, writer seq, k, replaces]) and its text, every delete of one of its lines, and every attribute set on it to that file's pages as atoms are added, a run at a time (storedLists appendAll). A view lays a file out from those pages in memory: membership checked once per atom, moves followed from the ones it already resolved, lines moved in from other files read from theirs. Same tree and order as before (packed-files.test.ts checks it against the in-memory graph through edits, deletes and moves). Graphs adopted before have no packs and lay out line by line as before; packFiles: false keeps that path for its tests. On game's export: first shared() 13 s to 2-3.6 s at 20,000 queries, warm 56-82 ms, pathsAt(head) 29-119 ms; files at a version 14 s to 3 s, compare 26 s to 11 s, a path's log 27 s to 4.5 s; every answer the harness finished matches Project.load.Compare627 // Appended as atoms are added, so a view lays a file out from a few pages instead of a row read per line. Kept from
628 // a fresh adoption on; a graph adopted before has none, and views lay out as before.
capacity206Each file's line history packed (disk-first 2, lines by file; abso Capacity). A stored graph appends every line written in a file ([n, parent code, writer seq, k, replaces]) and its text, every delete of one of its lines, and every attribute set on it to that file's pages as atoms are added, a run at a time (storedLists appendAll). A view lays a file out from those pages in memory: membership checked once per atom, moves followed from the ones it already resolved, lines moved in from other files read from theirs. Same tree and order as before (packed-files.test.ts checks it against the in-memory graph through edits, deletes and moves). Graphs adopted before have no packs and lay out line by line as before; packFiles: false keeps that path for its tests. On game's export: first shared() 13 s to 2-3.6 s at 20,000 queries, warm 56-82 ms, pathsAt(head) 29-119 ms; files at a version 14 s to 3 s, compare 26 s to 11 s, a path's log 27 s to 4.5 s; every answer the harness finished matches Project.load.Compare630 #fileLines: ReturnType<typeof storedLists<PackedLine>> | undefined;
631 #fileTexts: ReturnType<typeof storedLists<string | null>> | undefined;
632 #fileDeletes: ReturnType<typeof storedLists<PackedDelete>> | undefined;
633 #fileAttrs: ReturnType<typeof storedLists<PackedAttr>> | undefined;
capacity221Packed layout follows lines written in another file (disk-first 2; abso Capacity).
where {} on typescript-rs left 11 lines out of erasable_syntax.rs in cloud-ts-12's draft. cloud-ts-12 moved one block between files several times, wrote lines under its last line while it sat in uninitialized_props_forms.rs, then moved the block on. Those lines followed their parent with no move of their own. The packed layout read only the file's own lines and the files its moved-in lines were written in, so it never read them.
- Each file's packed history also keeps the runs written in another file under one of its lines (file-crossings). The packed layout follows them until no new file turns up.
- New adoptions write packed format 2. A graph packed at format 1 has no such list, so it lays files out line by line: correct, but slower until it is adopted again.
- packed-crossings.test.ts moves c.ts to d.ts, adds a line in d.ts, moves d.ts to e.ts, and checks files, where and every draft's text against the in-memory project.
Named tests: packed-crossings, packed-files, state-source, draft-reads-stored, version-files, project-writer-storage, writer-adoption, moves, queued-moves, files-reads, move-reconstruction (60 of 60); tsc and biome clean.Compare634 #fileCrossings: ReturnType<typeof storedLists<PackedCrossing>> | undefined;
capacity206Each file's line history packed (disk-first 2, lines by file; abso Capacity). A stored graph appends every line written in a file ([n, parent code, writer seq, k, replaces]) and its text, every delete of one of its lines, and every attribute set on it to that file's pages as atoms are added, a run at a time (storedLists appendAll). A view lays a file out from those pages in memory: membership checked once per atom, moves followed from the ones it already resolved, lines moved in from other files read from theirs. Same tree and order as before (packed-files.test.ts checks it against the in-memory graph through edits, deletes and moves). Graphs adopted before have no packs and lay out line by line as before; packFiles: false keeps that path for its tests. On game's export: first shared() 13 s to 2-3.6 s at 20,000 queries, warm 56-82 ms, pathsAt(head) 29-119 ms; files at a version 14 s to 3 s, compare 26 s to 11 s, a path's log 27 s to 4.5 s; every answer the harness finished matches Project.load.Compare635 /** Whether a new stored graph starts packing (GraphOptions.packFiles). */
636 #packFiles = true;
capacity221Packed layout follows lines written in another file (disk-first 2; abso Capacity).
where {} on typescript-rs left 11 lines out of erasable_syntax.rs in cloud-ts-12's draft. cloud-ts-12 moved one block between files several times, wrote lines under its last line while it sat in uninitialized_props_forms.rs, then moved the block on. Those lines followed their parent with no move of their own. The packed layout read only the file's own lines and the files its moved-in lines were written in, so it never read them.
- Each file's packed history also keeps the runs written in another file under one of its lines (file-crossings). The packed layout follows them until no new file turns up.
- New adoptions write packed format 2. A graph packed at format 1 has no such list, so it lays files out line by line: correct, but slower until it is adopted again.
- packed-crossings.test.ts moves c.ts to d.ts, adds a line in d.ts, moves d.ts to e.ts, and checks files, where and every draft's text against the in-memory project.
Named tests: packed-crossings, packed-files, state-source, draft-reads-stored, version-files, project-writer-storage, writer-adoption, moves, queued-moves, files-reads, move-reconstruction (60 of 60); tsc and biome clean.Compare637 /**
638 * How this graph's files are packed, read once when first asked so opening reads nothing: 0 not at all, 1 lines,
639 * deletes and attributes, 2 the runs written across files as well.
640 */
641 #formatKnown: number | undefined;
642 get #format(): number {
643 if (this.#formatKnown === undefined) {
644 const format = this.#storage?.read("file-lines:meta", "format");
645 this.#formatKnown = format === 1 || format === 2 ? format : 0;
646 }
647 return this.#formatKnown;
648 }
capacity206Each file's line history packed (disk-first 2, lines by file; abso Capacity). A stored graph appends every line written in a file ([n, parent code, writer seq, k, replaces]) and its text, every delete of one of its lines, and every attribute set on it to that file's pages as atoms are added, a run at a time (storedLists appendAll). A view lays a file out from those pages in memory: membership checked once per atom, moves followed from the ones it already resolved, lines moved in from other files read from theirs. Same tree and order as before (packed-files.test.ts checks it against the in-memory graph through edits, deletes and moves). Graphs adopted before have no packs and lay out line by line as before; packFiles: false keeps that path for its tests. On game's export: first shared() 13 s to 2-3.6 s at 20,000 queries, warm 56-82 ms, pathsAt(head) 29-119 ms; files at a version 14 s to 3 s, compare 26 s to 11 s, a path's log 27 s to 4.5 s; every answer the harness finished matches Project.load.Compare649 get #packed(): boolean {
capacity221Packed layout follows lines written in another file (disk-first 2; abso Capacity).
where {} on typescript-rs left 11 lines out of erasable_syntax.rs in cloud-ts-12's draft. cloud-ts-12 moved one block between files several times, wrote lines under its last line while it sat in uninitialized_props_forms.rs, then moved the block on. Those lines followed their parent with no move of their own. The packed layout read only the file's own lines and the files its moved-in lines were written in, so it never read them.
- Each file's packed history also keeps the runs written in another file under one of its lines (file-crossings). The packed layout follows them until no new file turns up.
- New adoptions write packed format 2. A graph packed at format 1 has no such list, so it lays files out line by line: correct, but slower until it is adopted again.
- packed-crossings.test.ts moves c.ts to d.ts, adds a line in d.ts, moves d.ts to e.ts, and checks files, where and every draft's text against the in-memory project.
Named tests: packed-crossings, packed-files, state-source, draft-reads-stored, version-files, project-writer-storage, writer-adoption, moves, queued-moves, files-reads, move-reconstruction (60 of 60); tsc and biome clean.Compare650 return this.#format >= 1;
651 }
652 get #crossings(): boolean {
653 return this.#format >= 2;
capacity206Each file's line history packed (disk-first 2, lines by file; abso Capacity). A stored graph appends every line written in a file ([n, parent code, writer seq, k, replaces]) and its text, every delete of one of its lines, and every attribute set on it to that file's pages as atoms are added, a run at a time (storedLists appendAll). A view lays a file out from those pages in memory: membership checked once per atom, moves followed from the ones it already resolved, lines moved in from other files read from theirs. Same tree and order as before (packed-files.test.ts checks it against the in-memory graph through edits, deletes and moves). Graphs adopted before have no packs and lay out line by line as before; packFiles: false keeps that path for its tests. On game's export: first shared() 13 s to 2-3.6 s at 20,000 queries, warm 56-82 ms, pathsAt(head) 29-119 ms; files at a version 14 s to 3 s, compare 26 s to 11 s, a path's log 27 s to 4.5 s; every answer the harness finished matches Project.load.Compare654 }
656 /** Whether this graph keeps each file's line history packed. */
657 get packedFiles(): boolean {
658 return this.#packed;
659 }
capacity221Packed layout follows lines written in another file (disk-first 2; abso Capacity).
where {} on typescript-rs left 11 lines out of erasable_syntax.rs in cloud-ts-12's draft. cloud-ts-12 moved one block between files several times, wrote lines under its last line while it sat in uninitialized_props_forms.rs, then moved the block on. Those lines followed their parent with no move of their own. The packed layout read only the file's own lines and the files its moved-in lines were written in, so it never read them.
- Each file's packed history also keeps the runs written in another file under one of its lines (file-crossings). The packed layout follows them until no new file turns up.
- New adoptions write packed format 2. A graph packed at format 1 has no such list, so it lays files out line by line: correct, but slower until it is adopted again.
- packed-crossings.test.ts moves c.ts to d.ts, adds a line in d.ts, moves d.ts to e.ts, and checks files, where and every draft's text against the in-memory project.
Named tests: packed-crossings, packed-files, state-source, draft-reads-stored, version-files, project-writer-storage, writer-adoption, moves, queued-moves, files-reads, move-reconstruction (60 of 60); tsc and biome clean.Compare660 /**
661 * Whether a file can be laid out from packed history alone: it also keeps the runs written across files. A graph
662 * packed before those were kept lays files out line by line.
663 */
664 get packedLayout(): boolean {
665 return this.#crossings;
666 }
capacity206Each file's line history packed (disk-first 2, lines by file; abso Capacity). A stored graph appends every line written in a file ([n, parent code, writer seq, k, replaces]) and its text, every delete of one of its lines, and every attribute set on it to that file's pages as atoms are added, a run at a time (storedLists appendAll). A view lays a file out from those pages in memory: membership checked once per atom, moves followed from the ones it already resolved, lines moved in from other files read from theirs. Same tree and order as before (packed-files.test.ts checks it against the in-memory graph through edits, deletes and moves). Graphs adopted before have no packs and lay out line by line as before; packFiles: false keeps that path for its tests. On game's export: first shared() 13 s to 2-3.6 s at 20,000 queries, warm 56-82 ms, pathsAt(head) 29-119 ms; files at a version 14 s to 3 s, compare 26 s to 11 s, a path's log 27 s to 4.5 s; every answer the harness finished matches Project.load.Compare667 /** A path's index, or undefined when nothing was ever written or set in it. */
668 pathIndexOf(path: string): number | undefined {
669 return this.#pathIndex.get(path);
670 }
671 /** The index of the path line n was written in. */
672 writtenInIndex(n: number): number {
673 return this.#lineFile.at(n);
674 }
675 *packedLines(file: number): IterableIterator<PackedLine> {
676 yield* this.#fileLines!.values(String(file));
677 }
678 *packedTexts(file: number): IterableIterator<string | null> {
679 yield* this.#fileTexts!.values(String(file));
680 }
681 *packedDeletes(file: number): IterableIterator<PackedDelete> {
682 yield* this.#fileDeletes!.values(String(file));
683 }
684 *packedAttrs(file: number): IterableIterator<PackedAttr> {
685 yield* this.#fileAttrs!.values(String(file));
686 }
capacity221Packed layout follows lines written in another file (disk-first 2; abso Capacity).
where {} on typescript-rs left 11 lines out of erasable_syntax.rs in cloud-ts-12's draft. cloud-ts-12 moved one block between files several times, wrote lines under its last line while it sat in uninitialized_props_forms.rs, then moved the block on. Those lines followed their parent with no move of their own. The packed layout read only the file's own lines and the files its moved-in lines were written in, so it never read them.
- Each file's packed history also keeps the runs written in another file under one of its lines (file-crossings). The packed layout follows them until no new file turns up.
- New adoptions write packed format 2. A graph packed at format 1 has no such list, so it lays files out line by line: correct, but slower until it is adopted again.
- packed-crossings.test.ts moves c.ts to d.ts, adds a line in d.ts, moves d.ts to e.ts, and checks files, where and every draft's text against the in-memory project.
Named tests: packed-crossings, packed-files, state-source, draft-reads-stored, version-files, project-writer-storage, writer-adoption, moves, queued-moves, files-reads, move-reconstruction (60 of 60); tsc and biome clean.Compare687 *packedCrossings(file: number): IterableIterator<PackedCrossing> {
688 yield* this.#fileCrossings!.values(String(file));
689 }
capacity206Each file's line history packed (disk-first 2, lines by file; abso Capacity). A stored graph appends every line written in a file ([n, parent code, writer seq, k, replaces]) and its text, every delete of one of its lines, and every attribute set on it to that file's pages as atoms are added, a run at a time (storedLists appendAll). A view lays a file out from those pages in memory: membership checked once per atom, moves followed from the ones it already resolved, lines moved in from other files read from theirs. Same tree and order as before (packed-files.test.ts checks it against the in-memory graph through edits, deletes and moves). Graphs adopted before have no packs and lay out line by line as before; packFiles: false keeps that path for its tests. On game's export: first shared() 13 s to 2-3.6 s at 20,000 queries, warm 56-82 ms, pathsAt(head) 29-119 ms; files at a version 14 s to 3 s, compare 26 s to 11 s, a path's log 27 s to 4.5 s; every answer the harness finished matches Project.load.Compare690
init0Start the project691 /** Where an atom's key and delete lists are when the graph doesn't keep them (#46): the stored atom. */
692 #lists: ((seq: number) => AtomLists) | undefined;
693 /** Recently read atoms' lists, most recent last, up to LIST_CACHE atoms. */
694 #listCache = new Map<number, AtomLists>();
695 #listCached = 0;
697 /** An atom's deletes, writes, reads and holds, read back from where they are stored. */
698 #listsOf(seq: number): AtomLists {
699 const hit = this.#listCache.get(seq);
700 if (hit) {
701 this.#listCache.delete(seq);
702 this.#listCache.set(seq, hit);
703 return hit;
704 }
705 const got = this.#lists!(seq);
706 const lists: AtomLists = {
707 deletes: frozenList(got.deletes),
708 writes: frozenList(got.writes),
709 reads: frozenList(got.reads),
710 holds: frozenList(got.holds),
711 };
712 this.#listCache.set(seq, lists);
713 this.#listCached += listItems(lists);
714 for (const [old, kept] of this.#listCache) {
715 if (this.#listCached <= LIST_CACHE || old === seq) break;
716 this.#listCache.delete(old);
717 this.#listCached -= listItems(kept);
718 }
719 return lists;
720 }
722 /** The reader an atom's lists use; made apart from add() so it keeps no atom alive (see #reader). */
723 #listReader(seq: number): () => AtomLists {
724 return () => this.#listsOf(seq);
725 }
727 /**
728 * A claim key as the index keeps it (#46): a line's L:, P: and G: keys by its n (n * 4, + 1, + 2), so the
729 * index holds numbers rather than one string per line; start-node and attribute keys stay strings. A key
730 * naming a line the graph doesn't have stays a string, which nothing has claimed.
731 */
732 #code(key: Key): Key | number {
733 const t = key.charCodeAt(0);
734 if (key.charCodeAt(1) !== 58 || key.charCodeAt(2) === 94) return key; // not "X:", or a start node "^"
735 const k = t === 76 ? 0 : t === 80 ? 1 : t === 71 ? 2 : -1; // L, P, G
736 if (k < 0) return key;
737 const n = this.#lineN(key.slice(2));
738 return n < 0 ? key : n * 4 + k;
739 }
741 /** An atom's lines' text, in k order. */
742 #textOf(seq: number): readonly string[] {
743 const hit = this.#textCache.get(seq);
744 if (hit) {
745 this.#textCache.delete(seq);
746 this.#textCache.set(seq, hit);
747 return hit;
748 }
749 const flat = this.#texts!(seq).flat();
750 let chars = 0;
751 for (const t of flat) chars += t.length + 1;
752 this.#textCache.set(seq, flat);
753 this.#textCached += chars;
754 for (const [old, lines] of this.#textCache) {
755 if (this.#textCached <= TEXT_CACHE || old === seq) break;
756 this.#textCache.delete(old);
757 for (const t of lines) this.#textCached -= t.length + 1;
758 }
759 return flat;
760 }
762 /**
763 * The reader an atom's runs use. Made in a function of its own: a closure made inside add() would
764 * keep add()'s whole scope alive, the atom as given with all its text included.
765 */
766 #reader(seq: number): (start: number, length: number) => readonly string[] {
767 return (start, length) => this.#textOf(seq).slice(start, start + length);
768 }
770 /** Line n's text. */
771 #text(n: number): string {
772 if (this.#lineText) return this.#lineText[n]!;
773 const seq = this.#lineAtom.at(n);
774 return this.#textOf(seq)[n - this.#lineBase[seq]!]!;
775 }
776 #paths: string[] = [];
codex-capacity-chair109Add opt-in persistent writer state, checked reopen and bounded adoptionCompare777 #pathIndex: StateMap<string, number> = new Map();
init0Start the project778 /** The first atom that deletes each line (its seq), or -1; a line deleted by more than one has the rest in #moreDeleters. */
codex-capacity-chair109Add opt-in persistent writer state, checked reopen and bounded adoptionCompare779 #deleter: NumberIndex = new Ints();
780 #moreDeleters: StateMap<number, number[]> = new Map();
codex-capacity-chair128Page deletion history and short-circuit current visibilityCompare781 #moreDeleterPages: ReturnType<typeof storedLists<number>> | undefined;
codex-capacity-chair109Add opt-in persistent writer state, checked reopen and bounded adoptionCompare782 #writers: StateMap<Key | number, AtomId | AtomId[]> = new Map();
codex-capacity-chair120Page persistent claim indexes and stream dependency queriesCompare783 #writersPages: ReturnType<typeof storedLists<AtomId>> | undefined;
codex-capacity-chair109Add opt-in persistent writer state, checked reopen and bounded adoptionCompare784 #readers: StateMap<Key | number, AtomId | AtomId[]> = new Map();
codex-capacity-chair120Page persistent claim indexes and stream dependency queriesCompare785 #readersPages: ReturnType<typeof storedLists<AtomId>> | undefined;
codex-capacity-chair109Add opt-in persistent writer state, checked reopen and bounded adoptionCompare786 #holders: StateMap<Key | number, AtomId | AtomId[]> = new Map();
codex-capacity-chair120Page persistent claim indexes and stream dependency queriesCompare787 #holdersPages: ReturnType<typeof storedLists<AtomId>> | undefined;
codex-capacity-chair109Add opt-in persistent writer state, checked reopen and bounded adoptionCompare788 #dependents: StateMap<AtomId, AtomId | AtomId[]> = new Map();
codex-capacity-chair122Page dependency and resolver indexes with streamed intersectionCompare789 #dependentsPages: ReturnType<typeof storedLists<AtomId>> | undefined;
codex-capacity-chair109Add opt-in persistent writer state, checked reopen and bounded adoptionCompare790 #resolvers: StateMap<AtomId, AtomId | AtomId[]> = new Map();
codex-capacity-chair122Page dependency and resolver indexes with streamed intersectionCompare791 #resolversPages: ReturnType<typeof storedLists<AtomId>> | undefined;
codex-capacity-chair109Add opt-in persistent writer state, checked reopen and bounded adoptionCompare792 #together: StateMap<AtomId, TogetherLink[]> = new Map();
codex-capacity-chair129Page together relationship history for bounded traversalCompare793 #togetherPages: ReturnType<typeof storedLists<TogetherLink>> | undefined;
codex-capacity-chair109Add opt-in persistent writer state, checked reopen and bounded adoptionCompare794 #fileAtoms: StateMap<string, AtomId[]> = new Map();
codex-capacity-chair119Page per-file atom indexes and stream current-view attribute scansCompare795 #fileAtomPages: ReturnType<typeof storedLists<AtomId>> | undefined;
init0Start the project796 /** First lines of runs (their n), by the node they were written after: a line's n, or -1 - a path's index. */
codex-capacity-chair109Add opt-in persistent writer state, checked reopen and bounded adoptionCompare797 #runStarts: StateMap<number, number | number[]> = new Map();
codex-capacity-chair130Stream paged child history into layout filteringCompare798 #runStartPages: ReturnType<typeof storedLists<number>> | undefined;
init0Start the project799 /** 1 for the first line of a run whose atom deleted the line it hangs off: the run replaces it. */
codex-capacity-chair109Add opt-in persistent writer state, checked reopen and bounded adoptionCompare800 #replacing: NumberIndex = new Ints(true);
801 #relocations: StateMap<LineId, RelocationInfo[]> = new Map();
codex-capacity-chair127Page persistent relocation indexes and stream projection readsCompare802 #relocationPages: ReturnType<typeof storedLists<RelocationInfo>> | undefined;
codex-capacity-chair109Add opt-in persistent writer state, checked reopen and bounded adoptionCompare803 #relocatedTo: StateMap<NodeId, RelocationInfo[]> = new Map();
codex-capacity-chair127Page persistent relocation indexes and stream projection readsCompare804 #relocatedToPages: ReturnType<typeof storedLists<RelocationInfo>> | undefined;
init0Start the project805 /** The same relocations by node code (a line's n, or -1 - a path's index), for views laid out by number. */
codex-capacity-chair109Add opt-in persistent writer state, checked reopen and bounded adoptionCompare806 #relocatedToCode: StateMap<number, RelocationInfo[]> = new Map();
codex-capacity-chair127Page persistent relocation indexes and stream projection readsCompare807 #relocatedToCodePages: ReturnType<typeof storedLists<RelocationInfo>> | undefined;
capacity228Lamport numbers 256 to a row, and movers read once per graph (disk-first 2; abso Capacity).
After 226, where on typescript-rs still read about 12,000 lamport rows (one per atom, for ordering a file's lines) and the movers list (1,024 rows, one per atom that moves lines) nine times over.
- A stored graph keeps its atoms' lamport numbers in pages of 256 (lamport-pages), from a fresh graph on. A graph that already keeps them a row each goes on doing so. The choice is made when a number is first needed, so opening still reads nothing.
- A stored graph reads its movers once and keeps them, checked against the stored list's length and last mover on each use so a rolled-back add can't leave one behind.
On typescript-rs adopted fresh, cold: where 59,000 reads to 39,000. Its time locally is now mostly work, not reads (5.2 s). 26 of 27 answers match replay; collisions still runs past 60 s.
New test lamport-pages: a fresh graph keeps pages and reopens with them; a graph with a row each reads them and writes the next atom as a row. Named tests: every engine test (288 of 288), membership-pages, stored-closure, draft-reads-stored, version-files, packed-crossings, project-writer-storage, writer-adoption, moves, view-cache (36 of 36); tsc and biome clean.Compare809 /** A stored graph's movers, read once (abso Capacity): every view walks them, a row each. */
810 #moverList: AtomId[] | undefined;
812 /** Each atom's deleted lines by n, packed (#46), or undefined when it deletes none. */
codex-capacity-chair109Add opt-in persistent writer state, checked reopen and bounded adoptionCompare813 #atomDeletes: (readonly number[] | Int32Array | undefined)[] = [];
814 #labels: StateMap<string, Label> = new Map();
816 #authors = new Map<string, string>();
818 /** Number of atoms (also the seq the next atom gets). */
819 get size(): number {
820 return this.#atoms.length;
821 }
823 /** The id the next accepted atom must have. */
824 nextId(): AtomId {
825 return atomId(this.#atoms.length);
826 }
828 has(id: AtomId): boolean {
829 const seq = this.#seq(id);
830 return seq >= 0 && seq < this.#atoms.length;
831 }
833 atom(id: AtomId): Atom {
834 const seq = this.#seq(id);
835 const atom = seq >= 0 ? this.#atoms[seq] : undefined;
836 if (!atom) throw new EngineError("unknown-atom", `no atom ${id}`);
837 return atom;
838 }
840 /** All atoms in seq order. */
841 atoms(): readonly Atom[] {
842 return this.#atoms;
843 }
845 /** lamport(a) = 1 + max lamport of its deps; 0 for an atom with no deps (such as a0). */
846 lamport(id: AtomId): number {
codex-capacity-chair148Read graph identities and metadata without decoding atom payloadsCompare847 if (!this.has(id)) throw new EngineError("unknown-atom", `no atom ${id}`);
capacity228Lamport numbers 256 to a row, and movers read once per graph (disk-first 2; abso Capacity).
After 226, where on typescript-rs still read about 12,000 lamport rows (one per atom, for ordering a file's lines) and the movers list (1,024 rows, one per atom that moves lines) nine times over.
- A stored graph keeps its atoms' lamport numbers in pages of 256 (lamport-pages), from a fresh graph on. A graph that already keeps them a row each goes on doing so. The choice is made when a number is first needed, so opening still reads nothing.
- A stored graph reads its movers once and keeps them, checked against the stored list's length and last mover on each use so a rolled-back add can't leave one behind.
On typescript-rs adopted fresh, cold: where 59,000 reads to 39,000. Its time locally is now mostly work, not reads (5.2 s). 26 of 27 answers match replay; collisions still runs past 60 s.
New test lamport-pages: a fresh graph keeps pages and reopens with them; a graph with a row each reads them and writes the next atom as a row. Named tests: every engine test (288 of 288), membership-pages, stored-closure, draft-reads-stored, version-files, packed-crossings, project-writer-storage, writer-adoption, moves, view-cache (36 of 36); tsc and biome clean.Compare848 return this.#lamportAt(this.#seq(id));
851 /** Compare by priority (lamport, then seq). Negative when a comes first (is lower). */
852 comparePriority(a: AtomId, b: AtomId): number {
853 return this.lamport(a) - this.lamport(b) || this.#seq(a) - this.#seq(b);
854 }
856 line(id: LineId): LineInfo | undefined {
857 const n = this.#lineN(id);
858 if (n < 0) return undefined;
859 const seq = this.#lineAtom.at(n);
860 return {
861 id,
codex-capacity-chair148Read graph identities and metadata without decoding atom payloadsCompare862 atom: this.idOfSeq(seq),
864 file: this.#paths[this.#lineFile.at(n)]!,
865 parent: this.#nodeName(this.#lineParent.at(n)),
866 text: this.#text(n),
867 };
868 }
870 /** A line's text, or undefined for an unknown line: line(id).text without making the record. */
871 lineText(id: LineId): string | undefined {
872 const n = this.#lineN(id);
873 return n < 0 ? undefined : this.#text(n);
874 }
876 /** The atom that wrote a line, or undefined: line(id).atom without making the record. */
877 lineAtom(id: LineId): AtomId | undefined {
878 const n = this.#lineN(id);
codex-capacity-chair148Read graph identities and metadata without decoding atom payloadsCompare879 return n < 0 ? undefined : this.idOfSeq(this.#lineAtom.at(n));
882 /** The file a line was written in, or undefined: line(id).file without making the record. */
883 lineFile(id: LineId): string | undefined {
884 const n = this.#lineN(id);
885 return n < 0 ? undefined : this.#paths[this.#lineFile.at(n)];
886 }
888 /** The node a line was written after, or undefined: line(id).parent without making the record. */
889 lineParent(id: LineId): NodeId | undefined {
890 const n = this.#lineN(id);
891 return n < 0 ? undefined : this.#nodeName(this.#lineParent.at(n));
892 }
894 // By number, for views (#46) ------------------------------------------------------
895 // 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
896 // keeps them, so a view can lay files out as arrays of numbers. For the engine's own use.
898 /** A line id's n, or -1 for an unknown line. */
899 lineN(id: LineId): number {
900 return this.#lineN(id);
901 }
903 /** A line's id from its n. */
904 lineIdOf(n: number): LineId {
905 return this.#lineName(n);
906 }
908 /** The lines an atom deletes, from the graph's own packed copy (#46): never a read of the log. */
909 deletedLines(id: AtomId): readonly LineId[] {
codex-capacity-chair162Add reviewed disk-first history and indexed graph storage for core issue 16; retain runtime activation gateCompare910 const seq = this.#seq(id);
911 const count = this.#storage?.read("atom-delete-counts", String(seq));
912 if (count !== undefined) {
913 const out: LineId[] = [];
914 for (const n of storedLists<number>(this.#storage!, "atom-deletes").values(String(seq)))
915 out.push(this.#lineName(n));
916 if (out.length !== count) throw Error("incomplete atom deletion index");
917 return out;
918 }
920 if (!ns) return EMPTY;
921 const out: LineId[] = new Array(ns.length);
922 for (let i = 0; i < ns.length; i++) out[i] = this.#lineName(ns[i]!);
923 return out;
capacity212Draft reads on a stored writer (disk-first 2; abso Capacity): where, drafts, status and collisions on website's export.
- where looks deleted lines up by number (graph.deletedNumbers, View.fileOfNumber, View.lineNumberOf). It takes the agent's view once instead of once per line, since each read weighed every cached view. It finds the draft's lines by writer (View.visibleWriters), with no text or id read per line.
- Draft files (overlaps.ts) go by number the same way.
- An agent's view takes its base's resolved moves when both hold the same atoms that move lines (View.shareMoves checks this).
- Draft collisions:
- build the union view only when two drafts share a file;
- work out each agent's touched files and its "shared now plus draft" view once;
- find claimants among the drafts from the drafts' own keys (collisions.ts claimantsAmong) instead of walking each key's history;
- have the definition rule keep a draft's uses, and the newer work's definitions, across partners.
- A stored list read in order reads its length once, not before every element.
draft-reads-stored.test.ts checks where and collisions against the in-memory project. It covers edits, a whole file deleted, a line collision, one name defined twice, and bases before and after a move. 135 of 136 related tests pass; none fail.
On website's export (1,387 entries) the answers match Project.load:
- status: 17 s to 4.5 s
- where: over 60 s to 8.8 s
- drafts: 14 s to 5.3 s
- collisions: over 60 s to 54 s, measured under the profiler before the last two changesCompare924 }
926 /** The numbers of the lines an atom deletes, from the graph's packed copy: no lookup per line id. */
927 *deletedNumbers(id: AtomId): IterableIterator<number> {
928 const seq = this.#seq(id);
929 if (this.#storage?.read("atom-delete-counts", String(seq)) !== undefined) {
930 yield* storedLists<number>(this.#storage!, "atom-deletes").values(String(seq));
931 return;
932 }
933 yield* this.#atomDeletes[seq] ?? EMPTY_NUMBERS;
936 /** How many lines an atom deletes, without reading its lists. */
937 deleteCount(id: AtomId): number {
codex-capacity-chair162Add reviewed disk-first history and indexed graph storage for core issue 16; retain runtime activation gateCompare938 const seq = this.#seq(id);
939 const count = this.#storage?.read("atom-delete-counts", String(seq));
940 if (count !== undefined) {
941 if (!Number.isSafeInteger(count) || (count as number) < 0) throw Error("invalid atom deletion count");
942 return count as number;
943 }
944 return this.#atomDeletes[seq]?.length ?? 0;
947 textOf(n: number): string {
948 return this.#text(n);
949 }
codex-capacity-chair175Reduce disk-backed record and publish allocations; reviewed in core ask 52 with parsed-code budget and exact aligned-line follow-ups. Keep disk-first activation off.Compare951 /** Historical text in bounded chunks, without decoding a whole stored line. */
952 *textChunks(n: number): IterableIterator<string> {
953 if (!this.#storage) {
954 const text = this.#text(n);
955 for (let offset = 0; offset < text.length; offset += StoredText.chunkCharacters)
956 yield text.slice(offset, offset + StoredText.chunkCharacters);
957 return;
958 }
959 if (!Number.isSafeInteger(n) || n < 0 || n >= this.#lineText!.length) throw Error("invalid line number");
960 const value = this.#storage.read("line-text", String(n));
961 if (typeof value === "string") {
962 yield value;
963 return;
964 }
965 const reference = value as { format?: number; text?: string } | undefined;
966 if (reference?.format !== 1 || typeof reference.text !== "string") throw Error("invalid long line reference");
967 yield* new StoredText(this.#storage, "atom-text:long").chunks(reference.text);
968 }
971 writerSeqOf(n: number): number {
972 return this.#lineAtom.at(n);
973 }
975 /** Line n's k: its place among its atom's lines. */
976 kOf(n: number): number {
977 return n - this.#lineBase[this.#lineAtom.at(n)]!;
978 }
980 /** The atom id with this seq, as the graph keeps it. */
981 idOfSeq(seq: number): AtomId {
codex-capacity-chair148Read graph identities and metadata without decoding atom payloadsCompare982 if (!Number.isSafeInteger(seq) || seq < 0 || seq >= this.#atoms.length)
983 throw new EngineError("unknown-atom", `no atom at sequence ${seq}`);
984 return atomId(seq);
capacity228Lamport numbers 256 to a row, and movers read once per graph (disk-first 2; abso Capacity).
After 226, where on typescript-rs still read about 12,000 lamport rows (one per atom, for ordering a file's lines) and the movers list (1,024 rows, one per atom that moves lines) nine times over.
- A stored graph keeps its atoms' lamport numbers in pages of 256 (lamport-pages), from a fresh graph on. A graph that already keeps them a row each goes on doing so. The choice is made when a number is first needed, so opening still reads nothing.
- A stored graph reads its movers once and keeps them, checked against the stored list's length and last mover on each use so a rolled-back add can't leave one behind.
On typescript-rs adopted fresh, cold: where 59,000 reads to 39,000. Its time locally is now mostly work, not reads (5.2 s). 26 of 27 answers match replay; collisions still runs past 60 s.
New test lamport-pages: a fresh graph keeps pages and reopens with them; a graph with a row each reads them and writes the next atom as a row. Named tests: every engine test (288 of 288), membership-pages, stored-closure, draft-reads-stored, version-files, packed-crossings, project-writer-storage, writer-adoption, moves, view-cache (36 of 36); tsc and biome clean.Compare985 }
987 #lamportAt(seq: number): number {
988 return this.#lamportPages ? this.#lamportPages.at(seq) : this.#lamport[seq]!;
991 lamportOfSeq(seq: number): number {
capacity228Lamport numbers 256 to a row, and movers read once per graph (disk-first 2; abso Capacity).
After 226, where on typescript-rs still read about 12,000 lamport rows (one per atom, for ordering a file's lines) and the movers list (1,024 rows, one per atom that moves lines) nine times over.
- A stored graph keeps its atoms' lamport numbers in pages of 256 (lamport-pages), from a fresh graph on. A graph that already keeps them a row each goes on doing so. The choice is made when a number is first needed, so opening still reads nothing.
- A stored graph reads its movers once and keeps them, checked against the stored list's length and last mover on each use so a rolled-back add can't leave one behind.
On typescript-rs adopted fresh, cold: where 59,000 reads to 39,000. Its time locally is now mostly work, not reads (5.2 s). 26 of 27 answers match replay; collisions still runs past 60 s.
New test lamport-pages: a fresh graph keeps pages and reopens with them; a graph with a row each reads them and writes the next atom as a row. Named tests: every engine test (288 of 288), membership-pages, stored-closure, draft-reads-stored, version-files, packed-crossings, project-writer-storage, writer-adoption, moves, view-cache (36 of 36); tsc and biome clean.Compare992 return this.#lamportAt(seq);
995 /** The file line n was written in. */
996 writtenIn(n: number): string {
997 return this.#paths[this.#lineFile.at(n)]!;
998 }
1000 /** The code of the node line n was written after. */
1001 parentCodeOf(n: number): number {
1002 return this.#lineParent.at(n);
1003 }
1005 /** A node's code, or undefined for a node the graph doesn't know (a start node of a file nothing was written in). */
1006 codeOf(node: NodeId): number | undefined {
1007 return this.#nodeCode(node);
1008 }
1010 /** The node a code names. */
1011 nodeOf(code: number): NodeId {
1012 return this.#nodeName(code);
1013 }
1015 /** The start node's code for a path, or undefined when nothing was ever written in it. */
1016 startCodeOf(path: string): number | undefined {
1017 const p = this.#pathIndex.get(path);
1018 return p === undefined ? undefined : -1 - p;
1019 }
1021 /** The lines (their n) written right after a node, as childrenOf, into `out`. */
codex-capacity-chair130Stream paged child history into layout filteringCompare1024 for (const n of this.eachChildN(code)) out.push(n);
1025 }
1026 *eachChildN(code: number): IterableIterator<number> {
1028 code >= 0 &&
1029 code + 1 < this.#lineTotal &&
1030 this.#lineAtom.at(code + 1) === this.#lineAtom.at(code) &&
1031 this.#lineParent.at(code + 1) === code
1032 )
capacity205Disk-first reads stop walking the whole history (disk-first 2, stage 1; abso Capacity). Shared's closure is kept on disk per version (spaces.ts indexClosure): the atoms a version needs beyond what it published, as events like membership's, with drops handled; views and Project.#closed trust a set marked closed, and over a closed stored base only a draft's own atoms are walked. A view resolves its moves once in memory (up to MOVED_LINES_KEPT, 20,000 moved lines) instead of again on disk for every file it lays out, and finds lines moved under a node from them. Graph.eachChildN skips the per-line children lookup when the paged child counts say none. On game's export (writer adopted, lock held): shared() went from not finishing in 8 minutes to 9-13 s cold and 0.15-0.25 s warm, 291,000 queries to 57,000; pathsAt(head) 0.1-0.2 s.Compare1034 if (this.#runStartPages) {
1035 // The paged child counts say a line has no other children without a row read per line (abso Capacity).
1036 if (code >= 0 && this.#childCounts && this.#childCounts.at(code, this.#lineTotal) === 0) return;
1037 yield* this.#runStartPages.values(String(code));
1038 } else yield* listOf(this.#runStarts.get(code));
codex-capacity-chair131Bound persisted no-move layout with ordered successor traversalCompare1041 get hasOrderedChildren(): boolean {
1042 return this.#storage !== undefined;
codex-capacity-chair132Bound persistent relocation projection memory with rollback-only scratchCompare1043 }
1044 /** Synchronous derived work against one graph identity. Scratch never commits. */
1045 withProjectionScratch<T>(operation: (scratch: GraphStateStorage) => T): T {
1046 if (!this.#storage) throw new Error("projection scratch requires persistent graph storage");
1047 const size = this.size;
1048 const lines = this.lineCount;
1049 return withProjectionScratch(
1050 this.#storage,
1051 () => {
1052 if (this.size !== size || this.lineCount !== lines) throw new Error("projection graph identity changed");
1053 },
1054 operation,
1055 );
1057 #childPriority(n: number): string {
1058 const seq = this.writerSeqOf(n);
1059 return orderedChildKey({
1060 n,
1061 replaces: this.replacesN(n) ? 1 : 0,
1062 lamport: this.lamportOfSeq(seq),
1063 seq,
1064 k: this.kOf(n),
1065 });
1066 }
1067 /** Persistent layout order with a strict successor cursor; moves are separate. */
1068 *orderedChildrenN(code: number, after?: number): IterableIterator<number> {
1069 if (!this.#storage) throw new Error("ordered children require indexed storage");
1070 const index = new OrderedIndex(this.#storage, "ordered-children", String(code));
codex-capacity-chair137Page explicit child counts with bounded corruption checksCompare1071 if (this.#storage.read("ordered-children", "format") !== 2)
codex-capacity-chair131Bound persisted no-move layout with ordered successor traversalCompare1072 throw new Error("ordered children require fresh adoption");
codex-capacity-chair137Page explicit child counts with bounded corruption checksCompare1073 const count = code >= 0 ? this.#childCounts!.at(code, this.#lineTotal) : index.size;
1074 if ((code < 0 || count > 0) && (count !== index.size || count !== this.#runStartPages!.length(String(code))))
1075 throw new Error("ordered child index count mismatch");
codex-capacity-chair131Bound persisted no-move layout with ordered successor traversalCompare1076 let implicit: number | undefined;
1077 if (
1078 code >= 0 &&
1079 code + 1 < this.#lineTotal &&
1080 this.#lineAtom.at(code + 1) === this.#lineAtom.at(code) &&
1081 this.#lineParent.at(code + 1) === code
1082 )
1083 implicit = code + 1;
codex-capacity-chair135Skip priority decoding for implicit-only child traversalCompare1084 // Most historical run lines have no explicit child. With zero or one
1085 // child, traversal needs no priority decoding or radix lookup. Keep the
1086 // format/count checks above even on this path.
1087 if (count === 0 && (after === undefined || after === implicit)) {
1088 if (implicit !== undefined && after !== implicit) yield implicit;
1089 return;
1090 }
codex-capacity-chair131Bound persisted no-move layout with ordered successor traversalCompare1091 const cursor = after === undefined ? undefined : this.#childPriority(after);
1092 if (implicit !== undefined && cursor !== undefined && this.#childPriority(implicit) <= cursor) implicit = undefined;
1093 for (const n of index.values(cursor)) {
1094 if (implicit !== undefined && this.#childPriority(implicit) < this.#childPriority(n)) {
1095 yield implicit;
1096 implicit = undefined;
1097 }
1098 yield n;
1099 }
1100 if (implicit !== undefined) yield implicit;
1101 }
1104 return this.#replacing.at(n) === 1;
1105 }
1107 /** The seqs of every atom that deletes line n (none: an empty list, shared). */
1108 deleterSeqsOf(n: number): readonly number[] {
codex-capacity-chair128Page deletion history and short-circuit current visibilityCompare1109 return [...this.eachDeleterSeqOf(n)];
1110 }
1111 *eachDeleterSeqOf(n: number): IterableIterator<number> {
codex-capacity-chair128Page deletion history and short-circuit current visibilityCompare1113 if (first < 0) return;
1114 yield first;
1115 if (this.#moreDeleterPages) yield* this.#moreDeleterPages.values(String(n));
1116 else yield* this.#moreDeleters.get(n) ?? EMPTY;
1119 /** Every relocation that puts a line right after the node with this code. */
1120 relocatedToCode(code: number): readonly RelocationInfo[] {
codex-capacity-chair127Page persistent relocation indexes and stream projection readsCompare1121 if (this.#relocatedToCodePages) return [...this.eachRelocatedToCode(code)];
1124 *eachRelocatedToCode(code: number): IterableIterator<RelocationInfo> {
1125 if (this.#relocatedToCodePages) yield* this.#relocatedToCodePages.values(String(code));
1126 else yield* this.#relocatedToCode.get(code) ?? EMPTY;
1129 /** How many lines every atom together has written. */
1130 get lineCount(): number {
1131 return this.#lineTotal;
1132 }
1134 /** A line id's n, or -1 when no accepted atom wrote it. */
1135 #lineN(id: LineId): number {
1136 const p = parseLineId(id);
1137 if (!p || p.seq >= this.#atoms.length) return -1;
1138 const base = this.#lineBase[p.seq]!;
1139 const end = p.seq + 1 < this.#lineBase.length ? this.#lineBase[p.seq + 1]! : this.#lineTotal;
1140 return p.k < end - base ? base + p.k : -1;
1141 }
1143 /** A line's id from its n. */
1144 #lineName(n: number): LineId {
1145 const seq = this.#lineAtom.at(n);
codex-capacity-chair148Read graph identities and metadata without decoding atom payloadsCompare1146 return `${this.idOfSeq(seq)}.${n - this.#lineBase[seq]!}`;
1149 /** A node's code: a line's n, or -1 - a path's index for a start node; undefined when unknown. */
1150 #nodeCode(node: NodeId): number | undefined {
1151 if (isStartNode(node)) {
1152 const p = this.#pathIndex.get(node.slice(1));
1153 return p === undefined ? undefined : -1 - p;
1154 }
1155 const n = this.#lineN(node);
1156 return n < 0 ? undefined : n;
1157 }
1159 #nodeName(code: number): NodeId {
1160 return code >= 0 ? this.#lineName(code) : startNode(this.#paths[-1 - code]!);
1161 }
1163 #pathOf(file: string): number {
1164 let p = this.#pathIndex.get(file);
1165 if (p === undefined) {
1166 p = this.#paths.push(file) - 1;
1167 this.#pathIndex.set(file, p);
1168 }
1169 return p;
1170 }
1172 /** The line ids an atom inserted, in k order. */
1173 linesOf(id: AtomId): LineId[] {
codex-capacity-chair175Reduce disk-backed record and publish allocations; reviewed in core ask 52 with parsed-code budget and exact aligned-line follow-ups. Keep disk-first activation off.Compare1174 return [...this.eachInsertedLine(id)];
1175 }
1176 /** Inserted identities without decoding or allocating the atom's text. */
1177 *eachInsertedLine(id: AtomId): IterableIterator<LineId> {
1178 const seq = this.atom(id).seq;
init0Start the project1179 const count = (seq + 1 < this.#lineBase.length ? this.#lineBase[seq + 1]! : this.#lineTotal) - this.#lineBase[seq]!;
codex-capacity-chair175Reduce disk-backed record and publish allocations; reviewed in core ask 52 with parsed-code budget and exact aligned-line follow-ups. Keep disk-first activation off.Compare1180 for (let k = 0; k < count; k++) yield lineId(id, k);
1183 /** Every atom that deletes this line (across the whole graph). */
1184 deletersOf(line: LineId): readonly AtomId[] {
1185 const n = this.#lineN(line);
1186 if (n < 0) return EMPTY;
codex-capacity-chair148Read graph identities and metadata without decoding atom payloadsCompare1187 return [...this.eachDeleterSeqOf(n)].map((seq) => this.idOfSeq(seq));
1190 writersOf(key: Key): readonly AtomId[] {
codex-capacity-chair120Page persistent claim indexes and stream dependency queriesCompare1191 return [...this.eachWriterOf(key)];
codex-capacity-chair120Page persistent claim indexes and stream dependency queriesCompare1193 *eachWriterOf(key: Key): IterableIterator<AtomId> {
1194 const code = this.#code(key);
1195 if (this.#writersPages) yield* this.#writersPages.values(JSON.stringify([typeof code, code]));
1196 else yield* listOf(this.#writers.get(code));
1197 }
1199 /** Atoms whose implicit reads include the key. */
1200 readersOf(key: Key): readonly AtomId[] {
codex-capacity-chair120Page persistent claim indexes and stream dependency queriesCompare1201 return [...this.eachReaderOf(key)];
1202 }
1203 *eachReaderOf(key: Key): IterableIterator<AtomId> {
1204 const code = this.#code(key);
1205 if (this.#readersPages) yield* this.#readersPages.values(JSON.stringify([typeof code, code]));
1206 else yield* listOf(this.#readers.get(code));
1209 /** Atoms whose explicit holds include the key. */
1210 holdersOf(key: Key): readonly AtomId[] {
codex-capacity-chair120Page persistent claim indexes and stream dependency queriesCompare1211 return [...this.eachHolderOf(key)];
1212 }
1213 *eachHolderOf(key: Key): IterableIterator<AtomId> {
1214 const code = this.#code(key);
1215 if (this.#holdersPages) yield* this.#holdersPages.values(JSON.stringify([typeof code, code]));
1216 else yield* listOf(this.#holders.get(code));
1219 /** Every atom that inserts or deletes a line of the file, in seq order. */
1220 atomsIn(file: string): readonly AtomId[] {
codex-capacity-chair119Page per-file atom indexes and stream current-view attribute scansCompare1221 if (this.#fileAtomPages) return [...this.#fileAtomPages.values(file)];
codex-capacity-chair119Page per-file atom indexes and stream current-view attribute scansCompare1223 }
1224 *eachAtomIn(file: string): IterableIterator<AtomId> {
1225 if (this.#fileAtomPages) yield* this.#fileAtomPages.values(file);
1226 else yield* this.#fileAtoms.get(file) ?? EMPTY;
codex-capacity-chair119Page per-file atom indexes and stream current-view attribute scansCompare1228 hasAtomsIn(file: string): boolean {
1229 return this.#fileAtomPages ? this.#fileAtomPages.length(file) > 0 : this.#fileAtoms.has(file);
1230 }
codex-capacity-chair118Avoid retaining deleted historical paths in indexed current viewsCompare1232 /** Unique historical file paths, streamed without collecting their names. */
1233 *knownFiles(): IterableIterator<string> {
codex-capacity-chair119Page per-file atom indexes and stream current-view attribute scansCompare1234 yield* this.#fileAtomPages ? this.#fileAtomPages.keys() : this.#fileAtoms.keys();
codex-capacity-chair118Avoid retaining deleted historical paths in indexed current viewsCompare1235 }
1238 * The files an atom inserts, deletes or moves lines in, or sets attributes
1239 * of, sorted. For lines, the file each was written in (or, for a move to a
1240 * start node, that file): a set's moves can have taken them elsewhere.
1241 */
1242 filesOf(id: AtomId): readonly string[] {
codex-capacity-chair148Read graph identities and metadata without decoding atom payloadsCompare1243 if (!this.has(id)) throw new EngineError("unknown-atom", `no atom ${id}`);
1245 }
1247 /** Lines written right after a node (not counting moves), in seq order. */
1250 const code = this.#nodeCode(node);
codex-capacity-chair130Stream paged child history into layout filteringCompare1251 return code === undefined ? [] : [...this.eachChildN(code)].map((n) => this.#lineName(n));
1254 /** Whether a line starts a run whose atom deleted the line it hangs off. */
1255 replaces(line: LineId): boolean {
1256 const n = this.#lineN(line);
1257 return n >= 0 && this.#replacing.at(n) === 1;
1258 }
1260 /** Every relocation of a line, in seq order. */
1261 relocationsOf(line: LineId): readonly RelocationInfo[] {
codex-capacity-chair127Page persistent relocation indexes and stream projection readsCompare1262 if (this.#relocationPages) return [...this.eachRelocationOf(line)];
1264 }
codex-capacity-chair127Page persistent relocation indexes and stream projection readsCompare1265 *eachRelocationOf(line: LineId): IterableIterator<RelocationInfo> {
1266 if (this.#relocationPages) yield* this.#relocationPages.values(line);
1267 else yield* this.#relocations.get(line) ?? EMPTY;
1268 }
1270 /** Every relocation that puts a line right after this node, in seq order. */
1271 relocatedTo(node: NodeId): readonly RelocationInfo[] {
codex-capacity-chair127Page persistent relocation indexes and stream projection readsCompare1272 if (this.#relocatedToPages) return [...this.#relocatedToPages.values(node)];
1274 }
1276 /** Atoms that move lines, in seq order. */
1277 movers(): readonly AtomId[] {
capacity228Lamport numbers 256 to a row, and movers read once per graph (disk-first 2; abso Capacity).
After 226, where on typescript-rs still read about 12,000 lamport rows (one per atom, for ordering a file's lines) and the movers list (1,024 rows, one per atom that moves lines) nine times over.
- A stored graph keeps its atoms' lamport numbers in pages of 256 (lamport-pages), from a fresh graph on. A graph that already keeps them a row each goes on doing so. The choice is made when a number is first needed, so opening still reads nothing.
- A stored graph reads its movers once and keeps them, checked against the stored list's length and last mover on each use so a rolled-back add can't leave one behind.
On typescript-rs adopted fresh, cold: where 59,000 reads to 39,000. Its time locally is now mostly work, not reads (5.2 s). 26 of 27 answers match replay; collisions still runs past 60 s.
New test lamport-pages: a fresh graph keeps pages and reopens with them; a graph with a row each reads them and writes the next atom as a row. Named tests: every engine test (288 of 288), membership-pages, stored-closure, draft-reads-stored, version-files, packed-crossings, project-writer-storage, writer-adoption, moves, view-cache (36 of 36); tsc and biome clean.Compare1278 if (!this.#storage) return this.#movers;
1279 // Checked against the stored list's length and last mover, so a rolled-back add can't leave one behind.
1280 const length = this.#movers.length;
1281 const list = this.#moverList;
1282 if (list && list.length === length && (length === 0 || list[length - 1] === this.#movers[length - 1])) return list;
1283 this.#moverList = [...this.#movers];
1284 return this.#moverList;
1287 /** Atoms that list this one directly in their deps. */
1288 dependentsOf(id: AtomId): readonly AtomId[] {
codex-capacity-chair122Page dependency and resolver indexes with streamed intersectionCompare1289 return [...this.eachDependentOf(id)];
codex-capacity-chair122Page dependency and resolver indexes with streamed intersectionCompare1291 *eachDependentOf(id: AtomId): IterableIterator<AtomId> {
1292 if (this.#dependentsPages) yield* this.#dependentsPages.values(id);
1293 else yield* listOf(this.#dependents.get(id));
1294 }
1296 /** Atoms whose `resolves` names this one. */
1297 resolversOf(id: AtomId): readonly AtomId[] {
codex-capacity-chair122Page dependency and resolver indexes with streamed intersectionCompare1298 return [...this.eachResolverOf(id)];
1299 }
1300 *eachResolverOf(id: AtomId): IterableIterator<AtomId> {
1301 if (this.#resolversPages) yield* this.#resolversPages.values(id);
1302 else yield* listOf(this.#resolvers.get(id));
1305 /** `together` reasons touching this atom, in either direction. */
1306 togetherLinks(id: AtomId): readonly TogetherLink[] {
codex-capacity-chair129Page together relationship history for bounded traversalCompare1307 return [...this.eachTogetherLink(id)];
codex-capacity-chair129Page together relationship history for bounded traversalCompare1309 *eachTogetherLink(id: AtomId): IterableIterator<TogetherLink> {
1310 if (this.#togetherPages) yield* this.#togetherPages.values(id);
1311 else yield* this.#together.get(id) ?? EMPTY;
1312 }
1314 /**
1315 * The atom plus everything it depends on, transitively. Computed on demand
1316 * and not cached: a cached set per atom costs memory quadratic in the length
1317 * of a dependency chain. Use `dependsOn` to ask about one pair.
1318 */
1319 closure(id: AtomId): Set<AtomId> {
1320 return this.closureOf([id]);
1321 }
1323 /** The atoms plus everything they depend on, transitively. */
1324 closureOf(ids: Iterable<AtomId>): Set<AtomId> {
1325 const out = new Set<AtomId>();
1326 const stack: AtomId[] = [];
1327 for (const id of ids) {
1328 this.atom(id);
1329 if (!out.has(id)) {
1330 out.add(id);
1331 stack.push(id);
1332 }
1333 }
1334 while (stack.length > 0) {
1335 for (const d of this.atom(stack.pop()!).deps) {
1336 if (!out.has(d)) {
1337 out.add(d);
1338 stack.push(d);
1339 }
1340 }
1341 }
1342 return out;
1343 }
1345 /** Whether `b` is in the closure of `a` (an atom is in its own closure). */
1346 dependsOn(a: AtomId, b: AtomId): boolean {
1347 const atom = this.atom(a);
1348 this.atom(b);
1349 return a === b || this.#reaches(atom.deps, b);
1350 }
1352 /**
1353 * Whether `target` is reachable along deps from any of `from` (themselves
1354 * included). A dependency always has a lower lamport than its dependent, so
1355 * the search never descends below the target's lamport.
1356 */
1357 #reaches(from: Iterable<AtomId>, target: AtomId): boolean {
capacity228Lamport numbers 256 to a row, and movers read once per graph (disk-first 2; abso Capacity).
After 226, where on typescript-rs still read about 12,000 lamport rows (one per atom, for ordering a file's lines) and the movers list (1,024 rows, one per atom that moves lines) nine times over.
- A stored graph keeps its atoms' lamport numbers in pages of 256 (lamport-pages), from a fresh graph on. A graph that already keeps them a row each goes on doing so. The choice is made when a number is first needed, so opening still reads nothing.
- A stored graph reads its movers once and keeps them, checked against the stored list's length and last mover on each use so a rolled-back add can't leave one behind.
On typescript-rs adopted fresh, cold: where 59,000 reads to 39,000. Its time locally is now mostly work, not reads (5.2 s). 26 of 27 answers match replay; collisions still runs past 60 s.
New test lamport-pages: a fresh graph keeps pages and reopens with them; a graph with a row each reads them and writes the next atom as a row. Named tests: every engine test (288 of 288), membership-pages, stored-closure, draft-reads-stored, version-files, packed-crossings, project-writer-storage, writer-adoption, moves, view-cache (36 of 36); tsc and biome clean.Compare1358 const floor = this.#lamportAt(this.#seq(target));
codex-capacity-chair139Bound persistent dependency reachability with rollback scratchCompare1359 if (this.#storage) {
1360 return this.withProjectionScratch((scratch) => {
1361 let length = 0;
1362 const push = (id: AtomId): void => {
1363 if (scratch.read("seen", id)) return;
1364 scratch.write("seen", id, true);
1365 scratch.write("stack", String(length++), id);
1366 };
codex-capacity-chair162Add reviewed disk-first history and indexed graph storage for core issue 16; retain runtime activation gateCompare1367 for (const id of from) {
1368 if (id === target) return true;
capacity228Lamport numbers 256 to a row, and movers read once per graph (disk-first 2; abso Capacity).
After 226, where on typescript-rs still read about 12,000 lamport rows (one per atom, for ordering a file's lines) and the movers list (1,024 rows, one per atom that moves lines) nine times over.
- A stored graph keeps its atoms' lamport numbers in pages of 256 (lamport-pages), from a fresh graph on. A graph that already keeps them a row each goes on doing so. The choice is made when a number is first needed, so opening still reads nothing.
- A stored graph reads its movers once and keeps them, checked against the stored list's length and last mover on each use so a rolled-back add can't leave one behind.
On typescript-rs adopted fresh, cold: where 59,000 reads to 39,000. Its time locally is now mostly work, not reads (5.2 s). 26 of 27 answers match replay; collisions still runs past 60 s.
New test lamport-pages: a fresh graph keeps pages and reopens with them; a graph with a row each reads them and writes the next atom as a row. Named tests: every engine test (288 of 288), membership-pages, stored-closure, draft-reads-stored, version-files, packed-crossings, project-writer-storage, writer-adoption, moves, view-cache (36 of 36); tsc and biome clean.Compare1369 if (this.#lamportAt(this.#seq(id)) > floor) push(id);
codex-capacity-chair162Add reviewed disk-first history and indexed graph storage for core issue 16; retain runtime activation gateCompare1370 }
codex-capacity-chair139Bound persistent dependency reachability with rollback scratchCompare1371 while (length > 0) {
1372 const key = String(--length);
1373 const current = scratch.read("stack", key) as AtomId;
1374 scratch.remove("stack", key);
capacity228Lamport numbers 256 to a row, and movers read once per graph (disk-first 2; abso Capacity).
After 226, where on typescript-rs still read about 12,000 lamport rows (one per atom, for ordering a file's lines) and the movers list (1,024 rows, one per atom that moves lines) nine times over.
- A stored graph keeps its atoms' lamport numbers in pages of 256 (lamport-pages), from a fresh graph on. A graph that already keeps them a row each goes on doing so. The choice is made when a number is first needed, so opening still reads nothing.
- A stored graph reads its movers once and keeps them, checked against the stored list's length and last mover on each use so a rolled-back add can't leave one behind.
On typescript-rs adopted fresh, cold: where 59,000 reads to 39,000. Its time locally is now mostly work, not reads (5.2 s). 26 of 27 answers match replay; collisions still runs past 60 s.
New test lamport-pages: a fresh graph keeps pages and reopens with them; a graph with a row each reads them and writes the next atom as a row. Named tests: every engine test (288 of 288), membership-pages, stored-closure, draft-reads-stored, version-files, packed-crossings, project-writer-storage, writer-adoption, moves, view-cache (36 of 36); tsc and biome clean.Compare1375 if (this.#lamportAt(this.#seq(current)) <= floor) continue;
codex-capacity-chair139Bound persistent dependency reachability with rollback scratchCompare1376 for (const dependency of this.atom(current).deps) {
1377 if (dependency === target) return true;
1378 push(dependency);
1379 }
1380 }
1381 return false;
1382 });
1383 }
1385 const stack = [...from];
1386 while (stack.length > 0) {
1387 const cur = stack.pop()!;
1388 if (cur === target) return true;
1389 if (seen.has(cur)) continue;
1390 seen.add(cur);
capacity228Lamport numbers 256 to a row, and movers read once per graph (disk-first 2; abso Capacity).
After 226, where on typescript-rs still read about 12,000 lamport rows (one per atom, for ordering a file's lines) and the movers list (1,024 rows, one per atom that moves lines) nine times over.
- A stored graph keeps its atoms' lamport numbers in pages of 256 (lamport-pages), from a fresh graph on. A graph that already keeps them a row each goes on doing so. The choice is made when a number is first needed, so opening still reads nothing.
- A stored graph reads its movers once and keeps them, checked against the stored list's length and last mover on each use so a rolled-back add can't leave one behind.
On typescript-rs adopted fresh, cold: where 59,000 reads to 39,000. Its time locally is now mostly work, not reads (5.2 s). 26 of 27 answers match replay; collisions still runs past 60 s.
New test lamport-pages: a fresh graph keeps pages and reopens with them; a graph with a row each reads them and writes the next atom as a row. Named tests: every engine test (288 of 288), membership-pages, stored-closure, draft-reads-stored, version-files, packed-crossings, project-writer-storage, writer-adoption, moves, view-cache (36 of 36); tsc and biome clean.Compare1391 if (this.#lamportAt(this.#seq(cur)) <= floor) continue;
1393 }
1394 return false;
1395 }
1397 /**
1398 * Accept an atom into the graph. It must carry the next id and seq, and
1399 * everything it touches must come from atoms in its dependency closure.
1400 * The atom is frozen. Adding to the graph does not add it to any set.
1401 */
1402 add(atom: Atom): void {
codex-capacity-chair149Index atom metadata for resumable projection adoptionCompare1403 if (this.#storage)
1404 this.#storage.transaction(() => {
1405 this.#add(atom);
1406 const result: unknown = this.#indexAcceptedAtom?.(atom, this.filesOf(atom.id), this.#storage!);
1407 if (result && typeof result === "object" && "then" in result)
1408 throw Error("accepted atom indexing must be synchronous");
1409 });
codex-capacity-chair109Add opt-in persistent writer state, checked reopen and bounded adoptionCompare1410 else this.#add(atom);
1411 }
codex-capacity-chair162Add reviewed disk-first history and indexed graph storage for core issue 16; retain runtime activation gateCompare1413 #validateAcceptedAtom(atom: Atom, scratch?: GraphStateStorage): void {
1414 const membership = <T extends string>(name: string): { has(key: T): boolean; add(key: T): unknown } => {
1415 if (!scratch) return new Set<T>();
1416 return { has: (key) => scratch.read(name, key) === true, add: (key) => scratch.write(name, key, true) };
1417 };
1419 const seq = this.#atoms.length;
1420 const bad = (why: string): never => {
1421 throw new EngineError("bad-atom", `atom ${atom.id}: ${why}`);
1422 };
1423 if (atom.seq !== seq || atom.id !== atomId(seq)) bad(`expected id ${atomId(seq)} with seq ${seq}`);
codex-capacity-chair162Add reviewed disk-first history and indexed graph storage for core issue 16; retain runtime activation gateCompare1425 const deps = membership<AtomId>("deps");
1427 if (!this.has(d)) bad(`dependency ${d} is not in the graph`);
1428 if (deps.has(d)) bad(`dependency ${d} listed twice`);
1429 deps.add(d);
1430 }
codex-capacity-chair162Add reviewed disk-first history and indexed graph storage for core issue 16; retain runtime activation gateCompare1431 for (const list of [atom.needs, atom.resolves])
1432 for (const d of list) {
1433 if (!deps.has(d)) bad(`${d} is in needs/resolves but not in deps`);
1434 }
init0Start the project1435 for (const r of atom.reasons) if (!this.has(r.to)) bad(`reason points at unknown atom ${r.to}`);
1437 // Everything it touches must come from its closure. Derived deps name the
1438 // writers directly, so this is usually one lookup per writer.
codex-capacity-chair162Add reviewed disk-first history and indexed graph storage for core issue 16; retain runtime activation gateCompare1439 const memoryBelow = scratch ? undefined : new Map<AtomId, boolean>();
1440 const below = {
1441 get: (key: AtomId) => (scratch ? (scratch.read("below", key) as boolean | undefined) : memoryBelow!.get(key)),
1442 set: (key: AtomId, value: boolean) => {
1443 if (scratch) scratch.write("below", key, value);
1444 else memoryBelow!.set(key, value);
1445 },
1446 };
1448 let hit = below.get(writer);
1449 if (hit === undefined) {
codex-capacity-chair162Add reviewed disk-first history and indexed graph storage for core issue 16; retain runtime activation gateCompare1450 hit = deps.has(writer) || this.#reaches(atom.deps, writer);
1452 }
1453 return hit;
1454 };
1455 const checkLine = (line: LineId, what: string): void => {
1456 const writer = this.lineAtom(line);
1457 if (writer === undefined) return bad(`${what} names unknown line ${line}`);
1458 if (!inClosure(writer)) bad(`${what} names line ${line} but ${writer} is not in its closure`);
1459 };
1461 for (const run of atom.inserts) {
1462 if (isStartNode(run.parent)) {
1463 if (run.parent !== startNode(run.file)) bad(`run in ${run.file} starts at ${run.parent}`);
1464 } else {
1465 // The parent may have been moved into run.file, so its own file can differ.
1466 checkLine(run.parent, "an insert");
1467 }
1468 }
codex-capacity-chair162Add reviewed disk-first history and indexed graph storage for core issue 16; retain runtime activation gateCompare1469 const writes = membership<Key>("writes");
1470 for (const key of atom.writes) writes.add(key);
1471 const moved = membership<LineId>("moved");
1473 checkLine(m.line, "a move");
1474 if (!isStartNode(m.parent)) checkLine(m.parent, "a move");
1475 if (m.line === m.parent) bad(`moves ${m.line} after itself`);
1476 if (moved.has(m.line)) bad(`moves ${m.line} twice`);
1477 moved.add(m.line);
codex-capacity-chair162Add reviewed disk-first history and indexed graph storage for core issue 16; retain runtime activation gateCompare1478 if (!writes.has(posKey(m.line)) || !writes.has(gapKey(m.parent))) {
init0Start the project1479 bad(`moves ${m.line} without writing ${posKey(m.line)} and ${gapKey(m.parent)}`);
1480 }
1481 }
codex-capacity-chair162Add reviewed disk-first history and indexed graph storage for core issue 16; retain runtime activation gateCompare1482 const deleted = membership<LineId>("deleted");
1484 checkLine(line, "a delete");
1485 if (deleted.has(line)) bad(`deletes ${line} twice`);
1486 deleted.add(line);
1487 }
codex-capacity-chair162Add reviewed disk-first history and indexed graph storage for core issue 16; retain runtime activation gateCompare1488 for (const line of atom.deletes)
1489 if (!writes.has(lineKey(line))) bad(`deletes ${line} without writing ${lineKey(line)}`);
1490 for (const list of [atom.writes, atom.reads, atom.holds])
1491 for (const key of list) {
1492 const parsed = parseKey(key);
1493 if (parsed.kind === "line") checkLine(parsed.node, `key ${key}`);
1494 else if ((parsed.kind === "gap" || parsed.kind === "pos") && !isStartNode(parsed.node))
1495 checkLine(parsed.node, `key ${key}`);
1496 }
1497 }
codex-capacity-chair109Add opt-in persistent writer state, checked reopen and bounded adoptionCompare1499 #add(atom: Atom): void {
codex-capacity-chair137Page explicit child counts with bounded corruption checksCompare1500 if (this.#storage && this.#storage.read("ordered-children", "format") !== 2) {
codex-capacity-chair131Bound persisted no-move layout with ordered successor traversalCompare1501 if (this.#atoms.length !== 0) throw new Error("ordered children require fresh adoption");
codex-capacity-chair137Page explicit child counts with bounded corruption checksCompare1502 this.#storage.write("ordered-children", "format", 2);
capacity206Each file's line history packed (disk-first 2, lines by file; abso Capacity). A stored graph appends every line written in a file ([n, parent code, writer seq, k, replaces]) and its text, every delete of one of its lines, and every attribute set on it to that file's pages as atoms are added, a run at a time (storedLists appendAll). A view lays a file out from those pages in memory: membership checked once per atom, moves followed from the ones it already resolved, lines moved in from other files read from theirs. Same tree and order as before (packed-files.test.ts checks it against the in-memory graph through edits, deletes and moves). Graphs adopted before have no packs and lay out line by line as before; packFiles: false keeps that path for its tests. On game's export: first shared() 13 s to 2-3.6 s at 20,000 queries, warm 56-82 ms, pathsAt(head) 29-119 ms; files at a version 14 s to 3 s, compare 26 s to 11 s, a path's log 27 s to 4.5 s; every answer the harness finished matches Project.load.Compare1503 }
1504 if (this.#storage && this.#atoms.length === 0 && this.#packFiles) {
capacity221Packed layout follows lines written in another file (disk-first 2; abso Capacity).
where {} on typescript-rs left 11 lines out of erasable_syntax.rs in cloud-ts-12's draft. cloud-ts-12 moved one block between files several times, wrote lines under its last line while it sat in uninitialized_props_forms.rs, then moved the block on. Those lines followed their parent with no move of their own. The packed layout read only the file's own lines and the files its moved-in lines were written in, so it never read them.
- Each file's packed history also keeps the runs written in another file under one of its lines (file-crossings). The packed layout follows them until no new file turns up.
- New adoptions write packed format 2. A graph packed at format 1 has no such list, so it lays files out line by line: correct, but slower until it is adopted again.
- packed-crossings.test.ts moves c.ts to d.ts, adds a line in d.ts, moves d.ts to e.ts, and checks files, where and every draft's text against the in-memory project.
Named tests: packed-crossings, packed-files, state-source, draft-reads-stored, version-files, project-writer-storage, writer-adoption, moves, queued-moves, files-reads, move-reconstruction (60 of 60); tsc and biome clean.Compare1505 this.#storage.write("file-lines:meta", "format", 2);
1506 this.#formatKnown = 2;
codex-capacity-chair162Add reviewed disk-first history and indexed graph storage for core issue 16; retain runtime activation gateCompare1508
1509 if (this.#storage) this.withProjectionScratch((scratch) => this.#validateAcceptedAtom(atom, scratch));
1510 else this.#validateAcceptedAtom(atom);
1511 const seq = this.#atoms.length;
1512 const deps = atom.deps;
1513 const deleted = this.#storage ? undefined : new Set(atom.deletes);
1514 const writes = this.#storage ? atom.writes : new Set(atom.writes);
1516 // Accept.
codex-capacity-chair162Add reviewed disk-first history and indexed graph storage for core issue 16; retain runtime activation gateCompare1517 // Persistent storage copies the accepted atom; a second frozen copy only duplicates its lists.
1518 const frozen = this.#storage
1519 ? atom
1520 : freezeAtom(
codex-capacity-chair109Add opt-in persistent writer state, checked reopen and bounded adoptionCompare1521 atom,
codex-capacity-chair162Add reviewed disk-first history and indexed graph storage for core issue 16; retain runtime activation gateCompare1522 (id) => this.idOfSeq(seqOf(id)),
1523 (author) => {
1524 if (this.#storage) return author;
1525 let a = this.#authors.get(author);
1526 if (a === undefined) this.#authors.set(author, (a = author));
1527 return a;
1528 },
1529 this.#texts ? this.#reader(seq) : undefined,
1530 this.#lists ? this.#listReader(seq) : undefined,
1531 );
codex-capacity-chair109Add opt-in persistent writer state, checked reopen and bounded adoptionCompare1532 this.#atoms.push(this.#storage ? atom : frozen);
1534 for (const d of deps) lam = Math.max(lam, this.lamport(d) + 1);
capacity228Lamport numbers 256 to a row, and movers read once per graph (disk-first 2; abso Capacity).
After 226, where on typescript-rs still read about 12,000 lamport rows (one per atom, for ordering a file's lines) and the movers list (1,024 rows, one per atom that moves lines) nine times over.
- A stored graph keeps its atoms' lamport numbers in pages of 256 (lamport-pages), from a fresh graph on. A graph that already keeps them a row each goes on doing so. The choice is made when a number is first needed, so opening still reads nothing.
- A stored graph reads its movers once and keeps them, checked against the stored list's length and last mover on each use so a rolled-back add can't leave one behind.
On typescript-rs adopted fresh, cold: where 59,000 reads to 39,000. Its time locally is now mostly work, not reads (5.2 s). 26 of 27 answers match replay; collisions still runs past 60 s.
New test lamport-pages: a fresh graph keeps pages and reopens with them; a graph with a row each reads them and writes the next atom as a row. Named tests: every engine test (288 of 288), membership-pages, stored-closure, draft-reads-stored, version-files, packed-crossings, project-writer-storage, writer-adoption, moves, view-cache (36 of 36); tsc and biome clean.Compare1535 if (this.#lamportPages) this.#lamportPages.push(lam);
1536 else this.#lamport.push(lam);
1538 // The run starts' parents and the deleted lines, as codes, before this atom's own lines exist.
1539 // The atom as given: with lists kept elsewhere, the frozen one reads them back from the log.
codex-capacity-chair162Add reviewed disk-first history and indexed graph storage for core issue 16; retain runtime activation gateCompare1540 const deletes = (line: LineId | NodeId): boolean => {
1541 if (isStartNode(line)) return false;
1542 if (deleted) return deleted.has(line);
1543 const n = this.#lineN(line);
1544 return this.#deleter.at(n) === seq || this.#moreDeleterPages!.last(String(n)) === seq;
1545 };
1546 const deletedN = this.#storage ? undefined : atom.deletes.map((line) => this.#lineN(line));
1547 this.#atomDeletes.push(deletedN?.length ? Int32Array.from(deletedN) : undefined);
1548 if (this.#storage) {
1549 const pages = storedLists<number>(this.#storage, "atom-deletes");
1550 for (const line of atom.deletes) pages.append(String(seq), this.#lineN(line));
1551 this.#storage.write("atom-delete-counts", String(seq), atom.deletes.length);
1552 }
1553 const deletedNumbers = function* (graph: Graph) {
1554 if (deletedN) yield* deletedN;
1555 else for (const line of atom.deletes) yield graph.#lineN(line);
1556 };
capacity206Each file's line history packed (disk-first 2, lines by file; abso Capacity). A stored graph appends every line written in a file ([n, parent code, writer seq, k, replaces]) and its text, every delete of one of its lines, and every attribute set on it to that file's pages as atoms are added, a run at a time (storedLists appendAll). A view lays a file out from those pages in memory: membership checked once per atom, moves followed from the ones it already resolved, lines moved in from other files read from theirs. Same tree and order as before (packed-files.test.ts checks it against the in-memory graph through edits, deletes and moves). Graphs adopted before have no packs and lay out line by line as before; packFiles: false keeps that path for its tests. On game's export: first shared() 13 s to 2-3.6 s at 20,000 queries, warm 56-82 ms, pathsAt(head) 29-119 ms; files at a version 14 s to 3 s, compare 26 s to 11 s, a path's log 27 s to 4.5 s; every answer the harness finished matches Project.load.Compare1557 const packedDeletes = new Map<number, PackedDelete[]>();
codex-capacity-chair162Add reviewed disk-first history and indexed graph storage for core issue 16; retain runtime activation gateCompare1558 for (const n of deletedNumbers(this)) {
capacity206Each file's line history packed (disk-first 2, lines by file; abso Capacity). A stored graph appends every line written in a file ([n, parent code, writer seq, k, replaces]) and its text, every delete of one of its lines, and every attribute set on it to that file's pages as atoms are added, a run at a time (storedLists appendAll). A view lays a file out from those pages in memory: membership checked once per atom, moves followed from the ones it already resolved, lines moved in from other files read from theirs. Same tree and order as before (packed-files.test.ts checks it against the in-memory graph through edits, deletes and moves). Graphs adopted before have no packs and lay out line by line as before; packFiles: false keeps that path for its tests. On game's export: first shared() 13 s to 2-3.6 s at 20,000 queries, warm 56-82 ms, pathsAt(head) 29-119 ms; files at a version 14 s to 3 s, compare 26 s to 11 s, a path's log 27 s to 4.5 s; every answer the harness finished matches Project.load.Compare1559 if (this.#packed) {
1560 const file = this.#lineFile.at(n);
1561 const list = packedDeletes.get(file);
1562 if (list) list.push([n, seq]);
1563 else packedDeletes.set(file, [[n, seq]]);
1564 }
codex-capacity-chair128Page deletion history and short-circuit current visibilityCompare1566 else if (this.#moreDeleterPages) this.#moreDeleterPages.append(String(n), seq);
capacity206Each file's line history packed (disk-first 2, lines by file; abso Capacity). A stored graph appends every line written in a file ([n, parent code, writer seq, k, replaces]) and its text, every delete of one of its lines, and every attribute set on it to that file's pages as atoms are added, a run at a time (storedLists appendAll). A view lays a file out from those pages in memory: membership checked once per atom, moves followed from the ones it already resolved, lines moved in from other files read from theirs. Same tree and order as before (packed-files.test.ts checks it against the in-memory graph through edits, deletes and moves). Graphs adopted before have no packs and lay out line by line as before; packFiles: false keeps that path for its tests. On game's export: first shared() 13 s to 2-3.6 s at 20,000 queries, warm 56-82 ms, pathsAt(head) 29-119 ms; files at a version 14 s to 3 s, compare 26 s to 11 s, a path's log 27 s to 4.5 s; every answer the harness finished matches Project.load.Compare1569 for (const [file, list] of packedDeletes) this.#fileDeletes!.appendAll(String(file), list);
1571 for (const run of atom.inserts) {
1572 const file = this.#pathOf(run.file);
1573 let parent = isStartNode(run.parent) ? -1 - file : this.#lineN(run.parent);
1574 const first = this.#lineTotal;
codex-capacity-chair137Page explicit child counts with bounded corruption checksCompare1575 if (parent >= 0) this.#childCounts?.increment(parent, first);
codex-capacity-chair131Bound persisted no-move layout with ordered successor traversalCompare1576 if (this.#storage)
1577 new OrderedIndex(this.#storage, "ordered-children", String(parent)).insert(
1578 orderedChildKey({
1579 n: first,
codex-capacity-chair162Add reviewed disk-first history and indexed graph storage for core issue 16; retain runtime activation gateCompare1580 replaces: deletes(run.parent) ? 1 : 0,
codex-capacity-chair131Bound persisted no-move layout with ordered successor traversalCompare1581 lamport: lam,
1582 seq,
1583 k: first - this.#lineBase[seq]!,
1584 }),
1585 first,
1586 );
codex-capacity-chair130Stream paged child history into layout filteringCompare1588 if (this.#runStartPages) this.#runStartPages.append(String(parent), first);
1589 else pushOne(this.#runStarts, parent, first);
capacity206Each file's line history packed (disk-first 2, lines by file; abso Capacity). A stored graph appends every line written in a file ([n, parent code, writer seq, k, replaces]) and its text, every delete of one of its lines, and every attribute set on it to that file's pages as atoms are added, a run at a time (storedLists appendAll). A view lays a file out from those pages in memory: membership checked once per atom, moves followed from the ones it already resolved, lines moved in from other files read from theirs. Same tree and order as before (packed-files.test.ts checks it against the in-memory graph through edits, deletes and moves). Graphs adopted before have no packs and lay out line by line as before; packFiles: false keeps that path for its tests. On game's export: first shared() 13 s to 2-3.6 s at 20,000 queries, warm 56-82 ms, pathsAt(head) 29-119 ms; files at a version 14 s to 3 s, compare 26 s to 11 s, a path's log 27 s to 4.5 s; every answer the harness finished matches Project.load.Compare1590 const replacesParent = deletes(run.parent) ? 1 : 0;
1591 if (this.#packed) {
capacity221Packed layout follows lines written in another file (disk-first 2; abso Capacity).
where {} on typescript-rs left 11 lines out of erasable_syntax.rs in cloud-ts-12's draft. cloud-ts-12 moved one block between files several times, wrote lines under its last line while it sat in uninitialized_props_forms.rs, then moved the block on. Those lines followed their parent with no move of their own. The packed layout read only the file's own lines and the files its moved-in lines were written in, so it never read them.
- Each file's packed history also keeps the runs written in another file under one of its lines (file-crossings). The packed layout follows them until no new file turns up.
- New adoptions write packed format 2. A graph packed at format 1 has no such list, so it lays files out line by line: correct, but slower until it is adopted again.
- packed-crossings.test.ts moves c.ts to d.ts, adds a line in d.ts, moves d.ts to e.ts, and checks files, where and every draft's text against the in-memory project.
Named tests: packed-crossings, packed-files, state-source, draft-reads-stored, version-files, project-writer-storage, writer-adoption, moves, queued-moves, files-reads, move-reconstruction (60 of 60); tsc and biome clean.Compare1592 if (this.#crossings && parent >= 0) {
1593 const from = this.#lineFile.at(parent);
1594 if (from !== file) this.#fileCrossings!.append(String(from), [parent, file]);
1595 }
capacity206Each file's line history packed (disk-first 2, lines by file; abso Capacity). A stored graph appends every line written in a file ([n, parent code, writer seq, k, replaces]) and its text, every delete of one of its lines, and every attribute set on it to that file's pages as atoms are added, a run at a time (storedLists appendAll). A view lays a file out from those pages in memory: membership checked once per atom, moves followed from the ones it already resolved, lines moved in from other files read from theirs. Same tree and order as before (packed-files.test.ts checks it against the in-memory graph through edits, deletes and moves). Graphs adopted before have no packs and lay out line by line as before; packFiles: false keeps that path for its tests. On game's export: first shared() 13 s to 2-3.6 s at 20,000 queries, warm 56-82 ms, pathsAt(head) 29-119 ms; files at a version 14 s to 3 s, compare 26 s to 11 s, a path's log 27 s to 4.5 s; every answer the harness finished matches Project.load.Compare1596 const base = this.#lineBase[seq]!;
1597 this.#fileLines!.appendAll(
1598 String(file),
1599 run.lines.map(
1600 (_, i): PackedLine => [
1601 first + i,
1602 i === 0 ? parent : first + i - 1,
1603 seq,
1604 first + i - base,
1605 i === 0 ? replacesParent : 0,
1606 ],
1607 ),
1608 );
1609 this.#fileTexts!.appendAll(
1610 String(file),
1611 run.lines.map((text) => (typeof text === "string" && text.length <= PACKED_TEXT ? text : null)),
1612 );
1613 }
codex-capacity-chair109Add opt-in persistent writer state, checked reopen and bounded adoptionCompare1615 const n = this.#lineTotal;
codex-capacity-chair137Page explicit child counts with bounded corruption checksCompare1616 this.#childCounts?.append(n);
1618 this.#lineFile.push(file);
1619 this.#lineParent.push(parent);
1620 this.#lineText?.push(run.lines[i]!);
1621 this.#deleter.push(-1);
codex-capacity-chair162Add reviewed disk-first history and indexed graph storage for core issue 16; retain runtime activation gateCompare1622 this.#replacing.push(i === 0 && deletes(run.parent) ? 1 : 0);
1624 }
1625 }
1626 (frozen.moves ?? []).forEach((m, i) => {
1627 const info: RelocationInfo = Object.freeze({ atom: frozen.id, line: m.line, parent: m.parent, k: i });
codex-capacity-chair127Page persistent relocation indexes and stream projection readsCompare1628 if (this.#relocationPages) this.#relocationPages.append(m.line, info);
1629 else pushIndex(this.#relocations, m.line, info);
1630 if (this.#relocatedToPages) this.#relocatedToPages.append(m.parent, info);
1631 else pushIndex(this.#relocatedTo, m.parent, info);
1632 const parentCode = isStartNode(m.parent) ? -1 - this.#pathOf(m.parent.slice(1)) : this.#lineN(m.parent);
1633 if (this.#relocatedToCodePages) this.#relocatedToCodePages.append(String(parentCode), info);
1634 else pushIndex(this.#relocatedToCode, parentCode, info);
1636 if (frozen.moves) this.#movers.push(frozen.id);
capacity206Each file's line history packed (disk-first 2, lines by file; abso Capacity). A stored graph appends every line written in a file ([n, parent code, writer seq, k, replaces]) and its text, every delete of one of its lines, and every attribute set on it to that file's pages as atoms are added, a run at a time (storedLists appendAll). A view lays a file out from those pages in memory: membership checked once per atom, moves followed from the ones it already resolved, lines moved in from other files read from theirs. Same tree and order as before (packed-files.test.ts checks it against the in-memory graph through edits, deletes and moves). Graphs adopted before have no packs and lay out line by line as before; packFiles: false keeps that path for its tests. On game's export: first shared() 13 s to 2-3.6 s at 20,000 queries, warm 56-82 ms, pathsAt(head) 29-119 ms; files at a version 14 s to 3 s, compare 26 s to 11 s, a path's log 27 s to 4.5 s; every answer the harness finished matches Project.load.Compare1637 if (this.#packed)
1638 for (const a of frozen.attrs ?? []) this.#fileAttrs!.append(String(this.#pathOf(a.file)), [seq, a.name, a.value]);
codex-capacity-chair162Add reviewed disk-first history and indexed graph storage for core issue 16; retain runtime activation gateCompare1639 for (const key of writes) {
codex-capacity-chair120Page persistent claim indexes and stream dependency queriesCompare1640 const code = this.#code(key);
codex-capacity-chair162Add reviewed disk-first history and indexed graph storage for core issue 16; retain runtime activation gateCompare1641 if (this.#writersPages) {
1642 const key = JSON.stringify([typeof code, code]);
1643 if (this.#writersPages.last(key) !== frozen.id) this.#writersPages.append(key, frozen.id);
1644 } else pushOne(this.#writers, code, frozen.id);
codex-capacity-chair162Add reviewed disk-first history and indexed graph storage for core issue 16; retain runtime activation gateCompare1646 for (const key of this.#storage ? atom.reads : new Set(atom.reads)) {
codex-capacity-chair120Page persistent claim indexes and stream dependency queriesCompare1647 const code = this.#code(key);
codex-capacity-chair162Add reviewed disk-first history and indexed graph storage for core issue 16; retain runtime activation gateCompare1648 if (this.#readersPages) {
1649 const key = JSON.stringify([typeof code, code]);
1650 if (this.#readersPages.last(key) !== frozen.id) this.#readersPages.append(key, frozen.id);
1651 } else pushOne(this.#readers, code, frozen.id);
codex-capacity-chair162Add reviewed disk-first history and indexed graph storage for core issue 16; retain runtime activation gateCompare1653 for (const key of this.#storage ? atom.holds : new Set(atom.holds)) {
codex-capacity-chair120Page persistent claim indexes and stream dependency queriesCompare1654 const code = this.#code(key);
codex-capacity-chair162Add reviewed disk-first history and indexed graph storage for core issue 16; retain runtime activation gateCompare1655 if (this.#holdersPages) {
1656 const key = JSON.stringify([typeof code, code]);
1657 if (this.#holdersPages.last(key) !== frozen.id) this.#holdersPages.append(key, frozen.id);
1658 } else pushOne(this.#holders, code, frozen.id);
1660 for (const d of deps) {
1661 if (this.#dependentsPages) this.#dependentsPages.append(d, frozen.id);
1662 else pushOne(this.#dependents, d, frozen.id);
1663 }
codex-capacity-chair162Add reviewed disk-first history and indexed graph storage for core issue 16; retain runtime activation gateCompare1664 for (const r of this.#storage ? frozen.resolves : new Set(frozen.resolves)) {
1665 if (this.#resolversPages) {
1666 if (this.#resolversPages.last(r) !== frozen.id) this.#resolversPages.append(r, frozen.id);
1667 } else pushOne(this.#resolvers, r, frozen.id);
1669 const files = new Set<string>();
1670 for (const run of atom.inserts) files.add(run.file);
codex-capacity-chair162Add reviewed disk-first history and indexed graph storage for core issue 16; retain runtime activation gateCompare1671 for (const n of deletedNumbers(this)) files.add(this.#paths[this.#lineFile.at(n)]!);
1673 for (const m of frozen.moves ?? []) {
1674 files.add(this.lineFile(m.line)!);
1675 files.add(isStartNode(m.parent) ? m.parent.slice(1) : this.lineFile(m.parent)!);
1676 }
1677 this.#atomFiles.push(Object.freeze([...files].sort()));
codex-capacity-chair119Page per-file atom indexes and stream current-view attribute scansCompare1678 for (const file of files) {
1679 if (this.#fileAtomPages) this.#fileAtomPages.append(file, frozen.id);
1680 else pushIndex(this.#fileAtoms, file, frozen.id);
1681 }
1683 if (r.kind !== "together" || r.to === frozen.id) continue;
1685 const forward = { other: r.to, text: r.text, from: frozen.id };
1686 const reverse = { other: frozen.id, text: r.text, from: frozen.id };
1687 if (this.#togetherPages) {
1688 this.#togetherPages.append(frozen.id, forward);
1689 this.#togetherPages.append(r.to, reverse);
1690 } else {
1691 pushIndex(this.#together, frozen.id, forward);
1692 pushIndex(this.#together, r.to, reverse);
1693 }
1695 }
1697 // Labels -----------------------------------------------------------------
1699 /**
1700 * Add or replace a label. Label names may not look like atom ids. A base is
1701 * resolved to its head only when it is used, never followed further, so
1702 * bases may name each other in any shape.
1703 */
1704 setLabel(label: Label): void {
1705 this.#putLabel(label, (name) => this.#labels.has(name));
1706 }
1708 #putLabel(label: Label, isLabel: (name: string) => boolean): void {
1709 const bad = (why: string): never => {
1710 throw new EngineError("bad-label", `label ${JSON.stringify(label?.name)}: ${why}`);
1711 };
1712 if (typeof label !== "object" || label === null) bad("not an object");
1713 if (typeof label.name !== "string" || label.name === "") bad("needs a name");
1714 if (isAtomId(label.name)) bad("a label name may not look like an atom id");
1715 if (!this.has(label.head)) bad(`head ${label.head} is not in the graph`);
1716 if (
1717 label.base !== undefined &&
1718 !(typeof label.base === "string" && (isLabel(label.base) || this.has(label.base)))
1719 ) {
1720 bad(`base ${label.base} is neither a label nor an atom`);
1721 }
1722 if (label.base === label.name) bad("a label cannot be its own base");
1723 if (typeof label.title !== "string" || typeof label.message !== "string") bad("needs a title and message");
1724 if (label.follows !== undefined && !Array.isArray(label.follows)) bad("follows must be a list of label names");
1725 const copy: Label = {
1726 name: label.name,
1727 head: label.head,
1728 ...(label.base !== undefined ? { base: label.base } : {}),
1729 title: label.title,
1730 message: label.message,
1731 ...(label.follows !== undefined ? { follows: Object.freeze([...label.follows]) } : {}),
1732 };
1733 this.#labels.set(label.name, Object.freeze(copy));
1734 }
1736 label(name: string): Label | undefined {
1737 return this.#labels.get(name);
1738 }
1740 /** Labels sorted by name. */
1741 labels(): Label[] {
1742 return [...this.#labels.values()].sort((a, b) => (a.name < b.name ? -1 : a.name > b.name ? 1 : 0));
1743 }
1745 /**
1746 * Remove a label. Labels that used it as their base get its head atom as
1747 * their base instead, so their contents don't change.
1748 */
1749 removeLabel(name: string): boolean {
codex-capacity-chair109Add opt-in persistent writer state, checked reopen and bounded adoptionCompare1750 return this.#storage ? this.#storage.transaction(() => this.#removeLabel(name)) : this.#removeLabel(name);
1751 }
1753 #removeLabel(name: string): boolean {
1755 if (!gone) return false;
1756 this.#labels.delete(name);
1757 for (const label of [...this.#labels.values()]) {
1758 if (label.base === name) this.#labels.set(label.name, Object.freeze({ ...label, base: gone.head }));
1759 }
1760 return true;
1761 }
1763 // JSON -------------------------------------------------------------------
1765 toJSON(): GraphJSON {
1766 return { format: GRAPH_FORMAT, version: 1, atoms: this.#atoms, labels: this.labels() };
1767 }
1769 /** Load a saved graph. Every atom is re-validated as it is added. */
1770 static fromJSON(data: unknown): Graph {
1771 const bad = (why: string): never => {
1772 throw new EngineError("bad-json", why);
1773 };
1774 if (typeof data !== "object" || data === null) bad("graph JSON must be an object");
1775 const obj = data as Partial<GraphJSON>;
1776 if (obj.format !== GRAPH_FORMAT) bad(`format must be ${GRAPH_FORMAT}`);
1777 if (obj.version !== 1) bad(`unsupported version ${String(obj.version)}`);
1778 if (!Array.isArray(obj.atoms) || !Array.isArray(obj.labels)) bad("atoms and labels must be arrays");
1779 const graph = new Graph();
1780 for (const atom of obj.atoms!) graph.add(atom);
1781 // Labels may name each other as bases, in any order and any shape.
1782 const names = new Set<string>();
1783 for (const label of obj.labels!) {
1784 const name: unknown = (label as Partial<Label> | null)?.name;
1785 if (typeof name !== "string") return bad("every label needs a name");
1786 if (names.has(name)) bad(`label ${name} appears twice`);
1787 names.add(name);
1788 }
1789 for (const label of obj.labels!) {
1790 try {
1791 graph.#putLabel(label, (name) => names.has(name));
1792 } catch (err) {
1793 if (err instanceof EngineError) bad(err.message);
1794 throw err;
1795 }
1796 }
1797 return graph;
1798 }
1800 #seq(id: AtomId): number {
1801 return typeof id === "string" ? seqOf(id) : -1;
1802 }
1803}
1805function validateShape(atom: Atom): void {
1806 const bad = (why: string): never => {
1807 throw new EngineError("bad-atom", `atom ${String((atom as { id?: unknown }).id)}: ${why}`);
1808 };
1809 if (typeof atom !== "object" || atom === null) bad("not an object");
1810 if (typeof atom.id !== "string" || !Number.isInteger(atom.seq)) bad("needs id and seq");
1811 if (typeof atom.author !== "string" || typeof atom.message !== "string") bad("needs author and message");
1812 if (typeof atom.time !== "number" || !Number.isFinite(atom.time)) bad("time must be a finite number");
1813 const lists = ["inserts", "deletes", "writes", "reads", "holds", "needs", "resolves", "reasons", "deps"] as const;
1814 for (const name of lists) if (!Array.isArray(atom[name])) bad(`${name} must be an array`);
1815 for (const run of atom.inserts as readonly InsertRun[]) {
1816 if (typeof run.file !== "string" || run.file === "" || run.file.includes("\n")) bad("a run needs a file path");
1817 if (typeof run.parent !== "string") bad("a run needs a parent");
1818 if (!Array.isArray(run.lines) || run.lines.length === 0) bad("a run needs at least one line");
1819 for (const text of run.lines) {
1820 if (typeof text !== "string" || text.includes("\n") || text.includes("\r"))
1821 bad("run lines must be strings without line breaks");
1822 }
1823 }
1824 if (atom.attrs !== undefined) {
1825 if (!Array.isArray(atom.attrs)) bad("attrs must be an array");
1826 for (const a of atom.attrs) {
1827 if (typeof a?.file !== "string" || a.file === "" || a.file.includes("\n") || !ATTR_NAMES.includes(a.name))
1828 bad("an attr needs a file and a name");
1829 if (a.value !== null && typeof a.value !== "string") bad("an attr value is a string or null");
1830 if (!atom.writes.includes(attrKey(a.file, a.name))) bad(`sets ${a.name} of ${a.file} without writing its key`);
1831 }
1832 }
1833 if (atom.moves !== undefined) {
1834 if (!Array.isArray(atom.moves) || atom.moves.length === 0) bad("moves must be a non-empty array");
1835 for (const m of atom.moves) {
1836 if (typeof m?.line !== "string" || typeof m.parent !== "string") bad("a move needs a line and a parent");
1837 }
1838 }
1839 for (const name of ["deletes", "writes", "reads", "holds", "needs", "resolves", "deps"] as const) {
1840 for (const x of atom[name]) if (typeof x !== "string") bad(`${name} must hold strings`);
1841 }
1842 for (const r of atom.reasons as readonly Reason[]) {
1843 if (typeof r.to !== "string" || typeof r.text !== "string" || !REASON_KINDS.includes(r.kind)) {
1844 bad("a reason needs to, kind (together, because-of or supersedes) and text");
1845 }
1846 }
1847}
1849/**
1850 * A frozen copy of an atom. An empty list is one shared frozen list, and atom
1851 * ids and authors are the graph's own strings (`canon`, `author`), so each is
1852 * kept once however often it's named (#46).
1853 */
1854function freezeAtom(
1855 atom: Atom,
1856 canon: (id: AtomId) => AtomId,
1857 author: (name: string) => string,
1858 text?: (start: number, length: number) => readonly string[],
1859 lists?: () => AtomLists,
1860): Atom {
1861 const list = <T>(xs: readonly T[], f?: (x: T) => T): readonly T[] =>
1862 xs.length === 0 ? EMPTY : Object.freeze(f ? xs.map(f) : [...xs]);
1863 // With text kept elsewhere (#46), a run's lines are read when asked for.
1864 let k = 0;
1865 const run = (r: InsertRun): InsertRun => {
1866 if (!text) return Object.freeze({ file: r.file, parent: r.parent, lines: Object.freeze([...r.lines]) });
1867 const start = k;
1868 const length = r.lines.length;
1869 k += length;
1870 return Object.freeze(new LazyRun(r.file, r.parent, text, start, length));
1871 };
1872 const copy: Atom = {
1873 id: atom.id,
1874 seq: atom.seq,
1875 author: author(atom.author),
1876 message: atom.message,
1877 time: atom.time,
1878 inserts: Object.freeze(atom.inserts.map(run)),
1879 ...(lists
1880 ? {}
1881 : { deletes: list(atom.deletes), writes: list(atom.writes), reads: list(atom.reads), holds: list(atom.holds) }),
1882 needs: list(atom.needs, canon),
1883 resolves: list(atom.resolves, canon),
1884 reasons: list(atom.reasons, (r) => Object.freeze({ to: canon(r.to), kind: r.kind, text: r.text })),
1885 deps: list(atom.deps, canon),
1886 ...(atom.attrs && atom.attrs.length > 0
1887 ? { attrs: Object.freeze(atom.attrs.map((a) => Object.freeze({ file: a.file, name: a.name, value: a.value }))) }
1888 : {}),
1889 ...(atom.moves
1890 ? { moves: Object.freeze(atom.moves.map((m) => Object.freeze({ line: m.line, parent: m.parent }))) }
1891 : {}),
1892 } as Atom;
1893 return Object.freeze(lists ? (new ListedAtom(copy, lists) as unknown as Atom) : copy);
1894}