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 261 --json
JSON
/christopher/abso-core/blame/src/engine/graph.ts?version=261&format=json
1,970 linesFirst import 50% · codex-capacity-chair 37% · capacity 14%Last change capacity in version 242,

1,970 lines from 32 changes in 31 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,
capacity239An atom's long lists kept 256 values to a row (list format 2; disk-first 2; abso Capacity). Collisions reads every key each draft atom writes. An atom's lists over 256 values were stored a row per value (readonlyStoredArray). On website, collisions read 75,000 of those rows (a draft deleting a big file has thousands of keys). - New atoms store such lists 256 values to a row (writePagedArray) and mark it listFormat 2. readonlyPagedArray reads them a page at a time, in order or by index. - An atom stored before keeps listFormat 1 and its row per value, and reads as before. The format is per atom record, so old and new atoms sit side by side. Only atoms stored from this version on, or a fresh adoption, get pages. On website adopted fresh, cold, one opened writer: collisions 9.6 s to 4.7 s (79,000 reads to 3,900), matching replay (0.4 s). Adoption took 87 s instead of 119 s. Tests: graph-atom-list-pages (new: a new atom's list is paged and reads whole; an atom rewritten as list format 1 reads whole). graph-atom-list-rollback now injects its failure on the list's second page. Every engine test (290 of 290), every worker/project test (341 of 341); tsc and biome clean.Compare24 readonlyPagedArray,
codex-capacity-chair162Add reviewed disk-first history and indexed graph storage for core issue 16; retain runtime activation gateCompare25 readonlyStoredArray,
codex-capacity-chair119Page per-file atom indexes and stream current-view attribute scansCompare26 type StateMap,
27 storedArray,
28 storedLists,
29 storedMap,
30 storedNumbers,
capacity239An atom's long lists kept 256 values to a row (list format 2; disk-first 2; abso Capacity). Collisions reads every key each draft atom writes. An atom's lists over 256 values were stored a row per value (readonlyStoredArray). On website, collisions read 75,000 of those rows (a draft deleting a big file has thousands of keys). - New atoms store such lists 256 values to a row (writePagedArray) and mark it listFormat 2. readonlyPagedArray reads them a page at a time, in order or by index. - An atom stored before keeps listFormat 1 and its row per value, and reads as before. The format is per atom record, so old and new atoms sit side by side. Only atoms stored from this version on, or a fresh adoption, get pages. On website adopted fresh, cold, one opened writer: collisions 9.6 s to 4.7 s (79,000 reads to 3,900), matching replay (0.4 s). Adoption took 87 s instead of 119 s. Tests: graph-atom-list-pages (new: a new atom's list is paged and reads whole; an atom rewritten as list format 1 reads whole). graph-atom-list-rollback now injects its failure on the list's second page. Every engine test (290 of 290), every worker/project test (341 of 341); tsc and biome clean.Compare31 writePagedArray,
codex-capacity-chair119Page per-file atom indexes and stream current-view attribute scansCompare32} from "./state-source.ts";
codex-capacity-chair162Add reviewed disk-first history and indexed graph storage for core issue 16; retain runtime activation gateCompare33import { StoredText } from "./stored-text.ts";
codex-capacity-chair119Page per-file atom indexes and stream current-view attribute scansCompare34import {
init0Start the project35 ATTR_NAMES,
36 type Atom,
37 type AtomId,
38 EngineError,
39 type InsertRun,
40 type Key,
41 type Label,
42 type LineId,
43 type NodeId,
44 REASON_KINDS,
45 type Reason,
46} from "./types.ts";
48/**
49 * Where a line was written and what it says. Its text never changes. A move
50 * can give it another parent in a set, even in another file: `view.parentOf`
51 * and `view.fileOf` say where it is in a set.
52 */
53export interface LineInfo {
54 readonly id: LineId;
55 readonly atom: AtomId;
56 readonly k: number;
57 /** The file it was written in. */
58 readonly file: string;
59 /** The node it was written after. */
60 readonly parent: NodeId;
61 readonly text: string;
64/** One relocation of a line, by the atom that made it; `k` is its place in that atom's moves. */
65export interface RelocationInfo {
66 readonly atom: AtomId;
67 readonly line: LineId;
68 readonly parent: NodeId;
69 readonly k: number;
72/** A `together` reason seen from one end: `other` is the atom at the far end. */
73export interface TogetherLink {
74 readonly other: AtomId;
75 readonly text: string;
76 /** The atom that carries the reason. */
77 readonly from: AtomId;
80export const GRAPH_FORMAT = "ai-first-vcs.graph";
82/** The saved form of a graph. Atoms are in seq order. */
83export interface GraphJSON {
84 readonly format: typeof GRAPH_FORMAT;
85 readonly version: 1;
86 readonly atoms: readonly Atom[];
87 readonly labels: readonly Label[];
90/**
91 * An index entry that holds a lone value as itself, and a list only once there
92 * are two (#46): most keys name one atom, and a list for each costs more than
93 * the value.
94 */
codex-capacity-chair109Add opt-in persistent writer state, checked reopen and bounded adoptionCompare95function pushOne<K, V>(map: StateMap<K, V | V[]>, key: K, value: V): void {
init0Start the project96 const had = map.get(key);
97 if (had === undefined) map.set(key, value);
codex-capacity-chair109Add opt-in persistent writer state, checked reopen and bounded adoptionCompare98 else if (Array.isArray(had)) {
99 had.push(value);
100 map.set(key, had);
101 } else map.set(key, [had, value]);
init0Start the project102}
104function listOf<V>(had: V | V[] | undefined): readonly V[] {
105 return had === undefined ? EMPTY : Array.isArray(had) ? had : [had];
codex-capacity-chair109Add opt-in persistent writer state, checked reopen and bounded adoptionCompare108function pushIndex<K, V>(map: StateMap<K, V[]>, key: K, value: V): void {
init0Start the project109 const list = map.get(key);
codex-capacity-chair109Add opt-in persistent writer state, checked reopen and bounded adoptionCompare110 if (list) {
111 list.push(value);
112 map.set(key, list);
113 } else map.set(key, [value]);
init0Start the project114}
116const EMPTY: readonly never[] = Object.freeze([]);
118/**
119 * A run whose lines are read when asked for (#46, text on disk): a few fields
120 * and a shared reader, where an object with its own accessor cost about 400
121 * bytes a run.
122 */
123class LazyRun implements InsertRun {
124 readonly file: string;
125 readonly parent: NodeId;
126 readonly #text: (start: number, length: number) => readonly string[];
127 readonly #start: number;
128 readonly #length: number;
129 constructor(
130 file: string,
131 parent: NodeId,
132 text: (start: number, length: number) => readonly string[],
133 start: number,
134 length: number,
135 ) {
136 this.file = file;
137 this.parent = parent;
138 this.#text = text;
139 this.#start = start;
140 this.#length = length;
141 }
142 get lines(): readonly string[] {
143 return this.#text(this.#start, this.#length);
144 }
145 toJSON(): InsertRun {
146 return { file: this.file, parent: this.parent, lines: this.lines };
147 }
150/** Characters of atoms' text a graph that keeps text elsewhere holds at most (#46): about 8 MB. */
151const TEXT_CACHE = 4_000_000;
152/** 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. */
153const LIST_CACHE = 50_000;
155/** An atom's deletes and claim keys: kept in the log rather than in memory when the graph has a `lists` reader (#46). */
156export interface AtomLists {
157 readonly deletes: readonly LineId[];
158 readonly writes: readonly Key[];
159 readonly reads: readonly Key[];
160 readonly holds: readonly Key[];
163function listItems(l: AtomLists): number {
164 return l.deletes.length + l.writes.length + l.reads.length + l.holds.length;
167function frozenList<T>(xs: readonly T[]): readonly T[] {
168 return xs.length === 0 ? (EMPTY as readonly T[]) : Object.freeze([...xs]);
171/**
172 * An atom whose deletes, writes, reads and holds are read back through `read` (#46). The getters live on the
173 * prototype, so each atom keeps one reader and a fixed shape, not four closures in a dictionary-mode object.
174 */
175class ListedAtom {
176 readonly #read: () => AtomLists;
177 constructor(fields: object, read: () => AtomLists) {
178 Object.assign(this, fields);
179 this.#read = read;
180 }
181 get deletes(): readonly LineId[] {
182 return this.#read().deletes;
183 }
184 get writes(): readonly Key[] {
185 return this.#read().writes;
186 }
187 get reads(): readonly Key[] {
188 return this.#read().reads;
189 }
190 get holds(): readonly Key[] {
191 return this.#read().holds;
192 }
193 toJSON(): object {
194 return { ...this, ...this.#read() };
195 }
198/** 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 adoptionCompare199interface NumberIndex {
200 readonly length: number;
201 push(n: number): void;
202 at(i: number): number;
203 set(i: number, n: number): void;
206class Ints implements NumberIndex {
init0Start the project207 #buf: Int32Array | Uint8Array;
208 /** bytes: values 0-255 only, one byte each. */
209 constructor(bytes = false) {
210 this.#buf = bytes ? new Uint8Array(1024) : new Int32Array(1024);
211 }
212 length = 0;
213 push(n: number): void {
214 if (this.length === this.#buf.length) {
215 const bigger =
216 this.#buf instanceof Uint8Array ? new Uint8Array(this.#buf.length * 2) : new Int32Array(this.#buf.length * 2);
217 bigger.set(this.#buf);
218 this.#buf = bigger;
219 }
220 this.#buf[this.length++] = n;
221 }
222 at(i: number): number {
223 return this.#buf[i]!;
224 }
225 set(i: number, n: number): void {
226 this.#buf[i] = n;
227 }
230/**
231 * A line id's place in the graph's line arrays, or -1: "a<seq>.<k>" is line
232 * `base[seq] + k`. Hand-parsed, as seqOf is, with the same rules: no leading
233 * zeros, and k within the lines its atom wrote.
234 */
235function parseLineId(id: string): { seq: number; k: number } | undefined {
236 if (typeof id !== "string") return undefined;
237 const n = id.length;
238 if (n < 4 || id.charCodeAt(0) !== 97 /* a */) return undefined;
239 let i = 1;
240 let seq = 0;
241 const seqStart = i;
242 for (; i < n; i++) {
243 const c = id.charCodeAt(i);
244 if (c === 46 /* . */) break;
245 if (c < 48 || c > 57) return undefined;
246 seq = seq * 10 + (c - 48);
247 }
248 if (i === seqStart || i >= n - 1 || i - seqStart > 15 || (i - seqStart > 1 && id.charCodeAt(seqStart) === 48))
249 return undefined;
250 const kStart = ++i;
251 let k = 0;
252 for (; i < n; i++) {
253 const c = id.charCodeAt(i);
254 if (c < 48 || c > 57) return undefined;
255 k = k * 10 + (c - 48);
256 }
257 if (i - kStart > 15 || (i - kStart > 1 && id.charCodeAt(kStart) === 48)) return undefined;
258 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.Compare261/** A line in its file's packed history: [n, parent code, writer seq, k, 1 when it replaces its parent]. */
262export type PackedLine = [number, number, number, number, number];
263/** A delete of a line in a file's packed history: [n, deleter seq]. */
264export type PackedDelete = [number, number];
265/** An attribute set on a file: [seq, name, value]. */
266export 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.Compare267/** A run written in another file under one of a file's lines: [the parent's n, the run's file index]. */
268export 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 changesCompare269const EMPTY_NUMBERS: readonly number[] = Object.freeze([]);
capacity240Path names kept in memory once read (disk-first 2; abso Capacity). After 239, collisions on website spent most of its 4.6 s naming files: finding a deleted line's file ends at a file's start node, and Graph.#nodeName read the stored path list for it every time, through the row cache. Line records, line files and an atom's files read it the same way. Graph.#pathName keeps path names by index in memory, up to 4,096, and clears them whenever the graph accepts an atom, so a name a rolled-back add made never stays. On website adopted fresh, cold, one opened writer: collisions 4.6 s to 1.6 s (replay 0.4 s), matching replay. typescript-rs: all 27 answers match. Named tests: every engine test (290 of 290), every worker/project test (341 of 341); tsc and biome clean.Compare270/** At most this many path names kept in memory (Graph.#pathName). */
271const PATH_NAMES = 4096;
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.Compare272/** Lines longer than this aren't packed with their file; their text is read on its own. */
273const PACKED_TEXT = 4096;
init0Start the project275export class Graph {
codex-capacity-chair109Add opt-in persistent writer state, checked reopen and bounded adoptionCompare276 readonly #storage?: GraphStateStorage;
codex-capacity-chair137Page explicit child counts with bounded corruption checksCompare277 readonly #childCounts?: ChildCounts;
init0Start the project278 #atoms: Atom[] = [];
279 #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.Compare280 /**
281 * A stored graph's lamport numbers, 256 to a row (abso Capacity). A graph that already has them a row each (#lamport)
282 * keeps that; the choice is made when first needed, so opening reads nothing.
283 */
284 #lamportPaged: ReturnType<typeof storedNumbers> | undefined;
285 #lamportPagesKnown: ReturnType<typeof storedNumbers> | null | undefined;
286 get #lamportPages(): ReturnType<typeof storedNumbers> | null {
287 if (this.#lamportPagesKnown === undefined)
288 this.#lamportPagesKnown =
289 this.#lamportPaged && this.#storage!.read("lamport:meta", "length") === undefined ? this.#lamportPaged : null;
290 return this.#lamportPagesKnown;
291 }
init0Start the project292 // Lines, packed (#46): line n is the k-th line atom seq wrote, n = #lineBase[seq] + k. Each holds its
293 // atom's seq, the file it was written in (an index into #paths) and its parent (a line's n, or -1 - a
294 // path's index for a file's start). Its text stays in the atom. Ids and LineInfo objects are made only
295 // when asked for, so a line costs about 16 bytes here instead of a record, its id and its parent's id.
296 #lineBase: number[] = [];
codex-capacity-chair109Add opt-in persistent writer state, checked reopen and bounded adoptionCompare297 #lineAtom: NumberIndex = new Ints();
298 #lineFile: NumberIndex = new Ints();
299 #lineParent: NumberIndex = new Ints();
init0Start the project300 /** Lines' text, when the graph keeps it; without it, it comes from `texts` (#46, text on disk). */
301 #lineText: string[] | undefined = [];
codex-capacity-chair109Add opt-in persistent writer state, checked reopen and bounded adoptionCompare302 get #lineTotal(): number {
303 return this.#lineAtom.length;
304 }
init0Start the project305 /** Where an atom's lines' text is when the graph doesn't keep it: each run's lines, by the atom's seq. */
306 #texts: ((seq: number) => readonly (readonly string[])[]) | undefined;
307 /** Recently read atoms' text, flattened, most recent last, up to TEXT_CACHE characters. */
308 #textCache = new Map<number, readonly string[]>();
309 #textCached = 0;
codex-capacity-chair149Index atom metadata for resumable projection adoptionCompare311 readonly #indexAcceptedAtom?: (atom: Atom, files: readonly string[], storage: GraphStateStorage) => void;
init0Start the project313 /**
314 * `texts`, when given, says where each atom's lines' text can be read back
315 * (#46): the graph then keeps no text, only each line's place, and reads an
316 * atom's text when a line of it is asked for, keeping the most recent.
317 */
318 constructor(
codex-capacity-chair109Add opt-in persistent writer state, checked reopen and bounded adoptionCompare319 options: {
320 texts?: (seq: number) => readonly (readonly string[])[];
321 lists?: (seq: number) => AtomLists;
322 storage?: GraphStateStorage;
codex-capacity-chair149Index atom metadata for resumable projection adoptionCompare323 /** Optional derived indexing inside persistent atom acceptance; must be synchronous. */
324 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.Compare325 /** false: a new stored graph keeps no packed file history, and lays files out line by line (tests of that path). */
326 packFiles?: boolean;
codex-capacity-chair109Add opt-in persistent writer state, checked reopen and bounded adoptionCompare327 } = {},
init0Start the project328 ) {
codex-capacity-chair149Index atom metadata for resumable projection adoptionCompare329 if (options.indexAcceptedAtom && !options.storage)
330 throw Error("accepted atom indexing requires persistent storage");
331 this.#indexAcceptedAtom = options.indexAcceptedAtom;
init0Start the project332 if (options.texts) {
333 this.#texts = options.texts;
334 this.#lineText = undefined;
335 }
336 if (options.lists) this.#lists = options.lists;
codex-capacity-chair109Add opt-in persistent writer state, checked reopen and bounded adoptionCompare337 this.#storage = options.storage;
codex-capacity-chair137Page explicit child counts with bounded corruption checksCompare338 if (options.storage) this.#childCounts = new ChildCounts(options.storage);
codex-capacity-chair109Add opt-in persistent writer state, checked reopen and bounded adoptionCompare339 if (options.storage) {
340 const storage = options.storage;
codex-capacity-chair113Page disk-first numeric graph indexes under bounded storage cacheCompare341 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 gateCompare342 const atomText = new StoredText(storage, "atom-text:long");
343 type TextReference = { text: string };
344 const listFields = [
345 "deletes",
346 "writes",
347 "reads",
348 "holds",
349 "needs",
350 "resolves",
351 "deps",
352 "reasons",
353 "attrs",
354 "moves",
355 ] as const;
356 type EncodedAtom = {
357 insertionFormat?: 1;
358 insertionRuns?: string;
359 textFormat?: 1;
capacity239An atom's long lists kept 256 values to a row (list format 2; disk-first 2; abso Capacity). Collisions reads every key each draft atom writes. An atom's lists over 256 values were stored a row per value (readonlyStoredArray). On website, collisions read 75,000 of those rows (a draft deleting a big file has thousands of keys). - New atoms store such lists 256 values to a row (writePagedArray) and mark it listFormat 2. readonlyPagedArray reads them a page at a time, in order or by index. - An atom stored before keeps listFormat 1 and its row per value, and reads as before. The format is per atom record, so old and new atoms sit side by side. Only atoms stored from this version on, or a fresh adoption, get pages. On website adopted fresh, cold, one opened writer: collisions 9.6 s to 4.7 s (79,000 reads to 3,900), matching replay (0.4 s). Adoption took 87 s instead of 119 s. Tests: graph-atom-list-pages (new: a new atom's list is paged and reads whole; an atom rewritten as list format 1 reads whole). graph-atom-list-rollback now injects its failure on the list's second page. Every engine test (290 of 290), every worker/project test (341 of 341); tsc and biome clean.Compare360 listFormat?: 1 | 2;
codex-capacity-chair162Add reviewed disk-first history and indexed graph storage for core issue 16; retain runtime activation gateCompare361 listCount?: number;
362 lists?: Partial<Record<(typeof listFields)[number], string>>;
363 atom: Atom;
364 };
365 this.#atoms = storedArray<Atom>(
366 storage,
367 "atoms",
368 (value) => {
369 const encoded = value as unknown as Partial<EncodedAtom>;
370 if (encoded.textFormat !== undefined && encoded.textFormat !== 1)
371 throw Error("invalid stored atom text format");
capacity239An atom's long lists kept 256 values to a row (list format 2; disk-first 2; abso Capacity). Collisions reads every key each draft atom writes. An atom's lists over 256 values were stored a row per value (readonlyStoredArray). On website, collisions read 75,000 of those rows (a draft deleting a big file has thousands of keys). - New atoms store such lists 256 values to a row (writePagedArray) and mark it listFormat 2. readonlyPagedArray reads them a page at a time, in order or by index. - An atom stored before keeps listFormat 1 and its row per value, and reads as before. The format is per atom record, so old and new atoms sit side by side. Only atoms stored from this version on, or a fresh adoption, get pages. On website adopted fresh, cold, one opened writer: collisions 9.6 s to 4.7 s (79,000 reads to 3,900), matching replay (0.4 s). Adoption took 87 s instead of 119 s. Tests: graph-atom-list-pages (new: a new atom's list is paged and reads whole; an atom rewritten as list format 1 reads whole). graph-atom-list-rollback now injects its failure on the list's second page. Every engine test (290 of 290), every worker/project test (341 of 341); tsc and biome clean.Compare372 if (encoded.listFormat !== undefined && encoded.listFormat !== 1 && encoded.listFormat !== 2)
codex-capacity-chair162Add reviewed disk-first history and indexed graph storage for core issue 16; retain runtime activation gateCompare373 throw Error("invalid stored atom list format");
capacity239An atom's long lists kept 256 values to a row (list format 2; disk-first 2; abso Capacity). Collisions reads every key each draft atom writes. An atom's lists over 256 values were stored a row per value (readonlyStoredArray). On website, collisions read 75,000 of those rows (a draft deleting a big file has thousands of keys). - New atoms store such lists 256 values to a row (writePagedArray) and mark it listFormat 2. readonlyPagedArray reads them a page at a time, in order or by index. - An atom stored before keeps listFormat 1 and its row per value, and reads as before. The format is per atom record, so old and new atoms sit side by side. Only atoms stored from this version on, or a fresh adoption, get pages. On website adopted fresh, cold, one opened writer: collisions 9.6 s to 4.7 s (79,000 reads to 3,900), matching replay (0.4 s). Adoption took 87 s instead of 119 s. Tests: graph-atom-list-pages (new: a new atom's list is paged and reads whole; an atom rewritten as list format 1 reads whole). graph-atom-list-rollback now injects its failure on the list's second page. Every engine test (290 of 290), every worker/project test (341 of 341); tsc and biome clean.Compare374 if (encoded.listFormat === 1 || encoded.listFormat === 2) {
codex-capacity-chair162Add reviewed disk-first history and indexed graph storage for core issue 16; retain runtime activation gateCompare375 if (
376 !encoded.lists ||
377 typeof encoded.lists !== "object" ||
378 Array.isArray(encoded.lists) ||
379 !Number.isSafeInteger(encoded.listCount) ||
380 encoded.listCount! < 1 ||
381 Object.keys(encoded.lists).length !== encoded.listCount ||
382 Object.keys(encoded.lists).some((field) => !listFields.includes(field as (typeof listFields)[number]))
383 )
384 throw Error("invalid stored atom list references");
385 }
386 if (encoded.insertionFormat !== undefined && encoded.insertionFormat !== 1)
387 throw Error("invalid stored insertion format");
388 const atom =
capacity239An atom's long lists kept 256 values to a row (list format 2; disk-first 2; abso Capacity). Collisions reads every key each draft atom writes. An atom's lists over 256 values were stored a row per value (readonlyStoredArray). On website, collisions read 75,000 of those rows (a draft deleting a big file has thousands of keys). - New atoms store such lists 256 values to a row (writePagedArray) and mark it listFormat 2. readonlyPagedArray reads them a page at a time, in order or by index. - An atom stored before keeps listFormat 1 and its row per value, and reads as before. The format is per atom record, so old and new atoms sit side by side. Only atoms stored from this version on, or a fresh adoption, get pages. On website adopted fresh, cold, one opened writer: collisions 9.6 s to 4.7 s (79,000 reads to 3,900), matching replay (0.4 s). Adoption took 87 s instead of 119 s. Tests: graph-atom-list-pages (new: a new atom's list is paged and reads whole; an atom rewritten as list format 1 reads whole). graph-atom-list-rollback now injects its failure on the list's second page. Every engine test (290 of 290), every worker/project test (341 of 341); tsc and biome clean.Compare389 encoded.textFormat === 1 ||
390 encoded.listFormat === 1 ||
391 encoded.listFormat === 2 ||
392 encoded.insertionFormat === 1
codex-capacity-chair162Add reviewed disk-first history and indexed graph storage for core issue 16; retain runtime activation gateCompare393 ? encoded.atom!
394 : 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.Compare395 if (encoded.insertionFormat === 1 && (!Array.isArray(atom.inserts) || atom.inserts.length !== 0))
396 throw Error("invalid stored insertion placeholder");
codex-capacity-chair162Add reviewed disk-first history and indexed graph storage for core issue 16; retain runtime activation gateCompare397 const text =
398 encoded.textFormat === 1
399 ? (start: number, length: number): readonly string[] => {
400 const result: string[] = [];
401 let index = 0;
402 for (const run of atom.inserts)
403 for (const raw of run.lines) {
404 if (index >= start && index < start + length) {
405 const reference = raw as unknown as TextReference;
406 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.Compare407 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 gateCompare408 result.push(atomText.read(reference.text));
409 else throw Error("invalid stored atom text reference");
410 }
411 if (++index >= start + length) return result;
412 }
413 throw Error("stored atom text range missing");
414 }
415 : undefined;
codex-capacity-chair176Avoid quadratic insertion-run offsets; cleared in review ask 52Compare416 // Sequential reads advance once per run without retaining a history-sized offset array.
417 let offsetRun = 0;
418 let offsetLine = 0;
419 const insertionStart = (index: number): number => {
420 if (index < offsetRun) {
421 offsetRun = 0;
422 offsetLine = 0;
423 }
424 while (offsetRun < index) {
425 offsetLine += readonlyStoredArray(storage, `atom-inserts:${atom.seq}:lines:${offsetRun}`).length;
426 offsetRun++;
427 }
428 return offsetLine;
429 };
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.Compare430 const streamed = (target: Atom): Atom => {
431 registerJsonChunkValue(target, () => {
432 const line = (raw: unknown, index: number): unknown => {
433 if (typeof raw === "string") return raw;
434 const reference = raw as TextReference;
435 if (!reference || reference.text !== JSON.stringify([String(atom.seq), index]))
436 throw Error("invalid stored atom text reference");
437 return new JsonStringChunks(() => atomText.chunks(reference.text));
438 };
439 let inserts: readonly unknown[];
440 if (encoded.insertionFormat === 1) {
441 const collection = `atom-inserts:${atom.seq}`;
442 inserts = readonlyStoredArray(storage, collection, (raw, index) => {
443 const run = raw as { file: string; parent: string; lines: string };
444 const lines = `${collection}:lines:${index}`;
445 if (run.lines !== lines || typeof run.file !== "string" || typeof run.parent !== "string")
446 throw Error("invalid stored insertion run");
codex-capacity-chair176Avoid quadratic insertion-run offsets; cleared in review ask 52Compare447 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.Compare448 return {
449 file: run.file,
450 parent: run.parent,
451 lines: readonlyStoredArray(storage, lines, (raw, i) => line(raw, start + i)),
452 };
453 });
454 } else {
455 let index = 0;
456 inserts = atom.inserts.map((run) => ({
457 file: run.file,
458 parent: run.parent,
459 lines: run.lines.map((raw) => line(raw, index++)),
460 }));
461 }
462 return { ...target, inserts };
463 });
464 return target;
465 };
codex-capacity-chair162Add reviewed disk-first history and indexed graph storage for core issue 16; retain runtime activation gateCompare466 const frozen = freezeAtom(
467 atom,
468 (id) => id,
469 (author) => author,
470 text,
471 );
capacity239An atom's long lists kept 256 values to a row (list format 2; disk-first 2; abso Capacity). Collisions reads every key each draft atom writes. An atom's lists over 256 values were stored a row per value (readonlyStoredArray). On website, collisions read 75,000 of those rows (a draft deleting a big file has thousands of keys). - New atoms store such lists 256 values to a row (writePagedArray) and mark it listFormat 2. readonlyPagedArray reads them a page at a time, in order or by index. - An atom stored before keeps listFormat 1 and its row per value, and reads as before. The format is per atom record, so old and new atoms sit side by side. Only atoms stored from this version on, or a fresh adoption, get pages. On website adopted fresh, cold, one opened writer: collisions 9.6 s to 4.7 s (79,000 reads to 3,900), matching replay (0.4 s). Adoption took 87 s instead of 119 s. Tests: graph-atom-list-pages (new: a new atom's list is paged and reads whole; an atom rewritten as list format 1 reads whole). graph-atom-list-rollback now injects its failure on the list's second page. Every engine test (290 of 290), every worker/project test (341 of 341); tsc and biome clean.Compare472 if (encoded.listFormat !== 1 && encoded.listFormat !== 2 && encoded.insertionFormat !== 1)
473 return streamed(frozen);
codex-capacity-chair162Add reviewed disk-first history and indexed graph storage for core issue 16; retain runtime activation gateCompare474 const result = { ...frozen };
475 if (encoded.insertionFormat === 1) {
476 const collection = `atom-inserts:${atom.seq}`;
477 if (encoded.insertionRuns !== collection) throw Error("invalid stored insertion reference");
478 const inserts = readonlyStoredArray<InsertRun>(storage, collection, (raw, index) => {
479 const run = raw as { file: string; parent: InsertRun["parent"]; lines: string };
480 const lines = `${collection}:lines:${index}`;
481 if (run.lines !== lines || typeof run.file !== "string" || typeof run.parent !== "string")
482 throw Error("invalid stored insertion run");
483 return Object.freeze({
484 file: run.file,
485 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.Compare486 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 gateCompare487 if (typeof rawLine === "string") return rawLine;
488 const ref = rawLine as TextReference;
codex-capacity-chair176Avoid quadratic insertion-run offsets; cleared in review ask 52Compare489 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.Compare490 if (!ref || ref.text !== JSON.stringify([String(atom.seq), atomLine]))
491 throw Error("invalid stored insertion text");
codex-capacity-chair162Add reviewed disk-first history and indexed graph storage for core issue 16; retain runtime activation gateCompare492 return atomText.read(ref.text);
493 }),
494 });
495 });
496 Object.defineProperty(result, "inserts", { value: inserts, enumerable: true });
497 }
498 for (const field of listFields) {
499 const collection = encoded.lists?.[field];
500 if (collection === undefined) continue;
501 if (typeof collection !== "string" || collection !== `atom-list:${atom.seq}:${field}`)
502 throw Error("invalid stored atom list reference");
capacity239An atom's long lists kept 256 values to a row (list format 2; disk-first 2; abso Capacity). Collisions reads every key each draft atom writes. An atom's lists over 256 values were stored a row per value (readonlyStoredArray). On website, collisions read 75,000 of those rows (a draft deleting a big file has thousands of keys). - New atoms store such lists 256 values to a row (writePagedArray) and mark it listFormat 2. readonlyPagedArray reads them a page at a time, in order or by index. - An atom stored before keeps listFormat 1 and its row per value, and reads as before. The format is per atom record, so old and new atoms sit side by side. Only atoms stored from this version on, or a fresh adoption, get pages. On website adopted fresh, cold, one opened writer: collisions 9.6 s to 4.7 s (79,000 reads to 3,900), matching replay (0.4 s). Adoption took 87 s instead of 119 s. Tests: graph-atom-list-pages (new: a new atom's list is paged and reads whole; an atom rewritten as list format 1 reads whole). graph-atom-list-rollback now injects its failure on the list's second page. Every engine test (290 of 290), every worker/project test (341 of 341); tsc and biome clean.Compare503 const list =
504 encoded.listFormat === 2
505 ? readonlyPagedArray(storage, collection)
506 : readonlyStoredArray(storage, collection);
507 Object.defineProperty(result, field, { value: list, enumerable: true });
codex-capacity-chair162Add reviewed disk-first history and indexed graph storage for core issue 16; retain runtime activation gateCompare508 }
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.Compare509 return streamed(Object.freeze(result));
codex-capacity-chair162Add reviewed disk-first history and indexed graph storage for core issue 16; retain runtime activation gateCompare510 },
511 (input, key) => {
512 const atom = { ...input };
513 const lists: Partial<Record<(typeof listFields)[number], string>> = {};
514 for (const field of listFields) {
515 const values = input[field];
516 if (!values || values.length <= 256) continue;
capacity239An atom's long lists kept 256 values to a row (list format 2; disk-first 2; abso Capacity). Collisions reads every key each draft atom writes. An atom's lists over 256 values were stored a row per value (readonlyStoredArray). On website, collisions read 75,000 of those rows (a draft deleting a big file has thousands of keys). - New atoms store such lists 256 values to a row (writePagedArray) and mark it listFormat 2. readonlyPagedArray reads them a page at a time, in order or by index. - An atom stored before keeps listFormat 1 and its row per value, and reads as before. The format is per atom record, so old and new atoms sit side by side. Only atoms stored from this version on, or a fresh adoption, get pages. On website adopted fresh, cold, one opened writer: collisions 9.6 s to 4.7 s (79,000 reads to 3,900), matching replay (0.4 s). Adoption took 87 s instead of 119 s. Tests: graph-atom-list-pages (new: a new atom's list is paged and reads whole; an atom rewritten as list format 1 reads whole). graph-atom-list-rollback now injects its failure on the list's second page. Every engine test (290 of 290), every worker/project test (341 of 341); tsc and biome clean.Compare517 // 256 to a row from list format 2 on (abso Capacity); an atom stored before keeps a row per value.
codex-capacity-chair162Add reviewed disk-first history and indexed graph storage for core issue 16; retain runtime activation gateCompare518 const collection = `atom-list:${input.seq}:${field}`;
capacity239An atom's long lists kept 256 values to a row (list format 2; disk-first 2; abso Capacity). Collisions reads every key each draft atom writes. An atom's lists over 256 values were stored a row per value (readonlyStoredArray). On website, collisions read 75,000 of those rows (a draft deleting a big file has thousands of keys). - New atoms store such lists 256 values to a row (writePagedArray) and mark it listFormat 2. readonlyPagedArray reads them a page at a time, in order or by index. - An atom stored before keeps listFormat 1 and its row per value, and reads as before. The format is per atom record, so old and new atoms sit side by side. Only atoms stored from this version on, or a fresh adoption, get pages. On website adopted fresh, cold, one opened writer: collisions 9.6 s to 4.7 s (79,000 reads to 3,900), matching replay (0.4 s). Adoption took 87 s instead of 119 s. Tests: graph-atom-list-pages (new: a new atom's list is paged and reads whole; an atom rewritten as list format 1 reads whole). graph-atom-list-rollback now injects its failure on the list's second page. Every engine test (290 of 290), every worker/project test (341 of 341); tsc and biome clean.Compare519 writePagedArray(storage, collection, values);
codex-capacity-chair162Add reviewed disk-first history and indexed graph storage for core issue 16; retain runtime activation gateCompare520 lists[field] = collection;
521 Object.defineProperty(atom, field, { value: [], enumerable: true });
522 }
523 const listCount = Object.keys(lists).length;
524 const hasLists = listCount > 0;
codex-capacity-chair166Read long insertion text lazily and stream files through Git commit constructionCompare525 let insertionCharacters = 0;
526 if (
527 atom.inserts.length > 256 ||
528 atom.inserts.some((run) => run.lines.length > 256) ||
529 atom.inserts.some((run) => run.lines.some((line) => (insertionCharacters += line.length) > 65536))
530 ) {
codex-capacity-chair162Add reviewed disk-first history and indexed graph storage for core issue 16; retain runtime activation gateCompare531 const collection = `atom-inserts:${input.seq}`;
532 const runs = storedArray<unknown>(storage, collection);
533 let runIndex = 0;
534 let lineIndex = 0;
535 for (const run of atom.inserts) {
536 const lineCollection = `${collection}:lines:${runIndex++}`;
537 const lines = storedArray<unknown>(storage, lineCollection);
538 for (const line of run.lines) {
539 const text = JSON.stringify([key, lineIndex++]);
540 if (line.length > StoredText.chunkCharacters) {
541 atomText.write(text, line);
542 lines.push({ text });
543 } else lines.push(line);
544 }
545 runs.push({ file: run.file, parent: run.parent, lines: lineCollection });
546 }
547 return {
548 insertionFormat: 1,
549 insertionRuns: collection,
capacity239An atom's long lists kept 256 values to a row (list format 2; disk-first 2; abso Capacity). Collisions reads every key each draft atom writes. An atom's lists over 256 values were stored a row per value (readonlyStoredArray). On website, collisions read 75,000 of those rows (a draft deleting a big file has thousands of keys). - New atoms store such lists 256 values to a row (writePagedArray) and mark it listFormat 2. readonlyPagedArray reads them a page at a time, in order or by index. - An atom stored before keeps listFormat 1 and its row per value, and reads as before. The format is per atom record, so old and new atoms sit side by side. Only atoms stored from this version on, or a fresh adoption, get pages. On website adopted fresh, cold, one opened writer: collisions 9.6 s to 4.7 s (79,000 reads to 3,900), matching replay (0.4 s). Adoption took 87 s instead of 119 s. Tests: graph-atom-list-pages (new: a new atom's list is paged and reads whole; an atom rewritten as list format 1 reads whole). graph-atom-list-rollback now injects its failure on the list's second page. Every engine test (290 of 290), every worker/project test (341 of 341); tsc and biome clean.Compare550 ...(hasLists ? { listFormat: 2, listCount, lists } : {}),
codex-capacity-chair162Add reviewed disk-first history and indexed graph storage for core issue 16; retain runtime activation gateCompare551 atom: { ...atom, inserts: [] },
552 };
553 }
554 if (!atom.inserts.some((run) => run.lines.some((line) => line.length > StoredText.chunkCharacters)))
capacity239An atom's long lists kept 256 values to a row (list format 2; disk-first 2; abso Capacity). Collisions reads every key each draft atom writes. An atom's lists over 256 values were stored a row per value (readonlyStoredArray). On website, collisions read 75,000 of those rows (a draft deleting a big file has thousands of keys). - New atoms store such lists 256 values to a row (writePagedArray) and mark it listFormat 2. readonlyPagedArray reads them a page at a time, in order or by index. - An atom stored before keeps listFormat 1 and its row per value, and reads as before. The format is per atom record, so old and new atoms sit side by side. Only atoms stored from this version on, or a fresh adoption, get pages. On website adopted fresh, cold, one opened writer: collisions 9.6 s to 4.7 s (79,000 reads to 3,900), matching replay (0.4 s). Adoption took 87 s instead of 119 s. Tests: graph-atom-list-pages (new: a new atom's list is paged and reads whole; an atom rewritten as list format 1 reads whole). graph-atom-list-rollback now injects its failure on the list's second page. Every engine test (290 of 290), every worker/project test (341 of 341); tsc and biome clean.Compare555 return hasLists ? { listFormat: 2, listCount, lists, atom } : atom;
codex-capacity-chair162Add reviewed disk-first history and indexed graph storage for core issue 16; retain runtime activation gateCompare556 let index = 0;
557 const inserts = atom.inserts.map((run) => ({
558 ...run,
559 lines: run.lines.map((line) => {
560 const text = JSON.stringify([key, index++]);
561 if (line.length <= StoredText.chunkCharacters) return line;
562 atomText.write(text, line);
563 return { text };
564 }),
565 }));
566 return {
567 textFormat: 1,
capacity239An atom's long lists kept 256 values to a row (list format 2; disk-first 2; abso Capacity). Collisions reads every key each draft atom writes. An atom's lists over 256 values were stored a row per value (readonlyStoredArray). On website, collisions read 75,000 of those rows (a draft deleting a big file has thousands of keys). - New atoms store such lists 256 values to a row (writePagedArray) and mark it listFormat 2. readonlyPagedArray reads them a page at a time, in order or by index. - An atom stored before keeps listFormat 1 and its row per value, and reads as before. The format is per atom record, so old and new atoms sit side by side. Only atoms stored from this version on, or a fresh adoption, get pages. On website adopted fresh, cold, one opened writer: collisions 9.6 s to 4.7 s (79,000 reads to 3,900), matching replay (0.4 s). Adoption took 87 s instead of 119 s. Tests: graph-atom-list-pages (new: a new atom's list is paged and reads whole; an atom rewritten as list format 1 reads whole). graph-atom-list-rollback now injects its failure on the list's second page. Every engine test (290 of 290), every worker/project test (341 of 341); tsc and biome clean.Compare568 ...(hasLists ? { listFormat: 2, listCount, lists } : {}),
codex-capacity-chair162Add reviewed disk-first history and indexed graph storage for core issue 16; retain runtime activation gateCompare569 atom: { ...atom, inserts },
570 };
571 },
codex-capacity-chair109Add opt-in persistent writer state, checked reopen and bounded adoptionCompare572 );
573 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.Compare574 this.#lamportPaged = storedNumbers(storage, "lamport-pages");
codex-capacity-chair109Add opt-in persistent writer state, checked reopen and bounded adoptionCompare575 this.#lineBase = storedArray(storage, "line-base");
576 this.#paths = storedArray(storage, "paths");
577 this.#movers = storedArray(storage, "movers");
578 this.#atomFiles = storedArray(storage, "atom-files");
579 this.#atomDeletes = storedArray(storage, "atom-deletes");
580 this.#lineAtom = numbers("line-atom");
581 this.#lineFile = numbers("line-file");
582 this.#lineParent = numbers("line-parent");
583 this.#deleter = numbers("deleter");
584 this.#replacing = numbers("replacing");
codex-capacity-chair162Add reviewed disk-first history and indexed graph storage for core issue 16; retain runtime activation gateCompare585 const longText = atomText;
586 this.#lineText = storedArray<string>(
587 storage,
588 "line-text",
589 (value) => {
590 if (typeof value === "string") return value;
591 const reference = value as unknown as { format: number; text: string };
592 if (reference?.format !== 1 || typeof reference.text !== "string") throw Error("invalid long line reference");
593 return longText.read(reference.text);
594 },
595 (value, key) => {
596 if (value.length <= StoredText.chunkCharacters) return value;
597 const number = Number(key);
598 const seq = this.#lineAtom.at(number);
599 const text = JSON.stringify([String(seq), number - this.#lineBase[seq]!]);
600 const header = storage.read("atom-text:long", text) as { characters?: number } | undefined;
601 if (header?.characters !== value.length) throw Error("long line atom text is missing");
602 return { format: 1, text };
603 },
604 );
codex-capacity-chair109Add opt-in persistent writer state, checked reopen and bounded adoptionCompare605 this.#pathIndex = storedMap(storage, "path-index");
codex-capacity-chair128Page deletion history and short-circuit current visibilityCompare606 this.#moreDeleterPages = storedLists<number>(storage, "more-deleters", (key) =>
607 JSON.stringify(["number", Number(key)]),
608 );
codex-capacity-chair120Page persistent claim indexes and stream dependency queriesCompare609 this.#writersPages = storedLists<AtomId>(storage, "writers", (key) => key);
610 this.#readersPages = storedLists<AtomId>(storage, "readers", (key) => key);
611 this.#holdersPages = storedLists<AtomId>(storage, "holders", (key) => key);
codex-capacity-chair122Page dependency and resolver indexes with streamed intersectionCompare612 this.#dependentsPages = storedLists<AtomId>(storage, "dependents");
613 this.#resolversPages = storedLists<AtomId>(storage, "resolvers");
codex-capacity-chair129Page together relationship history for bounded traversalCompare614 this.#togetherPages = storedLists<TogetherLink>(storage, "together");
capacity242why: reasons pointing at a change indexed, and a moved line looked for among its push (disk-first 2; abso Capacity). why on abso, warm, one kept reader: 2.9 s a call with about 24,000 reads, 20,000 of them atoms. - Reasons in: why listed the changes whose reasons point at the line's change by reading every atom in the project. The graph now keeps, for each atom, the atoms whose reasons point at it, in seq order, once each (reasons-in, Graph.reasonsTo), from a fresh stored graph on. A graph made before keeps none, reasonsTo says undefined, and why looks at every atom as before. - Moved from: the trail looked for a deleted copy of a line's text among every atom within 5,000 of the change. Only atoms pushed with it can count, so where the change is published its version's atoms are the candidates (Project.versionAtoms, trail's pushmates). A change still in a draft goes with every other draft change, so it looks near by as before. - trail takes atoms' numbers from their ids instead of reading each atom. On abso adopted fresh: why 244 ms on the first call, then 86 and 46 ms (was 2.9 s); 1,091 reads, then 469 and 73. It matches replay, which takes 951 ms. Heap after: 22.6 MB. New test reasons-to: the atoms pointing at an atom, in seq order, once each, whatever the kind and however many reasons one gives, in memory and stored. A stored graph without the index says undefined. Every engine test (292 of 292), every worker/project test (341 of 341); tsc and biome clean.Compare615 this.#reasonsInPages = storedLists<AtomId>(storage, "reasons-in");
codex-capacity-chair119Page per-file atom indexes and stream current-view attribute scansCompare616 this.#fileAtomPages = storedLists<AtomId>(storage, "file-atoms");
codex-capacity-chair130Stream paged child history into layout filteringCompare617 this.#runStartPages = storedLists<number>(storage, "run-starts", (key) =>
618 JSON.stringify(["number", Number(key)]),
619 );
codex-capacity-chair127Page persistent relocation indexes and stream projection readsCompare620 this.#relocationPages = storedLists<RelocationInfo>(storage, "relocations");
621 this.#relocatedToPages = storedLists<RelocationInfo>(storage, "relocated-to");
622 this.#relocatedToCodePages = storedLists<RelocationInfo>(storage, "relocated-to-code", (key) =>
623 JSON.stringify(["number", Number(key)]),
624 );
codex-capacity-chair109Add opt-in persistent writer state, checked reopen and bounded adoptionCompare625 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.Compare626 this.#fileLines = storedLists<PackedLine>(storage, "file-lines");
627 this.#fileTexts = storedLists<string | null>(storage, "file-texts");
628 this.#fileDeletes = storedLists<PackedDelete>(storage, "file-deletes");
629 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.Compare630 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.Compare631 this.#packFiles = options.packFiles ?? true;
codex-capacity-chair109Add opt-in persistent writer state, checked reopen and bounded adoptionCompare632 }
init0Start the project633 }
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.Compare634
635 // Each file's line history packed, in pages (abso Capacity) ---------------------------------------------------
636 // 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.Compare637 // text, every delete of one of those lines ([n, deleter seq]), every attribute set on it ([seq, name, value]), and
638 // every run written in another file under one of its lines ([parent n, the run's file]): a line follows its parent,
639 // 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.Compare640 // 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
641 // a fresh adoption on; a graph adopted before has none, and views lay out as before.
init0Start the project642
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.Compare643 #fileLines: ReturnType<typeof storedLists<PackedLine>> | undefined;
644 #fileTexts: ReturnType<typeof storedLists<string | null>> | undefined;
645 #fileDeletes: ReturnType<typeof storedLists<PackedDelete>> | undefined;
646 #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.Compare647 #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.Compare648 /** Whether a new stored graph starts packing (GraphOptions.packFiles). */
649 #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.Compare650 /**
651 * How this graph's files are packed, read once when first asked so opening reads nothing: 0 not at all, 1 lines,
652 * deletes and attributes, 2 the runs written across files as well.
653 */
654 #formatKnown: number | undefined;
655 get #format(): number {
656 if (this.#formatKnown === undefined) {
657 const format = this.#storage?.read("file-lines:meta", "format");
658 this.#formatKnown = format === 1 || format === 2 ? format : 0;
659 }
660 return this.#formatKnown;
661 }
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.Compare662 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.Compare663 return this.#format >= 1;
664 }
665 get #crossings(): boolean {
666 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.Compare667 }
669 /** Whether this graph keeps each file's line history packed. */
670 get packedFiles(): boolean {
671 return this.#packed;
672 }
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.Compare673 /**
674 * Whether a file can be laid out from packed history alone: it also keeps the runs written across files. A graph
675 * packed before those were kept lays files out line by line.
676 */
677 get packedLayout(): boolean {
678 return this.#crossings;
679 }
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.Compare680 /** A path's index, or undefined when nothing was ever written or set in it. */
681 pathIndexOf(path: string): number | undefined {
682 return this.#pathIndex.get(path);
683 }
684 /** The index of the path line n was written in. */
685 writtenInIndex(n: number): number {
686 return this.#lineFile.at(n);
687 }
688 *packedLines(file: number): IterableIterator<PackedLine> {
689 yield* this.#fileLines!.values(String(file));
690 }
691 *packedTexts(file: number): IterableIterator<string | null> {
692 yield* this.#fileTexts!.values(String(file));
693 }
694 *packedDeletes(file: number): IterableIterator<PackedDelete> {
695 yield* this.#fileDeletes!.values(String(file));
696 }
697 *packedAttrs(file: number): IterableIterator<PackedAttr> {
698 yield* this.#fileAttrs!.values(String(file));
699 }
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.Compare700 *packedCrossings(file: number): IterableIterator<PackedCrossing> {
701 yield* this.#fileCrossings!.values(String(file));
702 }
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.Compare703
init0Start the project704 /** Where an atom's key and delete lists are when the graph doesn't keep them (#46): the stored atom. */
705 #lists: ((seq: number) => AtomLists) | undefined;
706 /** Recently read atoms' lists, most recent last, up to LIST_CACHE atoms. */
707 #listCache = new Map<number, AtomLists>();
708 #listCached = 0;
710 /** An atom's deletes, writes, reads and holds, read back from where they are stored. */
711 #listsOf(seq: number): AtomLists {
712 const hit = this.#listCache.get(seq);
713 if (hit) {
714 this.#listCache.delete(seq);
715 this.#listCache.set(seq, hit);
716 return hit;
717 }
718 const got = this.#lists!(seq);
719 const lists: AtomLists = {
720 deletes: frozenList(got.deletes),
721 writes: frozenList(got.writes),
722 reads: frozenList(got.reads),
723 holds: frozenList(got.holds),
724 };
725 this.#listCache.set(seq, lists);
726 this.#listCached += listItems(lists);
727 for (const [old, kept] of this.#listCache) {
728 if (this.#listCached <= LIST_CACHE || old === seq) break;
729 this.#listCache.delete(old);
730 this.#listCached -= listItems(kept);
731 }
732 return lists;
733 }
735 /** The reader an atom's lists use; made apart from add() so it keeps no atom alive (see #reader). */
736 #listReader(seq: number): () => AtomLists {
737 return () => this.#listsOf(seq);
738 }
740 /**
741 * 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
742 * index holds numbers rather than one string per line; start-node and attribute keys stay strings. A key
743 * naming a line the graph doesn't have stays a string, which nothing has claimed.
744 */
745 #code(key: Key): Key | number {
746 const t = key.charCodeAt(0);
747 if (key.charCodeAt(1) !== 58 || key.charCodeAt(2) === 94) return key; // not "X:", or a start node "^"
748 const k = t === 76 ? 0 : t === 80 ? 1 : t === 71 ? 2 : -1; // L, P, G
749 if (k < 0) return key;
750 const n = this.#lineN(key.slice(2));
751 return n < 0 ? key : n * 4 + k;
752 }
754 /** An atom's lines' text, in k order. */
755 #textOf(seq: number): readonly string[] {
756 const hit = this.#textCache.get(seq);
757 if (hit) {
758 this.#textCache.delete(seq);
759 this.#textCache.set(seq, hit);
760 return hit;
761 }
762 const flat = this.#texts!(seq).flat();
763 let chars = 0;
764 for (const t of flat) chars += t.length + 1;
765 this.#textCache.set(seq, flat);
766 this.#textCached += chars;
767 for (const [old, lines] of this.#textCache) {
768 if (this.#textCached <= TEXT_CACHE || old === seq) break;
769 this.#textCache.delete(old);
770 for (const t of lines) this.#textCached -= t.length + 1;
771 }
772 return flat;
773 }
775 /**
776 * The reader an atom's runs use. Made in a function of its own: a closure made inside add() would
777 * keep add()'s whole scope alive, the atom as given with all its text included.
778 */
779 #reader(seq: number): (start: number, length: number) => readonly string[] {
780 return (start, length) => this.#textOf(seq).slice(start, start + length);
781 }
783 /** Line n's text. */
784 #text(n: number): string {
785 if (this.#lineText) return this.#lineText[n]!;
786 const seq = this.#lineAtom.at(n);
787 return this.#textOf(seq)[n - this.#lineBase[seq]!]!;
788 }
789 #paths: string[] = [];
codex-capacity-chair109Add opt-in persistent writer state, checked reopen and bounded adoptionCompare790 #pathIndex: StateMap<string, number> = new Map();
init0Start the project791 /** 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 adoptionCompare792 #deleter: NumberIndex = new Ints();
793 #moreDeleters: StateMap<number, number[]> = new Map();
codex-capacity-chair128Page deletion history and short-circuit current visibilityCompare794 #moreDeleterPages: ReturnType<typeof storedLists<number>> | undefined;
codex-capacity-chair109Add opt-in persistent writer state, checked reopen and bounded adoptionCompare795 #writers: StateMap<Key | number, AtomId | AtomId[]> = new Map();
codex-capacity-chair120Page persistent claim indexes and stream dependency queriesCompare796 #writersPages: ReturnType<typeof storedLists<AtomId>> | undefined;
codex-capacity-chair109Add opt-in persistent writer state, checked reopen and bounded adoptionCompare797 #readers: StateMap<Key | number, AtomId | AtomId[]> = new Map();
codex-capacity-chair120Page persistent claim indexes and stream dependency queriesCompare798 #readersPages: ReturnType<typeof storedLists<AtomId>> | undefined;
codex-capacity-chair109Add opt-in persistent writer state, checked reopen and bounded adoptionCompare799 #holders: StateMap<Key | number, AtomId | AtomId[]> = new Map();
codex-capacity-chair120Page persistent claim indexes and stream dependency queriesCompare800 #holdersPages: ReturnType<typeof storedLists<AtomId>> | undefined;
codex-capacity-chair109Add opt-in persistent writer state, checked reopen and bounded adoptionCompare801 #dependents: StateMap<AtomId, AtomId | AtomId[]> = new Map();
codex-capacity-chair122Page dependency and resolver indexes with streamed intersectionCompare802 #dependentsPages: ReturnType<typeof storedLists<AtomId>> | undefined;
codex-capacity-chair109Add opt-in persistent writer state, checked reopen and bounded adoptionCompare803 #resolvers: StateMap<AtomId, AtomId | AtomId[]> = new Map();
codex-capacity-chair122Page dependency and resolver indexes with streamed intersectionCompare804 #resolversPages: ReturnType<typeof storedLists<AtomId>> | undefined;
codex-capacity-chair109Add opt-in persistent writer state, checked reopen and bounded adoptionCompare805 #together: StateMap<AtomId, TogetherLink[]> = new Map();
codex-capacity-chair129Page together relationship history for bounded traversalCompare806 #togetherPages: ReturnType<typeof storedLists<TogetherLink>> | undefined;
capacity242why: reasons pointing at a change indexed, and a moved line looked for among its push (disk-first 2; abso Capacity). why on abso, warm, one kept reader: 2.9 s a call with about 24,000 reads, 20,000 of them atoms. - Reasons in: why listed the changes whose reasons point at the line's change by reading every atom in the project. The graph now keeps, for each atom, the atoms whose reasons point at it, in seq order, once each (reasons-in, Graph.reasonsTo), from a fresh stored graph on. A graph made before keeps none, reasonsTo says undefined, and why looks at every atom as before. - Moved from: the trail looked for a deleted copy of a line's text among every atom within 5,000 of the change. Only atoms pushed with it can count, so where the change is published its version's atoms are the candidates (Project.versionAtoms, trail's pushmates). A change still in a draft goes with every other draft change, so it looks near by as before. - trail takes atoms' numbers from their ids instead of reading each atom. On abso adopted fresh: why 244 ms on the first call, then 86 and 46 ms (was 2.9 s); 1,091 reads, then 469 and 73. It matches replay, which takes 951 ms. Heap after: 22.6 MB. New test reasons-to: the atoms pointing at an atom, in seq order, once each, whatever the kind and however many reasons one gives, in memory and stored. A stored graph without the index says undefined. Every engine test (292 of 292), every worker/project test (341 of 341); tsc and biome clean.Compare807 /** The atoms whose reasons point at each atom, in seq order, once each (abso Capacity). */
808 #reasonsIn = new Map<AtomId, AtomId[]>();
809 #reasonsInPages: ReturnType<typeof storedLists<AtomId>> | undefined;
810 /** Whether a stored graph keeps reasons-in: from a fresh graph on, worked out when first needed. */
811 #reasonsInKnown: boolean | undefined;
812 get #reasonsInKept(): boolean {
813 if (!this.#storage) return true;
814 this.#reasonsInKnown ??= this.#storage.read("reasons-in:meta", "kept") === 1;
815 return this.#reasonsInKnown;
816 }
codex-capacity-chair109Add opt-in persistent writer state, checked reopen and bounded adoptionCompare817 #fileAtoms: StateMap<string, AtomId[]> = new Map();
codex-capacity-chair119Page per-file atom indexes and stream current-view attribute scansCompare818 #fileAtomPages: ReturnType<typeof storedLists<AtomId>> | undefined;
init0Start the project819 /** 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 adoptionCompare820 #runStarts: StateMap<number, number | number[]> = new Map();
codex-capacity-chair130Stream paged child history into layout filteringCompare821 #runStartPages: ReturnType<typeof storedLists<number>> | undefined;
init0Start the project822 /** 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 adoptionCompare823 #replacing: NumberIndex = new Ints(true);
824 #relocations: StateMap<LineId, RelocationInfo[]> = new Map();
codex-capacity-chair127Page persistent relocation indexes and stream projection readsCompare825 #relocationPages: ReturnType<typeof storedLists<RelocationInfo>> | undefined;
codex-capacity-chair109Add opt-in persistent writer state, checked reopen and bounded adoptionCompare826 #relocatedTo: StateMap<NodeId, RelocationInfo[]> = new Map();
codex-capacity-chair127Page persistent relocation indexes and stream projection readsCompare827 #relocatedToPages: ReturnType<typeof storedLists<RelocationInfo>> | undefined;
init0Start the project828 /** 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 adoptionCompare829 #relocatedToCode: StateMap<number, RelocationInfo[]> = new Map();
codex-capacity-chair127Page persistent relocation indexes and stream projection readsCompare830 #relocatedToCodePages: ReturnType<typeof storedLists<RelocationInfo>> | undefined;
init0Start the project831 #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.Compare832 /** A stored graph's movers, read once (abso Capacity): every view walks them, a row each. */
833 #moverList: AtomId[] | undefined;
init0Start the project834 #atomFiles: (readonly string[])[] = [];
835 /** 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 adoptionCompare836 #atomDeletes: (readonly number[] | Int32Array | undefined)[] = [];
837 #labels: StateMap<string, Label> = new Map();
init0Start the project838 /** Each author's name kept once (#46). */
839 #authors = new Map<string, string>();
841 /** Number of atoms (also the seq the next atom gets). */
842 get size(): number {
843 return this.#atoms.length;
844 }
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.Compare846 /**
847 * How many atoms this graph object has accepted since it was made (abso Capacity): in memory, so a cache over the
848 * graph can tell nothing was added without reading storage. A rolled-back add still counts, which only makes such a
849 * cache look again.
850 */
851 get accepted(): number {
852 return this.#accepted;
853 }
854 #accepted = 0;
init0Start the project856 /** The id the next accepted atom must have. */
857 nextId(): AtomId {
858 return atomId(this.#atoms.length);
859 }
861 has(id: AtomId): boolean {
862 const seq = this.#seq(id);
863 return seq >= 0 && seq < this.#atoms.length;
864 }
866 atom(id: AtomId): Atom {
867 const seq = this.#seq(id);
868 const atom = seq >= 0 ? this.#atoms[seq] : undefined;
869 if (!atom) throw new EngineError("unknown-atom", `no atom ${id}`);
870 return atom;
871 }
873 /** All atoms in seq order. */
874 atoms(): readonly Atom[] {
875 return this.#atoms;
876 }
878 /** lamport(a) = 1 + max lamport of its deps; 0 for an atom with no deps (such as a0). */
879 lamport(id: AtomId): number {
codex-capacity-chair148Read graph identities and metadata without decoding atom payloadsCompare880 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.Compare881 return this.#lamportAt(this.#seq(id));
init0Start the project882 }
884 /** Compare by priority (lamport, then seq). Negative when a comes first (is lower). */
885 comparePriority(a: AtomId, b: AtomId): number {
886 return this.lamport(a) - this.lamport(b) || this.#seq(a) - this.#seq(b);
887 }
889 line(id: LineId): LineInfo | undefined {
890 const n = this.#lineN(id);
891 if (n < 0) return undefined;
892 const seq = this.#lineAtom.at(n);
893 return {
894 id,
codex-capacity-chair148Read graph identities and metadata without decoding atom payloadsCompare895 atom: this.idOfSeq(seq),
init0Start the project896 k: n - this.#lineBase[seq]!,
capacity240Path names kept in memory once read (disk-first 2; abso Capacity). After 239, collisions on website spent most of its 4.6 s naming files: finding a deleted line's file ends at a file's start node, and Graph.#nodeName read the stored path list for it every time, through the row cache. Line records, line files and an atom's files read it the same way. Graph.#pathName keeps path names by index in memory, up to 4,096, and clears them whenever the graph accepts an atom, so a name a rolled-back add made never stays. On website adopted fresh, cold, one opened writer: collisions 4.6 s to 1.6 s (replay 0.4 s), matching replay. typescript-rs: all 27 answers match. Named tests: every engine test (290 of 290), every worker/project test (341 of 341); tsc and biome clean.Compare897 file: this.#pathName(this.#lineFile.at(n)),
init0Start the project898 parent: this.#nodeName(this.#lineParent.at(n)),
899 text: this.#text(n),
900 };
901 }
903 /** A line's text, or undefined for an unknown line: line(id).text without making the record. */
904 lineText(id: LineId): string | undefined {
905 const n = this.#lineN(id);
906 return n < 0 ? undefined : this.#text(n);
907 }
909 /** The atom that wrote a line, or undefined: line(id).atom without making the record. */
910 lineAtom(id: LineId): AtomId | undefined {
911 const n = this.#lineN(id);
codex-capacity-chair148Read graph identities and metadata without decoding atom payloadsCompare912 return n < 0 ? undefined : this.idOfSeq(this.#lineAtom.at(n));
init0Start the project913 }
915 /** The file a line was written in, or undefined: line(id).file without making the record. */
916 lineFile(id: LineId): string | undefined {
917 const n = this.#lineN(id);
capacity240Path names kept in memory once read (disk-first 2; abso Capacity). After 239, collisions on website spent most of its 4.6 s naming files: finding a deleted line's file ends at a file's start node, and Graph.#nodeName read the stored path list for it every time, through the row cache. Line records, line files and an atom's files read it the same way. Graph.#pathName keeps path names by index in memory, up to 4,096, and clears them whenever the graph accepts an atom, so a name a rolled-back add made never stays. On website adopted fresh, cold, one opened writer: collisions 4.6 s to 1.6 s (replay 0.4 s), matching replay. typescript-rs: all 27 answers match. Named tests: every engine test (290 of 290), every worker/project test (341 of 341); tsc and biome clean.Compare918 return n < 0 ? undefined : this.#pathName(this.#lineFile.at(n));
init0Start the project919 }
921 /** The node a line was written after, or undefined: line(id).parent without making the record. */
922 lineParent(id: LineId): NodeId | undefined {
923 const n = this.#lineN(id);
924 return n < 0 ? undefined : this.#nodeName(this.#lineParent.at(n));
925 }
927 // By number, for views (#46) ------------------------------------------------------
928 // 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
929 // keeps them, so a view can lay files out as arrays of numbers. For the engine's own use.
931 /** A line id's n, or -1 for an unknown line. */
932 lineN(id: LineId): number {
933 return this.#lineN(id);
934 }
936 /** A line's id from its n. */
937 lineIdOf(n: number): LineId {
938 return this.#lineName(n);
939 }
941 /** The lines an atom deletes, from the graph's own packed copy (#46): never a read of the log. */
942 deletedLines(id: AtomId): readonly LineId[] {
codex-capacity-chair162Add reviewed disk-first history and indexed graph storage for core issue 16; retain runtime activation gateCompare943 const seq = this.#seq(id);
944 const count = this.#storage?.read("atom-delete-counts", String(seq));
945 if (count !== undefined) {
946 const out: LineId[] = [];
947 for (const n of storedLists<number>(this.#storage!, "atom-deletes").values(String(seq)))
948 out.push(this.#lineName(n));
949 if (out.length !== count) throw Error("incomplete atom deletion index");
950 return out;
951 }
init0Start the project952 const ns = this.#atomDeletes[this.#seq(id)];
953 if (!ns) return EMPTY;
954 const out: LineId[] = new Array(ns.length);
955 for (let i = 0; i < ns.length; i++) out[i] = this.#lineName(ns[i]!);
956 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 changesCompare957 }
959 /** The numbers of the lines an atom deletes, from the graph's packed copy: no lookup per line id. */
960 *deletedNumbers(id: AtomId): IterableIterator<number> {
961 const seq = this.#seq(id);
962 if (this.#storage?.read("atom-delete-counts", String(seq)) !== undefined) {
963 yield* storedLists<number>(this.#storage!, "atom-deletes").values(String(seq));
964 return;
965 }
966 yield* this.#atomDeletes[seq] ?? EMPTY_NUMBERS;
init0Start the project967 }
969 /** How many lines an atom deletes, without reading its lists. */
970 deleteCount(id: AtomId): number {
codex-capacity-chair162Add reviewed disk-first history and indexed graph storage for core issue 16; retain runtime activation gateCompare971 const seq = this.#seq(id);
972 const count = this.#storage?.read("atom-delete-counts", String(seq));
973 if (count !== undefined) {
974 if (!Number.isSafeInteger(count) || (count as number) < 0) throw Error("invalid atom deletion count");
975 return count as number;
976 }
977 return this.#atomDeletes[seq]?.length ?? 0;
init0Start the project978 }
980 textOf(n: number): string {
981 return this.#text(n);
982 }
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.Compare984 /** Historical text in bounded chunks, without decoding a whole stored line. */
985 *textChunks(n: number): IterableIterator<string> {
986 if (!this.#storage) {
987 const text = this.#text(n);
988 for (let offset = 0; offset < text.length; offset += StoredText.chunkCharacters)
989 yield text.slice(offset, offset + StoredText.chunkCharacters);
990 return;
991 }
992 if (!Number.isSafeInteger(n) || n < 0 || n >= this.#lineText!.length) throw Error("invalid line number");
993 const value = this.#storage.read("line-text", String(n));
994 if (typeof value === "string") {
995 yield value;
996 return;
997 }
998 const reference = value as { format?: number; text?: string } | undefined;
999 if (reference?.format !== 1 || typeof reference.text !== "string") throw Error("invalid long line reference");
1000 yield* new StoredText(this.#storage, "atom-text:long").chunks(reference.text);
init0Start the project1003 /** The seq of the atom that wrote line n. */
1004 writerSeqOf(n: number): number {
1005 return this.#lineAtom.at(n);
1008 /** Line n's k: its place among its atom's lines. */
1009 kOf(n: number): number {
1010 return n - this.#lineBase[this.#lineAtom.at(n)]!;
1013 /** The atom id with this seq, as the graph keeps it. */
1014 idOfSeq(seq: number): AtomId {
codex-capacity-chair148Read graph identities and metadata without decoding atom payloadsCompare1015 if (!Number.isSafeInteger(seq) || seq < 0 || seq >= this.#atoms.length)
1016 throw new EngineError("unknown-atom", `no atom at sequence ${seq}`);
1017 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.Compare1018 }
1020 #lamportAt(seq: number): number {
1021 return this.#lamportPages ? this.#lamportPages.at(seq) : this.#lamport[seq]!;
init0Start the project1022 }
1024 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.Compare1025 return this.#lamportAt(seq);
init0Start the project1026 }
1028 /** The file line n was written in. */
1029 writtenIn(n: number): string {
capacity240Path names kept in memory once read (disk-first 2; abso Capacity). After 239, collisions on website spent most of its 4.6 s naming files: finding a deleted line's file ends at a file's start node, and Graph.#nodeName read the stored path list for it every time, through the row cache. Line records, line files and an atom's files read it the same way. Graph.#pathName keeps path names by index in memory, up to 4,096, and clears them whenever the graph accepts an atom, so a name a rolled-back add made never stays. On website adopted fresh, cold, one opened writer: collisions 4.6 s to 1.6 s (replay 0.4 s), matching replay. typescript-rs: all 27 answers match. Named tests: every engine test (290 of 290), every worker/project test (341 of 341); tsc and biome clean.Compare1030 return this.#pathName(this.#lineFile.at(n));
init0Start the project1031 }
1033 /** The code of the node line n was written after. */
1034 parentCodeOf(n: number): number {
1035 return this.#lineParent.at(n);
1038 /** A node's code, or undefined for a node the graph doesn't know (a start node of a file nothing was written in). */
1039 codeOf(node: NodeId): number | undefined {
1040 return this.#nodeCode(node);
1043 /** The node a code names. */
1044 nodeOf(code: number): NodeId {
1045 return this.#nodeName(code);
1048 /** The start node's code for a path, or undefined when nothing was ever written in it. */
1049 startCodeOf(path: string): number | undefined {
1050 const p = this.#pathIndex.get(path);
1051 return p === undefined ? undefined : -1 - p;
1054 /** The lines (their n) written right after a node, as childrenOf, into `out`. */
codex-capacity-chair130Stream paged child history into layout filteringCompare1055
init0Start the project1056 childrenN(code: number, out: number[]): void {
codex-capacity-chair130Stream paged child history into layout filteringCompare1057 for (const n of this.eachChildN(code)) out.push(n);
1059 *eachChildN(code: number): IterableIterator<number> {
init0Start the project1060 if (
1061 code >= 0 &&
1062 code + 1 < this.#lineTotal &&
1063 this.#lineAtom.at(code + 1) === this.#lineAtom.at(code) &&
1064 this.#lineParent.at(code + 1) === code
codex-capacity-chair130Stream paged child history into layout filteringCompare1066 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.Compare1067 if (this.#runStartPages) {
1068 // The paged child counts say a line has no other children without a row read per line (abso Capacity).
1069 if (code >= 0 && this.#childCounts && this.#childCounts.at(code, this.#lineTotal) === 0) return;
1070 yield* this.#runStartPages.values(String(code));
1071 } else yield* listOf(this.#runStarts.get(code));
init0Start the project1072 }
codex-capacity-chair131Bound persisted no-move layout with ordered successor traversalCompare1074 get hasOrderedChildren(): boolean {
1075 return this.#storage !== undefined;
codex-capacity-chair132Bound persistent relocation projection memory with rollback-only scratchCompare1076 }
1077 /** Synchronous derived work against one graph identity. Scratch never commits. */
1078 withProjectionScratch<T>(operation: (scratch: GraphStateStorage) => T): T {
1079 if (!this.#storage) throw new Error("projection scratch requires persistent graph storage");
1080 const size = this.size;
1081 const lines = this.lineCount;
1082 return withProjectionScratch(
1083 this.#storage,
1084 () => {
1085 if (this.size !== size || this.lineCount !== lines) throw new Error("projection graph identity changed");
1086 },
1087 operation,
1088 );
codex-capacity-chair131Bound persisted no-move layout with ordered successor traversalCompare1089 }
1090 #childPriority(n: number): string {
1091 const seq = this.writerSeqOf(n);
1092 return orderedChildKey({
1093 n,
1094 replaces: this.replacesN(n) ? 1 : 0,
1095 lamport: this.lamportOfSeq(seq),
1096 seq,
1097 k: this.kOf(n),
1098 });
1100 /** Persistent layout order with a strict successor cursor; moves are separate. */
1101 *orderedChildrenN(code: number, after?: number): IterableIterator<number> {
1102 if (!this.#storage) throw new Error("ordered children require indexed storage");
1103 const index = new OrderedIndex(this.#storage, "ordered-children", String(code));
codex-capacity-chair137Page explicit child counts with bounded corruption checksCompare1104 if (this.#storage.read("ordered-children", "format") !== 2)
codex-capacity-chair131Bound persisted no-move layout with ordered successor traversalCompare1105 throw new Error("ordered children require fresh adoption");
codex-capacity-chair137Page explicit child counts with bounded corruption checksCompare1106 const count = code >= 0 ? this.#childCounts!.at(code, this.#lineTotal) : index.size;
1107 if ((code < 0 || count > 0) && (count !== index.size || count !== this.#runStartPages!.length(String(code))))
1108 throw new Error("ordered child index count mismatch");
codex-capacity-chair131Bound persisted no-move layout with ordered successor traversalCompare1109 let implicit: number | undefined;
1110 if (
1111 code >= 0 &&
1112 code + 1 < this.#lineTotal &&
1113 this.#lineAtom.at(code + 1) === this.#lineAtom.at(code) &&
1114 this.#lineParent.at(code + 1) === code
1116 implicit = code + 1;
codex-capacity-chair135Skip priority decoding for implicit-only child traversalCompare1117 // Most historical run lines have no explicit child. With zero or one
1118 // child, traversal needs no priority decoding or radix lookup. Keep the
1119 // format/count checks above even on this path.
1120 if (count === 0 && (after === undefined || after === implicit)) {
1121 if (implicit !== undefined && after !== implicit) yield implicit;
1122 return;
codex-capacity-chair131Bound persisted no-move layout with ordered successor traversalCompare1124 const cursor = after === undefined ? undefined : this.#childPriority(after);
1125 if (implicit !== undefined && cursor !== undefined && this.#childPriority(implicit) <= cursor) implicit = undefined;
1126 for (const n of index.values(cursor)) {
1127 if (implicit !== undefined && this.#childPriority(implicit) < this.#childPriority(n)) {
1128 yield implicit;
1129 implicit = undefined;
1131 yield n;
1133 if (implicit !== undefined) yield implicit;
init0Start the project1136 replacesN(n: number): boolean {
1137 return this.#replacing.at(n) === 1;
1140 /** The seqs of every atom that deletes line n (none: an empty list, shared). */
1141 deleterSeqsOf(n: number): readonly number[] {
codex-capacity-chair128Page deletion history and short-circuit current visibilityCompare1142 return [...this.eachDeleterSeqOf(n)];
1144 *eachDeleterSeqOf(n: number): IterableIterator<number> {
init0Start the project1145 const first = this.#deleter.at(n);
codex-capacity-chair128Page deletion history and short-circuit current visibilityCompare1146 if (first < 0) return;
1147 yield first;
1148 if (this.#moreDeleterPages) yield* this.#moreDeleterPages.values(String(n));
1149 else yield* this.#moreDeleters.get(n) ?? EMPTY;
init0Start the project1150 }
1152 /** Every relocation that puts a line right after the node with this code. */
1153 relocatedToCode(code: number): readonly RelocationInfo[] {
codex-capacity-chair127Page persistent relocation indexes and stream projection readsCompare1154 if (this.#relocatedToCodePages) return [...this.eachRelocatedToCode(code)];
init0Start the project1155 return this.#relocatedToCode.get(code) ?? EMPTY;
codex-capacity-chair127Page persistent relocation indexes and stream projection readsCompare1156 }
1157 *eachRelocatedToCode(code: number): IterableIterator<RelocationInfo> {
1158 if (this.#relocatedToCodePages) yield* this.#relocatedToCodePages.values(String(code));
1159 else yield* this.#relocatedToCode.get(code) ?? EMPTY;
init0Start the project1160 }
1162 /** How many lines every atom together has written. */
1163 get lineCount(): number {
1164 return this.#lineTotal;
1167 /** A line id's n, or -1 when no accepted atom wrote it. */
1168 #lineN(id: LineId): number {
1169 const p = parseLineId(id);
1170 if (!p || p.seq >= this.#atoms.length) return -1;
1171 const base = this.#lineBase[p.seq]!;
1172 const end = p.seq + 1 < this.#lineBase.length ? this.#lineBase[p.seq + 1]! : this.#lineTotal;
1173 return p.k < end - base ? base + p.k : -1;
1176 /** A line's id from its n. */
1177 #lineName(n: number): LineId {
1178 const seq = this.#lineAtom.at(n);
codex-capacity-chair148Read graph identities and metadata without decoding atom payloadsCompare1179 return `${this.idOfSeq(seq)}.${n - this.#lineBase[seq]!}`;
init0Start the project1180 }
1182 /** A node's code: a line's n, or -1 - a path's index for a start node; undefined when unknown. */
1183 #nodeCode(node: NodeId): number | undefined {
1184 if (isStartNode(node)) {
1185 const p = this.#pathIndex.get(node.slice(1));
1186 return p === undefined ? undefined : -1 - p;
1188 const n = this.#lineN(node);
1189 return n < 0 ? undefined : n;
1192 #nodeName(code: number): NodeId {
capacity240Path names kept in memory once read (disk-first 2; abso Capacity). After 239, collisions on website spent most of its 4.6 s naming files: finding a deleted line's file ends at a file's start node, and Graph.#nodeName read the stored path list for it every time, through the row cache. Line records, line files and an atom's files read it the same way. Graph.#pathName keeps path names by index in memory, up to 4,096, and clears them whenever the graph accepts an atom, so a name a rolled-back add made never stays. On website adopted fresh, cold, one opened writer: collisions 4.6 s to 1.6 s (replay 0.4 s), matching replay. typescript-rs: all 27 answers match. Named tests: every engine test (290 of 290), every worker/project test (341 of 341); tsc and biome clean.Compare1193 return code >= 0 ? this.#lineName(code) : startNode(this.#pathName(-1 - code));
init0Start the project1194 }
capacity240Path names kept in memory once read (disk-first 2; abso Capacity). After 239, collisions on website spent most of its 4.6 s naming files: finding a deleted line's file ends at a file's start node, and Graph.#nodeName read the stored path list for it every time, through the row cache. Line records, line files and an atom's files read it the same way. Graph.#pathName keeps path names by index in memory, up to 4,096, and clears them whenever the graph accepts an atom, so a name a rolled-back add made never stays. On website adopted fresh, cold, one opened writer: collisions 4.6 s to 1.6 s (replay 0.4 s), matching replay. typescript-rs: all 27 answers match. Named tests: every engine test (290 of 290), every worker/project test (341 of 341); tsc and biome clean.Compare1196 /**
1197 * A path's name by its index, kept in memory once read (abso Capacity): finding a deleted line's file names the file
1198 * it reaches, and a stored graph read the path list each time. Cleared when the graph accepts an atom, so a name a
1199 * rolled-back add made never stays.
1200 */
1201 #pathName(index: number): string {
1202 if (this.#pathNamesAt !== this.#accepted) {
1203 this.#pathNames.clear();
1204 this.#pathNamesAt = this.#accepted;
1206 let name = this.#pathNames.get(index);
1207 if (name === undefined) {
1208 name = this.#paths[index]!;
1209 if (this.#pathNames.size >= PATH_NAMES) this.#pathNames.clear();
1210 this.#pathNames.set(index, name);
1212 return name;
1214 readonly #pathNames = new Map<number, string>();
1215 #pathNamesAt = -1;
init0Start the project1217 #pathOf(file: string): number {
1218 let p = this.#pathIndex.get(file);
1219 if (p === undefined) {
1220 p = this.#paths.push(file) - 1;
1221 this.#pathIndex.set(file, p);
1223 return p;
1226 /** The line ids an atom inserted, in k order. */
1227 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.Compare1228 return [...this.eachInsertedLine(id)];
1230 /** Inserted identities without decoding or allocating the atom's text. */
1231 *eachInsertedLine(id: AtomId): IterableIterator<LineId> {
1232 const seq = this.atom(id).seq;
init0Start the project1233 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.Compare1234 for (let k = 0; k < count; k++) yield lineId(id, k);
init0Start the project1235 }
1237 /** Every atom that deletes this line (across the whole graph). */
1238 deletersOf(line: LineId): readonly AtomId[] {
1239 const n = this.#lineN(line);
1240 if (n < 0) return EMPTY;
codex-capacity-chair148Read graph identities and metadata without decoding atom payloadsCompare1241 return [...this.eachDeleterSeqOf(n)].map((seq) => this.idOfSeq(seq));
init0Start the project1242 }
1244 writersOf(key: Key): readonly AtomId[] {
codex-capacity-chair120Page persistent claim indexes and stream dependency queriesCompare1245 return [...this.eachWriterOf(key)];
init0Start the project1246 }
codex-capacity-chair120Page persistent claim indexes and stream dependency queriesCompare1247 *eachWriterOf(key: Key): IterableIterator<AtomId> {
1248 const code = this.#code(key);
1249 if (this.#writersPages) yield* this.#writersPages.values(JSON.stringify([typeof code, code]));
1250 else yield* listOf(this.#writers.get(code));
init0Start the project1252
1253 /** Atoms whose implicit reads include the key. */
1254 readersOf(key: Key): readonly AtomId[] {
codex-capacity-chair120Page persistent claim indexes and stream dependency queriesCompare1255 return [...this.eachReaderOf(key)];
1257 *eachReaderOf(key: Key): IterableIterator<AtomId> {
1258 const code = this.#code(key);
1259 if (this.#readersPages) yield* this.#readersPages.values(JSON.stringify([typeof code, code]));
1260 else yield* listOf(this.#readers.get(code));
init0Start the project1261 }
1263 /** Atoms whose explicit holds include the key. */
1264 holdersOf(key: Key): readonly AtomId[] {
codex-capacity-chair120Page persistent claim indexes and stream dependency queriesCompare1265 return [...this.eachHolderOf(key)];
1267 *eachHolderOf(key: Key): IterableIterator<AtomId> {
1268 const code = this.#code(key);
1269 if (this.#holdersPages) yield* this.#holdersPages.values(JSON.stringify([typeof code, code]));
1270 else yield* listOf(this.#holders.get(code));
init0Start the project1271 }
1273 /** Every atom that inserts or deletes a line of the file, in seq order. */
1274 atomsIn(file: string): readonly AtomId[] {
codex-capacity-chair119Page per-file atom indexes and stream current-view attribute scansCompare1275 if (this.#fileAtomPages) return [...this.#fileAtomPages.values(file)];
init0Start the project1276 return this.#fileAtoms.get(file) ?? EMPTY;
codex-capacity-chair119Page per-file atom indexes and stream current-view attribute scansCompare1277 }
1278 *eachAtomIn(file: string): IterableIterator<AtomId> {
1279 if (this.#fileAtomPages) yield* this.#fileAtomPages.values(file);
1280 else yield* this.#fileAtoms.get(file) ?? EMPTY;
init0Start the project1281 }
codex-capacity-chair119Page per-file atom indexes and stream current-view attribute scansCompare1282 hasAtomsIn(file: string): boolean {
1283 return this.#fileAtomPages ? this.#fileAtomPages.length(file) > 0 : this.#fileAtoms.has(file);
init0Start the project1285
codex-capacity-chair118Avoid retaining deleted historical paths in indexed current viewsCompare1286 /** Unique historical file paths, streamed without collecting their names. */
1287 *knownFiles(): IterableIterator<string> {
codex-capacity-chair119Page per-file atom indexes and stream current-view attribute scansCompare1288 yield* this.#fileAtomPages ? this.#fileAtomPages.keys() : this.#fileAtoms.keys();
codex-capacity-chair118Avoid retaining deleted historical paths in indexed current viewsCompare1289 }
init0Start the project1291 /**
1292 * The files an atom inserts, deletes or moves lines in, or sets attributes
1293 * of, sorted. For lines, the file each was written in (or, for a move to a
1294 * start node, that file): a set's moves can have taken them elsewhere.
1295 */
1296 filesOf(id: AtomId): readonly string[] {
codex-capacity-chair148Read graph identities and metadata without decoding atom payloadsCompare1297 if (!this.has(id)) throw new EngineError("unknown-atom", `no atom ${id}`);
init0Start the project1298 return this.#atomFiles[this.#seq(id)]!;
1301 /** Lines written right after a node (not counting moves), in seq order. */
codex-capacity-chair130Stream paged child history into layout filteringCompare1302
init0Start the project1303 childrenOf(node: NodeId): LineId[] {
1304 const code = this.#nodeCode(node);
codex-capacity-chair130Stream paged child history into layout filteringCompare1305 return code === undefined ? [] : [...this.eachChildN(code)].map((n) => this.#lineName(n));
init0Start the project1306 }
1308 /** Whether a line starts a run whose atom deleted the line it hangs off. */
1309 replaces(line: LineId): boolean {
1310 const n = this.#lineN(line);
1311 return n >= 0 && this.#replacing.at(n) === 1;
1314 /** Every relocation of a line, in seq order. */
1315 relocationsOf(line: LineId): readonly RelocationInfo[] {
codex-capacity-chair127Page persistent relocation indexes and stream projection readsCompare1316 if (this.#relocationPages) return [...this.eachRelocationOf(line)];
init0Start the project1317 return this.#relocations.get(line) ?? EMPTY;
codex-capacity-chair127Page persistent relocation indexes and stream projection readsCompare1319 *eachRelocationOf(line: LineId): IterableIterator<RelocationInfo> {
1320 if (this.#relocationPages) yield* this.#relocationPages.values(line);
1321 else yield* this.#relocations.get(line) ?? EMPTY;
init0Start the project1323
1324 /** Every relocation that puts a line right after this node, in seq order. */
1325 relocatedTo(node: NodeId): readonly RelocationInfo[] {
codex-capacity-chair127Page persistent relocation indexes and stream projection readsCompare1326 if (this.#relocatedToPages) return [...this.#relocatedToPages.values(node)];
init0Start the project1327 return this.#relocatedTo.get(node) ?? EMPTY;
1330 /** Atoms that move lines, in seq order. */
1331 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.Compare1332 if (!this.#storage) return this.#movers;
1333 // Checked against the stored list's length and last mover, so a rolled-back add can't leave one behind.
1334 const length = this.#movers.length;
1335 const list = this.#moverList;
1336 if (list && list.length === length && (length === 0 || list[length - 1] === this.#movers[length - 1])) return list;
1337 this.#moverList = [...this.#movers];
1338 return this.#moverList;
init0Start the project1339 }
1341 /** Atoms that list this one directly in their deps. */
1342 dependentsOf(id: AtomId): readonly AtomId[] {
codex-capacity-chair122Page dependency and resolver indexes with streamed intersectionCompare1343 return [...this.eachDependentOf(id)];
init0Start the project1344 }
codex-capacity-chair122Page dependency and resolver indexes with streamed intersectionCompare1345 *eachDependentOf(id: AtomId): IterableIterator<AtomId> {
1346 if (this.#dependentsPages) yield* this.#dependentsPages.values(id);
1347 else yield* listOf(this.#dependents.get(id));
init0Start the project1349
1350 /** Atoms whose `resolves` names this one. */
1351 resolversOf(id: AtomId): readonly AtomId[] {
codex-capacity-chair122Page dependency and resolver indexes with streamed intersectionCompare1352 return [...this.eachResolverOf(id)];
1354 *eachResolverOf(id: AtomId): IterableIterator<AtomId> {
1355 if (this.#resolversPages) yield* this.#resolversPages.values(id);
1356 else yield* listOf(this.#resolvers.get(id));
init0Start the project1357 }
capacity242why: reasons pointing at a change indexed, and a moved line looked for among its push (disk-first 2; abso Capacity). why on abso, warm, one kept reader: 2.9 s a call with about 24,000 reads, 20,000 of them atoms. - Reasons in: why listed the changes whose reasons point at the line's change by reading every atom in the project. The graph now keeps, for each atom, the atoms whose reasons point at it, in seq order, once each (reasons-in, Graph.reasonsTo), from a fresh stored graph on. A graph made before keeps none, reasonsTo says undefined, and why looks at every atom as before. - Moved from: the trail looked for a deleted copy of a line's text among every atom within 5,000 of the change. Only atoms pushed with it can count, so where the change is published its version's atoms are the candidates (Project.versionAtoms, trail's pushmates). A change still in a draft goes with every other draft change, so it looks near by as before. - trail takes atoms' numbers from their ids instead of reading each atom. On abso adopted fresh: why 244 ms on the first call, then 86 and 46 ms (was 2.9 s); 1,091 reads, then 469 and 73. It matches replay, which takes 951 ms. Heap after: 22.6 MB. New test reasons-to: the atoms pointing at an atom, in seq order, once each, whatever the kind and however many reasons one gives, in memory and stored. A stored graph without the index says undefined. Every engine test (292 of 292), every worker/project test (341 of 341); tsc and biome clean.Compare1359 /**
1360 * The atoms whose reasons point at this one, in seq order, once each; or undefined when a stored graph made before
1361 * this index keeps none, and the caller looks at every atom (abso Capacity).
1362 */
1363 reasonsTo(id: AtomId): readonly AtomId[] | undefined {
1364 if (!this.#reasonsInKept) return undefined;
1365 if (this.#reasonsInPages) return [...this.#reasonsInPages.values(id)];
1366 return this.#reasonsIn.get(id) ?? [];
init0Start the project1369 /** `together` reasons touching this atom, in either direction. */
1370 togetherLinks(id: AtomId): readonly TogetherLink[] {
codex-capacity-chair129Page together relationship history for bounded traversalCompare1371 return [...this.eachTogetherLink(id)];
init0Start the project1372 }
codex-capacity-chair129Page together relationship history for bounded traversalCompare1373 *eachTogetherLink(id: AtomId): IterableIterator<TogetherLink> {
1374 if (this.#togetherPages) yield* this.#togetherPages.values(id);
1375 else yield* this.#together.get(id) ?? EMPTY;
init0Start the project1377
1378 /**
1379 * The atom plus everything it depends on, transitively. Computed on demand
1380 * and not cached: a cached set per atom costs memory quadratic in the length
1381 * of a dependency chain. Use `dependsOn` to ask about one pair.
1382 */
1383 closure(id: AtomId): Set<AtomId> {
1384 return this.closureOf([id]);
1387 /** The atoms plus everything they depend on, transitively. */
1388 closureOf(ids: Iterable<AtomId>): Set<AtomId> {
1389 const out = new Set<AtomId>();
1390 const stack: AtomId[] = [];
1391 for (const id of ids) {
1392 this.atom(id);
1393 if (!out.has(id)) {
1394 out.add(id);
1395 stack.push(id);
1398 while (stack.length > 0) {
1399 for (const d of this.atom(stack.pop()!).deps) {
1400 if (!out.has(d)) {
1401 out.add(d);
1402 stack.push(d);
1406 return out;
1409 /** Whether `b` is in the closure of `a` (an atom is in its own closure). */
1410 dependsOn(a: AtomId, b: AtomId): boolean {
1411 const atom = this.atom(a);
1412 this.atom(b);
1413 return a === b || this.#reaches(atom.deps, b);
1416 /**
1417 * Whether `target` is reachable along deps from any of `from` (themselves
1418 * included). A dependency always has a lower lamport than its dependent, so
1419 * the search never descends below the target's lamport.
1420 */
1421 #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.Compare1422 const floor = this.#lamportAt(this.#seq(target));
codex-capacity-chair139Bound persistent dependency reachability with rollback scratchCompare1423 if (this.#storage) {
1424 return this.withProjectionScratch((scratch) => {
1425 let length = 0;
1426 const push = (id: AtomId): void => {
1427 if (scratch.read("seen", id)) return;
1428 scratch.write("seen", id, true);
1429 scratch.write("stack", String(length++), id);
1430 };
codex-capacity-chair162Add reviewed disk-first history and indexed graph storage for core issue 16; retain runtime activation gateCompare1431 for (const id of from) {
1432 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.Compare1433 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 gateCompare1434 }
codex-capacity-chair139Bound persistent dependency reachability with rollback scratchCompare1435 while (length > 0) {
1436 const key = String(--length);
1437 const current = scratch.read("stack", key) as AtomId;
1438 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.Compare1439 if (this.#lamportAt(this.#seq(current)) <= floor) continue;
codex-capacity-chair139Bound persistent dependency reachability with rollback scratchCompare1440 for (const dependency of this.atom(current).deps) {
1441 if (dependency === target) return true;
1442 push(dependency);
1445 return false;
1446 });
init0Start the project1448 const seen = new Set<AtomId>();
1449 const stack = [...from];
1450 while (stack.length > 0) {
1451 const cur = stack.pop()!;
1452 if (cur === target) return true;
1453 if (seen.has(cur)) continue;
1454 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.Compare1455 if (this.#lamportAt(this.#seq(cur)) <= floor) continue;
init0Start the project1456 for (const d of this.atom(cur).deps) if (!seen.has(d)) stack.push(d);
1458 return false;
1461 /**
1462 * Accept an atom into the graph. It must carry the next id and seq, and
1463 * everything it touches must come from atoms in its dependency closure.
1464 * The atom is frozen. Adding to the graph does not add it to any set.
1465 */
1466 add(atom: Atom): void {
codex-capacity-chair149Index atom metadata for resumable projection adoptionCompare1467 if (this.#storage)
1468 this.#storage.transaction(() => {
1469 this.#add(atom);
1470 const result: unknown = this.#indexAcceptedAtom?.(atom, this.filesOf(atom.id), this.#storage!);
1471 if (result && typeof result === "object" && "then" in result)
1472 throw Error("accepted atom indexing must be synchronous");
1473 });
codex-capacity-chair109Add opt-in persistent writer state, checked reopen and bounded adoptionCompare1474 else this.#add(atom);
codex-capacity-chair162Add reviewed disk-first history and indexed graph storage for core issue 16; retain runtime activation gateCompare1477 #validateAcceptedAtom(atom: Atom, scratch?: GraphStateStorage): void {
1478 const membership = <T extends string>(name: string): { has(key: T): boolean; add(key: T): unknown } => {
1479 if (!scratch) return new Set<T>();
1480 return { has: (key) => scratch.read(name, key) === true, add: (key) => scratch.write(name, key, true) };
1481 };
init0Start the project1482 validateShape(atom);
1483 const seq = this.#atoms.length;
1484 const bad = (why: string): never => {
1485 throw new EngineError("bad-atom", `atom ${atom.id}: ${why}`);
1486 };
1487 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 gateCompare1489 const deps = membership<AtomId>("deps");
init0Start the project1490 for (const d of atom.deps) {
1491 if (!this.has(d)) bad(`dependency ${d} is not in the graph`);
1492 if (deps.has(d)) bad(`dependency ${d} listed twice`);
1493 deps.add(d);
codex-capacity-chair162Add reviewed disk-first history and indexed graph storage for core issue 16; retain runtime activation gateCompare1495 for (const list of [atom.needs, atom.resolves])
1496 for (const d of list) {
1497 if (!deps.has(d)) bad(`${d} is in needs/resolves but not in deps`);
init0Start the project1499 for (const r of atom.reasons) if (!this.has(r.to)) bad(`reason points at unknown atom ${r.to}`);
1501 // Everything it touches must come from its closure. Derived deps name the
1502 // 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 gateCompare1503 const memoryBelow = scratch ? undefined : new Map<AtomId, boolean>();
1504 const below = {
1505 get: (key: AtomId) => (scratch ? (scratch.read("below", key) as boolean | undefined) : memoryBelow!.get(key)),
1506 set: (key: AtomId, value: boolean) => {
1507 if (scratch) scratch.write("below", key, value);
1508 else memoryBelow!.set(key, value);
1509 },
1510 };
init0Start the project1511 const inClosure = (writer: AtomId): boolean => {
1512 let hit = below.get(writer);
1513 if (hit === undefined) {
codex-capacity-chair162Add reviewed disk-first history and indexed graph storage for core issue 16; retain runtime activation gateCompare1514 hit = deps.has(writer) || this.#reaches(atom.deps, writer);
init0Start the project1515 below.set(writer, hit);
1517 return hit;
1518 };
1519 const checkLine = (line: LineId, what: string): void => {
1520 const writer = this.lineAtom(line);
1521 if (writer === undefined) return bad(`${what} names unknown line ${line}`);
1522 if (!inClosure(writer)) bad(`${what} names line ${line} but ${writer} is not in its closure`);
1523 };
1525 for (const run of atom.inserts) {
1526 if (isStartNode(run.parent)) {
1527 if (run.parent !== startNode(run.file)) bad(`run in ${run.file} starts at ${run.parent}`);
1528 } else {
1529 // The parent may have been moved into run.file, so its own file can differ.
1530 checkLine(run.parent, "an insert");
codex-capacity-chair162Add reviewed disk-first history and indexed graph storage for core issue 16; retain runtime activation gateCompare1533 const writes = membership<Key>("writes");
1534 for (const key of atom.writes) writes.add(key);
1535 const moved = membership<LineId>("moved");
init0Start the project1536 for (const m of atom.moves ?? []) {
1537 checkLine(m.line, "a move");
1538 if (!isStartNode(m.parent)) checkLine(m.parent, "a move");
1539 if (m.line === m.parent) bad(`moves ${m.line} after itself`);
1540 if (moved.has(m.line)) bad(`moves ${m.line} twice`);
1541 moved.add(m.line);
codex-capacity-chair162Add reviewed disk-first history and indexed graph storage for core issue 16; retain runtime activation gateCompare1542 if (!writes.has(posKey(m.line)) || !writes.has(gapKey(m.parent))) {
init0Start the project1543 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 gateCompare1546 const deleted = membership<LineId>("deleted");
init0Start the project1547 for (const line of atom.deletes) {
1548 checkLine(line, "a delete");
1549 if (deleted.has(line)) bad(`deletes ${line} twice`);
1550 deleted.add(line);
codex-capacity-chair162Add reviewed disk-first history and indexed graph storage for core issue 16; retain runtime activation gateCompare1552 for (const line of atom.deletes)
1553 if (!writes.has(lineKey(line))) bad(`deletes ${line} without writing ${lineKey(line)}`);
1554 for (const list of [atom.writes, atom.reads, atom.holds])
1555 for (const key of list) {
1556 const parsed = parseKey(key);
1557 if (parsed.kind === "line") checkLine(parsed.node, `key ${key}`);
1558 else if ((parsed.kind === "gap" || parsed.kind === "pos") && !isStartNode(parsed.node))
1559 checkLine(parsed.node, `key ${key}`);
codex-capacity-chair109Add opt-in persistent writer state, checked reopen and bounded adoptionCompare1563 #add(atom: Atom): void {
codex-capacity-chair137Page explicit child counts with bounded corruption checksCompare1564 if (this.#storage && this.#storage.read("ordered-children", "format") !== 2) {
codex-capacity-chair131Bound persisted no-move layout with ordered successor traversalCompare1565 if (this.#atoms.length !== 0) throw new Error("ordered children require fresh adoption");
codex-capacity-chair137Page explicit child counts with bounded corruption checksCompare1566 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.Compare1567 }
1568 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.Compare1569 this.#storage.write("file-lines:meta", "format", 2);
capacity242why: reasons pointing at a change indexed, and a moved line looked for among its push (disk-first 2; abso Capacity). why on abso, warm, one kept reader: 2.9 s a call with about 24,000 reads, 20,000 of them atoms. - Reasons in: why listed the changes whose reasons point at the line's change by reading every atom in the project. The graph now keeps, for each atom, the atoms whose reasons point at it, in seq order, once each (reasons-in, Graph.reasonsTo), from a fresh stored graph on. A graph made before keeps none, reasonsTo says undefined, and why looks at every atom as before. - Moved from: the trail looked for a deleted copy of a line's text among every atom within 5,000 of the change. Only atoms pushed with it can count, so where the change is published its version's atoms are the candidates (Project.versionAtoms, trail's pushmates). A change still in a draft goes with every other draft change, so it looks near by as before. - trail takes atoms' numbers from their ids instead of reading each atom. On abso adopted fresh: why 244 ms on the first call, then 86 and 46 ms (was 2.9 s); 1,091 reads, then 469 and 73. It matches replay, which takes 951 ms. Heap after: 22.6 MB. New test reasons-to: the atoms pointing at an atom, in seq order, once each, whatever the kind and however many reasons one gives, in memory and stored. A stored graph without the index says undefined. Every engine test (292 of 292), every worker/project test (341 of 341); tsc and biome clean.Compare1570 this.#storage.write("reasons-in:meta", "kept", 1);
1571 this.#reasonsInKnown = 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.Compare1572 this.#formatKnown = 2;
init0Start the project1573 }
codex-capacity-chair162Add reviewed disk-first history and indexed graph storage for core issue 16; retain runtime activation gateCompare1574
1575 if (this.#storage) this.withProjectionScratch((scratch) => this.#validateAcceptedAtom(atom, scratch));
1576 else this.#validateAcceptedAtom(atom);
1577 const seq = this.#atoms.length;
1578 const deps = atom.deps;
1579 const deleted = this.#storage ? undefined : new Set(atom.deletes);
1580 const writes = this.#storage ? atom.writes : new Set(atom.writes);
init0Start the project1581
1582 // Accept.
codex-capacity-chair162Add reviewed disk-first history and indexed graph storage for core issue 16; retain runtime activation gateCompare1583 // Persistent storage copies the accepted atom; a second frozen copy only duplicates its lists.
1584 const frozen = this.#storage
1585 ? atom
1586 : freezeAtom(
codex-capacity-chair109Add opt-in persistent writer state, checked reopen and bounded adoptionCompare1587 atom,
codex-capacity-chair162Add reviewed disk-first history and indexed graph storage for core issue 16; retain runtime activation gateCompare1588 (id) => this.idOfSeq(seqOf(id)),
1589 (author) => {
1590 if (this.#storage) return author;
1591 let a = this.#authors.get(author);
1592 if (a === undefined) this.#authors.set(author, (a = author));
1593 return a;
1594 },
1595 this.#texts ? this.#reader(seq) : undefined,
1596 this.#lists ? this.#listReader(seq) : undefined,
1597 );
codex-capacity-chair109Add opt-in persistent writer state, checked reopen and bounded adoptionCompare1598 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.Compare1599 this.#accepted++;
init0Start the project1600 let lam = 0;
1601 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.Compare1602 if (this.#lamportPages) this.#lamportPages.push(lam);
1603 else this.#lamport.push(lam);
init0Start the project1604
1605 // The run starts' parents and the deleted lines, as codes, before this atom's own lines exist.
1606 // 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 gateCompare1607 const deletes = (line: LineId | NodeId): boolean => {
1608 if (isStartNode(line)) return false;
1609 if (deleted) return deleted.has(line);
1610 const n = this.#lineN(line);
1611 return this.#deleter.at(n) === seq || this.#moreDeleterPages!.last(String(n)) === seq;
1612 };
1613 const deletedN = this.#storage ? undefined : atom.deletes.map((line) => this.#lineN(line));
1614 this.#atomDeletes.push(deletedN?.length ? Int32Array.from(deletedN) : undefined);
1615 if (this.#storage) {
1616 const pages = storedLists<number>(this.#storage, "atom-deletes");
1617 for (const line of atom.deletes) pages.append(String(seq), this.#lineN(line));
1618 this.#storage.write("atom-delete-counts", String(seq), atom.deletes.length);
1620 const deletedNumbers = function* (graph: Graph) {
1621 if (deletedN) yield* deletedN;
1622 else for (const line of atom.deletes) yield graph.#lineN(line);
1623 };
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.Compare1624 const packedDeletes = new Map<number, PackedDelete[]>();
codex-capacity-chair162Add reviewed disk-first history and indexed graph storage for core issue 16; retain runtime activation gateCompare1625 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.Compare1626 if (this.#packed) {
1627 const file = this.#lineFile.at(n);
1628 const list = packedDeletes.get(file);
1629 if (list) list.push([n, seq]);
1630 else packedDeletes.set(file, [[n, seq]]);
init0Start the project1632 if (this.#deleter.at(n) < 0) this.#deleter.set(n, seq);
codex-capacity-chair128Page deletion history and short-circuit current visibilityCompare1633 else if (this.#moreDeleterPages) this.#moreDeleterPages.append(String(n), seq);
init0Start the project1634 else pushIndex(this.#moreDeleters, n, seq);
codex-capacity-chair120Page persistent claim indexes and stream dependency queriesCompare1635 }
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.Compare1636 for (const [file, list] of packedDeletes) this.#fileDeletes!.appendAll(String(file), list);
init0Start the project1637 this.#lineBase.push(this.#lineTotal);
1638 for (const run of atom.inserts) {
1639 const file = this.#pathOf(run.file);
1640 let parent = isStartNode(run.parent) ? -1 - file : this.#lineN(run.parent);
1641 const first = this.#lineTotal;
codex-capacity-chair137Page explicit child counts with bounded corruption checksCompare1642 if (parent >= 0) this.#childCounts?.increment(parent, first);
codex-capacity-chair131Bound persisted no-move layout with ordered successor traversalCompare1643 if (this.#storage)
1644 new OrderedIndex(this.#storage, "ordered-children", String(parent)).insert(
1645 orderedChildKey({
1646 n: first,
codex-capacity-chair162Add reviewed disk-first history and indexed graph storage for core issue 16; retain runtime activation gateCompare1647 replaces: deletes(run.parent) ? 1 : 0,
codex-capacity-chair131Bound persisted no-move layout with ordered successor traversalCompare1648 lamport: lam,
1649 seq,
1650 k: first - this.#lineBase[seq]!,
1651 }),
1652 first,
1653 );
codex-capacity-chair130Stream paged child history into layout filteringCompare1655 if (this.#runStartPages) this.#runStartPages.append(String(parent), first);
1656 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.Compare1657 const replacesParent = deletes(run.parent) ? 1 : 0;
1658 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.Compare1659 if (this.#crossings && parent >= 0) {
1660 const from = this.#lineFile.at(parent);
1661 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.Compare1663 const base = this.#lineBase[seq]!;
1664 this.#fileLines!.appendAll(
1665 String(file),
1666 run.lines.map(
1667 (_, i): PackedLine => [
1668 first + i,
1669 i === 0 ? parent : first + i - 1,
1670 seq,
1671 first + i - base,
1672 i === 0 ? replacesParent : 0,
1673 ],
1674 ),
1675 );
1676 this.#fileTexts!.appendAll(
1677 String(file),
1678 run.lines.map((text) => (typeof text === "string" && text.length <= PACKED_TEXT ? text : null)),
1679 );
init0Start the project1681 for (let i = 0; i < run.lines.length; i++) {
codex-capacity-chair109Add opt-in persistent writer state, checked reopen and bounded adoptionCompare1682 const n = this.#lineTotal;
codex-capacity-chair137Page explicit child counts with bounded corruption checksCompare1683 this.#childCounts?.append(n);
init0Start the project1684 this.#lineAtom.push(seq);
1685 this.#lineFile.push(file);
1686 this.#lineParent.push(parent);
1687 this.#lineText?.push(run.lines[i]!);
1688 this.#deleter.push(-1);
codex-capacity-chair162Add reviewed disk-first history and indexed graph storage for core issue 16; retain runtime activation gateCompare1689 this.#replacing.push(i === 0 && deletes(run.parent) ? 1 : 0);
init0Start the project1690 parent = n;
1693 (frozen.moves ?? []).forEach((m, i) => {
1694 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 readsCompare1695 if (this.#relocationPages) this.#relocationPages.append(m.line, info);
1696 else pushIndex(this.#relocations, m.line, info);
1697 if (this.#relocatedToPages) this.#relocatedToPages.append(m.parent, info);
1698 else pushIndex(this.#relocatedTo, m.parent, info);
1699 const parentCode = isStartNode(m.parent) ? -1 - this.#pathOf(m.parent.slice(1)) : this.#lineN(m.parent);
1700 if (this.#relocatedToCodePages) this.#relocatedToCodePages.append(String(parentCode), info);
1701 else pushIndex(this.#relocatedToCode, parentCode, info);
init0Start the project1702 });
1703 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.Compare1704 if (this.#packed)
1705 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 gateCompare1706 for (const key of writes) {
codex-capacity-chair120Page persistent claim indexes and stream dependency queriesCompare1707 const code = this.#code(key);
codex-capacity-chair162Add reviewed disk-first history and indexed graph storage for core issue 16; retain runtime activation gateCompare1708 if (this.#writersPages) {
1709 const key = JSON.stringify([typeof code, code]);
1710 if (this.#writersPages.last(key) !== frozen.id) this.#writersPages.append(key, frozen.id);
1711 } else pushOne(this.#writers, code, frozen.id);
codex-capacity-chair120Page persistent claim indexes and stream dependency queriesCompare1712 }
codex-capacity-chair162Add reviewed disk-first history and indexed graph storage for core issue 16; retain runtime activation gateCompare1713 for (const key of this.#storage ? atom.reads : new Set(atom.reads)) {
codex-capacity-chair120Page persistent claim indexes and stream dependency queriesCompare1714 const code = this.#code(key);
codex-capacity-chair162Add reviewed disk-first history and indexed graph storage for core issue 16; retain runtime activation gateCompare1715 if (this.#readersPages) {
1716 const key = JSON.stringify([typeof code, code]);
1717 if (this.#readersPages.last(key) !== frozen.id) this.#readersPages.append(key, frozen.id);
1718 } else pushOne(this.#readers, code, frozen.id);
codex-capacity-chair120Page persistent claim indexes and stream dependency queriesCompare1719 }
codex-capacity-chair162Add reviewed disk-first history and indexed graph storage for core issue 16; retain runtime activation gateCompare1720 for (const key of this.#storage ? atom.holds : new Set(atom.holds)) {
codex-capacity-chair120Page persistent claim indexes and stream dependency queriesCompare1721 const code = this.#code(key);
codex-capacity-chair162Add reviewed disk-first history and indexed graph storage for core issue 16; retain runtime activation gateCompare1722 if (this.#holdersPages) {
1723 const key = JSON.stringify([typeof code, code]);
1724 if (this.#holdersPages.last(key) !== frozen.id) this.#holdersPages.append(key, frozen.id);
1725 } else pushOne(this.#holders, code, frozen.id);
codex-capacity-chair122Page dependency and resolver indexes with streamed intersectionCompare1726 }
1727 for (const d of deps) {
1728 if (this.#dependentsPages) this.#dependentsPages.append(d, frozen.id);
1729 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 gateCompare1731 for (const r of this.#storage ? frozen.resolves : new Set(frozen.resolves)) {
1732 if (this.#resolversPages) {
1733 if (this.#resolversPages.last(r) !== frozen.id) this.#resolversPages.append(r, frozen.id);
1734 } else pushOne(this.#resolvers, r, frozen.id);
init0Start the project1735 }
1736 const files = new Set<string>();
1737 for (const run of atom.inserts) files.add(run.file);
capacity240Path names kept in memory once read (disk-first 2; abso Capacity). After 239, collisions on website spent most of its 4.6 s naming files: finding a deleted line's file ends at a file's start node, and Graph.#nodeName read the stored path list for it every time, through the row cache. Line records, line files and an atom's files read it the same way. Graph.#pathName keeps path names by index in memory, up to 4,096, and clears them whenever the graph accepts an atom, so a name a rolled-back add made never stays. On website adopted fresh, cold, one opened writer: collisions 4.6 s to 1.6 s (replay 0.4 s), matching replay. typescript-rs: all 27 answers match. Named tests: every engine test (290 of 290), every worker/project test (341 of 341); tsc and biome clean.Compare1738 for (const n of deletedNumbers(this)) files.add(this.#pathName(this.#lineFile.at(n)));
init0Start the project1739 for (const a of frozen.attrs ?? []) files.add(a.file);
1740 for (const m of frozen.moves ?? []) {
1741 files.add(this.lineFile(m.line)!);
1742 files.add(isStartNode(m.parent) ? m.parent.slice(1) : this.lineFile(m.parent)!);
1744 this.#atomFiles.push(Object.freeze([...files].sort()));
codex-capacity-chair119Page per-file atom indexes and stream current-view attribute scansCompare1745 for (const file of files) {
1746 if (this.#fileAtomPages) this.#fileAtomPages.append(file, frozen.id);
1747 else pushIndex(this.#fileAtoms, file, frozen.id);
capacity242why: reasons pointing at a change indexed, and a moved line looked for among its push (disk-first 2; abso Capacity). why on abso, warm, one kept reader: 2.9 s a call with about 24,000 reads, 20,000 of them atoms. - Reasons in: why listed the changes whose reasons point at the line's change by reading every atom in the project. The graph now keeps, for each atom, the atoms whose reasons point at it, in seq order, once each (reasons-in, Graph.reasonsTo), from a fresh stored graph on. A graph made before keeps none, reasonsTo says undefined, and why looks at every atom as before. - Moved from: the trail looked for a deleted copy of a line's text among every atom within 5,000 of the change. Only atoms pushed with it can count, so where the change is published its version's atoms are the candidates (Project.versionAtoms, trail's pushmates). A change still in a draft goes with every other draft change, so it looks near by as before. - trail takes atoms' numbers from their ids instead of reading each atom. On abso adopted fresh: why 244 ms on the first call, then 86 and 46 ms (was 2.9 s); 1,091 reads, then 469 and 73. It matches replay, which takes 951 ms. Heap after: 22.6 MB. New test reasons-to: the atoms pointing at an atom, in seq order, once each, whatever the kind and however many reasons one gives, in memory and stored. A stored graph without the index says undefined. Every engine test (292 of 292), every worker/project test (341 of 341); tsc and biome clean.Compare1748 }
1749 if (this.#reasonsInKept) {
1750 const pointed = new Set<AtomId>();
1751 for (const r of frozen.reasons) {
1752 if (pointed.has(r.to)) continue;
1753 pointed.add(r.to);
1754 if (this.#reasonsInPages) this.#reasonsInPages.append(r.to, frozen.id);
1755 else pushIndex(this.#reasonsIn, r.to, frozen.id);
codex-capacity-chair119Page per-file atom indexes and stream current-view attribute scansCompare1757 }
init0Start the project1758 for (const r of frozen.reasons) {
1759 if (r.kind !== "together" || r.to === frozen.id) continue;
codex-capacity-chair129Page together relationship history for bounded traversalCompare1760
1761 const forward = { other: r.to, text: r.text, from: frozen.id };
1762 const reverse = { other: frozen.id, text: r.text, from: frozen.id };
1763 if (this.#togetherPages) {
1764 this.#togetherPages.append(frozen.id, forward);
1765 this.#togetherPages.append(r.to, reverse);
1766 } else {
1767 pushIndex(this.#together, frozen.id, forward);
1768 pushIndex(this.#together, r.to, reverse);
init0Start the project1770 }
1773 // Labels -----------------------------------------------------------------
1775 /**
1776 * Add or replace a label. Label names may not look like atom ids. A base is
1777 * resolved to its head only when it is used, never followed further, so
1778 * bases may name each other in any shape.
1779 */
1780 setLabel(label: Label): void {
1781 this.#putLabel(label, (name) => this.#labels.has(name));
1784 #putLabel(label: Label, isLabel: (name: string) => boolean): void {
1785 const bad = (why: string): never => {
1786 throw new EngineError("bad-label", `label ${JSON.stringify(label?.name)}: ${why}`);
1787 };
1788 if (typeof label !== "object" || label === null) bad("not an object");
1789 if (typeof label.name !== "string" || label.name === "") bad("needs a name");
1790 if (isAtomId(label.name)) bad("a label name may not look like an atom id");
1791 if (!this.has(label.head)) bad(`head ${label.head} is not in the graph`);
1792 if (
1793 label.base !== undefined &&
1794 !(typeof label.base === "string" && (isLabel(label.base) || this.has(label.base)))
1795 ) {
1796 bad(`base ${label.base} is neither a label nor an atom`);
1798 if (label.base === label.name) bad("a label cannot be its own base");
1799 if (typeof label.title !== "string" || typeof label.message !== "string") bad("needs a title and message");
1800 if (label.follows !== undefined && !Array.isArray(label.follows)) bad("follows must be a list of label names");
1801 const copy: Label = {
1802 name: label.name,
1803 head: label.head,
1804 ...(label.base !== undefined ? { base: label.base } : {}),
1805 title: label.title,
1806 message: label.message,
1807 ...(label.follows !== undefined ? { follows: Object.freeze([...label.follows]) } : {}),
1808 };
1809 this.#labels.set(label.name, Object.freeze(copy));
1812 label(name: string): Label | undefined {
1813 return this.#labels.get(name);
1816 /** Labels sorted by name. */
1817 labels(): Label[] {
1818 return [...this.#labels.values()].sort((a, b) => (a.name < b.name ? -1 : a.name > b.name ? 1 : 0));
1821 /**
1822 * Remove a label. Labels that used it as their base get its head atom as
1823 * their base instead, so their contents don't change.
1824 */
1825 removeLabel(name: string): boolean {
codex-capacity-chair109Add opt-in persistent writer state, checked reopen and bounded adoptionCompare1826 return this.#storage ? this.#storage.transaction(() => this.#removeLabel(name)) : this.#removeLabel(name);
1829 #removeLabel(name: string): boolean {
init0Start the project1830 const gone = this.#labels.get(name);
1831 if (!gone) return false;
1832 this.#labels.delete(name);
1833 for (const label of [...this.#labels.values()]) {
1834 if (label.base === name) this.#labels.set(label.name, Object.freeze({ ...label, base: gone.head }));
1836 return true;
1839 // JSON -------------------------------------------------------------------
1841 toJSON(): GraphJSON {
1842 return { format: GRAPH_FORMAT, version: 1, atoms: this.#atoms, labels: this.labels() };
1845 /** Load a saved graph. Every atom is re-validated as it is added. */
1846 static fromJSON(data: unknown): Graph {
1847 const bad = (why: string): never => {
1848 throw new EngineError("bad-json", why);
1849 };
1850 if (typeof data !== "object" || data === null) bad("graph JSON must be an object");
1851 const obj = data as Partial<GraphJSON>;
1852 if (obj.format !== GRAPH_FORMAT) bad(`format must be ${GRAPH_FORMAT}`);
1853 if (obj.version !== 1) bad(`unsupported version ${String(obj.version)}`);
1854 if (!Array.isArray(obj.atoms) || !Array.isArray(obj.labels)) bad("atoms and labels must be arrays");
1855 const graph = new Graph();
1856 for (const atom of obj.atoms!) graph.add(atom);
1857 // Labels may name each other as bases, in any order and any shape.
1858 const names = new Set<string>();
1859 for (const label of obj.labels!) {
1860 const name: unknown = (label as Partial<Label> | null)?.name;
1861 if (typeof name !== "string") return bad("every label needs a name");
1862 if (names.has(name)) bad(`label ${name} appears twice`);
1863 names.add(name);
1865 for (const label of obj.labels!) {
1866 try {
1867 graph.#putLabel(label, (name) => names.has(name));
1868 } catch (err) {
1869 if (err instanceof EngineError) bad(err.message);
1870 throw err;
1873 return graph;
1876 #seq(id: AtomId): number {
1877 return typeof id === "string" ? seqOf(id) : -1;
1881function validateShape(atom: Atom): void {
1882 const bad = (why: string): never => {
1883 throw new EngineError("bad-atom", `atom ${String((atom as { id?: unknown }).id)}: ${why}`);
1884 };
1885 if (typeof atom !== "object" || atom === null) bad("not an object");
1886 if (typeof atom.id !== "string" || !Number.isInteger(atom.seq)) bad("needs id and seq");
1887 if (typeof atom.author !== "string" || typeof atom.message !== "string") bad("needs author and message");
1888 if (typeof atom.time !== "number" || !Number.isFinite(atom.time)) bad("time must be a finite number");
1889 const lists = ["inserts", "deletes", "writes", "reads", "holds", "needs", "resolves", "reasons", "deps"] as const;
1890 for (const name of lists) if (!Array.isArray(atom[name])) bad(`${name} must be an array`);
1891 for (const run of atom.inserts as readonly InsertRun[]) {
1892 if (typeof run.file !== "string" || run.file === "" || run.file.includes("\n")) bad("a run needs a file path");
1893 if (typeof run.parent !== "string") bad("a run needs a parent");
1894 if (!Array.isArray(run.lines) || run.lines.length === 0) bad("a run needs at least one line");
1895 for (const text of run.lines) {
1896 if (typeof text !== "string" || text.includes("\n") || text.includes("\r"))
1897 bad("run lines must be strings without line breaks");
1900 if (atom.attrs !== undefined) {
1901 if (!Array.isArray(atom.attrs)) bad("attrs must be an array");
1902 for (const a of atom.attrs) {
1903 if (typeof a?.file !== "string" || a.file === "" || a.file.includes("\n") || !ATTR_NAMES.includes(a.name))
1904 bad("an attr needs a file and a name");
1905 if (a.value !== null && typeof a.value !== "string") bad("an attr value is a string or null");
1906 if (!atom.writes.includes(attrKey(a.file, a.name))) bad(`sets ${a.name} of ${a.file} without writing its key`);
1909 if (atom.moves !== undefined) {
1910 if (!Array.isArray(atom.moves) || atom.moves.length === 0) bad("moves must be a non-empty array");
1911 for (const m of atom.moves) {
1912 if (typeof m?.line !== "string" || typeof m.parent !== "string") bad("a move needs a line and a parent");
1915 for (const name of ["deletes", "writes", "reads", "holds", "needs", "resolves", "deps"] as const) {
1916 for (const x of atom[name]) if (typeof x !== "string") bad(`${name} must hold strings`);
1918 for (const r of atom.reasons as readonly Reason[]) {
1919 if (typeof r.to !== "string" || typeof r.text !== "string" || !REASON_KINDS.includes(r.kind)) {
1920 bad("a reason needs to, kind (together, because-of or supersedes) and text");
1925/**
1926 * A frozen copy of an atom. An empty list is one shared frozen list, and atom
1927 * ids and authors are the graph's own strings (`canon`, `author`), so each is
1928 * kept once however often it's named (#46).
1929 */
1930function freezeAtom(
1931 atom: Atom,
1932 canon: (id: AtomId) => AtomId,
1933 author: (name: string) => string,
1934 text?: (start: number, length: number) => readonly string[],
1935 lists?: () => AtomLists,
1936): Atom {
1937 const list = <T>(xs: readonly T[], f?: (x: T) => T): readonly T[] =>
1938 xs.length === 0 ? EMPTY : Object.freeze(f ? xs.map(f) : [...xs]);
1939 // With text kept elsewhere (#46), a run's lines are read when asked for.
1940 let k = 0;
1941 const run = (r: InsertRun): InsertRun => {
1942 if (!text) return Object.freeze({ file: r.file, parent: r.parent, lines: Object.freeze([...r.lines]) });
1943 const start = k;
1944 const length = r.lines.length;
1945 k += length;
1946 return Object.freeze(new LazyRun(r.file, r.parent, text, start, length));
1947 };
1948 const copy: Atom = {
1949 id: atom.id,
1950 seq: atom.seq,
1951 author: author(atom.author),
1952 message: atom.message,
1953 time: atom.time,
1954 inserts: Object.freeze(atom.inserts.map(run)),
1955 ...(lists
1956 ? {}
1957 : { deletes: list(atom.deletes), writes: list(atom.writes), reads: list(atom.reads), holds: list(atom.holds) }),
1958 needs: list(atom.needs, canon),
1959 resolves: list(atom.resolves, canon),
1960 reasons: list(atom.reasons, (r) => Object.freeze({ to: canon(r.to), kind: r.kind, text: r.text })),
1961 deps: list(atom.deps, canon),
1962 ...(atom.attrs && atom.attrs.length > 0
1963 ? { attrs: Object.freeze(atom.attrs.map((a) => Object.freeze({ file: a.file, name: a.name, value: a.value }))) }
1964 : {}),
1965 ...(atom.moves
1966 ? { moves: Object.freeze(atom.moves.map((m) => Object.freeze({ line: m.line, parent: m.parent }))) }
1967 : {}),
1968 } as Atom;
1969 return Object.freeze(lists ? (new ListedAtom(copy, lists) as unknown as Atom) : copy);