Skip to content

abso-core

Public

abso is version control for agents: the client, the engine and a server you can run on your own Cloudflare account.

Check passed
MCP
blame on this site's /mcp
CLI
abso blame src/engine/graph.ts --version 238 --json
JSON
/christopher/abso-core/blame/src/engine/graph.ts?version=238&format=json
1,905 linesFirst import 52% · codex-capacity-chair 38% · capacity 10%Last change capacity in version 238,

1,905 lines from 29 changes in 28 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.
4
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";
init0Start the project7import {
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";
init0Start the project22import {
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 {
init0Start the project33 ATTR_NAMES,
34 type Atom,
35 type AtomId,
36 EngineError,
37 type InsertRun,
38 type Key,
39 type Label,
40 type LineId,
41 type NodeId,
42 REASON_KINDS,
43 type Reason,
44} from "./types.ts";
46/**
47 * Where a line was written and what it says. Its text never changes. A move
48 * can give it another parent in a set, even in another file: `view.parentOf`
49 * and `view.fileOf` say where it is in a set.
50 */
51export interface LineInfo {
52 readonly id: LineId;
53 readonly atom: AtomId;
54 readonly k: number;
55 /** The file it was written in. */
56 readonly file: string;
57 /** The node it was written after. */
58 readonly parent: NodeId;
59 readonly text: string;
62/** One relocation of a line, by the atom that made it; `k` is its place in that atom's moves. */
63export interface RelocationInfo {
64 readonly atom: AtomId;
65 readonly line: LineId;
66 readonly parent: NodeId;
67 readonly k: number;
70/** A `together` reason seen from one end: `other` is the atom at the far end. */
71export interface TogetherLink {
72 readonly other: AtomId;
73 readonly text: string;
74 /** The atom that carries the reason. */
75 readonly from: AtomId;
78export const GRAPH_FORMAT = "ai-first-vcs.graph";
80/** The saved form of a graph. Atoms are in seq order. */
81export interface GraphJSON {
82 readonly format: typeof GRAPH_FORMAT;
83 readonly version: 1;
84 readonly atoms: readonly Atom[];
85 readonly labels: readonly Label[];
88/**
89 * An index entry that holds a lone value as itself, and a list only once there
90 * are two (#46): most keys name one atom, and a list for each costs more than
91 * the value.
92 */
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 {
init0Start the project94 const had = map.get(key);
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]);
init0Start the project100}
102function listOf<V>(had: V | V[] | undefined): readonly V[] {
103 return had === undefined ? EMPTY : Array.isArray(had) ? had : [had];
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 {
init0Start the project107 const list = map.get(key);
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]);
init0Start the project112}
114const EMPTY: readonly never[] = Object.freeze([]);
116/**
117 * A run whose lines are read when asked for (#46, text on disk): a few fields
118 * and a shared reader, where an object with its own accessor cost about 400
119 * bytes a run.
120 */
121class LazyRun implements InsertRun {
122 readonly file: string;
123 readonly parent: NodeId;
124 readonly #text: (start: number, length: number) => readonly string[];
125 readonly #start: number;
126 readonly #length: number;
127 constructor(
128 file: string,
129 parent: NodeId,
130 text: (start: number, length: number) => readonly string[],
131 start: number,
132 length: number,
133 ) {
134 this.file = file;
135 this.parent = parent;
136 this.#text = text;
137 this.#start = start;
138 this.#length = length;
139 }
140 get lines(): readonly string[] {
141 return this.#text(this.#start, this.#length);
142 }
143 toJSON(): InsertRun {
144 return { file: this.file, parent: this.parent, lines: this.lines };
145 }
148/** Characters of atoms' text a graph that keeps text elsewhere holds at most (#46): about 8 MB. */
149const TEXT_CACHE = 4_000_000;
150/** How many list items (deletes and keys) are kept read back (#46): publishes and syncs meet few atoms, but one reformat's atom can hold 100,000. */
151const LIST_CACHE = 50_000;
153/** An atom's deletes and claim keys: kept in the log rather than in memory when the graph has a `lists` reader (#46). */
154export interface AtomLists {
155 readonly deletes: readonly LineId[];
156 readonly writes: readonly Key[];
157 readonly reads: readonly Key[];
158 readonly holds: readonly Key[];
161function listItems(l: AtomLists): number {
162 return l.deletes.length + l.writes.length + l.reads.length + l.holds.length;
165function frozenList<T>(xs: readonly T[]): readonly T[] {
166 return xs.length === 0 ? (EMPTY as readonly T[]) : Object.freeze([...xs]);
169/**
170 * An atom whose deletes, writes, reads and holds are read back through `read` (#46). The getters live on the
171 * prototype, so each atom keeps one reader and a fixed shape, not four closures in a dictionary-mode object.
172 */
173class ListedAtom {
174 readonly #read: () => AtomLists;
175 constructor(fields: object, read: () => AtomLists) {
176 Object.assign(this, fields);
177 this.#read = read;
178 }
179 get deletes(): readonly LineId[] {
180 return this.#read().deletes;
181 }
182 get writes(): readonly Key[] {
183 return this.#read().writes;
184 }
185 get reads(): readonly Key[] {
186 return this.#read().reads;
187 }
188 get holds(): readonly Key[] {
189 return this.#read().holds;
190 }
191 toJSON(): object {
192 return { ...this, ...this.#read() };
193 }
196/** A growable array of 32-bit integers: a line's fields cost 4 bytes each, not an object and its strings (#46). */
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;
204class Ints implements NumberIndex {
init0Start the project205 #buf: Int32Array | Uint8Array;
206 /** bytes: values 0-255 only, one byte each. */
207 constructor(bytes = false) {
208 this.#buf = bytes ? new Uint8Array(1024) : new Int32Array(1024);
209 }
210 length = 0;
211 push(n: number): void {
212 if (this.length === this.#buf.length) {
213 const bigger =
214 this.#buf instanceof Uint8Array ? new Uint8Array(this.#buf.length * 2) : new Int32Array(this.#buf.length * 2);
215 bigger.set(this.#buf);
216 this.#buf = bigger;
217 }
218 this.#buf[this.length++] = n;
219 }
220 at(i: number): number {
221 return this.#buf[i]!;
222 }
223 set(i: number, n: number): void {
224 this.#buf[i] = n;
225 }
228/**
229 * A line id's place in the graph's line arrays, or -1: "a<seq>.<k>" is line
230 * `base[seq] + k`. Hand-parsed, as seqOf is, with the same rules: no leading
231 * zeros, and k within the lines its atom wrote.
232 */
233function parseLineId(id: string): { seq: number; k: number } | undefined {
234 if (typeof id !== "string") return undefined;
235 const n = id.length;
236 if (n < 4 || id.charCodeAt(0) !== 97 /* a */) return undefined;
237 let i = 1;
238 let seq = 0;
239 const seqStart = i;
240 for (; i < n; i++) {
241 const c = id.charCodeAt(i);
242 if (c === 46 /* . */) break;
243 if (c < 48 || c > 57) return undefined;
244 seq = seq * 10 + (c - 48);
245 }
246 if (i === seqStart || i >= n - 1 || i - seqStart > 15 || (i - seqStart > 1 && id.charCodeAt(seqStart) === 48))
247 return undefined;
248 const kStart = ++i;
249 let k = 0;
250 for (; i < n; i++) {
251 const c = id.charCodeAt(i);
252 if (c < 48 || c > 57) return undefined;
253 k = k * 10 + (c - 48);
254 }
255 if (i - kStart > 15 || (i - kStart > 1 && id.charCodeAt(kStart) === 48)) return undefined;
256 return { seq, k };
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;
init0Start the project271export class Graph {
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;
init0Start the project274 #atoms: Atom[] = [];
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;
init0Start the project309 /**
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 } = {},
init0Start the project324 ) {
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;
init0Start the project328 if (options.texts) {
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 }
init0Start the project620 }
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.
init0Start the project629
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;
init0Start the project808 #movers: 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.Compare809 /** A stored graph's movers, read once (abso Capacity): every view walks them, a row each. */
810 #moverList: AtomId[] | undefined;
init0Start the project811 #atomFiles: (readonly string[])[] = [];
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();
init0Start the project815 /** Each author's name kept once (#46). */
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 }
capacity238Collisions: deleted lines found by number, and the move index skips graphs that gained nothing (disk-first 2; abso Capacity). Collisions on website took 20.7 s cold with one opened writer (replay 0.4 s), and 46 s on typescript-rs (replay 5 s). - touchedFiles finds each deleted line's file by its number where the view can (fileOfNumber). A draft deleting a big file has thousands; making each one's id only to look its number up again was most of the time. - Graph.accepted counts the atoms a graph object has taken in, in memory. The move index (MoveSkeleton) is brought up to date on every lookup of a line's file. It now reads the movers list only when that count has changed: checking the stored list's length and last mover each time cost 3.3 s of collisions on website. A rolled-back add still counts, which only makes it look again. On website adopted fresh, cold: collisions 20.7 s to 9.6 s. On typescript-rs: 46 s to 11.7 s. Both match replay, and all 27 typescript-rs answers match. Still slow: reading every draft atom's write keys, a row per key once there are more than 256 (75,000 rows on website). Named tests: every engine test (288 of 288), every worker/project test (341 of 341); tsc and biome clean.Compare823 /**
824 * How many atoms this graph object has accepted since it was made (abso Capacity): in memory, so a cache over the
825 * graph can tell nothing was added without reading storage. A rolled-back add still counts, which only makes such a
826 * cache look again.
827 */
828 get accepted(): number {
829 return this.#accepted;
830 }
831 #accepted = 0;
init0Start the project833 /** The id the next accepted atom must have. */
834 nextId(): AtomId {
835 return atomId(this.#atoms.length);
836 }
838 has(id: AtomId): boolean {
839 const seq = this.#seq(id);
840 return seq >= 0 && seq < this.#atoms.length;
841 }
843 atom(id: AtomId): Atom {
844 const seq = this.#seq(id);
845 const atom = seq >= 0 ? this.#atoms[seq] : undefined;
846 if (!atom) throw new EngineError("unknown-atom", `no atom ${id}`);
847 return atom;
848 }
850 /** All atoms in seq order. */
851 atoms(): readonly Atom[] {
852 return this.#atoms;
853 }
855 /** lamport(a) = 1 + max lamport of its deps; 0 for an atom with no deps (such as a0). */
856 lamport(id: AtomId): number {
codex-capacity-chair148Read graph identities and metadata without decoding atom payloadsCompare857 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.Compare858 return this.#lamportAt(this.#seq(id));
init0Start the project859 }
861 /** Compare by priority (lamport, then seq). Negative when a comes first (is lower). */
862 comparePriority(a: AtomId, b: AtomId): number {
863 return this.lamport(a) - this.lamport(b) || this.#seq(a) - this.#seq(b);
864 }
866 line(id: LineId): LineInfo | undefined {
867 const n = this.#lineN(id);
868 if (n < 0) return undefined;
869 const seq = this.#lineAtom.at(n);
870 return {
871 id,
codex-capacity-chair148Read graph identities and metadata without decoding atom payloadsCompare872 atom: this.idOfSeq(seq),
init0Start the project873 k: n - this.#lineBase[seq]!,
874 file: this.#paths[this.#lineFile.at(n)]!,
875 parent: this.#nodeName(this.#lineParent.at(n)),
876 text: this.#text(n),
877 };
878 }
880 /** A line's text, or undefined for an unknown line: line(id).text without making the record. */
881 lineText(id: LineId): string | undefined {
882 const n = this.#lineN(id);
883 return n < 0 ? undefined : this.#text(n);
884 }
886 /** The atom that wrote a line, or undefined: line(id).atom without making the record. */
887 lineAtom(id: LineId): AtomId | undefined {
888 const n = this.#lineN(id);
codex-capacity-chair148Read graph identities and metadata without decoding atom payloadsCompare889 return n < 0 ? undefined : this.idOfSeq(this.#lineAtom.at(n));
init0Start the project890 }
892 /** The file a line was written in, or undefined: line(id).file without making the record. */
893 lineFile(id: LineId): string | undefined {
894 const n = this.#lineN(id);
895 return n < 0 ? undefined : this.#paths[this.#lineFile.at(n)];
896 }
898 /** The node a line was written after, or undefined: line(id).parent without making the record. */
899 lineParent(id: LineId): NodeId | undefined {
900 const n = this.#lineN(id);
901 return n < 0 ? undefined : this.#nodeName(this.#lineParent.at(n));
902 }
904 // By number, for views (#46) ------------------------------------------------------
905 // 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
906 // keeps them, so a view can lay files out as arrays of numbers. For the engine's own use.
908 /** A line id's n, or -1 for an unknown line. */
909 lineN(id: LineId): number {
910 return this.#lineN(id);
911 }
913 /** A line's id from its n. */
914 lineIdOf(n: number): LineId {
915 return this.#lineName(n);
916 }
918 /** The lines an atom deletes, from the graph's own packed copy (#46): never a read of the log. */
919 deletedLines(id: AtomId): readonly LineId[] {
codex-capacity-chair162Add reviewed disk-first history and indexed graph storage for core issue 16; retain runtime activation gateCompare920 const seq = this.#seq(id);
921 const count = this.#storage?.read("atom-delete-counts", String(seq));
922 if (count !== undefined) {
923 const out: LineId[] = [];
924 for (const n of storedLists<number>(this.#storage!, "atom-deletes").values(String(seq)))
925 out.push(this.#lineName(n));
926 if (out.length !== count) throw Error("incomplete atom deletion index");
927 return out;
928 }
init0Start the project929 const ns = this.#atomDeletes[this.#seq(id)];
930 if (!ns) return EMPTY;
931 const out: LineId[] = new Array(ns.length);
932 for (let i = 0; i < ns.length; i++) out[i] = this.#lineName(ns[i]!);
933 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 changesCompare934 }
936 /** The numbers of the lines an atom deletes, from the graph's packed copy: no lookup per line id. */
937 *deletedNumbers(id: AtomId): IterableIterator<number> {
938 const seq = this.#seq(id);
939 if (this.#storage?.read("atom-delete-counts", String(seq)) !== undefined) {
940 yield* storedLists<number>(this.#storage!, "atom-deletes").values(String(seq));
941 return;
942 }
943 yield* this.#atomDeletes[seq] ?? EMPTY_NUMBERS;
init0Start the project944 }
946 /** How many lines an atom deletes, without reading its lists. */
947 deleteCount(id: AtomId): number {
codex-capacity-chair162Add reviewed disk-first history and indexed graph storage for core issue 16; retain runtime activation gateCompare948 const seq = this.#seq(id);
949 const count = this.#storage?.read("atom-delete-counts", String(seq));
950 if (count !== undefined) {
951 if (!Number.isSafeInteger(count) || (count as number) < 0) throw Error("invalid atom deletion count");
952 return count as number;
953 }
954 return this.#atomDeletes[seq]?.length ?? 0;
init0Start the project955 }
957 textOf(n: number): string {
958 return this.#text(n);
959 }
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.Compare961 /** Historical text in bounded chunks, without decoding a whole stored line. */
962 *textChunks(n: number): IterableIterator<string> {
963 if (!this.#storage) {
964 const text = this.#text(n);
965 for (let offset = 0; offset < text.length; offset += StoredText.chunkCharacters)
966 yield text.slice(offset, offset + StoredText.chunkCharacters);
967 return;
968 }
969 if (!Number.isSafeInteger(n) || n < 0 || n >= this.#lineText!.length) throw Error("invalid line number");
970 const value = this.#storage.read("line-text", String(n));
971 if (typeof value === "string") {
972 yield value;
973 return;
974 }
975 const reference = value as { format?: number; text?: string } | undefined;
976 if (reference?.format !== 1 || typeof reference.text !== "string") throw Error("invalid long line reference");
977 yield* new StoredText(this.#storage, "atom-text:long").chunks(reference.text);
978 }
init0Start the project980 /** The seq of the atom that wrote line n. */
981 writerSeqOf(n: number): number {
982 return this.#lineAtom.at(n);
983 }
985 /** Line n's k: its place among its atom's lines. */
986 kOf(n: number): number {
987 return n - this.#lineBase[this.#lineAtom.at(n)]!;
988 }
990 /** The atom id with this seq, as the graph keeps it. */
991 idOfSeq(seq: number): AtomId {
codex-capacity-chair148Read graph identities and metadata without decoding atom payloadsCompare992 if (!Number.isSafeInteger(seq) || seq < 0 || seq >= this.#atoms.length)
993 throw new EngineError("unknown-atom", `no atom at sequence ${seq}`);
994 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.Compare995 }
997 #lamportAt(seq: number): number {
998 return this.#lamportPages ? this.#lamportPages.at(seq) : this.#lamport[seq]!;
init0Start the project999 }
1001 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.Compare1002 return this.#lamportAt(seq);
init0Start the project1003 }
1005 /** The file line n was written in. */
1006 writtenIn(n: number): string {
1007 return this.#paths[this.#lineFile.at(n)]!;
1010 /** The code of the node line n was written after. */
1011 parentCodeOf(n: number): number {
1012 return this.#lineParent.at(n);
1015 /** A node's code, or undefined for a node the graph doesn't know (a start node of a file nothing was written in). */
1016 codeOf(node: NodeId): number | undefined {
1017 return this.#nodeCode(node);
1020 /** The node a code names. */
1021 nodeOf(code: number): NodeId {
1022 return this.#nodeName(code);
1025 /** The start node's code for a path, or undefined when nothing was ever written in it. */
1026 startCodeOf(path: string): number | undefined {
1027 const p = this.#pathIndex.get(path);
1028 return p === undefined ? undefined : -1 - p;
1031 /** The lines (their n) written right after a node, as childrenOf, into `out`. */
codex-capacity-chair130Stream paged child history into layout filteringCompare1032
init0Start the project1033 childrenN(code: number, out: number[]): void {
codex-capacity-chair130Stream paged child history into layout filteringCompare1034 for (const n of this.eachChildN(code)) out.push(n);
1036 *eachChildN(code: number): IterableIterator<number> {
init0Start the project1037 if (
1038 code >= 0 &&
1039 code + 1 < this.#lineTotal &&
1040 this.#lineAtom.at(code + 1) === this.#lineAtom.at(code) &&
1041 this.#lineParent.at(code + 1) === code
codex-capacity-chair130Stream paged child history into layout filteringCompare1043 yield code + 1;
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.Compare1044 if (this.#runStartPages) {
1045 // The paged child counts say a line has no other children without a row read per line (abso Capacity).
1046 if (code >= 0 && this.#childCounts && this.#childCounts.at(code, this.#lineTotal) === 0) return;
1047 yield* this.#runStartPages.values(String(code));
1048 } else yield* listOf(this.#runStarts.get(code));
init0Start the project1049 }
codex-capacity-chair131Bound persisted no-move layout with ordered successor traversalCompare1051 get hasOrderedChildren(): boolean {
1052 return this.#storage !== undefined;
codex-capacity-chair132Bound persistent relocation projection memory with rollback-only scratchCompare1053 }
1054 /** Synchronous derived work against one graph identity. Scratch never commits. */
1055 withProjectionScratch<T>(operation: (scratch: GraphStateStorage) => T): T {
1056 if (!this.#storage) throw new Error("projection scratch requires persistent graph storage");
1057 const size = this.size;
1058 const lines = this.lineCount;
1059 return withProjectionScratch(
1060 this.#storage,
1061 () => {
1062 if (this.size !== size || this.lineCount !== lines) throw new Error("projection graph identity changed");
1063 },
1064 operation,
1065 );
codex-capacity-chair131Bound persisted no-move layout with ordered successor traversalCompare1066 }
1067 #childPriority(n: number): string {
1068 const seq = this.writerSeqOf(n);
1069 return orderedChildKey({
1070 n,
1071 replaces: this.replacesN(n) ? 1 : 0,
1072 lamport: this.lamportOfSeq(seq),
1073 seq,
1074 k: this.kOf(n),
1075 });
1077 /** Persistent layout order with a strict successor cursor; moves are separate. */
1078 *orderedChildrenN(code: number, after?: number): IterableIterator<number> {
1079 if (!this.#storage) throw new Error("ordered children require indexed storage");
1080 const index = new OrderedIndex(this.#storage, "ordered-children", String(code));
codex-capacity-chair137Page explicit child counts with bounded corruption checksCompare1081 if (this.#storage.read("ordered-children", "format") !== 2)
codex-capacity-chair131Bound persisted no-move layout with ordered successor traversalCompare1082 throw new Error("ordered children require fresh adoption");
codex-capacity-chair137Page explicit child counts with bounded corruption checksCompare1083 const count = code >= 0 ? this.#childCounts!.at(code, this.#lineTotal) : index.size;
1084 if ((code < 0 || count > 0) && (count !== index.size || count !== this.#runStartPages!.length(String(code))))
1085 throw new Error("ordered child index count mismatch");
codex-capacity-chair131Bound persisted no-move layout with ordered successor traversalCompare1086 let implicit: number | undefined;
1087 if (
1088 code >= 0 &&
1089 code + 1 < this.#lineTotal &&
1090 this.#lineAtom.at(code + 1) === this.#lineAtom.at(code) &&
1091 this.#lineParent.at(code + 1) === code
1093 implicit = code + 1;
codex-capacity-chair135Skip priority decoding for implicit-only child traversalCompare1094 // Most historical run lines have no explicit child. With zero or one
1095 // child, traversal needs no priority decoding or radix lookup. Keep the
1096 // format/count checks above even on this path.
1097 if (count === 0 && (after === undefined || after === implicit)) {
1098 if (implicit !== undefined && after !== implicit) yield implicit;
1099 return;
codex-capacity-chair131Bound persisted no-move layout with ordered successor traversalCompare1101 const cursor = after === undefined ? undefined : this.#childPriority(after);
1102 if (implicit !== undefined && cursor !== undefined && this.#childPriority(implicit) <= cursor) implicit = undefined;
1103 for (const n of index.values(cursor)) {
1104 if (implicit !== undefined && this.#childPriority(implicit) < this.#childPriority(n)) {
1105 yield implicit;
1106 implicit = undefined;
1108 yield n;
1110 if (implicit !== undefined) yield implicit;
init0Start the project1113 replacesN(n: number): boolean {
1114 return this.#replacing.at(n) === 1;
1117 /** The seqs of every atom that deletes line n (none: an empty list, shared). */
1118 deleterSeqsOf(n: number): readonly number[] {
codex-capacity-chair128Page deletion history and short-circuit current visibilityCompare1119 return [...this.eachDeleterSeqOf(n)];
1121 *eachDeleterSeqOf(n: number): IterableIterator<number> {
init0Start the project1122 const first = this.#deleter.at(n);
codex-capacity-chair128Page deletion history and short-circuit current visibilityCompare1123 if (first < 0) return;
1124 yield first;
1125 if (this.#moreDeleterPages) yield* this.#moreDeleterPages.values(String(n));
1126 else yield* this.#moreDeleters.get(n) ?? EMPTY;
init0Start the project1127 }
1129 /** Every relocation that puts a line right after the node with this code. */
1130 relocatedToCode(code: number): readonly RelocationInfo[] {
codex-capacity-chair127Page persistent relocation indexes and stream projection readsCompare1131 if (this.#relocatedToCodePages) return [...this.eachRelocatedToCode(code)];
init0Start the project1132 return this.#relocatedToCode.get(code) ?? EMPTY;
codex-capacity-chair127Page persistent relocation indexes and stream projection readsCompare1133 }
1134 *eachRelocatedToCode(code: number): IterableIterator<RelocationInfo> {
1135 if (this.#relocatedToCodePages) yield* this.#relocatedToCodePages.values(String(code));
1136 else yield* this.#relocatedToCode.get(code) ?? EMPTY;
init0Start the project1137 }
1139 /** How many lines every atom together has written. */
1140 get lineCount(): number {
1141 return this.#lineTotal;
1144 /** A line id's n, or -1 when no accepted atom wrote it. */
1145 #lineN(id: LineId): number {
1146 const p = parseLineId(id);
1147 if (!p || p.seq >= this.#atoms.length) return -1;
1148 const base = this.#lineBase[p.seq]!;
1149 const end = p.seq + 1 < this.#lineBase.length ? this.#lineBase[p.seq + 1]! : this.#lineTotal;
1150 return p.k < end - base ? base + p.k : -1;
1153 /** A line's id from its n. */
1154 #lineName(n: number): LineId {
1155 const seq = this.#lineAtom.at(n);
codex-capacity-chair148Read graph identities and metadata without decoding atom payloadsCompare1156 return `${this.idOfSeq(seq)}.${n - this.#lineBase[seq]!}`;
init0Start the project1157 }
1159 /** A node's code: a line's n, or -1 - a path's index for a start node; undefined when unknown. */
1160 #nodeCode(node: NodeId): number | undefined {
1161 if (isStartNode(node)) {
1162 const p = this.#pathIndex.get(node.slice(1));
1163 return p === undefined ? undefined : -1 - p;
1165 const n = this.#lineN(node);
1166 return n < 0 ? undefined : n;
1169 #nodeName(code: number): NodeId {
1170 return code >= 0 ? this.#lineName(code) : startNode(this.#paths[-1 - code]!);
1173 #pathOf(file: string): number {
1174 let p = this.#pathIndex.get(file);
1175 if (p === undefined) {
1176 p = this.#paths.push(file) - 1;
1177 this.#pathIndex.set(file, p);
1179 return p;
1182 /** The line ids an atom inserted, in k order. */
1183 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.Compare1184 return [...this.eachInsertedLine(id)];
1186 /** Inserted identities without decoding or allocating the atom's text. */
1187 *eachInsertedLine(id: AtomId): IterableIterator<LineId> {
1188 const seq = this.atom(id).seq;
init0Start the project1189 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.Compare1190 for (let k = 0; k < count; k++) yield lineId(id, k);
init0Start the project1191 }
1193 /** Every atom that deletes this line (across the whole graph). */
1194 deletersOf(line: LineId): readonly AtomId[] {
1195 const n = this.#lineN(line);
1196 if (n < 0) return EMPTY;
codex-capacity-chair148Read graph identities and metadata without decoding atom payloadsCompare1197 return [...this.eachDeleterSeqOf(n)].map((seq) => this.idOfSeq(seq));
init0Start the project1198 }
1200 writersOf(key: Key): readonly AtomId[] {
codex-capacity-chair120Page persistent claim indexes and stream dependency queriesCompare1201 return [...this.eachWriterOf(key)];
init0Start the project1202 }
codex-capacity-chair120Page persistent claim indexes and stream dependency queriesCompare1203 *eachWriterOf(key: Key): IterableIterator<AtomId> {
1204 const code = this.#code(key);
1205 if (this.#writersPages) yield* this.#writersPages.values(JSON.stringify([typeof code, code]));
1206 else yield* listOf(this.#writers.get(code));
init0Start the project1208
1209 /** Atoms whose implicit reads include the key. */
1210 readersOf(key: Key): readonly AtomId[] {
codex-capacity-chair120Page persistent claim indexes and stream dependency queriesCompare1211 return [...this.eachReaderOf(key)];
1213 *eachReaderOf(key: Key): IterableIterator<AtomId> {
1214 const code = this.#code(key);
1215 if (this.#readersPages) yield* this.#readersPages.values(JSON.stringify([typeof code, code]));
1216 else yield* listOf(this.#readers.get(code));
init0Start the project1217 }
1219 /** Atoms whose explicit holds include the key. */
1220 holdersOf(key: Key): readonly AtomId[] {
codex-capacity-chair120Page persistent claim indexes and stream dependency queriesCompare1221 return [...this.eachHolderOf(key)];
1223 *eachHolderOf(key: Key): IterableIterator<AtomId> {
1224 const code = this.#code(key);
1225 if (this.#holdersPages) yield* this.#holdersPages.values(JSON.stringify([typeof code, code]));
1226 else yield* listOf(this.#holders.get(code));
init0Start the project1227 }
1229 /** Every atom that inserts or deletes a line of the file, in seq order. */
1230 atomsIn(file: string): readonly AtomId[] {
codex-capacity-chair119Page per-file atom indexes and stream current-view attribute scansCompare1231 if (this.#fileAtomPages) return [...this.#fileAtomPages.values(file)];
init0Start the project1232 return this.#fileAtoms.get(file) ?? EMPTY;
codex-capacity-chair119Page per-file atom indexes and stream current-view attribute scansCompare1233 }
1234 *eachAtomIn(file: string): IterableIterator<AtomId> {
1235 if (this.#fileAtomPages) yield* this.#fileAtomPages.values(file);
1236 else yield* this.#fileAtoms.get(file) ?? EMPTY;
init0Start the project1237 }
codex-capacity-chair119Page per-file atom indexes and stream current-view attribute scansCompare1238 hasAtomsIn(file: string): boolean {
1239 return this.#fileAtomPages ? this.#fileAtomPages.length(file) > 0 : this.#fileAtoms.has(file);
init0Start the project1241
codex-capacity-chair118Avoid retaining deleted historical paths in indexed current viewsCompare1242 /** Unique historical file paths, streamed without collecting their names. */
1243 *knownFiles(): IterableIterator<string> {
codex-capacity-chair119Page per-file atom indexes and stream current-view attribute scansCompare1244 yield* this.#fileAtomPages ? this.#fileAtomPages.keys() : this.#fileAtoms.keys();
codex-capacity-chair118Avoid retaining deleted historical paths in indexed current viewsCompare1245 }
init0Start the project1247 /**
1248 * The files an atom inserts, deletes or moves lines in, or sets attributes
1249 * of, sorted. For lines, the file each was written in (or, for a move to a
1250 * start node, that file): a set's moves can have taken them elsewhere.
1251 */
1252 filesOf(id: AtomId): readonly string[] {
codex-capacity-chair148Read graph identities and metadata without decoding atom payloadsCompare1253 if (!this.has(id)) throw new EngineError("unknown-atom", `no atom ${id}`);
init0Start the project1254 return this.#atomFiles[this.#seq(id)]!;
1257 /** Lines written right after a node (not counting moves), in seq order. */
codex-capacity-chair130Stream paged child history into layout filteringCompare1258
init0Start the project1259 childrenOf(node: NodeId): LineId[] {
1260 const code = this.#nodeCode(node);
codex-capacity-chair130Stream paged child history into layout filteringCompare1261 return code === undefined ? [] : [...this.eachChildN(code)].map((n) => this.#lineName(n));
init0Start the project1262 }
1264 /** Whether a line starts a run whose atom deleted the line it hangs off. */
1265 replaces(line: LineId): boolean {
1266 const n = this.#lineN(line);
1267 return n >= 0 && this.#replacing.at(n) === 1;
1270 /** Every relocation of a line, in seq order. */
1271 relocationsOf(line: LineId): readonly RelocationInfo[] {
codex-capacity-chair127Page persistent relocation indexes and stream projection readsCompare1272 if (this.#relocationPages) return [...this.eachRelocationOf(line)];
init0Start the project1273 return this.#relocations.get(line) ?? EMPTY;
codex-capacity-chair127Page persistent relocation indexes and stream projection readsCompare1275 *eachRelocationOf(line: LineId): IterableIterator<RelocationInfo> {
1276 if (this.#relocationPages) yield* this.#relocationPages.values(line);
1277 else yield* this.#relocations.get(line) ?? EMPTY;
init0Start the project1279
1280 /** Every relocation that puts a line right after this node, in seq order. */
1281 relocatedTo(node: NodeId): readonly RelocationInfo[] {
codex-capacity-chair127Page persistent relocation indexes and stream projection readsCompare1282 if (this.#relocatedToPages) return [...this.#relocatedToPages.values(node)];
init0Start the project1283 return this.#relocatedTo.get(node) ?? EMPTY;
1286 /** Atoms that move lines, in seq order. */
1287 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.Compare1288 if (!this.#storage) return this.#movers;
1289 // Checked against the stored list's length and last mover, so a rolled-back add can't leave one behind.
1290 const length = this.#movers.length;
1291 const list = this.#moverList;
1292 if (list && list.length === length && (length === 0 || list[length - 1] === this.#movers[length - 1])) return list;
1293 this.#moverList = [...this.#movers];
1294 return this.#moverList;
init0Start the project1295 }
1297 /** Atoms that list this one directly in their deps. */
1298 dependentsOf(id: AtomId): readonly AtomId[] {
codex-capacity-chair122Page dependency and resolver indexes with streamed intersectionCompare1299 return [...this.eachDependentOf(id)];
init0Start the project1300 }
codex-capacity-chair122Page dependency and resolver indexes with streamed intersectionCompare1301 *eachDependentOf(id: AtomId): IterableIterator<AtomId> {
1302 if (this.#dependentsPages) yield* this.#dependentsPages.values(id);
1303 else yield* listOf(this.#dependents.get(id));
init0Start the project1305
1306 /** Atoms whose `resolves` names this one. */
1307 resolversOf(id: AtomId): readonly AtomId[] {
codex-capacity-chair122Page dependency and resolver indexes with streamed intersectionCompare1308 return [...this.eachResolverOf(id)];
1310 *eachResolverOf(id: AtomId): IterableIterator<AtomId> {
1311 if (this.#resolversPages) yield* this.#resolversPages.values(id);
1312 else yield* listOf(this.#resolvers.get(id));
init0Start the project1313 }
1315 /** `together` reasons touching this atom, in either direction. */
1316 togetherLinks(id: AtomId): readonly TogetherLink[] {
codex-capacity-chair129Page together relationship history for bounded traversalCompare1317 return [...this.eachTogetherLink(id)];
init0Start the project1318 }
codex-capacity-chair129Page together relationship history for bounded traversalCompare1319 *eachTogetherLink(id: AtomId): IterableIterator<TogetherLink> {
1320 if (this.#togetherPages) yield* this.#togetherPages.values(id);
1321 else yield* this.#together.get(id) ?? EMPTY;
init0Start the project1323
1324 /**
1325 * The atom plus everything it depends on, transitively. Computed on demand
1326 * and not cached: a cached set per atom costs memory quadratic in the length
1327 * of a dependency chain. Use `dependsOn` to ask about one pair.
1328 */
1329 closure(id: AtomId): Set<AtomId> {
1330 return this.closureOf([id]);
1333 /** The atoms plus everything they depend on, transitively. */
1334 closureOf(ids: Iterable<AtomId>): Set<AtomId> {
1335 const out = new Set<AtomId>();
1336 const stack: AtomId[] = [];
1337 for (const id of ids) {
1338 this.atom(id);
1339 if (!out.has(id)) {
1340 out.add(id);
1341 stack.push(id);
1344 while (stack.length > 0) {
1345 for (const d of this.atom(stack.pop()!).deps) {
1346 if (!out.has(d)) {
1347 out.add(d);
1348 stack.push(d);
1352 return out;
1355 /** Whether `b` is in the closure of `a` (an atom is in its own closure). */
1356 dependsOn(a: AtomId, b: AtomId): boolean {
1357 const atom = this.atom(a);
1358 this.atom(b);
1359 return a === b || this.#reaches(atom.deps, b);
1362 /**
1363 * Whether `target` is reachable along deps from any of `from` (themselves
1364 * included). A dependency always has a lower lamport than its dependent, so
1365 * the search never descends below the target's lamport.
1366 */
1367 #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.Compare1368 const floor = this.#lamportAt(this.#seq(target));
codex-capacity-chair139Bound persistent dependency reachability with rollback scratchCompare1369 if (this.#storage) {
1370 return this.withProjectionScratch((scratch) => {
1371 let length = 0;
1372 const push = (id: AtomId): void => {
1373 if (scratch.read("seen", id)) return;
1374 scratch.write("seen", id, true);
1375 scratch.write("stack", String(length++), id);
1376 };
codex-capacity-chair162Add reviewed disk-first history and indexed graph storage for core issue 16; retain runtime activation gateCompare1377 for (const id of from) {
1378 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.Compare1379 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 gateCompare1380 }
codex-capacity-chair139Bound persistent dependency reachability with rollback scratchCompare1381 while (length > 0) {
1382 const key = String(--length);
1383 const current = scratch.read("stack", key) as AtomId;
1384 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.Compare1385 if (this.#lamportAt(this.#seq(current)) <= floor) continue;
codex-capacity-chair139Bound persistent dependency reachability with rollback scratchCompare1386 for (const dependency of this.atom(current).deps) {
1387 if (dependency === target) return true;
1388 push(dependency);
1391 return false;
1392 });
init0Start the project1394 const seen = new Set<AtomId>();
1395 const stack = [...from];
1396 while (stack.length > 0) {
1397 const cur = stack.pop()!;
1398 if (cur === target) return true;
1399 if (seen.has(cur)) continue;
1400 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.Compare1401 if (this.#lamportAt(this.#seq(cur)) <= floor) continue;
init0Start the project1402 for (const d of this.atom(cur).deps) if (!seen.has(d)) stack.push(d);
1404 return false;
1407 /**
1408 * Accept an atom into the graph. It must carry the next id and seq, and
1409 * everything it touches must come from atoms in its dependency closure.
1410 * The atom is frozen. Adding to the graph does not add it to any set.
1411 */
1412 add(atom: Atom): void {
codex-capacity-chair149Index atom metadata for resumable projection adoptionCompare1413 if (this.#storage)
1414 this.#storage.transaction(() => {
1415 this.#add(atom);
1416 const result: unknown = this.#indexAcceptedAtom?.(atom, this.filesOf(atom.id), this.#storage!);
1417 if (result && typeof result === "object" && "then" in result)
1418 throw Error("accepted atom indexing must be synchronous");
1419 });
codex-capacity-chair109Add opt-in persistent writer state, checked reopen and bounded adoptionCompare1420 else this.#add(atom);
codex-capacity-chair162Add reviewed disk-first history and indexed graph storage for core issue 16; retain runtime activation gateCompare1423 #validateAcceptedAtom(atom: Atom, scratch?: GraphStateStorage): void {
1424 const membership = <T extends string>(name: string): { has(key: T): boolean; add(key: T): unknown } => {
1425 if (!scratch) return new Set<T>();
1426 return { has: (key) => scratch.read(name, key) === true, add: (key) => scratch.write(name, key, true) };
1427 };
init0Start the project1428 validateShape(atom);
1429 const seq = this.#atoms.length;
1430 const bad = (why: string): never => {
1431 throw new EngineError("bad-atom", `atom ${atom.id}: ${why}`);
1432 };
1433 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 gateCompare1435 const deps = membership<AtomId>("deps");
init0Start the project1436 for (const d of atom.deps) {
1437 if (!this.has(d)) bad(`dependency ${d} is not in the graph`);
1438 if (deps.has(d)) bad(`dependency ${d} listed twice`);
1439 deps.add(d);
codex-capacity-chair162Add reviewed disk-first history and indexed graph storage for core issue 16; retain runtime activation gateCompare1441 for (const list of [atom.needs, atom.resolves])
1442 for (const d of list) {
1443 if (!deps.has(d)) bad(`${d} is in needs/resolves but not in deps`);
init0Start the project1445 for (const r of atom.reasons) if (!this.has(r.to)) bad(`reason points at unknown atom ${r.to}`);
1447 // Everything it touches must come from its closure. Derived deps name the
1448 // 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 gateCompare1449 const memoryBelow = scratch ? undefined : new Map<AtomId, boolean>();
1450 const below = {
1451 get: (key: AtomId) => (scratch ? (scratch.read("below", key) as boolean | undefined) : memoryBelow!.get(key)),
1452 set: (key: AtomId, value: boolean) => {
1453 if (scratch) scratch.write("below", key, value);
1454 else memoryBelow!.set(key, value);
1455 },
1456 };
init0Start the project1457 const inClosure = (writer: AtomId): boolean => {
1458 let hit = below.get(writer);
1459 if (hit === undefined) {
codex-capacity-chair162Add reviewed disk-first history and indexed graph storage for core issue 16; retain runtime activation gateCompare1460 hit = deps.has(writer) || this.#reaches(atom.deps, writer);
init0Start the project1461 below.set(writer, hit);
1463 return hit;
1464 };
1465 const checkLine = (line: LineId, what: string): void => {
1466 const writer = this.lineAtom(line);
1467 if (writer === undefined) return bad(`${what} names unknown line ${line}`);
1468 if (!inClosure(writer)) bad(`${what} names line ${line} but ${writer} is not in its closure`);
1469 };
1471 for (const run of atom.inserts) {
1472 if (isStartNode(run.parent)) {
1473 if (run.parent !== startNode(run.file)) bad(`run in ${run.file} starts at ${run.parent}`);
1474 } else {
1475 // The parent may have been moved into run.file, so its own file can differ.
1476 checkLine(run.parent, "an insert");
codex-capacity-chair162Add reviewed disk-first history and indexed graph storage for core issue 16; retain runtime activation gateCompare1479 const writes = membership<Key>("writes");
1480 for (const key of atom.writes) writes.add(key);
1481 const moved = membership<LineId>("moved");
init0Start the project1482 for (const m of atom.moves ?? []) {
1483 checkLine(m.line, "a move");
1484 if (!isStartNode(m.parent)) checkLine(m.parent, "a move");
1485 if (m.line === m.parent) bad(`moves ${m.line} after itself`);
1486 if (moved.has(m.line)) bad(`moves ${m.line} twice`);
1487 moved.add(m.line);
codex-capacity-chair162Add reviewed disk-first history and indexed graph storage for core issue 16; retain runtime activation gateCompare1488 if (!writes.has(posKey(m.line)) || !writes.has(gapKey(m.parent))) {
init0Start the project1489 bad(`moves ${m.line} without writing ${posKey(m.line)} and ${gapKey(m.parent)}`);
codex-capacity-chair162Add reviewed disk-first history and indexed graph storage for core issue 16; retain runtime activation gateCompare1492 const deleted = membership<LineId>("deleted");
init0Start the project1493 for (const line of atom.deletes) {
1494 checkLine(line, "a delete");
1495 if (deleted.has(line)) bad(`deletes ${line} twice`);
1496 deleted.add(line);
codex-capacity-chair162Add reviewed disk-first history and indexed graph storage for core issue 16; retain runtime activation gateCompare1498 for (const line of atom.deletes)
1499 if (!writes.has(lineKey(line))) bad(`deletes ${line} without writing ${lineKey(line)}`);
1500 for (const list of [atom.writes, atom.reads, atom.holds])
1501 for (const key of list) {
1502 const parsed = parseKey(key);
1503 if (parsed.kind === "line") checkLine(parsed.node, `key ${key}`);
1504 else if ((parsed.kind === "gap" || parsed.kind === "pos") && !isStartNode(parsed.node))
1505 checkLine(parsed.node, `key ${key}`);
codex-capacity-chair109Add opt-in persistent writer state, checked reopen and bounded adoptionCompare1509 #add(atom: Atom): void {
codex-capacity-chair137Page explicit child counts with bounded corruption checksCompare1510 if (this.#storage && this.#storage.read("ordered-children", "format") !== 2) {
codex-capacity-chair131Bound persisted no-move layout with ordered successor traversalCompare1511 if (this.#atoms.length !== 0) throw new Error("ordered children require fresh adoption");
codex-capacity-chair137Page explicit child counts with bounded corruption checksCompare1512 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.Compare1513 }
1514 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.Compare1515 this.#storage.write("file-lines:meta", "format", 2);
1516 this.#formatKnown = 2;
init0Start the project1517 }
codex-capacity-chair162Add reviewed disk-first history and indexed graph storage for core issue 16; retain runtime activation gateCompare1518
1519 if (this.#storage) this.withProjectionScratch((scratch) => this.#validateAcceptedAtom(atom, scratch));
1520 else this.#validateAcceptedAtom(atom);
1521 const seq = this.#atoms.length;
1522 const deps = atom.deps;
1523 const deleted = this.#storage ? undefined : new Set(atom.deletes);
1524 const writes = this.#storage ? atom.writes : new Set(atom.writes);
init0Start the project1525
1526 // Accept.
codex-capacity-chair162Add reviewed disk-first history and indexed graph storage for core issue 16; retain runtime activation gateCompare1527 // Persistent storage copies the accepted atom; a second frozen copy only duplicates its lists.
1528 const frozen = this.#storage
1529 ? atom
1530 : freezeAtom(
codex-capacity-chair109Add opt-in persistent writer state, checked reopen and bounded adoptionCompare1531 atom,
codex-capacity-chair162Add reviewed disk-first history and indexed graph storage for core issue 16; retain runtime activation gateCompare1532 (id) => this.idOfSeq(seqOf(id)),
1533 (author) => {
1534 if (this.#storage) return author;
1535 let a = this.#authors.get(author);
1536 if (a === undefined) this.#authors.set(author, (a = author));
1537 return a;
1538 },
1539 this.#texts ? this.#reader(seq) : undefined,
1540 this.#lists ? this.#listReader(seq) : undefined,
1541 );
codex-capacity-chair109Add opt-in persistent writer state, checked reopen and bounded adoptionCompare1542 this.#atoms.push(this.#storage ? atom : frozen);
capacity238Collisions: deleted lines found by number, and the move index skips graphs that gained nothing (disk-first 2; abso Capacity). Collisions on website took 20.7 s cold with one opened writer (replay 0.4 s), and 46 s on typescript-rs (replay 5 s). - touchedFiles finds each deleted line's file by its number where the view can (fileOfNumber). A draft deleting a big file has thousands; making each one's id only to look its number up again was most of the time. - Graph.accepted counts the atoms a graph object has taken in, in memory. The move index (MoveSkeleton) is brought up to date on every lookup of a line's file. It now reads the movers list only when that count has changed: checking the stored list's length and last mover each time cost 3.3 s of collisions on website. A rolled-back add still counts, which only makes it look again. On website adopted fresh, cold: collisions 20.7 s to 9.6 s. On typescript-rs: 46 s to 11.7 s. Both match replay, and all 27 typescript-rs answers match. Still slow: reading every draft atom's write keys, a row per key once there are more than 256 (75,000 rows on website). Named tests: every engine test (288 of 288), every worker/project test (341 of 341); tsc and biome clean.Compare1543 this.#accepted++;
init0Start the project1544 let lam = 0;
1545 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.Compare1546 if (this.#lamportPages) this.#lamportPages.push(lam);
1547 else this.#lamport.push(lam);
init0Start the project1548
1549 // The run starts' parents and the deleted lines, as codes, before this atom's own lines exist.
1550 // 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 gateCompare1551 const deletes = (line: LineId | NodeId): boolean => {
1552 if (isStartNode(line)) return false;
1553 if (deleted) return deleted.has(line);
1554 const n = this.#lineN(line);
1555 return this.#deleter.at(n) === seq || this.#moreDeleterPages!.last(String(n)) === seq;
1556 };
1557 const deletedN = this.#storage ? undefined : atom.deletes.map((line) => this.#lineN(line));
1558 this.#atomDeletes.push(deletedN?.length ? Int32Array.from(deletedN) : undefined);
1559 if (this.#storage) {
1560 const pages = storedLists<number>(this.#storage, "atom-deletes");
1561 for (const line of atom.deletes) pages.append(String(seq), this.#lineN(line));
1562 this.#storage.write("atom-delete-counts", String(seq), atom.deletes.length);
1564 const deletedNumbers = function* (graph: Graph) {
1565 if (deletedN) yield* deletedN;
1566 else for (const line of atom.deletes) yield graph.#lineN(line);
1567 };
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.Compare1568 const packedDeletes = new Map<number, PackedDelete[]>();
codex-capacity-chair162Add reviewed disk-first history and indexed graph storage for core issue 16; retain runtime activation gateCompare1569 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.Compare1570 if (this.#packed) {
1571 const file = this.#lineFile.at(n);
1572 const list = packedDeletes.get(file);
1573 if (list) list.push([n, seq]);
1574 else packedDeletes.set(file, [[n, seq]]);
init0Start the project1576 if (this.#deleter.at(n) < 0) this.#deleter.set(n, seq);
codex-capacity-chair128Page deletion history and short-circuit current visibilityCompare1577 else if (this.#moreDeleterPages) this.#moreDeleterPages.append(String(n), seq);
init0Start the project1578 else pushIndex(this.#moreDeleters, n, seq);
codex-capacity-chair120Page persistent claim indexes and stream dependency queriesCompare1579 }
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.Compare1580 for (const [file, list] of packedDeletes) this.#fileDeletes!.appendAll(String(file), list);
init0Start the project1581 this.#lineBase.push(this.#lineTotal);
1582 for (const run of atom.inserts) {
1583 const file = this.#pathOf(run.file);
1584 let parent = isStartNode(run.parent) ? -1 - file : this.#lineN(run.parent);
1585 const first = this.#lineTotal;
codex-capacity-chair137Page explicit child counts with bounded corruption checksCompare1586 if (parent >= 0) this.#childCounts?.increment(parent, first);
codex-capacity-chair131Bound persisted no-move layout with ordered successor traversalCompare1587 if (this.#storage)
1588 new OrderedIndex(this.#storage, "ordered-children", String(parent)).insert(
1589 orderedChildKey({
1590 n: first,
codex-capacity-chair162Add reviewed disk-first history and indexed graph storage for core issue 16; retain runtime activation gateCompare1591 replaces: deletes(run.parent) ? 1 : 0,
codex-capacity-chair131Bound persisted no-move layout with ordered successor traversalCompare1592 lamport: lam,
1593 seq,
1594 k: first - this.#lineBase[seq]!,
1595 }),
1596 first,
1597 );
codex-capacity-chair130Stream paged child history into layout filteringCompare1599 if (this.#runStartPages) this.#runStartPages.append(String(parent), first);
1600 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.Compare1601 const replacesParent = deletes(run.parent) ? 1 : 0;
1602 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.Compare1603 if (this.#crossings && parent >= 0) {
1604 const from = this.#lineFile.at(parent);
1605 if (from !== file) this.#fileCrossings!.append(String(from), [parent, file]);
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.Compare1607 const base = this.#lineBase[seq]!;
1608 this.#fileLines!.appendAll(
1609 String(file),
1610 run.lines.map(
1611 (_, i): PackedLine => [
1612 first + i,
1613 i === 0 ? parent : first + i - 1,
1614 seq,
1615 first + i - base,
1616 i === 0 ? replacesParent : 0,
1617 ],
1618 ),
1619 );
1620 this.#fileTexts!.appendAll(
1621 String(file),
1622 run.lines.map((text) => (typeof text === "string" && text.length <= PACKED_TEXT ? text : null)),
1623 );
init0Start the project1625 for (let i = 0; i < run.lines.length; i++) {
codex-capacity-chair109Add opt-in persistent writer state, checked reopen and bounded adoptionCompare1626 const n = this.#lineTotal;
codex-capacity-chair137Page explicit child counts with bounded corruption checksCompare1627 this.#childCounts?.append(n);
init0Start the project1628 this.#lineAtom.push(seq);
1629 this.#lineFile.push(file);
1630 this.#lineParent.push(parent);
1631 this.#lineText?.push(run.lines[i]!);
1632 this.#deleter.push(-1);
codex-capacity-chair162Add reviewed disk-first history and indexed graph storage for core issue 16; retain runtime activation gateCompare1633 this.#replacing.push(i === 0 && deletes(run.parent) ? 1 : 0);
init0Start the project1634 parent = n;
1637 (frozen.moves ?? []).forEach((m, i) => {
1638 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 readsCompare1639 if (this.#relocationPages) this.#relocationPages.append(m.line, info);
1640 else pushIndex(this.#relocations, m.line, info);
1641 if (this.#relocatedToPages) this.#relocatedToPages.append(m.parent, info);
1642 else pushIndex(this.#relocatedTo, m.parent, info);
1643 const parentCode = isStartNode(m.parent) ? -1 - this.#pathOf(m.parent.slice(1)) : this.#lineN(m.parent);
1644 if (this.#relocatedToCodePages) this.#relocatedToCodePages.append(String(parentCode), info);
1645 else pushIndex(this.#relocatedToCode, parentCode, info);
init0Start the project1646 });
1647 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.Compare1648 if (this.#packed)
1649 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 gateCompare1650 for (const key of writes) {
codex-capacity-chair120Page persistent claim indexes and stream dependency queriesCompare1651 const code = this.#code(key);
codex-capacity-chair162Add reviewed disk-first history and indexed graph storage for core issue 16; retain runtime activation gateCompare1652 if (this.#writersPages) {
1653 const key = JSON.stringify([typeof code, code]);
1654 if (this.#writersPages.last(key) !== frozen.id) this.#writersPages.append(key, frozen.id);
1655 } else pushOne(this.#writers, code, frozen.id);
codex-capacity-chair120Page persistent claim indexes and stream dependency queriesCompare1656 }
codex-capacity-chair162Add reviewed disk-first history and indexed graph storage for core issue 16; retain runtime activation gateCompare1657 for (const key of this.#storage ? atom.reads : new Set(atom.reads)) {
codex-capacity-chair120Page persistent claim indexes and stream dependency queriesCompare1658 const code = this.#code(key);
codex-capacity-chair162Add reviewed disk-first history and indexed graph storage for core issue 16; retain runtime activation gateCompare1659 if (this.#readersPages) {
1660 const key = JSON.stringify([typeof code, code]);
1661 if (this.#readersPages.last(key) !== frozen.id) this.#readersPages.append(key, frozen.id);
1662 } else pushOne(this.#readers, code, frozen.id);
codex-capacity-chair120Page persistent claim indexes and stream dependency queriesCompare1663 }
codex-capacity-chair162Add reviewed disk-first history and indexed graph storage for core issue 16; retain runtime activation gateCompare1664 for (const key of this.#storage ? atom.holds : new Set(atom.holds)) {
codex-capacity-chair120Page persistent claim indexes and stream dependency queriesCompare1665 const code = this.#code(key);
codex-capacity-chair162Add reviewed disk-first history and indexed graph storage for core issue 16; retain runtime activation gateCompare1666 if (this.#holdersPages) {
1667 const key = JSON.stringify([typeof code, code]);
1668 if (this.#holdersPages.last(key) !== frozen.id) this.#holdersPages.append(key, frozen.id);
1669 } else pushOne(this.#holders, code, frozen.id);
codex-capacity-chair122Page dependency and resolver indexes with streamed intersectionCompare1670 }
1671 for (const d of deps) {
1672 if (this.#dependentsPages) this.#dependentsPages.append(d, frozen.id);
1673 else pushOne(this.#dependents, d, frozen.id);
codex-capacity-chair162Add reviewed disk-first history and indexed graph storage for core issue 16; retain runtime activation gateCompare1675 for (const r of this.#storage ? frozen.resolves : new Set(frozen.resolves)) {
1676 if (this.#resolversPages) {
1677 if (this.#resolversPages.last(r) !== frozen.id) this.#resolversPages.append(r, frozen.id);
1678 } else pushOne(this.#resolvers, r, frozen.id);
init0Start the project1679 }
1680 const files = new Set<string>();
1681 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 gateCompare1682 for (const n of deletedNumbers(this)) files.add(this.#paths[this.#lineFile.at(n)]!);
init0Start the project1683 for (const a of frozen.attrs ?? []) files.add(a.file);
1684 for (const m of frozen.moves ?? []) {
1685 files.add(this.lineFile(m.line)!);
1686 files.add(isStartNode(m.parent) ? m.parent.slice(1) : this.lineFile(m.parent)!);
1688 this.#atomFiles.push(Object.freeze([...files].sort()));
codex-capacity-chair119Page per-file atom indexes and stream current-view attribute scansCompare1689 for (const file of files) {
1690 if (this.#fileAtomPages) this.#fileAtomPages.append(file, frozen.id);
1691 else pushIndex(this.#fileAtoms, file, frozen.id);
init0Start the project1693 for (const r of frozen.reasons) {
1694 if (r.kind !== "together" || r.to === frozen.id) continue;
codex-capacity-chair129Page together relationship history for bounded traversalCompare1695
1696 const forward = { other: r.to, text: r.text, from: frozen.id };
1697 const reverse = { other: frozen.id, text: r.text, from: frozen.id };
1698 if (this.#togetherPages) {
1699 this.#togetherPages.append(frozen.id, forward);
1700 this.#togetherPages.append(r.to, reverse);
1701 } else {
1702 pushIndex(this.#together, frozen.id, forward);
1703 pushIndex(this.#together, r.to, reverse);
init0Start the project1705 }
1708 // Labels -----------------------------------------------------------------
1710 /**
1711 * Add or replace a label. Label names may not look like atom ids. A base is
1712 * resolved to its head only when it is used, never followed further, so
1713 * bases may name each other in any shape.
1714 */
1715 setLabel(label: Label): void {
1716 this.#putLabel(label, (name) => this.#labels.has(name));
1719 #putLabel(label: Label, isLabel: (name: string) => boolean): void {
1720 const bad = (why: string): never => {
1721 throw new EngineError("bad-label", `label ${JSON.stringify(label?.name)}: ${why}`);
1722 };
1723 if (typeof label !== "object" || label === null) bad("not an object");
1724 if (typeof label.name !== "string" || label.name === "") bad("needs a name");
1725 if (isAtomId(label.name)) bad("a label name may not look like an atom id");
1726 if (!this.has(label.head)) bad(`head ${label.head} is not in the graph`);
1727 if (
1728 label.base !== undefined &&
1729 !(typeof label.base === "string" && (isLabel(label.base) || this.has(label.base)))
1730 ) {
1731 bad(`base ${label.base} is neither a label nor an atom`);
1733 if (label.base === label.name) bad("a label cannot be its own base");
1734 if (typeof label.title !== "string" || typeof label.message !== "string") bad("needs a title and message");
1735 if (label.follows !== undefined && !Array.isArray(label.follows)) bad("follows must be a list of label names");
1736 const copy: Label = {
1737 name: label.name,
1738 head: label.head,
1739 ...(label.base !== undefined ? { base: label.base } : {}),
1740 title: label.title,
1741 message: label.message,
1742 ...(label.follows !== undefined ? { follows: Object.freeze([...label.follows]) } : {}),
1743 };
1744 this.#labels.set(label.name, Object.freeze(copy));
1747 label(name: string): Label | undefined {
1748 return this.#labels.get(name);
1751 /** Labels sorted by name. */
1752 labels(): Label[] {
1753 return [...this.#labels.values()].sort((a, b) => (a.name < b.name ? -1 : a.name > b.name ? 1 : 0));
1756 /**
1757 * Remove a label. Labels that used it as their base get its head atom as
1758 * their base instead, so their contents don't change.
1759 */
1760 removeLabel(name: string): boolean {
codex-capacity-chair109Add opt-in persistent writer state, checked reopen and bounded adoptionCompare1761 return this.#storage ? this.#storage.transaction(() => this.#removeLabel(name)) : this.#removeLabel(name);
1764 #removeLabel(name: string): boolean {
init0Start the project1765 const gone = this.#labels.get(name);
1766 if (!gone) return false;
1767 this.#labels.delete(name);
1768 for (const label of [...this.#labels.values()]) {
1769 if (label.base === name) this.#labels.set(label.name, Object.freeze({ ...label, base: gone.head }));
1771 return true;
1774 // JSON -------------------------------------------------------------------
1776 toJSON(): GraphJSON {
1777 return { format: GRAPH_FORMAT, version: 1, atoms: this.#atoms, labels: this.labels() };
1780 /** Load a saved graph. Every atom is re-validated as it is added. */
1781 static fromJSON(data: unknown): Graph {
1782 const bad = (why: string): never => {
1783 throw new EngineError("bad-json", why);
1784 };
1785 if (typeof data !== "object" || data === null) bad("graph JSON must be an object");
1786 const obj = data as Partial<GraphJSON>;
1787 if (obj.format !== GRAPH_FORMAT) bad(`format must be ${GRAPH_FORMAT}`);
1788 if (obj.version !== 1) bad(`unsupported version ${String(obj.version)}`);
1789 if (!Array.isArray(obj.atoms) || !Array.isArray(obj.labels)) bad("atoms and labels must be arrays");
1790 const graph = new Graph();
1791 for (const atom of obj.atoms!) graph.add(atom);
1792 // Labels may name each other as bases, in any order and any shape.
1793 const names = new Set<string>();
1794 for (const label of obj.labels!) {
1795 const name: unknown = (label as Partial<Label> | null)?.name;
1796 if (typeof name !== "string") return bad("every label needs a name");
1797 if (names.has(name)) bad(`label ${name} appears twice`);
1798 names.add(name);
1800 for (const label of obj.labels!) {
1801 try {
1802 graph.#putLabel(label, (name) => names.has(name));
1803 } catch (err) {
1804 if (err instanceof EngineError) bad(err.message);
1805 throw err;
1808 return graph;
1811 #seq(id: AtomId): number {
1812 return typeof id === "string" ? seqOf(id) : -1;
1816function validateShape(atom: Atom): void {
1817 const bad = (why: string): never => {
1818 throw new EngineError("bad-atom", `atom ${String((atom as { id?: unknown }).id)}: ${why}`);
1819 };
1820 if (typeof atom !== "object" || atom === null) bad("not an object");
1821 if (typeof atom.id !== "string" || !Number.isInteger(atom.seq)) bad("needs id and seq");
1822 if (typeof atom.author !== "string" || typeof atom.message !== "string") bad("needs author and message");
1823 if (typeof atom.time !== "number" || !Number.isFinite(atom.time)) bad("time must be a finite number");
1824 const lists = ["inserts", "deletes", "writes", "reads", "holds", "needs", "resolves", "reasons", "deps"] as const;
1825 for (const name of lists) if (!Array.isArray(atom[name])) bad(`${name} must be an array`);
1826 for (const run of atom.inserts as readonly InsertRun[]) {
1827 if (typeof run.file !== "string" || run.file === "" || run.file.includes("\n")) bad("a run needs a file path");
1828 if (typeof run.parent !== "string") bad("a run needs a parent");
1829 if (!Array.isArray(run.lines) || run.lines.length === 0) bad("a run needs at least one line");
1830 for (const text of run.lines) {
1831 if (typeof text !== "string" || text.includes("\n") || text.includes("\r"))
1832 bad("run lines must be strings without line breaks");
1835 if (atom.attrs !== undefined) {
1836 if (!Array.isArray(atom.attrs)) bad("attrs must be an array");
1837 for (const a of atom.attrs) {
1838 if (typeof a?.file !== "string" || a.file === "" || a.file.includes("\n") || !ATTR_NAMES.includes(a.name))
1839 bad("an attr needs a file and a name");
1840 if (a.value !== null && typeof a.value !== "string") bad("an attr value is a string or null");
1841 if (!atom.writes.includes(attrKey(a.file, a.name))) bad(`sets ${a.name} of ${a.file} without writing its key`);
1844 if (atom.moves !== undefined) {
1845 if (!Array.isArray(atom.moves) || atom.moves.length === 0) bad("moves must be a non-empty array");
1846 for (const m of atom.moves) {
1847 if (typeof m?.line !== "string" || typeof m.parent !== "string") bad("a move needs a line and a parent");
1850 for (const name of ["deletes", "writes", "reads", "holds", "needs", "resolves", "deps"] as const) {
1851 for (const x of atom[name]) if (typeof x !== "string") bad(`${name} must hold strings`);
1853 for (const r of atom.reasons as readonly Reason[]) {
1854 if (typeof r.to !== "string" || typeof r.text !== "string" || !REASON_KINDS.includes(r.kind)) {
1855 bad("a reason needs to, kind (together, because-of or supersedes) and text");
1860/**
1861 * A frozen copy of an atom. An empty list is one shared frozen list, and atom
1862 * ids and authors are the graph's own strings (`canon`, `author`), so each is
1863 * kept once however often it's named (#46).
1864 */
1865function freezeAtom(
1866 atom: Atom,
1867 canon: (id: AtomId) => AtomId,
1868 author: (name: string) => string,
1869 text?: (start: number, length: number) => readonly string[],
1870 lists?: () => AtomLists,
1871): Atom {
1872 const list = <T>(xs: readonly T[], f?: (x: T) => T): readonly T[] =>
1873 xs.length === 0 ? EMPTY : Object.freeze(f ? xs.map(f) : [...xs]);
1874 // With text kept elsewhere (#46), a run's lines are read when asked for.
1875 let k = 0;
1876 const run = (r: InsertRun): InsertRun => {
1877 if (!text) return Object.freeze({ file: r.file, parent: r.parent, lines: Object.freeze([...r.lines]) });
1878 const start = k;
1879 const length = r.lines.length;
1880 k += length;
1881 return Object.freeze(new LazyRun(r.file, r.parent, text, start, length));
1882 };
1883 const copy: Atom = {
1884 id: atom.id,
1885 seq: atom.seq,
1886 author: author(atom.author),
1887 message: atom.message,
1888 time: atom.time,
1889 inserts: Object.freeze(atom.inserts.map(run)),
1890 ...(lists
1891 ? {}
1892 : { deletes: list(atom.deletes), writes: list(atom.writes), reads: list(atom.reads), holds: list(atom.holds) }),
1893 needs: list(atom.needs, canon),
1894 resolves: list(atom.resolves, canon),
1895 reasons: list(atom.reasons, (r) => Object.freeze({ to: canon(r.to), kind: r.kind, text: r.text })),
1896 deps: list(atom.deps, canon),
1897 ...(atom.attrs && atom.attrs.length > 0
1898 ? { attrs: Object.freeze(atom.attrs.map((a) => Object.freeze({ file: a.file, name: a.name, value: a.value }))) }
1899 : {}),
1900 ...(atom.moves
1901 ? { moves: Object.freeze(atom.moves.map((m) => Object.freeze({ line: m.line, parent: m.parent }))) }
1902 : {}),
1903 } as Atom;
1904 return Object.freeze(lists ? (new ListedAtom(copy, lists) as unknown as Atom) : copy);