- MCP
- blame on this site's /mcp
- CLI
- abso blame src/engine/view.ts --version 211 --json
- JSON
- /christopher/abso-core/blame/src/engine/view.ts?version=211&format=json
943 linesFirst import 45% · codex-capacity-chair 28% · capacity 22% · codex-capacity-policy 5%Last change capacity in version 207,
943 lines from 25 changes in 22 versions.
init0Start the project1// Projection: the files a closed set of atoms produces. A pure function of the
2// set. Each file is a tree of lines hanging off its start node; linearizing it
3// depth-first, children in descending priority, gives the file's sequence. A
4// line hangs off the node it was written after, unless a move in the set gave
5// it another parent (#28): then the newest such move decides.
6//
7// A laid-out file is kept as arrays of line numbers (the graph's n), not as a
8// record per line (#46): a record, its id and two index entries cost about
9// 370 bytes a line, and the view cache holds up to 200,000 lines. Records are
10// made when a caller asks for them, and the latest asked for is kept.
12import type { Graph, RelocationInfo } from "./graph.ts";
13import { isStartNode } from "./keys.ts";
codex-capacity-chair132Bound persistent relocation projection memory with rollback-only scratchCompare14import { resolveScratchMoves, scratchLayoutNodes } from "./relocation-scratch.ts";
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.Compare15import { isClosedSet, StableSet } from "./state-source.ts";
17import { type AtomId, type AtomSet, EngineError, type LineId, type NodeId } from "./types.ts";
19/** A line in a file's full sequence, tombstones included. */
20export interface SeqLine {
21 readonly id: LineId;
22 readonly text: string;
23 /** The atom that wrote it. */
24 readonly atom: AtomId;
25 /** Atoms in the set that delete it, by seq. Empty when it is visible. */
26 readonly deletedBy: readonly AtomId[];
27 readonly visible: boolean;
28}
30/** A visible line of a projected file. */
31export interface VisibleLine {
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.Compare32 readonly textChunks?: () => Iterable<string>;
34 readonly text: string;
35 readonly atom: AtomId;
36}
38/** A file's attributes in a view. */
39export interface FileAttrs {
40 /** Kept with no lines (an empty file). */
41 readonly exists: boolean;
42 readonly exec: boolean;
43 /** The target, when the file is a symbolic link. */
44 readonly link: string | null;
45 /** The SHA-256 of its bytes, when the file is binary. */
46 readonly blob: string | null;
47}
codex-capacity-chair143Add inactive disk projection provider and verified transactional readers (#16)Compare49/** Structural read boundary shared by historical and transaction-bound projections. */
capacity207Each shared version's changed files kept as it lands (disk-first 2; abso Capacity, version-files.ts). A version's files are decided from what it touched: visible lines in and out per file, their texts' balance, a running count of each file's visible lines for made and taken out, and mode and blob; a version with moves, drops or a closure change, or whose lines in and out have the same texts, is laid out as before. Views of consecutive versions share resolved moves and where lines sit (View.shareMoves). PathIndex.keep records them, into the shapes table when the host gives one. version-files.test.ts checks log, path logs and every show against the in-memory project through edits, new and removed files, same text put back, a move and a drop. On game's export all 27 harness answers now match Project.load: the log 70 ms (was over 30 s), a path's history 0.56 s (was over 30 s), the tree 3.1-3.4 s (was over 30 s); adoption about 85 s; heap 14.4 MB at most.Compare50export type ReadView = Omit<Pick<View, keyof View>, "sameText" | "visibleCount" | "shareMoves"> & {
codex-capacity-chair143Add inactive disk projection provider and verified transactional readers (#16)Compare51 sameText(path: string, other: ReadView): boolean;
52};
init0Start the project54const NO_ATTRS: FileAttrs = { exists: false, exec: false, link: null, blob: null };
55const NONE: readonly never[] = Object.freeze([]);
57interface FileState {
58 readonly attrs: FileAttrs;
codex-capacity-chair110Keep current-file views and key scans from retaining historical stateCompare59 /** Full history is retained only when a sequence caller explicitly requests it. */
60 readonly complete: boolean;
62 readonly seq: Int32Array;
63 /** Its visible lines' n, in order. */
64 readonly vis: Int32Array;
65 /** For each deleted position in seq: the seqs of the atoms in the set that delete it, by priority. */
66 readonly deletedBy: ReadonlyMap<number, readonly number[]>;
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.Compare67 /** Its visible lines' text, when laid out from the file's packed history: null for a line too long to pack. */
68 readonly visText?: readonly (string | null)[];
70 seqIndex?: Map<number, number>;
71 visIndex?: Map<number, number>;
72}
74interface Child {
75 readonly n: number;
76 /** 1 when the child's atom deleted the parent (the child replaces it), else 0. A moved line is 0. */
77 readonly replaces: number;
78 readonly lamport: number;
79 readonly seq: number;
80 readonly k: number;
81}
83const EMPTY_INTS = new Int32Array(0);
codex-capacity-chair110Keep current-file views and key scans from retaining historical stateCompare84const NO_FILE: FileState = { attrs: NO_ATTRS, complete: true, seq: EMPTY_INTS, vis: EMPTY_INTS, deletedBy: new Map() };
codex-capacity-policy103Test deterministic replay and account view cache weightCompare86// Approximate retained-container costs for View.weight(): reference slots,
87// object headers, and map/set entries. These are cache-budget units, not V8
88// heap measurements. Referenced Graph strings and records are not charged.
89const ARRAY_HEADER_BYTES = 24;
90const OBJECT_BYTES = 32;
91const MAP_HEADER_BYTES = 32;
92const MAP_ENTRY_BYTES = 40;
93const SET_ENTRY_BYTES = 32;
94const REFERENCE_BYTES = 8;
codex-capacity-chair125Bound file-location ancestry scratch and memoCompare95const FILE_LOCATION_MEMO_ENTRIES = 256;
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.Compare96/**
97 * Moved lines a view resolves once and keeps (abso Capacity): a stored graph otherwise resolved every move again on
98 * disk for each file it laid out. Game's whole history has 290; past this many, the view goes back to that.
99 */
100export const MOVED_LINES_KEPT = 20_000;
101class TooManyMoves extends Error {}
102const NO_LINES: readonly number[] = Object.freeze([]);
capacity207Each shared version's changed files kept as it lands (disk-first 2; abso Capacity, version-files.ts). A version's files are decided from what it touched: visible lines in and out per file, their texts' balance, a running count of each file's visible lines for made and taken out, and mode and blob; a version with moves, drops or a closure change, or whose lines in and out have the same texts, is laid out as before. Views of consecutive versions share resolved moves and where lines sit (View.shareMoves). PathIndex.keep records them, into the shapes table when the host gives one. version-files.test.ts checks log, path logs and every show against the in-memory project through edits, new and removed files, same text put back, a move and a drop. On game's export all 27 harness answers now match Project.load: the log 70 ms (was over 30 s), a path's history 0.56 s (was over 30 s), the tree 3.1-3.4 s (was over 30 s); adoption about 85 s; heap 14.4 MB at most.Compare103/** Lines whose place views sharing moves remember, at most: about 40 bytes each. */
104const SHARED_FILE_MEMO = 200_000;
107 * The projection of a closed set. Construct once, then ask for files, lines
108 * and sequences. Throws `not-closed` if some atom's dependency is missing.
109 * Each file is laid out the first time it is asked for, so a view of a large
110 * set costs little until files are read.
111 */
112export class View {
113 readonly graph: Graph;
114 /** The set, made from #in the first time it's asked for: a view keeps a byte per atom, not a copy of the set (#46). */
codex-capacity-chair109Add opt-in persistent writer state, checked reopen and bounded adoptionCompare115 #set: AtomSet | undefined;
116 readonly #stable: StableSet<AtomId> | undefined;
codex-capacity-chair116Bound repeated indexed view membership lookupsCompare117 /** Fixed-size memo for immutable indexed membership, independent of history size. */
118 #membershipSeq = new Float64Array(256).fill(-1);
119 #membershipValue = new Uint8Array(256);
121 /** Every file the set wrote in, sorted; worked out the first time it's asked for. */
122 #knownList: string[] | undefined;
123 /** 1 for each atom (by seq) in the set. */
124 #in: Uint8Array;
125 /** Atoms in the set that move lines. */
codex-capacity-chair123Stream mover history when opening persisted viewsCompare126 #movers: AtomId[] | undefined;
127 #hasMoves = false;
init0Start the project128 /** Each moved line's relocation that counts in this set; built on first use. */
129 #relocs: Map<LineId, RelocationInfo> | undefined;
130 /** The same, by n, with the new parent's code. */
131 #relocsN: Map<number, { readonly r: RelocationInfo; readonly parent: number }> | undefined;
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.Compare132 /** The moved lines under each node, by its code, made from the relocations on first use. */
133 #movedInto: Map<number, number[]> | undefined;
134 /** Whether this view's moves are too many to keep, so they're resolved on disk per layout; undefined until asked. */
135 #movesOnDisk: boolean | undefined;
codex-capacity-chair125Bound file-location ancestry scratch and memoCompare136 /** Bounded memo: ancestry can span the entire history even for one visible line. */
138 /** The latest records asked for: one file's lines, one file's sequence, one file's text. */
139 #linesCache: { path: string; lines: readonly VisibleLine[] } | undefined;
140 #seqCache: { path: string; seq: readonly SeqLine[] } | undefined;
141 #textCache: { path: string; text: string } | undefined;
143 constructor(graph: Graph, set: Iterable<AtomId>) {
codex-capacity-chair109Add opt-in persistent writer state, checked reopen and bounded adoptionCompare144 this.graph = graph;
145 if (set instanceof StableSet) {
146 this.#stable = set;
147 this.#set = set;
148 this.#in = new Uint8Array(0);
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.Compare149 // A set kept closed when it was written needs no proof here (abso Capacity).
150 for (const id of isClosedSet(set) ? [] : set) {
codex-capacity-chair109Add opt-in persistent writer state, checked reopen and bounded adoptionCompare151 const atom = graph.atom(id);
152 for (const dependency of atom.deps) {
153 graph.atom(dependency);
154 if (!set.has(dependency))
155 throw new EngineError("not-closed", `set is not closed: ${id} depends on ${dependency}`);
156 }
157 }
codex-capacity-chair123Stream mover history when opening persisted viewsCompare158 for (const id of graph.movers()) {
159 if (set.has(id)) {
160 this.#hasMoves = true;
161 break;
162 }
163 }
164 this.#relocs = this.#hasMoves ? undefined : new Map();
165 this.#relocsN = this.#hasMoves ? undefined : new Map();
codex-capacity-chair109Add opt-in persistent writer state, checked reopen and bounded adoptionCompare166 return;
167 }
169 for (const id of set) {
170 const atom = graph.atom(id);
171 inSet[atom.seq] = 1;
172 }
codex-capacity-chair109Add opt-in persistent writer state, checked reopen and bounded adoptionCompare173 // Validate one atom at a time. Keeping all decoded atoms here defeats
174 // storage-backed Graph reads even though the view only needs membership.
175 for (let seq = 0; seq < inSet.length; seq++) {
176 if (inSet[seq] !== 1) continue;
177 const atom = graph.atom(graph.idOfSeq(seq));
179 if (inSet[graph.atom(d).seq] !== 1)
180 throw new EngineError("not-closed", `set is not closed: ${atom.id} depends on ${d}`);
181 }
182 }
183 this.graph = graph;
184 this.#in = inSet;
185 this.#movers = graph.movers().filter((id) => inSet[graph.atom(id).seq] === 1);
codex-capacity-chair123Stream mover history when opening persisted viewsCompare186 this.#hasMoves = this.#movers.length > 0;
188 this.#relocsN = this.#movers.length === 0 ? new Map() : undefined;
189 }
191 /** The set of atoms this view projects. */
192 get set(): AtomSet {
193 if (!this.#set) {
194 const out = new Set<AtomId>();
195 for (let seq = 0; seq < this.#in.length; seq++) if (this.#in[seq] === 1) out.add(this.graph.idOfSeq(seq));
196 this.#set = out;
197 }
198 return this.#set;
199 }
201 /** Whether the atom with this seq is in the set. */
202 #has(seq: number): boolean {
204 const slot = seq % this.#membershipSeq.length;
205 if (this.#membershipSeq[slot] === seq) return this.#membershipValue[slot] === 1;
206 const present = this.#stable.has(this.graph.idOfSeq(seq));
207 this.#membershipSeq[slot] = seq;
208 this.#membershipValue[slot] = present ? 1 : 0;
209 return present;
210 }
212 }
214 /**
215 * The relocation that counts for each moved line: the newest (by priority)
216 * in the set. Two moves made apart can loop lines into each other, so no
217 * start node reaches them; then the oldest relocation on the loop is
218 * ignored, and the next newest of that line counts, until none loop.
219 */
220 #relocations(): Map<LineId, RelocationInfo> {
221 if (this.#relocs) return this.#relocs;
222 const graph = this.graph;
223 const stronger = (a: RelocationInfo, b: RelocationInfo): boolean => graph.comparePriority(a.atom, b.atom) > 0;
codex-capacity-chair126Identify suppressed relocation cycles across persistent readsCompare224 // Persistent reads decode new objects. Cycle suppression must identify the
225 // logical move, not one particular decoded JavaScript object.
226 const identity = (r: RelocationInfo): string => JSON.stringify([r.atom, r.k]);
227 const ignored = new Set<string>();
229 let best: RelocationInfo | undefined;
codex-capacity-chair127Page persistent relocation indexes and stream projection readsCompare230 for (const r of graph.eachRelocationOf(line)) {
codex-capacity-chair126Identify suppressed relocation cycles across persistent readsCompare231 if (this.#has(graph.atom(r.atom).seq) && !ignored.has(identity(r)) && (!best || stronger(r, best))) best = r;
233 return best;
234 };
235 const relocs = new Map<LineId, RelocationInfo>();
codex-capacity-chair123Stream mover history when opening persisted viewsCompare236 for (const id of this.#eachMover()) {
238 if (!relocs.has(m.line)) relocs.set(m.line, pick(m.line)!);
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.Compare239 if (graph.hasOrderedChildren && relocs.size > MOVED_LINES_KEPT) throw new TooManyMoves();
241 }
242 const parentOf = (line: LineId): NodeId => relocs.get(line)?.parent ?? graph.lineParent(line)!;
243 const reaches = new Set<LineId>();
244 for (const line of [...relocs.keys()]) {
245 for (;;) {
246 const path: LineId[] = [];
247 const onPath = new Map<LineId, number>();
248 let cur: NodeId = line;
249 let loopAt = -1;
250 while (!isStartNode(cur) && !reaches.has(cur)) {
251 const at = onPath.get(cur);
252 if (at !== undefined) {
253 loopAt = at;
254 break;
255 }
256 onPath.set(cur, path.length);
257 path.push(cur);
258 cur = parentOf(cur);
259 }
260 if (loopAt < 0) {
261 for (const l of path) reaches.add(l);
262 break;
263 }
264 let weakest: RelocationInfo | undefined;
265 for (const l of path.slice(loopAt)) {
266 const r = relocs.get(l);
267 if (r && (!weakest || stronger(weakest, r))) weakest = r;
268 }
codex-capacity-chair126Identify suppressed relocation cycles across persistent readsCompare269 ignored.add(identity(weakest!));
271 if (next) relocs.set(weakest!.line, next);
272 else relocs.delete(weakest!.line);
273 }
274 }
275 this.#relocs = relocs;
276 return relocs;
277 }
capacity207Each shared version's changed files kept as it lands (disk-first 2; abso Capacity, version-files.ts). A version's files are decided from what it touched: visible lines in and out per file, their texts' balance, a running count of each file's visible lines for made and taken out, and mode and blob; a version with moves, drops or a closure change, or whose lines in and out have the same texts, is laid out as before. Views of consecutive versions share resolved moves and where lines sit (View.shareMoves). PathIndex.keep records them, into the shapes table when the host gives one. version-files.test.ts checks log, path logs and every show against the in-memory project through edits, new and removed files, same text put back, a move and a drop. On game's export all 27 harness answers now match Project.load: the log 70 ms (was over 30 s), a path's history 0.56 s (was over 30 s), the tree 3.1-3.4 s (was over 30 s); adoption about 85 s; heap 14.4 MB at most.Compare279 /** Where lines sit, shared with views that took this one's moves (shareMoves): unbounded up to SHARED_FILE_MEMO. */
280 #fileOfShared: Map<number, string> | undefined;
282 /**
283 * Take another view's resolved moves (abso Capacity). Only for a set that differs from that view's by atoms that
284 * move nothing, drop nothing and change no closure: its moves resolve the same, and every line it shares with that
285 * view sits where it sat there.
286 */
287 shareMoves(from: View): void {
288 if (from.graph !== this.graph || from.#hasMoves !== this.#hasMoves || !this.#hasMoves) return;
289 if (from.#scratchMoves()) return;
290 this.#relocs = from.#relocations();
291 this.#relocsN = from.#relocationsN();
292 this.#movesOnDisk = false;
293 this.#movedFrom = from.#movedInFrom();
294 from.#fileOfShared ??= new Map();
295 this.#fileOfShared = from.#fileOfShared;
296 }
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.Compare298 /** Whether moves are resolved on disk for each layout: only a stored graph's view with more than MOVED_LINES_KEPT. */
299 #scratchMoves(): boolean {
300 if (!this.#hasMoves || !this.graph.hasOrderedChildren) return false;
301 if (this.#movesOnDisk === undefined) {
302 try {
303 this.#relocations();
304 this.#movesOnDisk = false;
305 } catch (error) {
306 if (!(error instanceof TooManyMoves)) throw error;
307 this.#movesOnDisk = true;
308 }
309 }
310 return this.#movesOnDisk;
311 }
314 #relocationsN(): Map<number, { readonly r: RelocationInfo; readonly parent: number }> {
315 if (this.#relocsN) return this.#relocsN;
316 const out = new Map<number, { readonly r: RelocationInfo; readonly parent: number }>();
317 for (const [line, r] of this.#relocations())
318 out.set(this.graph.lineN(line), { r, parent: this.graph.codeOf(r.parent)! });
319 this.#relocsN = out;
320 return out;
321 }
323 /** The node a line hangs off in this set: where it was written, or where a move put it. */
324 parentOf(line: LineId): NodeId {
codex-capacity-chair132Bound persistent relocation projection memory with rollback-only scratchCompare325 if (this.graph.lineParent(line) === undefined) throw new EngineError("unknown-line", `no line ${line}`);
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.Compare326 if (this.#scratchMoves())
codex-capacity-chair132Bound persistent relocation projection memory with rollback-only scratchCompare327 return this.graph.withProjectionScratch((scratch) =>
328 resolveScratchMoves(this.graph, (id) => this.#has(this.graph.atom(id).seq), scratch).parent(line),
329 );
codex-capacity-chair123Stream mover history when opening persisted viewsCompare330 const r = this.#hasMoves ? this.#relocations().get(line) : undefined;
332 const parent = this.graph.lineParent(line);
333 if (parent === undefined) throw new EngineError("unknown-line", `no line ${line}`);
334 return parent;
335 }
337 /** Whether any atom in the set moves lines. */
338 hasMoves(): boolean {
codex-capacity-chair123Stream mover history when opening persisted viewsCompare339 return this.#hasMoves;
340 }
341 *#eachMover(): IterableIterator<AtomId> {
342 if (this.#movers) yield* this.#movers;
343 else for (const id of this.graph.movers()) if (this.#stable!.has(id)) yield id;
346 /** The file a line is in, in this set: the one its chain of parents reaches. */
347 fileOf(line: LineId): string {
348 const n = this.graph.lineN(line);
349 if (n < 0) throw new EngineError("unknown-line", `no line ${line}`);
350 return this.#fileOfN(n);
351 }
353 #fileOfN(n: number): string {
354 const graph = this.graph;
codex-capacity-chair123Stream mover history when opening persisted viewsCompare355 if (!this.#hasMoves) return graph.writtenIn(n);
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.Compare356 if (this.#scratchMoves())
codex-capacity-chair132Bound persistent relocation projection memory with rollback-only scratchCompare357 return graph.withProjectionScratch((scratch) => {
358 const moves = resolveScratchMoves(graph, (id) => this.#has(graph.atom(id).seq), scratch);
359 let current = graph.nodeOf(n);
360 while (!isStartNode(current)) current = moves.parent(current);
361 return current.slice(1);
362 });
codex-capacity-chair125Bound file-location ancestry scratch and memoCompare364 // Keep only a fixed tail of the walk for path compression. The selected
365 // relocation graph is acyclic, so traversal needs no history-sized stack.
369 let file: string | undefined;
370 while (file === undefined) {
371 if (cur < 0) file = graph.nodeOf(cur).slice(1);
372 else {
capacity207Each shared version's changed files kept as it lands (disk-first 2; abso Capacity, version-files.ts). A version's files are decided from what it touched: visible lines in and out per file, their texts' balance, a running count of each file's visible lines for made and taken out, and mode and blob; a version with moves, drops or a closure change, or whose lines in and out have the same texts, is laid out as before. Views of consecutive versions share resolved moves and where lines sit (View.shareMoves). PathIndex.keep records them, into the shapes table when the host gives one. version-files.test.ts checks log, path logs and every show against the in-memory project through edits, new and removed files, same text put back, a move and a drop. On game's export all 27 harness answers now match Project.load: the log 70 ms (was over 30 s), a path's history 0.56 s (was over 30 s), the tree 3.1-3.4 s (was over 30 s); adoption about 85 s; heap 14.4 MB at most.Compare373 file = (this.#fileOfShared ?? this.#fileOf).get(cur);
capacity207Each shared version's changed files kept as it lands (disk-first 2; abso Capacity, version-files.ts). A version's files are decided from what it touched: visible lines in and out per file, their texts' balance, a running count of each file's visible lines for made and taken out, and mode and blob; a version with moves, drops or a closure change, or whose lines in and out have the same texts, is laid out as before. Views of consecutive versions share resolved moves and where lines sit (View.shareMoves). PathIndex.keep records them, into the shapes table when the host gives one. version-files.test.ts checks log, path logs and every show against the in-memory project through edits, new and removed files, same text put back, a move and a drop. On game's export all 27 harness answers now match Project.load: the log 70 ms (was over 30 s), a path's history 0.56 s (was over 30 s), the tree 3.1-3.4 s (was over 30 s); adoption about 85 s; heap 14.4 MB at most.Compare375 if (this.#fileOfShared) path.push(cur);
376 else path[visited++ % FILE_LOCATION_MEMO_ENTRIES] = cur;
378 }
379 }
capacity207Each shared version's changed files kept as it lands (disk-first 2; abso Capacity, version-files.ts). A version's files are decided from what it touched: visible lines in and out per file, their texts' balance, a running count of each file's visible lines for made and taken out, and mode and blob; a version with moves, drops or a closure change, or whose lines in and out have the same texts, is laid out as before. Views of consecutive versions share resolved moves and where lines sit (View.shareMoves). PathIndex.keep records them, into the shapes table when the host gives one. version-files.test.ts checks log, path logs and every show against the in-memory project through edits, new and removed files, same text put back, a move and a drop. On game's export all 27 harness answers now match Project.load: the log 70 ms (was over 30 s), a path's history 0.56 s (was over 30 s), the tree 3.1-3.4 s (was over 30 s); adoption about 85 s; heap 14.4 MB at most.Compare380 }
381 const shared = this.#fileOfShared;
382 if (shared) {
383 if (shared.size > SHARED_FILE_MEMO) shared.clear();
384 for (const l of path) shared.set(l, file);
385 return file;
387 for (const l of path) {
388 if (!this.#fileOf.has(l) && this.#fileOf.size >= FILE_LOCATION_MEMO_ENTRIES)
389 this.#fileOf.delete(this.#fileOf.keys().next().value!);
390 this.#fileOf.set(l, file);
392 return file;
393 }
395 /** The lines hanging off a node in this set, in layout order. */
396 #children(code: number): Child[] {
397 const graph = this.graph;
codex-capacity-chair123Stream mover history when opening persisted viewsCompare398 const relocs = this.#hasMoves ? this.#relocationsN() : undefined;
codex-capacity-chair130Stream paged child history into layout filteringCompare400 for (const n of graph.eachChildN(code)) {
402 if (!this.#has(seq) || relocs?.has(n)) continue;
403 out.push({ n, replaces: graph.replacesN(n) ? 1 : 0, lamport: graph.lamportOfSeq(seq), seq, k: graph.kOf(n) });
404 }
405 if (relocs) {
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.Compare406 // The lines this set's moves put under each node, from the moves it already resolved: no row read per node
407 // (abso Capacity).
408 if (!this.#movedInto) {
409 this.#movedInto = new Map();
410 for (const [n, { parent }] of relocs) {
411 const into = this.#movedInto.get(parent);
412 if (into) into.push(n);
413 else this.#movedInto.set(parent, [n]);
414 }
415 }
416 for (const n of this.#movedInto.get(code) ?? NO_LINES) {
417 const r = relocs.get(n)!.r;
419 out.push({ n, replaces: 0, lamport: graph.lamportOfSeq(seq), seq, k: r.k });
420 }
421 }
422 // A line's replacements (runs of atoms that deleted it) first, then the
423 // rest; each group in descending priority (lamport, then seq); lines of
424 // one atom keep k order. A replacement already outranks every insertion
425 // after the line that reads it (it depends on them, or conflicts with
426 // them); the grouping also puts it above a `before` insertion, which
427 // doesn't read the line above, so the new text lands in the replaced
428 // line's place. A moved line ranks like an insertion by the moving atom.
429 if (out.length > 1)
430 out.sort((a, b) => b.replaces - a.replaces || b.lamport - a.lamport || b.seq - a.seq || a.k - b.k);
431 return out;
432 }
codex-capacity-chair131Bound persisted no-move layout with ordered successor traversalCompare434 /** Parent/successor traversal keeps no history-sized ancestry or sibling frontier. */
435 *#layoutNodes(start: number): IterableIterator<number> {
436 const graph = this.graph;
437 if (graph.hasOrderedChildren && !this.#hasMoves) {
438 const first = (parent: number, after?: number): number | undefined => {
439 for (const n of graph.orderedChildrenN(parent, after)) if (this.#has(graph.writerSeqOf(n))) return n;
440 return undefined;
441 };
442 let n = first(start);
443 while (n !== undefined) {
444 yield n;
445 const child = first(n);
446 if (child !== undefined) {
447 n = child;
448 continue;
449 }
450 let previous = n;
451 for (;;) {
452 const parent = graph.parentCodeOf(previous);
453 const sibling = first(parent, previous);
454 if (sibling !== undefined) {
455 n = sibling;
456 break;
457 }
458 if (parent === start) {
459 n = undefined;
460 break;
461 }
462 if (parent < 0 || parent >= previous) throw new Error("invalid persistent layout ancestry");
463 previous = parent;
464 }
465 }
466 return;
467 }
codex-capacity-chair131Bound persisted no-move layout with ordered successor traversalCompare469 const push = (parent: number): void => {
470 const children = this.#children(parent);
471 for (let i = children.length - 1; i >= 0; i--) stack.push(children[i]!.n);
472 };
473 push(start);
474 while (stack.length) {
475 const n = stack.pop()!;
476 yield n;
477 push(n);
478 }
479 }
codex-capacity-chair110Keep current-file views and key scans from retaining historical stateCompare482 #layout(path: string, complete: boolean): FileState {
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.Compare484 if (graph.packedFiles && !this.#scratchMoves()) return this.#layoutPacked(path, complete);
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.Compare485 if (this.#scratchMoves())
codex-capacity-chair132Bound persistent relocation projection memory with rollback-only scratchCompare486 return graph.withProjectionScratch((scratch) =>
487 this.#layoutResolved(
488 path,
489 complete,
490 scratchLayoutNodes(graph, (id) => this.#has(graph.atom(id).seq), scratch, `^${path}`),
491 ),
492 );
493 return this.#layoutResolved(path, complete);
494 }
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.Compare496 /** For each path, the files that lines moved into it were written in: worked out once per view. */
497 #movedFrom: Map<string, Set<number>> | undefined;
498 #movedInFrom(): Map<string, Set<number>> {
499 if (this.#movedFrom) return this.#movedFrom;
500 const graph = this.graph;
501 const out = new Map<string, Set<number>>();
502 if (this.#hasMoves) {
503 const relocs = this.#relocationsN();
504 // Where each node sits, walked once for the whole view: through the moves, up to a file's start.
505 const memo = new Map<number, string>();
506 const fileOf = (code: number): string => {
507 const walked: number[] = [];
508 let cur = code;
509 let file: string | undefined;
510 while (file === undefined) {
511 if (cur < 0) file = graph.nodeOf(cur).slice(1);
512 else {
513 file = memo.get(cur);
514 if (file === undefined) {
515 walked.push(cur);
516 cur = relocs.get(cur)?.parent ?? graph.parentCodeOf(cur);
517 }
518 }
519 }
520 for (const n of walked) memo.set(n, file);
521 return file;
522 };
523 for (const [n, { parent }] of relocs) {
524 const into = fileOf(parent);
525 let from = out.get(into);
526 if (!from) out.set(into, (from = new Set()));
527 from.add(graph.writtenInIndex(n));
528 }
529 }
530 this.#movedFrom = out;
531 return out;
532 }
534 /**
535 * Lay one file out from its packed history (abso Capacity, Graph.packedLines): the lines written in it, and in the
536 * files its moved-in lines came from, read a page at a time; the same tree and order as #layoutResolved, built in
537 * memory with no read per line.
538 */
539 #layoutPacked(path: string, complete: boolean): FileState {
540 const graph = this.graph;
541 const attrs = this.#attributes(path);
542 const start = graph.startCodeOf(path);
543 if (start === undefined) return { attrs, complete, seq: EMPTY_INTS, vis: EMPTY_INTS, deletedBy: new Map() };
544 const relocs = this.#hasMoves ? this.#relocationsN() : undefined;
545 const files = new Set<number>([-1 - start, ...(this.#movedInFrom().get(path) ?? [])]);
546 const children = new Map<number, Child[]>();
547 const texts = new Map<number, string | null>();
548 const deleters = new Map<number, number[]>();
549 for (const file of files) {
550 const lineTexts = graph.packedTexts(file);
551 for (const [n, parent, seq, k, replaces] of graph.packedLines(file)) {
552 const text = lineTexts.next().value as string | null;
553 if (!this.#has(seq)) continue;
554 const moved = relocs?.get(n);
555 let at = parent;
556 let child: Child = { n, replaces, lamport: graph.lamportOfSeq(seq), seq, k };
557 if (moved) {
558 const mover = graph.atom(moved.r.atom).seq;
559 child = { n, replaces: 0, lamport: graph.lamportOfSeq(mover), seq: mover, k: moved.r.k };
560 at = moved.parent;
561 }
562 const list = children.get(at);
563 if (list) list.push(child);
564 else children.set(at, [child]);
565 texts.set(n, text);
566 }
567 for (const [n, deleter] of graph.packedDeletes(file)) {
568 if (!this.#has(deleter)) continue;
569 const by = deleters.get(n);
570 if (by) by.push(deleter);
571 else deleters.set(n, [deleter]);
572 }
573 }
574 const order = (a: Child, b: Child) =>
575 b.replaces - a.replaces || b.lamport - a.lamport || b.seq - a.seq || a.k - b.k;
576 const priority = (a: number, b: number) => graph.lamportOfSeq(a) - graph.lamportOfSeq(b) || a - b;
577 const seq: number[] = [];
578 const vis: number[] = [];
579 const visText: (string | null)[] = [];
580 const deletedBy = new Map<number, readonly number[]>();
581 const stack: number[] = [];
582 const push = (code: number) => {
583 const list = children.get(code);
584 if (!list) return;
585 if (list.length > 1) list.sort(order);
586 for (let i = list.length - 1; i >= 0; i--) stack.push(list[i]!.n);
587 };
588 push(start);
589 while (stack.length) {
590 const n = stack.pop()!;
591 const by = deleters.get(n);
592 if (by) {
593 if (complete) deletedBy.set(seq.length, by.length > 1 ? by.sort(priority) : by);
594 } else {
595 vis.push(n);
596 visText.push(texts.get(n) ?? null);
597 }
598 if (complete) seq.push(n);
599 push(n);
600 }
601 return { attrs, complete, seq: Int32Array.from(seq), vis: Int32Array.from(vis), deletedBy, visText };
602 }
codex-capacity-chair140Avoid line projection for file attribute queriesCompare604 #attributes(path: string): FileAttrs {
codex-capacity-chair132Bound persistent relocation projection memory with rollback-only scratchCompare605 const graph = this.graph;
607 const setters = new Map<string, { id: AtomId; value: string | null }>();
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.Compare608 const file = graph.packedFiles ? graph.pathIndexOf(path) : undefined;
609 if (graph.packedFiles) {
610 for (const [seq, name, value] of file === undefined ? [] : graph.packedAttrs(file)) {
611 if (!this.#has(seq)) continue;
612 const id = graph.idOfSeq(seq);
613 const best = setters.get(name);
614 if (!best || graph.comparePriority(best.id, id) < 0) setters.set(name, { id, value });
615 }
616 return {
617 exists: setters.get("exists")?.value === "1",
618 exec: setters.get("exec")?.value === "1",
619 link: setters.get("link")?.value ?? null,
620 blob: setters.get("blob")?.value ?? null,
621 };
622 }
codex-capacity-chair119Page per-file atom indexes and stream current-view attribute scansCompare623 for (const id of graph.eachAtomIn(path)) {
625 for (const a of graph.atom(id).attrs ?? []) {
626 if (a.file !== path) continue;
627 const best = setters.get(a.name);
628 if (!best || graph.comparePriority(best.id, id) < 0) setters.set(a.name, { id, value: a.value });
629 }
630 }
632 return {
634 exec: setters.get("exec")?.value === "1",
635 link: setters.get("link")?.value ?? null,
636 blob: setters.get("blob")?.value ?? null,
637 };
codex-capacity-chair132Bound persistent relocation projection memory with rollback-only scratchCompare640 #layoutResolved(path: string, complete: boolean, nodes?: Iterable<number>): FileState {
codex-capacity-chair140Avoid line projection for file attribute queriesCompare641 const graph = this.graph;
642 const attrs = this.#attributes(path);
644 const vis: number[] = [];
645 const deletedBy = new Map<number, readonly number[]>();
648 const priority = (a: number, b: number) => graph.lamportOfSeq(a) - graph.lamportOfSeq(b) || a - b;
codex-capacity-chair132Bound persistent relocation projection memory with rollback-only scratchCompare649 for (const n of nodes ?? (start === undefined ? [] : this.#layoutNodes(start))) {
codex-capacity-chair128Page deletion history and short-circuit current visibilityCompare650 let deleted = false;
651 const by: number[] = [];
652 for (const deleter of graph.eachDeleterSeqOf(n)) {
653 if (!this.#has(deleter)) continue;
654 deleted = true;
655 if (!complete) break;
656 by.push(deleter);
657 }
658 if (deleted) {
659 if (complete) deletedBy.set(seq.length, by.length > 1 ? by.sort(priority) : by);
codex-capacity-chair110Keep current-file views and key scans from retaining historical stateCompare660 } else vis.push(n);
661 if (complete) seq.push(n);
codex-capacity-chair110Keep current-file views and key scans from retaining historical stateCompare664 return { attrs, complete, seq: Int32Array.from(seq), vis: Int32Array.from(vis), deletedBy };
667 get #known(): string[] {
668 if (!this.#knownList) {
669 const known = new Set<string>();
codex-capacity-chair109Add opt-in persistent writer state, checked reopen and bounded adoptionCompare670 if (this.#stable) {
671 for (const id of this.#stable) for (const file of this.graph.filesOf(id)) known.add(file);
672 } else {
673 for (let seq = 0; seq < this.#in.length; seq++)
674 if (this.#in[seq] === 1) for (const file of this.graph.filesOf(this.graph.idOfSeq(seq))) known.add(file);
675 }
677 }
678 return this.#knownList;
679 }
681 /** Files with at least one visible line, sorted. */
682 paths(): string[] {
codex-capacity-chair118Avoid retaining deleted historical paths in indexed current viewsCompare683 if (this.#stable) {
684 const paths: string[] = [];
685 for (const path of this.graph.knownFiles()) {
686 if (this.hasFile(path)) paths.push(path);
687 else this.#files.delete(path);
688 }
689 return paths.sort();
690 }
692 }
694 /** Every file the set has ever written a line in, including fully deleted ones. */
695 knownPaths(): string[] {
696 return [...this.#known];
capacity207Each shared version's changed files kept as it lands (disk-first 2; abso Capacity, version-files.ts). A version's files are decided from what it touched: visible lines in and out per file, their texts' balance, a running count of each file's visible lines for made and taken out, and mode and blob; a version with moves, drops or a closure change, or whose lines in and out have the same texts, is laid out as before. Views of consecutive versions share resolved moves and where lines sit (View.shareMoves). PathIndex.keep records them, into the shapes table when the host gives one. version-files.test.ts checks log, path logs and every show against the in-memory project through edits, new and removed files, same text put back, a move and a drop. On game's export all 27 harness answers now match Project.load: the log 70 ms (was over 30 s), a path's history 0.56 s (was over 30 s), the tree 3.1-3.4 s (was over 30 s); adoption about 85 s; heap 14.4 MB at most.Compare697 }
699 /** How many visible lines a file has. */
700 visibleCount(path: string): number {
701 return this.#file(path).vis.length;
704 /** Whether the file exists in this projection (has a visible line). */
705 hasFile(path: string): boolean {
codex-capacity-chair140Avoid line projection for file attribute queriesCompare706 const attrs = this.attrs(path);
707 return attrs.exists || attrs.link !== null || attrs.blob !== null || this.#file(path).vis.length > 0;
710 /** A file's attributes: kept while empty, executable, a link's target. */
711 attrs(path: string): FileAttrs {
codex-capacity-chair140Avoid line projection for file attribute queriesCompare712 return this.#files.get(path)?.attrs ?? this.#attributes(path);
715 /** The projected text of a file ("" if it has no visible lines). */
716 text(path: string): string {
717 if (this.#textCache?.path === path) return this.#textCache.text;
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.Compare718 const { vis, visText } = this.#file(path);
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.Compare720 for (let i = 0; i < vis.length; i++) lines[i] = visText?.[i] ?? this.graph.textOf(vis[i]!);
722 this.#textCache = { path, text };
723 return text;
724 }
726 /** Whether a file reads the same here and in `other` (of the same graph), compared line by line without joining either (#46). */
codex-capacity-chair143Add inactive disk projection provider and verified transactional readers (#16)Compare727 sameText(path: string, other: ReadView): boolean {
728 if (!(other instanceof View)) {
729 const a = this.lines(path),
730 b = other.lines(path);
731 return a.length === b.length && a.every((line, i) => line.text === b[i]!.text);
732 }
734 const b = other.#file(path).vis;
735 if (a.length !== b.length) return false;
736 for (let i = 0; i < a.length; i++)
737 if (a[i] !== b[i] && this.graph.textOf(a[i]!) !== this.graph.textOf(b[i]!)) return false;
738 return true;
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.Compare739 }
741 *lineChunks(path: string): IterableIterator<() => Iterable<string>> {
742 for (const n of this.#file(path).vis) yield () => this.graph.textChunks(n);
743 }
745 /** Visible lines without retaining their text in the view cache. */
746 *visibleLines(path: string): IterableIterator<VisibleLine> {
747 const graph = this.graph;
748 for (const n of this.#file(path).vis)
749 yield { id: graph.lineIdOf(n), text: graph.textOf(n), atom: graph.idOfSeq(graph.writerSeqOf(n)) };
750 }
752 /** Atom-building line handles; text is loaded only when requested. */
753 buildLines(path: string): readonly VisibleLine[] {
754 const graph = this.graph;
755 const vis = this.#file(path).vis;
756 const lines: VisibleLine[] = new Array(vis.length);
757 for (let i = 0; i < vis.length; i++) {
758 const n = vis[i]!;
759 lines[i] = {
760 id: graph.lineIdOf(n),
761 textChunks: () => graph.textChunks(n),
762 get text() {
763 return graph.textOf(n);
764 },
765 atom: graph.idOfSeq(graph.writerSeqOf(n)),
766 };
767 }
768 return lines;
771 /** Visible lines with their ids. */
772 lines(path: string): readonly VisibleLine[] {
773 if (this.#linesCache?.path === path) return this.#linesCache.lines;
774 const graph = this.graph;
775 const vis = this.#file(path).vis;
776 const lines: VisibleLine[] = new Array(vis.length);
777 for (let i = 0; i < vis.length; i++) {
778 const n = vis[i]!;
779 lines[i] = { id: graph.lineIdOf(n), text: graph.textOf(n), atom: graph.idOfSeq(graph.writerSeqOf(n)) };
780 }
781 this.#linesCache = { path, lines };
782 return lines;
783 }
785 /** The full linearized sequence of a file, tombstones included. */
786 sequence(path: string): readonly SeqLine[] {
787 if (this.#seqCache?.path === path) return this.#seqCache.seq;
788 const graph = this.graph;
codex-capacity-chair110Keep current-file views and key scans from retaining historical stateCompare789 const f = this.#file(path, true);
791 for (let i = 0; i < f.seq.length; i++) {
792 const n = f.seq[i]!;
793 const by = f.deletedBy.get(i);
794 out[i] = {
795 id: graph.lineIdOf(n),
796 text: graph.textOf(n),
797 atom: graph.idOfSeq(graph.writerSeqOf(n)),
798 deletedBy: by ? by.map((s) => graph.idOfSeq(s)) : NONE,
799 visible: by === undefined,
800 };
801 }
802 this.#seqCache = { path, seq: out };
803 return out;
804 }
codex-capacity-chair138Find reason-warning neighbors without materializing file historyCompare806 /** Two visible neighbours without retaining the file's historical sequence. */
807 visibleNeighbours(path: string, line: LineId): LineId[] {
808 const graph = this.graph;
809 const target = graph.lineN(line);
810 const start = graph.startCodeOf(path);
811 if (target < 0 || start === undefined) return [];
812 const scan = (nodes: Iterable<number>): LineId[] => {
813 let previous: LineId | undefined;
814 let found = false;
815 for (const n of nodes) {
816 if (n === target) {
817 found = true;
818 continue;
819 }
820 let deleted = false;
821 for (const seq of graph.eachDeleterSeqOf(n))
822 if (this.#has(seq)) {
823 deleted = true;
824 break;
825 }
826 if (deleted) continue;
827 const id = graph.lineIdOf(n);
828 if (found) return previous === undefined ? [id] : [previous, id];
829 previous = id;
830 }
831 return found && previous !== undefined ? [previous] : [];
832 };
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.Compare833 if (this.#scratchMoves())
codex-capacity-chair138Find reason-warning neighbors without materializing file historyCompare834 return graph.withProjectionScratch((scratch) =>
835 scan(scratchLayoutNodes(graph, (id) => this.#has(graph.atom(id).seq), scratch, graph.nodeOf(start))),
836 );
837 return scan(this.#layoutNodes(start));
838 }
841 sequenceIndex(path: string, line: LineId): number {
codex-capacity-chair110Keep current-file views and key scans from retaining historical stateCompare842 const f = this.#file(path, true);
844 f.seqIndex = new Map();
845 for (let i = 0; i < f.seq.length; i++) f.seqIndex.set(f.seq[i]!, i);
846 }
847 return f.seqIndex.get(this.graph.lineN(line)) ?? -1;
848 }
850 /** Index of a line in `lines(path)` (0-based visible line number), or -1 if not visible. */
851 lineNumber(path: string, line: LineId): number {
852 const f = this.#file(path);
853 if (!f.visIndex) {
854 f.visIndex = new Map();
855 for (let i = 0; i < f.vis.length; i++) f.visIndex.set(f.vis[i]!, i);
856 }
857 return f.visIndex.get(this.graph.lineN(line)) ?? -1;
858 }
860 /** All projected text files, path -> text, in path order. Binary files are in `blobs()`. */
861 files(): Record<string, string> {
862 const out: Record<string, string> = {};
863 for (const path of this.paths()) if (this.#file(path).attrs.blob === null) out[path] = this.text(path);
864 return out;
865 }
867 /** Binary files, path -> the SHA-256 of their bytes, in path order. */
868 blobs(): Record<string, string> {
869 const out: Record<string, string> = {};
870 for (const path of this.paths()) {
871 const blob = this.#file(path).attrs.blob;
872 if (blob !== null) out[path] = blob;
873 }
874 return out;
875 }
877 /**
codex-capacity-policy103Test deterministic replay and account view cache weightCompare878 * About how many bytes of retained state this view costs (#46). This uses
879 * approximate ownership costs for containers and wrappers, not V8 heap
880 * measurements. Graph-owned strings and records count only as references.
881 * This method only inspects already-created state: it does not lay out files,
882 * populate lazy caches, enumerate the graph, or count temporary traversal
883 * containers and shared empty singleton payloads as retained view state.
885 weight(): number {
codex-capacity-policy103Test deterministic replay and account view cache weightCompare886 let n = this.#in.byteLength;
codex-capacity-chair116Bound repeated indexed view membership lookupsCompare887 n += 2 * ARRAY_HEADER_BYTES + this.#membershipSeq.byteLength + this.#membershipValue.byteLength;
codex-capacity-chair123Stream mover history when opening persisted viewsCompare888 if (this.#movers) n += ARRAY_HEADER_BYTES + REFERENCE_BYTES * this.#movers.length;
codex-capacity-policy103Test deterministic replay and account view cache weightCompare889 n += MAP_HEADER_BYTES; // #files exists from construction.
890 n += MAP_HEADER_BYTES; // #fileOf exists from construction.
codex-capacity-chair109Add opt-in persistent writer state, checked reopen and bounded adoptionCompare891 if (this.#stable) n += this.#stable.retainedBytes;
892 else if (this.#set) n += OBJECT_BYTES + SET_ENTRY_BYTES * this.#set.size;
codex-capacity-policy103Test deterministic replay and account view cache weightCompare893 if (this.#knownList) n += ARRAY_HEADER_BYTES + REFERENCE_BYTES * this.#knownList.length;
894 if (this.#relocs) n += MAP_HEADER_BYTES + MAP_ENTRY_BYTES * this.#relocs.size;
895 if (this.#relocsN) n += MAP_HEADER_BYTES + (MAP_ENTRY_BYTES + OBJECT_BYTES) * this.#relocsN.size;
896 n += MAP_ENTRY_BYTES * this.#fileOf.size;
897 for (const f of this.#files.values()) {
898 n += MAP_ENTRY_BYTES;
899 if (f !== NO_FILE) {
900 // FileState and FileAttrs are per laid-out file; typed-array
901 // headers are separate from their payload byte lengths below.
902 n += OBJECT_BYTES + OBJECT_BYTES + 2 * ARRAY_HEADER_BYTES;
903 n += f.seq.byteLength + f.vis.byteLength;
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.Compare904 if (f.visText) for (const text of f.visText) n += REFERENCE_BYTES + 2 * (text?.length ?? 0);
codex-capacity-policy103Test deterministic replay and account view cache weightCompare905 n += MAP_HEADER_BYTES + (MAP_ENTRY_BYTES + ARRAY_HEADER_BYTES) * f.deletedBy.size;
906 for (const deleters of f.deletedBy.values()) n += REFERENCE_BYTES * deleters.length;
907 if (f.seqIndex) n += MAP_HEADER_BYTES + MAP_ENTRY_BYTES * f.seqIndex.size;
908 if (f.visIndex) n += MAP_HEADER_BYTES + MAP_ENTRY_BYTES * f.visIndex.size;
909 }
910 }
911 if (this.#linesCache)
912 n += OBJECT_BYTES + REFERENCE_BYTES + ARRAY_HEADER_BYTES + 100 * this.#linesCache.lines.length;
913 if (this.#seqCache) {
914 n += OBJECT_BYTES + REFERENCE_BYTES + ARRAY_HEADER_BYTES + 120 * this.#seqCache.seq.length;
915 for (const line of this.#seqCache.seq)
916 if (line.deletedBy !== NONE) n += ARRAY_HEADER_BYTES + REFERENCE_BYTES * line.deletedBy.length;
917 }
918 if (this.#textCache) n += OBJECT_BYTES + REFERENCE_BYTES + ARRAY_HEADER_BYTES + 2 * this.#textCache.text.length;
920 }
codex-capacity-chair110Keep current-file views and key scans from retaining historical stateCompare922 #file(path: string, complete = false): FileState {
codex-capacity-chair110Keep current-file views and key scans from retaining historical stateCompare924 if (!state || (complete && !state.complete)) {
codex-capacity-chair119Page per-file atom indexes and stream current-view attribute scansCompare925 state = this.graph.hasAtomsIn(path) ? this.#layout(path, complete) : NO_FILE;
927 }
928 return state;
929 }
930}
932/** The files of a closed set, path -> text. */
933export function project(graph: Graph, set: Iterable<AtomId>): Record<string, string> {
934 return new View(graph, set).files();
935}
937/** Where a node sits in a file's sequence: the index just after it (0 for a start node). */
codex-capacity-chair143Add inactive disk projection provider and verified transactional readers (#16)Compare938export function indexAfter(view: Pick<ReadView, "sequenceIndex">, path: string, node: NodeId): number {
940 const i = view.sequenceIndex(path, node);
941 if (i < 0) throw new EngineError("not-in-view", `line ${node} is not in ${path} in this view`);
942 return i + 1;
943}