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/view.ts --version 213 --json
JSON
/christopher/abso-core/blame/src/engine/view.ts?version=213&format=json
965 linesFirst import 43% · codex-capacity-chair 28% · capacity 24% · codex-capacity-policy 5%Last change capacity in version 212,

965 lines from 26 changes in 23 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";
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 changesCompare13import { isStartNode, seqOf } 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";
init0Start the project16import { joinLines } from "./text.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;
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>;
init0Start the project33 readonly id: LineId;
34 readonly text: string;
35 readonly atom: AtomId;
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;
codex-capacity-chair143Add inactive disk projection provider and verified transactional readers (#16)Compare49/** Structural read boundary shared by historical and transaction-bound projections. */
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 changesCompare50export type ReadView = Omit<
51 Pick<View, keyof View>,
52 "sameText" | "visibleCount" | "shareMoves" | "fileOfNumber" | "lineNumberOf" | "visibleWriters"
53> & {
codex-capacity-chair143Add inactive disk projection provider and verified transactional readers (#16)Compare54 sameText(path: string, other: ReadView): boolean;
55};
init0Start the project57const NO_ATTRS: FileAttrs = { exists: false, exec: false, link: null, blob: null };
58const NONE: readonly never[] = Object.freeze([]);
60interface FileState {
61 readonly attrs: FileAttrs;
codex-capacity-chair110Keep current-file views and key scans from retaining historical stateCompare62 /** Full history is retained only when a sequence caller explicitly requests it. */
63 readonly complete: boolean;
init0Start the project64 /** The file's sequence, tombstones included: each line's n. */
65 readonly seq: Int32Array;
66 /** Its visible lines' n, in order. */
67 readonly vis: Int32Array;
68 /** For each deleted position in seq: the seqs of the atoms in the set that delete it, by priority. */
69 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.Compare70 /** Its visible lines' text, when laid out from the file's packed history: null for a line too long to pack. */
71 readonly visText?: readonly (string | null)[];
init0Start the project72 /** Positions by n, built the first time they're asked for. */
73 seqIndex?: Map<number, number>;
74 visIndex?: Map<number, number>;
77interface Child {
78 readonly n: number;
79 /** 1 when the child's atom deleted the parent (the child replaces it), else 0. A moved line is 0. */
80 readonly replaces: number;
81 readonly lamport: number;
82 readonly seq: number;
83 readonly k: number;
86const EMPTY_INTS = new Int32Array(0);
codex-capacity-chair110Keep current-file views and key scans from retaining historical stateCompare87const NO_FILE: FileState = { attrs: NO_ATTRS, complete: true, seq: EMPTY_INTS, vis: EMPTY_INTS, deletedBy: new Map() };
init0Start the project88
codex-capacity-policy103Test deterministic replay and account view cache weightCompare89// Approximate retained-container costs for View.weight(): reference slots,
90// object headers, and map/set entries. These are cache-budget units, not V8
91// heap measurements. Referenced Graph strings and records are not charged.
92const ARRAY_HEADER_BYTES = 24;
93const OBJECT_BYTES = 32;
94const MAP_HEADER_BYTES = 32;
95const MAP_ENTRY_BYTES = 40;
96const SET_ENTRY_BYTES = 32;
97const REFERENCE_BYTES = 8;
codex-capacity-chair125Bound file-location ancestry scratch and memoCompare98const 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.Compare99/**
100 * Moved lines a view resolves once and keeps (abso Capacity): a stored graph otherwise resolved every move again on
101 * disk for each file it laid out. Game's whole history has 290; past this many, the view goes back to that.
102 */
103export const MOVED_LINES_KEPT = 20_000;
104class TooManyMoves extends Error {}
105const 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.Compare106/** Lines whose place views sharing moves remember, at most: about 40 bytes each. */
107const SHARED_FILE_MEMO = 200_000;
codex-capacity-policy103Test deterministic replay and account view cache weightCompare108
init0Start the project109/**
110 * The projection of a closed set. Construct once, then ask for files, lines
111 * and sequences. Throws `not-closed` if some atom's dependency is missing.
112 * Each file is laid out the first time it is asked for, so a view of a large
113 * set costs little until files are read.
114 */
115export class View {
116 readonly graph: Graph;
117 /** 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 adoptionCompare118 #set: AtomSet | undefined;
119 readonly #stable: StableSet<AtomId> | undefined;
codex-capacity-chair116Bound repeated indexed view membership lookupsCompare120 /** Fixed-size memo for immutable indexed membership, independent of history size. */
121 #membershipSeq = new Float64Array(256).fill(-1);
122 #membershipValue = new Uint8Array(256);
init0Start the project123 #files = new Map<string, FileState>();
124 /** Every file the set wrote in, sorted; worked out the first time it's asked for. */
125 #knownList: string[] | undefined;
126 /** 1 for each atom (by seq) in the set. */
127 #in: Uint8Array;
128 /** Atoms in the set that move lines. */
codex-capacity-chair123Stream mover history when opening persisted viewsCompare129 #movers: AtomId[] | undefined;
130 #hasMoves = false;
init0Start the project131 /** Each moved line's relocation that counts in this set; built on first use. */
132 #relocs: Map<LineId, RelocationInfo> | undefined;
133 /** The same, by n, with the new parent's code. */
134 #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.Compare135 /** The moved lines under each node, by its code, made from the relocations on first use. */
136 #movedInto: Map<number, number[]> | undefined;
137 /** Whether this view's moves are too many to keep, so they're resolved on disk per layout; undefined until asked. */
138 #movesOnDisk: boolean | undefined;
codex-capacity-chair125Bound file-location ancestry scratch and memoCompare139 /** Bounded memo: ancestry can span the entire history even for one visible line. */
init0Start the project140 #fileOf = new Map<number, string>();
141 /** The latest records asked for: one file's lines, one file's sequence, one file's text. */
142 #linesCache: { path: string; lines: readonly VisibleLine[] } | undefined;
143 #seqCache: { path: string; seq: readonly SeqLine[] } | undefined;
144 #textCache: { path: string; text: string } | undefined;
146 constructor(graph: Graph, set: Iterable<AtomId>) {
codex-capacity-chair109Add opt-in persistent writer state, checked reopen and bounded adoptionCompare147 this.graph = graph;
148 if (set instanceof StableSet) {
149 this.#stable = set;
150 this.#set = set;
151 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.Compare152 // A set kept closed when it was written needs no proof here (abso Capacity).
153 for (const id of isClosedSet(set) ? [] : set) {
codex-capacity-chair109Add opt-in persistent writer state, checked reopen and bounded adoptionCompare154 const atom = graph.atom(id);
155 for (const dependency of atom.deps) {
156 graph.atom(dependency);
157 if (!set.has(dependency))
158 throw new EngineError("not-closed", `set is not closed: ${id} depends on ${dependency}`);
159 }
160 }
codex-capacity-chair123Stream mover history when opening persisted viewsCompare161 for (const id of graph.movers()) {
162 if (set.has(id)) {
163 this.#hasMoves = true;
164 break;
165 }
166 }
167 this.#relocs = this.#hasMoves ? undefined : new Map();
168 this.#relocsN = this.#hasMoves ? undefined : new Map();
codex-capacity-chair109Add opt-in persistent writer state, checked reopen and bounded adoptionCompare169 return;
170 }
init0Start the project171 const inSet = new Uint8Array(graph.size);
172 for (const id of set) {
173 const atom = graph.atom(id);
174 inSet[atom.seq] = 1;
175 }
codex-capacity-chair109Add opt-in persistent writer state, checked reopen and bounded adoptionCompare176 // Validate one atom at a time. Keeping all decoded atoms here defeats
177 // storage-backed Graph reads even though the view only needs membership.
178 for (let seq = 0; seq < inSet.length; seq++) {
179 if (inSet[seq] !== 1) continue;
180 const atom = graph.atom(graph.idOfSeq(seq));
init0Start the project181 for (const d of atom.deps) {
182 if (inSet[graph.atom(d).seq] !== 1)
183 throw new EngineError("not-closed", `set is not closed: ${atom.id} depends on ${d}`);
184 }
185 }
186 this.graph = graph;
187 this.#in = inSet;
188 this.#movers = graph.movers().filter((id) => inSet[graph.atom(id).seq] === 1);
codex-capacity-chair123Stream mover history when opening persisted viewsCompare189 this.#hasMoves = this.#movers.length > 0;
init0Start the project190 this.#relocs = this.#movers.length === 0 ? new Map() : undefined;
191 this.#relocsN = this.#movers.length === 0 ? new Map() : undefined;
192 }
194 /** The set of atoms this view projects. */
195 get set(): AtomSet {
196 if (!this.#set) {
197 const out = new Set<AtomId>();
198 for (let seq = 0; seq < this.#in.length; seq++) if (this.#in[seq] === 1) out.add(this.graph.idOfSeq(seq));
199 this.#set = out;
200 }
201 return this.#set;
202 }
204 /** Whether the atom with this seq is in the set. */
205 #has(seq: number): boolean {
codex-capacity-chair116Bound repeated indexed view membership lookupsCompare206 if (this.#stable) {
207 const slot = seq % this.#membershipSeq.length;
208 if (this.#membershipSeq[slot] === seq) return this.#membershipValue[slot] === 1;
209 const present = this.#stable.has(this.graph.idOfSeq(seq));
210 this.#membershipSeq[slot] = seq;
211 this.#membershipValue[slot] = present ? 1 : 0;
212 return present;
213 }
init0Start the project214 return seq < this.#in.length && this.#in[seq] === 1;
215 }
217 /**
218 * The relocation that counts for each moved line: the newest (by priority)
219 * in the set. Two moves made apart can loop lines into each other, so no
220 * start node reaches them; then the oldest relocation on the loop is
221 * ignored, and the next newest of that line counts, until none loop.
222 */
223 #relocations(): Map<LineId, RelocationInfo> {
224 if (this.#relocs) return this.#relocs;
225 const graph = this.graph;
226 const stronger = (a: RelocationInfo, b: RelocationInfo): boolean => graph.comparePriority(a.atom, b.atom) > 0;
codex-capacity-chair126Identify suppressed relocation cycles across persistent readsCompare227 // Persistent reads decode new objects. Cycle suppression must identify the
228 // logical move, not one particular decoded JavaScript object.
229 const identity = (r: RelocationInfo): string => JSON.stringify([r.atom, r.k]);
230 const ignored = new Set<string>();
init0Start the project231 const pick = (line: LineId): RelocationInfo | undefined => {
232 let best: RelocationInfo | undefined;
codex-capacity-chair127Page persistent relocation indexes and stream projection readsCompare233 for (const r of graph.eachRelocationOf(line)) {
codex-capacity-chair126Identify suppressed relocation cycles across persistent readsCompare234 if (this.#has(graph.atom(r.atom).seq) && !ignored.has(identity(r)) && (!best || stronger(r, best))) best = r;
init0Start the project235 }
236 return best;
237 };
238 const relocs = new Map<LineId, RelocationInfo>();
codex-capacity-chair123Stream mover history when opening persisted viewsCompare239 for (const id of this.#eachMover()) {
init0Start the project240 for (const m of graph.atom(id).moves!) {
241 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.Compare242 if (graph.hasOrderedChildren && relocs.size > MOVED_LINES_KEPT) throw new TooManyMoves();
init0Start the project243 }
244 }
245 const parentOf = (line: LineId): NodeId => relocs.get(line)?.parent ?? graph.lineParent(line)!;
246 const reaches = new Set<LineId>();
247 for (const line of [...relocs.keys()]) {
248 for (;;) {
249 const path: LineId[] = [];
250 const onPath = new Map<LineId, number>();
251 let cur: NodeId = line;
252 let loopAt = -1;
253 while (!isStartNode(cur) && !reaches.has(cur)) {
254 const at = onPath.get(cur);
255 if (at !== undefined) {
256 loopAt = at;
257 break;
258 }
259 onPath.set(cur, path.length);
260 path.push(cur);
261 cur = parentOf(cur);
262 }
263 if (loopAt < 0) {
264 for (const l of path) reaches.add(l);
265 break;
266 }
267 let weakest: RelocationInfo | undefined;
268 for (const l of path.slice(loopAt)) {
269 const r = relocs.get(l);
270 if (r && (!weakest || stronger(weakest, r))) weakest = r;
271 }
codex-capacity-chair126Identify suppressed relocation cycles across persistent readsCompare272 ignored.add(identity(weakest!));
init0Start the project273 const next = pick(weakest!.line);
274 if (next) relocs.set(weakest!.line, next);
275 else relocs.delete(weakest!.line);
276 }
277 }
278 this.#relocs = relocs;
279 return relocs;
280 }
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.Compare282 /** Where lines sit, shared with views that took this one's moves (shareMoves): unbounded up to SHARED_FILE_MEMO. */
283 #fileOfShared: Map<number, string> | undefined;
285 /**
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 changesCompare286 * Take another view's resolved moves (abso Capacity), when both sets hold the very same atoms that move lines: the
287 * moves then resolve the same, and every line sits where it sits there. Checked here, so any caller may ask.
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.Compare288 */
289 shareMoves(from: View): void {
290 if (from.graph !== this.graph || from.#hasMoves !== this.#hasMoves || !this.#hasMoves) return;
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 changesCompare291 if (this.#relocs || from.#scratchMoves()) return;
292 for (const id of this.graph.movers()) {
293 const seq = seqOf(id);
294 if (this.#has(seq) !== from.#has(seq)) return;
295 }
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.Compare296 this.#relocs = from.#relocations();
297 this.#relocsN = from.#relocationsN();
298 this.#movesOnDisk = false;
299 this.#movedFrom = from.#movedInFrom();
300 from.#fileOfShared ??= new Map();
301 this.#fileOfShared = from.#fileOfShared;
302 }
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.Compare304 /** Whether moves are resolved on disk for each layout: only a stored graph's view with more than MOVED_LINES_KEPT. */
305 #scratchMoves(): boolean {
306 if (!this.#hasMoves || !this.graph.hasOrderedChildren) return false;
307 if (this.#movesOnDisk === undefined) {
308 try {
309 this.#relocations();
310 this.#movesOnDisk = false;
311 } catch (error) {
312 if (!(error instanceof TooManyMoves)) throw error;
313 this.#movesOnDisk = true;
314 }
315 }
316 return this.#movesOnDisk;
317 }
init0Start the project319 /** The relocations by n, with each new parent's code. */
320 #relocationsN(): Map<number, { readonly r: RelocationInfo; readonly parent: number }> {
321 if (this.#relocsN) return this.#relocsN;
322 const out = new Map<number, { readonly r: RelocationInfo; readonly parent: number }>();
323 for (const [line, r] of this.#relocations())
324 out.set(this.graph.lineN(line), { r, parent: this.graph.codeOf(r.parent)! });
325 this.#relocsN = out;
326 return out;
327 }
329 /** The node a line hangs off in this set: where it was written, or where a move put it. */
330 parentOf(line: LineId): NodeId {
codex-capacity-chair132Bound persistent relocation projection memory with rollback-only scratchCompare331 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.Compare332 if (this.#scratchMoves())
codex-capacity-chair132Bound persistent relocation projection memory with rollback-only scratchCompare333 return this.graph.withProjectionScratch((scratch) =>
334 resolveScratchMoves(this.graph, (id) => this.#has(this.graph.atom(id).seq), scratch).parent(line),
335 );
codex-capacity-chair123Stream mover history when opening persisted viewsCompare336 const r = this.#hasMoves ? this.#relocations().get(line) : undefined;
init0Start the project337 if (r) return r.parent;
338 const parent = this.graph.lineParent(line);
339 if (parent === undefined) throw new EngineError("unknown-line", `no line ${line}`);
340 return parent;
341 }
343 /** Whether any atom in the set moves lines. */
344 hasMoves(): boolean {
codex-capacity-chair123Stream mover history when opening persisted viewsCompare345 return this.#hasMoves;
346 }
347 *#eachMover(): IterableIterator<AtomId> {
348 if (this.#movers) yield* this.#movers;
349 else for (const id of this.graph.movers()) if (this.#stable!.has(id)) yield id;
init0Start the project350 }
352 /** The file a line is in, in this set: the one its chain of parents reaches. */
353 fileOf(line: LineId): string {
354 const n = this.graph.lineN(line);
355 if (n < 0) throw new EngineError("unknown-line", `no line ${line}`);
356 return this.#fileOfN(n);
357 }
359 #fileOfN(n: number): string {
360 const graph = this.graph;
codex-capacity-chair123Stream mover history when opening persisted viewsCompare361 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.Compare362 if (this.#scratchMoves())
codex-capacity-chair132Bound persistent relocation projection memory with rollback-only scratchCompare363 return graph.withProjectionScratch((scratch) => {
364 const moves = resolveScratchMoves(graph, (id) => this.#has(graph.atom(id).seq), scratch);
365 let current = graph.nodeOf(n);
366 while (!isStartNode(current)) current = moves.parent(current);
367 return current.slice(1);
368 });
init0Start the project369 const relocs = this.#relocationsN();
codex-capacity-chair125Bound file-location ancestry scratch and memoCompare370 // Keep only a fixed tail of the walk for path compression. The selected
371 // relocation graph is acyclic, so traversal needs no history-sized stack.
init0Start the project372 const path: number[] = [];
codex-capacity-chair125Bound file-location ancestry scratch and memoCompare373 let visited = 0;
init0Start the project374 let cur = n;
375 let file: string | undefined;
376 while (file === undefined) {
377 if (cur < 0) file = graph.nodeOf(cur).slice(1);
378 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.Compare379 file = (this.#fileOfShared ?? this.#fileOf).get(cur);
init0Start the project380 if (file === undefined) {
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.Compare381 if (this.#fileOfShared) path.push(cur);
382 else path[visited++ % FILE_LOCATION_MEMO_ENTRIES] = cur;
init0Start the project383 cur = relocs.get(cur)?.parent ?? graph.parentCodeOf(cur);
384 }
385 }
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.Compare386 }
387 const shared = this.#fileOfShared;
388 if (shared) {
389 if (shared.size > SHARED_FILE_MEMO) shared.clear();
390 for (const l of path) shared.set(l, file);
391 return file;
codex-capacity-chair125Bound file-location ancestry scratch and memoCompare392 }
393 for (const l of path) {
394 if (!this.#fileOf.has(l) && this.#fileOf.size >= FILE_LOCATION_MEMO_ENTRIES)
395 this.#fileOf.delete(this.#fileOf.keys().next().value!);
396 this.#fileOf.set(l, file);
init0Start the project397 }
398 return file;
399 }
401 /** The lines hanging off a node in this set, in layout order. */
402 #children(code: number): Child[] {
403 const graph = this.graph;
codex-capacity-chair123Stream mover history when opening persisted viewsCompare404 const relocs = this.#hasMoves ? this.#relocationsN() : undefined;
init0Start the project405 const out: Child[] = [];
codex-capacity-chair130Stream paged child history into layout filteringCompare406 for (const n of graph.eachChildN(code)) {
init0Start the project407 const seq = graph.writerSeqOf(n);
408 if (!this.#has(seq) || relocs?.has(n)) continue;
409 out.push({ n, replaces: graph.replacesN(n) ? 1 : 0, lamport: graph.lamportOfSeq(seq), seq, k: graph.kOf(n) });
410 }
411 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.Compare412 // The lines this set's moves put under each node, from the moves it already resolved: no row read per node
413 // (abso Capacity).
414 if (!this.#movedInto) {
415 this.#movedInto = new Map();
416 for (const [n, { parent }] of relocs) {
417 const into = this.#movedInto.get(parent);
418 if (into) into.push(n);
419 else this.#movedInto.set(parent, [n]);
420 }
421 }
422 for (const n of this.#movedInto.get(code) ?? NO_LINES) {
423 const r = relocs.get(n)!.r;
init0Start the project424 const seq = graph.atom(r.atom).seq;
425 out.push({ n, replaces: 0, lamport: graph.lamportOfSeq(seq), seq, k: r.k });
426 }
427 }
428 // A line's replacements (runs of atoms that deleted it) first, then the
429 // rest; each group in descending priority (lamport, then seq); lines of
430 // one atom keep k order. A replacement already outranks every insertion
431 // after the line that reads it (it depends on them, or conflicts with
432 // them); the grouping also puts it above a `before` insertion, which
433 // doesn't read the line above, so the new text lands in the replaced
434 // line's place. A moved line ranks like an insertion by the moving atom.
435 if (out.length > 1)
436 out.sort((a, b) => b.replaces - a.replaces || b.lamport - a.lamport || b.seq - a.seq || a.k - b.k);
437 return out;
438 }
codex-capacity-chair131Bound persisted no-move layout with ordered successor traversalCompare440 /** Parent/successor traversal keeps no history-sized ancestry or sibling frontier. */
441 *#layoutNodes(start: number): IterableIterator<number> {
442 const graph = this.graph;
443 if (graph.hasOrderedChildren && !this.#hasMoves) {
444 const first = (parent: number, after?: number): number | undefined => {
445 for (const n of graph.orderedChildrenN(parent, after)) if (this.#has(graph.writerSeqOf(n))) return n;
446 return undefined;
447 };
448 let n = first(start);
449 while (n !== undefined) {
450 yield n;
451 const child = first(n);
452 if (child !== undefined) {
453 n = child;
454 continue;
455 }
456 let previous = n;
457 for (;;) {
458 const parent = graph.parentCodeOf(previous);
459 const sibling = first(parent, previous);
460 if (sibling !== undefined) {
461 n = sibling;
462 break;
463 }
464 if (parent === start) {
465 n = undefined;
466 break;
467 }
468 if (parent < 0 || parent >= previous) throw new Error("invalid persistent layout ancestry");
469 previous = parent;
470 }
471 }
472 return;
473 }
init0Start the project474 const stack: number[] = [];
codex-capacity-chair131Bound persisted no-move layout with ordered successor traversalCompare475 const push = (parent: number): void => {
476 const children = this.#children(parent);
477 for (let i = children.length - 1; i >= 0; i--) stack.push(children[i]!.n);
478 };
479 push(start);
480 while (stack.length) {
481 const n = stack.pop()!;
482 yield n;
483 push(n);
484 }
485 }
init0Start the project487 /** Lay out one file: its line tree from the set's atoms, linearized. */
codex-capacity-chair110Keep current-file views and key scans from retaining historical stateCompare488 #layout(path: string, complete: boolean): FileState {
init0Start the project489 const graph = this.graph;
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.Compare490 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.Compare491 if (this.#scratchMoves())
codex-capacity-chair132Bound persistent relocation projection memory with rollback-only scratchCompare492 return graph.withProjectionScratch((scratch) =>
493 this.#layoutResolved(
494 path,
495 complete,
496 scratchLayoutNodes(graph, (id) => this.#has(graph.atom(id).seq), scratch, `^${path}`),
497 ),
498 );
499 return this.#layoutResolved(path, complete);
500 }
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.Compare502 /** For each path, the files that lines moved into it were written in: worked out once per view. */
503 #movedFrom: Map<string, Set<number>> | undefined;
504 #movedInFrom(): Map<string, Set<number>> {
505 if (this.#movedFrom) return this.#movedFrom;
506 const graph = this.graph;
507 const out = new Map<string, Set<number>>();
508 if (this.#hasMoves) {
509 const relocs = this.#relocationsN();
510 // Where each node sits, walked once for the whole view: through the moves, up to a file's start.
511 const memo = new Map<number, string>();
512 const fileOf = (code: number): string => {
513 const walked: number[] = [];
514 let cur = code;
515 let file: string | undefined;
516 while (file === undefined) {
517 if (cur < 0) file = graph.nodeOf(cur).slice(1);
518 else {
519 file = memo.get(cur);
520 if (file === undefined) {
521 walked.push(cur);
522 cur = relocs.get(cur)?.parent ?? graph.parentCodeOf(cur);
523 }
524 }
525 }
526 for (const n of walked) memo.set(n, file);
527 return file;
528 };
529 for (const [n, { parent }] of relocs) {
530 const into = fileOf(parent);
531 let from = out.get(into);
532 if (!from) out.set(into, (from = new Set()));
533 from.add(graph.writtenInIndex(n));
534 }
535 }
536 this.#movedFrom = out;
537 return out;
538 }
540 /**
541 * Lay one file out from its packed history (abso Capacity, Graph.packedLines): the lines written in it, and in the
542 * files its moved-in lines came from, read a page at a time; the same tree and order as #layoutResolved, built in
543 * memory with no read per line.
544 */
545 #layoutPacked(path: string, complete: boolean): FileState {
546 const graph = this.graph;
547 const attrs = this.#attributes(path);
548 const start = graph.startCodeOf(path);
549 if (start === undefined) return { attrs, complete, seq: EMPTY_INTS, vis: EMPTY_INTS, deletedBy: new Map() };
550 const relocs = this.#hasMoves ? this.#relocationsN() : undefined;
551 const files = new Set<number>([-1 - start, ...(this.#movedInFrom().get(path) ?? [])]);
552 const children = new Map<number, Child[]>();
553 const texts = new Map<number, string | null>();
554 const deleters = new Map<number, number[]>();
555 for (const file of files) {
556 const lineTexts = graph.packedTexts(file);
557 for (const [n, parent, seq, k, replaces] of graph.packedLines(file)) {
558 const text = lineTexts.next().value as string | null;
559 if (!this.#has(seq)) continue;
560 const moved = relocs?.get(n);
561 let at = parent;
562 let child: Child = { n, replaces, lamport: graph.lamportOfSeq(seq), seq, k };
563 if (moved) {
564 const mover = graph.atom(moved.r.atom).seq;
565 child = { n, replaces: 0, lamport: graph.lamportOfSeq(mover), seq: mover, k: moved.r.k };
566 at = moved.parent;
567 }
568 const list = children.get(at);
569 if (list) list.push(child);
570 else children.set(at, [child]);
571 texts.set(n, text);
572 }
573 for (const [n, deleter] of graph.packedDeletes(file)) {
574 if (!this.#has(deleter)) continue;
575 const by = deleters.get(n);
576 if (by) by.push(deleter);
577 else deleters.set(n, [deleter]);
578 }
579 }
580 const order = (a: Child, b: Child) =>
581 b.replaces - a.replaces || b.lamport - a.lamport || b.seq - a.seq || a.k - b.k;
582 const priority = (a: number, b: number) => graph.lamportOfSeq(a) - graph.lamportOfSeq(b) || a - b;
583 const seq: number[] = [];
584 const vis: number[] = [];
585 const visText: (string | null)[] = [];
586 const deletedBy = new Map<number, readonly number[]>();
587 const stack: number[] = [];
588 const push = (code: number) => {
589 const list = children.get(code);
590 if (!list) return;
591 if (list.length > 1) list.sort(order);
592 for (let i = list.length - 1; i >= 0; i--) stack.push(list[i]!.n);
593 };
594 push(start);
595 while (stack.length) {
596 const n = stack.pop()!;
597 const by = deleters.get(n);
598 if (by) {
599 if (complete) deletedBy.set(seq.length, by.length > 1 ? by.sort(priority) : by);
600 } else {
601 vis.push(n);
602 visText.push(texts.get(n) ?? null);
603 }
604 if (complete) seq.push(n);
605 push(n);
606 }
607 return { attrs, complete, seq: Int32Array.from(seq), vis: Int32Array.from(vis), deletedBy, visText };
608 }
codex-capacity-chair140Avoid line projection for file attribute queriesCompare610 #attributes(path: string): FileAttrs {
codex-capacity-chair132Bound persistent relocation projection memory with rollback-only scratchCompare611 const graph = this.graph;
init0Start the project612 // For each attribute, the highest-priority setter in the set wins.
613 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.Compare614 const file = graph.packedFiles ? graph.pathIndexOf(path) : undefined;
615 if (graph.packedFiles) {
616 for (const [seq, name, value] of file === undefined ? [] : graph.packedAttrs(file)) {
617 if (!this.#has(seq)) continue;
618 const id = graph.idOfSeq(seq);
619 const best = setters.get(name);
620 if (!best || graph.comparePriority(best.id, id) < 0) setters.set(name, { id, value });
621 }
622 return {
623 exists: setters.get("exists")?.value === "1",
624 exec: setters.get("exec")?.value === "1",
625 link: setters.get("link")?.value ?? null,
626 blob: setters.get("blob")?.value ?? null,
627 };
628 }
codex-capacity-chair119Page per-file atom indexes and stream current-view attribute scansCompare629 for (const id of graph.eachAtomIn(path)) {
init0Start the project630 if (!this.#has(graph.atom(id).seq)) continue;
631 for (const a of graph.atom(id).attrs ?? []) {
632 if (a.file !== path) continue;
633 const best = setters.get(a.name);
634 if (!best || graph.comparePriority(best.id, id) < 0) setters.set(a.name, { id, value: a.value });
635 }
636 }
codex-capacity-chair140Avoid line projection for file attribute queriesCompare637
638 return {
init0Start the project639 exists: setters.get("exists")?.value === "1",
640 exec: setters.get("exec")?.value === "1",
641 link: setters.get("link")?.value ?? null,
642 blob: setters.get("blob")?.value ?? null,
643 };
codex-capacity-chair140Avoid line projection for file attribute queriesCompare644 }
init0Start the project645
codex-capacity-chair132Bound persistent relocation projection memory with rollback-only scratchCompare646 #layoutResolved(path: string, complete: boolean, nodes?: Iterable<number>): FileState {
codex-capacity-chair140Avoid line projection for file attribute queriesCompare647 const graph = this.graph;
648 const attrs = this.#attributes(path);
init0Start the project649 const seq: number[] = [];
650 const vis: number[] = [];
651 const deletedBy = new Map<number, readonly number[]>();
codex-capacity-chair131Bound persisted no-move layout with ordered successor traversalCompare652
init0Start the project653 const start = graph.startCodeOf(path);
654 const priority = (a: number, b: number) => graph.lamportOfSeq(a) - graph.lamportOfSeq(b) || a - b;
codex-capacity-chair132Bound persistent relocation projection memory with rollback-only scratchCompare655 for (const n of nodes ?? (start === undefined ? [] : this.#layoutNodes(start))) {
codex-capacity-chair128Page deletion history and short-circuit current visibilityCompare656 let deleted = false;
657 const by: number[] = [];
658 for (const deleter of graph.eachDeleterSeqOf(n)) {
659 if (!this.#has(deleter)) continue;
660 deleted = true;
661 if (!complete) break;
662 by.push(deleter);
663 }
664 if (deleted) {
665 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 stateCompare666 } else vis.push(n);
667 if (complete) seq.push(n);
init0Start the project668 }
codex-capacity-chair140Avoid line projection for file attribute queriesCompare669
codex-capacity-chair110Keep current-file views and key scans from retaining historical stateCompare670 return { attrs, complete, seq: Int32Array.from(seq), vis: Int32Array.from(vis), deletedBy };
init0Start the project671 }
673 get #known(): string[] {
674 if (!this.#knownList) {
675 const known = new Set<string>();
codex-capacity-chair109Add opt-in persistent writer state, checked reopen and bounded adoptionCompare676 if (this.#stable) {
677 for (const id of this.#stable) for (const file of this.graph.filesOf(id)) known.add(file);
678 } else {
679 for (let seq = 0; seq < this.#in.length; seq++)
680 if (this.#in[seq] === 1) for (const file of this.graph.filesOf(this.graph.idOfSeq(seq))) known.add(file);
681 }
init0Start the project682 this.#knownList = [...known].sort();
683 }
684 return this.#knownList;
685 }
687 /** Files with at least one visible line, sorted. */
688 paths(): string[] {
codex-capacity-chair118Avoid retaining deleted historical paths in indexed current viewsCompare689 if (this.#stable) {
690 const paths: string[] = [];
691 for (const path of this.graph.knownFiles()) {
692 if (this.hasFile(path)) paths.push(path);
693 else this.#files.delete(path);
694 }
695 return paths.sort();
696 }
init0Start the project697 return this.#known.filter((p) => this.hasFile(p));
698 }
700 /** Every file the set has ever written a line in, including fully deleted ones. */
701 knownPaths(): string[] {
702 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.Compare703 }
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 changesCompare705 /** The file line n sits in, in this set: fileOf by the line's number, with no lookup of its id. */
706 fileOfNumber(n: number): string {
707 return this.#fileOfN(n);
708 }
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.Compare710 /** How many visible lines a file has. */
711 visibleCount(path: string): number {
712 return this.#file(path).vis.length;
init0Start the project713 }
715 /** Whether the file exists in this projection (has a visible line). */
716 hasFile(path: string): boolean {
codex-capacity-chair140Avoid line projection for file attribute queriesCompare717 const attrs = this.attrs(path);
718 return attrs.exists || attrs.link !== null || attrs.blob !== null || this.#file(path).vis.length > 0;
init0Start the project719 }
721 /** A file's attributes: kept while empty, executable, a link's target. */
722 attrs(path: string): FileAttrs {
codex-capacity-chair140Avoid line projection for file attribute queriesCompare723 return this.#files.get(path)?.attrs ?? this.#attributes(path);
init0Start the project724 }
726 /** The projected text of a file ("" if it has no visible lines). */
727 text(path: string): string {
728 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.Compare729 const { vis, visText } = this.#file(path);
init0Start the project730 const lines: string[] = new Array(vis.length);
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.Compare731 for (let i = 0; i < vis.length; i++) lines[i] = visText?.[i] ?? this.graph.textOf(vis[i]!);
init0Start the project732 const text = joinLines(lines);
733 this.#textCache = { path, text };
734 return text;
735 }
737 /** 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)Compare738 sameText(path: string, other: ReadView): boolean {
739 if (!(other instanceof View)) {
740 const a = this.lines(path),
741 b = other.lines(path);
742 return a.length === b.length && a.every((line, i) => line.text === b[i]!.text);
743 }
init0Start the project744 const a = this.#file(path).vis;
745 const b = other.#file(path).vis;
746 if (a.length !== b.length) return false;
747 for (let i = 0; i < a.length; i++)
748 if (a[i] !== b[i] && this.graph.textOf(a[i]!) !== this.graph.textOf(b[i]!)) return false;
749 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.Compare750 }
752 *lineChunks(path: string): IterableIterator<() => Iterable<string>> {
753 for (const n of this.#file(path).vis) yield () => this.graph.textChunks(n);
754 }
756 /** Visible lines without retaining their text in the view cache. */
757 *visibleLines(path: string): IterableIterator<VisibleLine> {
758 const graph = this.graph;
759 for (const n of this.#file(path).vis)
760 yield { id: graph.lineIdOf(n), text: graph.textOf(n), atom: graph.idOfSeq(graph.writerSeqOf(n)) };
761 }
763 /** Atom-building line handles; text is loaded only when requested. */
764 buildLines(path: string): readonly VisibleLine[] {
765 const graph = this.graph;
766 const vis = this.#file(path).vis;
767 const lines: VisibleLine[] = new Array(vis.length);
768 for (let i = 0; i < vis.length; i++) {
769 const n = vis[i]!;
770 lines[i] = {
771 id: graph.lineIdOf(n),
772 textChunks: () => graph.textChunks(n),
773 get text() {
774 return graph.textOf(n);
775 },
776 atom: graph.idOfSeq(graph.writerSeqOf(n)),
777 };
778 }
779 return lines;
init0Start the project780 }
782 /** Visible lines with their ids. */
783 lines(path: string): readonly VisibleLine[] {
784 if (this.#linesCache?.path === path) return this.#linesCache.lines;
785 const graph = this.graph;
786 const vis = this.#file(path).vis;
787 const lines: VisibleLine[] = new Array(vis.length);
788 for (let i = 0; i < vis.length; i++) {
789 const n = vis[i]!;
790 lines[i] = { id: graph.lineIdOf(n), text: graph.textOf(n), atom: graph.idOfSeq(graph.writerSeqOf(n)) };
791 }
792 this.#linesCache = { path, lines };
793 return lines;
794 }
796 /** The full linearized sequence of a file, tombstones included. */
797 sequence(path: string): readonly SeqLine[] {
798 if (this.#seqCache?.path === path) return this.#seqCache.seq;
799 const graph = this.graph;
codex-capacity-chair110Keep current-file views and key scans from retaining historical stateCompare800 const f = this.#file(path, true);
init0Start the project801 const out: SeqLine[] = new Array(f.seq.length);
802 for (let i = 0; i < f.seq.length; i++) {
803 const n = f.seq[i]!;
804 const by = f.deletedBy.get(i);
805 out[i] = {
806 id: graph.lineIdOf(n),
807 text: graph.textOf(n),
808 atom: graph.idOfSeq(graph.writerSeqOf(n)),
809 deletedBy: by ? by.map((s) => graph.idOfSeq(s)) : NONE,
810 visible: by === undefined,
811 };
812 }
813 this.#seqCache = { path, seq: out };
814 return out;
815 }
codex-capacity-chair138Find reason-warning neighbors without materializing file historyCompare817 /** Two visible neighbours without retaining the file's historical sequence. */
818 visibleNeighbours(path: string, line: LineId): LineId[] {
819 const graph = this.graph;
820 const target = graph.lineN(line);
821 const start = graph.startCodeOf(path);
822 if (target < 0 || start === undefined) return [];
823 const scan = (nodes: Iterable<number>): LineId[] => {
824 let previous: LineId | undefined;
825 let found = false;
826 for (const n of nodes) {
827 if (n === target) {
828 found = true;
829 continue;
830 }
831 let deleted = false;
832 for (const seq of graph.eachDeleterSeqOf(n))
833 if (this.#has(seq)) {
834 deleted = true;
835 break;
836 }
837 if (deleted) continue;
838 const id = graph.lineIdOf(n);
839 if (found) return previous === undefined ? [id] : [previous, id];
840 previous = id;
841 }
842 return found && previous !== undefined ? [previous] : [];
843 };
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.Compare844 if (this.#scratchMoves())
codex-capacity-chair138Find reason-warning neighbors without materializing file historyCompare845 return graph.withProjectionScratch((scratch) =>
846 scan(scratchLayoutNodes(graph, (id) => this.#has(graph.atom(id).seq), scratch, graph.nodeOf(start))),
847 );
848 return scan(this.#layoutNodes(start));
849 }
init0Start the project851 /** Index of a line in `sequence(path)`, or -1. */
852 sequenceIndex(path: string, line: LineId): number {
codex-capacity-chair110Keep current-file views and key scans from retaining historical stateCompare853 const f = this.#file(path, true);
init0Start the project854 if (!f.seqIndex) {
855 f.seqIndex = new Map();
856 for (let i = 0; i < f.seq.length; i++) f.seqIndex.set(f.seq[i]!, i);
857 }
858 return f.seqIndex.get(this.graph.lineN(line)) ?? -1;
859 }
861 /** Index of a line in `lines(path)` (0-based visible line number), or -1 if not visible. */
862 lineNumber(path: string, line: LineId): 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 changesCompare863 return this.lineNumberOf(path, this.graph.lineN(line));
864 }
866 /** lineNumber by the line's number, with no lookup of its id. */
867 lineNumberOf(path: string, n: number): number {
init0Start the project868 const f = this.#file(path);
869 if (!f.visIndex) {
870 f.visIndex = new Map();
871 for (let i = 0; i < f.vis.length; i++) f.visIndex.set(f.vis[i]!, i);
872 }
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 changesCompare873 return f.visIndex.get(n) ?? -1;
874 }
876 /** The seq of the atom that wrote each visible line, in order: lines() without ids or text. */
877 visibleWriters(path: string): number[] {
878 const graph = this.graph;
879 return Array.from(this.#file(path).vis, (n) => graph.writerSeqOf(n));
init0Start the project880 }
882 /** All projected text files, path -> text, in path order. Binary files are in `blobs()`. */
883 files(): Record<string, string> {
884 const out: Record<string, string> = {};
885 for (const path of this.paths()) if (this.#file(path).attrs.blob === null) out[path] = this.text(path);
886 return out;
887 }
889 /** Binary files, path -> the SHA-256 of their bytes, in path order. */
890 blobs(): Record<string, string> {
891 const out: Record<string, string> = {};
892 for (const path of this.paths()) {
893 const blob = this.#file(path).attrs.blob;
894 if (blob !== null) out[path] = blob;
895 }
896 return out;
897 }
899 /**
codex-capacity-policy103Test deterministic replay and account view cache weightCompare900 * About how many bytes of retained state this view costs (#46). This uses
901 * approximate ownership costs for containers and wrappers, not V8 heap
902 * measurements. Graph-owned strings and records count only as references.
903 * This method only inspects already-created state: it does not lay out files,
904 * populate lazy caches, enumerate the graph, or count temporary traversal
905 * containers and shared empty singleton payloads as retained view state.
init0Start the project906 */
907 weight(): number {
codex-capacity-policy103Test deterministic replay and account view cache weightCompare908 let n = this.#in.byteLength;
codex-capacity-chair116Bound repeated indexed view membership lookupsCompare909 n += 2 * ARRAY_HEADER_BYTES + this.#membershipSeq.byteLength + this.#membershipValue.byteLength;
codex-capacity-chair123Stream mover history when opening persisted viewsCompare910 if (this.#movers) n += ARRAY_HEADER_BYTES + REFERENCE_BYTES * this.#movers.length;
codex-capacity-policy103Test deterministic replay and account view cache weightCompare911 n += MAP_HEADER_BYTES; // #files exists from construction.
912 n += MAP_HEADER_BYTES; // #fileOf exists from construction.
codex-capacity-chair109Add opt-in persistent writer state, checked reopen and bounded adoptionCompare913 if (this.#stable) n += this.#stable.retainedBytes;
914 else if (this.#set) n += OBJECT_BYTES + SET_ENTRY_BYTES * this.#set.size;
codex-capacity-policy103Test deterministic replay and account view cache weightCompare915 if (this.#knownList) n += ARRAY_HEADER_BYTES + REFERENCE_BYTES * this.#knownList.length;
916 if (this.#relocs) n += MAP_HEADER_BYTES + MAP_ENTRY_BYTES * this.#relocs.size;
917 if (this.#relocsN) n += MAP_HEADER_BYTES + (MAP_ENTRY_BYTES + OBJECT_BYTES) * this.#relocsN.size;
918 n += MAP_ENTRY_BYTES * this.#fileOf.size;
919 for (const f of this.#files.values()) {
920 n += MAP_ENTRY_BYTES;
921 if (f !== NO_FILE) {
922 // FileState and FileAttrs are per laid-out file; typed-array
923 // headers are separate from their payload byte lengths below.
924 n += OBJECT_BYTES + OBJECT_BYTES + 2 * ARRAY_HEADER_BYTES;
925 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.Compare926 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 weightCompare927 n += MAP_HEADER_BYTES + (MAP_ENTRY_BYTES + ARRAY_HEADER_BYTES) * f.deletedBy.size;
928 for (const deleters of f.deletedBy.values()) n += REFERENCE_BYTES * deleters.length;
929 if (f.seqIndex) n += MAP_HEADER_BYTES + MAP_ENTRY_BYTES * f.seqIndex.size;
930 if (f.visIndex) n += MAP_HEADER_BYTES + MAP_ENTRY_BYTES * f.visIndex.size;
931 }
932 }
933 if (this.#linesCache)
934 n += OBJECT_BYTES + REFERENCE_BYTES + ARRAY_HEADER_BYTES + 100 * this.#linesCache.lines.length;
935 if (this.#seqCache) {
936 n += OBJECT_BYTES + REFERENCE_BYTES + ARRAY_HEADER_BYTES + 120 * this.#seqCache.seq.length;
937 for (const line of this.#seqCache.seq)
938 if (line.deletedBy !== NONE) n += ARRAY_HEADER_BYTES + REFERENCE_BYTES * line.deletedBy.length;
939 }
940 if (this.#textCache) n += OBJECT_BYTES + REFERENCE_BYTES + ARRAY_HEADER_BYTES + 2 * this.#textCache.text.length;
init0Start the project941 return n;
942 }
codex-capacity-chair110Keep current-file views and key scans from retaining historical stateCompare944 #file(path: string, complete = false): FileState {
init0Start the project945 let state = this.#files.get(path);
codex-capacity-chair110Keep current-file views and key scans from retaining historical stateCompare946 if (!state || (complete && !state.complete)) {
codex-capacity-chair119Page per-file atom indexes and stream current-view attribute scansCompare947 state = this.graph.hasAtomsIn(path) ? this.#layout(path, complete) : NO_FILE;
init0Start the project948 this.#files.set(path, state);
949 }
950 return state;
951 }
954/** The files of a closed set, path -> text. */
955export function project(graph: Graph, set: Iterable<AtomId>): Record<string, string> {
956 return new View(graph, set).files();
959/** 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)Compare960export function indexAfter(view: Pick<ReadView, "sequenceIndex">, path: string, node: NodeId): number {
init0Start the project961 if (isStartNode(node)) return 0;
962 const i = view.sequenceIndex(path, node);
963 if (i < 0) throw new EngineError("not-in-view", `line ${node} is not in ${path} in this view`);
964 return i + 1;