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 215 --json
JSON
/christopher/abso-core/blame/src/engine/view.ts?version=215&format=json
1,011 linesFirst import 38% · capacity 33% · codex-capacity-chair 25% · codex-capacity-policy 4%Last change capacity in version 215,

1,011 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";
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;
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.Compare98/**
99 * Moved lines a view resolves once and keeps (abso Capacity): a stored graph otherwise resolved every move again on
100 * disk for each file it laid out. Game's whole history has 290; past this many, the view goes back to that.
101 */
102export const MOVED_LINES_KEPT = 20_000;
103class TooManyMoves extends Error {}
104const NO_LINES: readonly number[] = Object.freeze([]);
capacity215Moves resolved over the moved lines alone, and closure over a named draft's own atoms (disk-first 2; abso Capacity), for abso's status and drafts. - view.ts MoveSkeleton: once per graph, and extended as it grows, each mover's moved lines, each moved line's relocations, and for any node the nearest node above it that a move ever relocated (or its file's start), memoised up to 200,000 nodes. A view's relocations and its loop check now hop between moved lines instead of walking every moved line's file up to its start, and fileOf hops the same way. The per-view location memos are gone. On abso's export (1,687 moved lines, 972 movers), status went from 104 s to 41 s under the profiler; agent views no longer re-walk each base's moves. - project.ts #closed opens unions down to their closed parts. An agent in a named draft has the draft's atoms over a closed shared base, one union deeper than #closed looked, so it walked all of shared's atoms and their dependencies. Tests: 97 of 97 across moves, relocation, projection-move-resolution, packed-files, view, drop, queued-moves, named-drafts, stored-closure, stored-membership, version-files, draft-reads-stored and writer storage. tsc clean.Compare105/** Nodes whose nearest moved line above a graph remembers, at most: about 40 bytes each. */
106const CLIMB_MEMO = 200_000;
codex-capacity-policy103Test deterministic replay and account view cache weightCompare107
capacity215Moves resolved over the moved lines alone, and closure over a named draft's own atoms (disk-first 2; abso Capacity), for abso's status and drafts. - view.ts MoveSkeleton: once per graph, and extended as it grows, each mover's moved lines, each moved line's relocations, and for any node the nearest node above it that a move ever relocated (or its file's start), memoised up to 200,000 nodes. A view's relocations and its loop check now hop between moved lines instead of walking every moved line's file up to its start, and fileOf hops the same way. The per-view location memos are gone. On abso's export (1,687 moved lines, 972 movers), status went from 104 s to 41 s under the profiler; agent views no longer re-walk each base's moves. - project.ts #closed opens unions down to their closed parts. An agent in a named draft has the draft's atoms over a closed shared base, one union deeper than #closed looked, so it walked all of shared's atoms and their dependencies. Tests: 97 of 97 across moves, relocation, projection-move-resolution, packed-files, view, drop, queued-moves, named-drafts, stored-closure, stored-membership, version-files, draft-reads-stored and writer storage. tsc clean.Compare108/** One relocation of a moved line, with its line's number and its new parent's code. */
109interface MoveEntry {
110 readonly n: number;
111 readonly r: RelocationInfo;
112 readonly parent: number;
init0Start the project115/**
capacity215Moves resolved over the moved lines alone, and closure over a named draft's own atoms (disk-first 2; abso Capacity), for abso's status and drafts. - view.ts MoveSkeleton: once per graph, and extended as it grows, each mover's moved lines, each moved line's relocations, and for any node the nearest node above it that a move ever relocated (or its file's start), memoised up to 200,000 nodes. A view's relocations and its loop check now hop between moved lines instead of walking every moved line's file up to its start, and fileOf hops the same way. The per-view location memos are gone. On abso's export (1,687 moved lines, 972 movers), status went from 104 s to 41 s under the profiler; agent views no longer re-walk each base's moves. - project.ts #closed opens unions down to their closed parts. An agent in a named draft has the draft's atoms over a closed shared base, one union deeper than #closed looked, so it walked all of shared's atoms and their dependencies. Tests: 97 of 97 across moves, relocation, projection-move-resolution, packed-files, view, drop, queued-moves, named-drafts, stored-closure, stored-membership, version-files, draft-reads-stored and writer storage. tsc clean.Compare116 * A graph's moves, whatever the set (abso Capacity): each mover's moved lines, each moved line's relocations in seq
117 * order, and for any node the nearest node at or above it, by where lines were written, that a move ever relocated,
118 * or its file's start. Worked out once per graph and extended as it grows. A view's moves then resolve over the moved
119 * lines alone: before, every view walked each moved line's file up to its start, a read per line.
120 */
121class MoveSkeleton {
122 readonly #graph: Graph;
123 #seen = 0;
124 /** Movers in seq order, with the numbers of the lines each moves, in its moves' order. */
125 readonly movers: { readonly seq: number; readonly lines: readonly number[] }[] = [];
126 /** Every relocation of each moved line, by the line's number, in seq order. */
127 readonly byLine = new Map<number, MoveEntry[]>();
128 readonly #climbed = new Map<number, number>();
130 constructor(graph: Graph) {
131 this.#graph = graph;
132 }
134 /** Take in movers the graph gained since. */
135 update(): this {
136 const graph = this.#graph;
137 const all = graph.movers();
138 if (this.#seen === all.length) return this;
139 for (; this.#seen < all.length; this.#seen++) {
140 const id = all[this.#seen]!;
141 const lines: number[] = [];
142 graph.atom(id).moves!.forEach((m, k) => {
143 const n = graph.lineN(m.line);
144 const r: RelocationInfo = Object.freeze({ atom: id, line: m.line, parent: m.parent, k });
145 const entry: MoveEntry = { n, r, parent: graph.codeOf(m.parent)! };
146 const list = this.byLine.get(n);
147 if (list) list.push(entry);
148 else this.byLine.set(n, [entry]);
149 lines.push(n);
150 });
151 this.movers.push({ seq: seqOf(id), lines });
152 }
153 // A new moved line can sit between a node and the one it climbed to.
154 this.#climbed.clear();
155 return this;
156 }
158 /** The nearest node at or above this one, by where lines were written, that a move ever relocated; or its file's start. */
159 climb(code: number): number {
160 const walked: number[] = [];
161 let c = code;
162 while (c >= 0 && !this.byLine.has(c)) {
163 const known = this.#climbed.get(c);
164 if (known !== undefined) {
165 c = known;
166 break;
167 }
168 walked.push(c);
169 c = this.#graph.parentCodeOf(c);
170 }
171 if (this.#climbed.size + walked.length > CLIMB_MEMO) this.#climbed.clear();
172 for (const w of walked) this.#climbed.set(w, c);
173 return c;
174 }
177const skeletons = new WeakMap<Graph, MoveSkeleton>();
178function skeletonOf(graph: Graph): MoveSkeleton {
179 let skeleton = skeletons.get(graph);
180 if (!skeleton) skeletons.set(graph, (skeleton = new MoveSkeleton(graph)));
181 return skeleton.update();
184/**
init0Start the project185 * The projection of a closed set. Construct once, then ask for files, lines
186 * and sequences. Throws `not-closed` if some atom's dependency is missing.
187 * Each file is laid out the first time it is asked for, so a view of a large
188 * set costs little until files are read.
189 */
190export class View {
191 readonly graph: Graph;
192 /** 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 adoptionCompare193 #set: AtomSet | undefined;
194 readonly #stable: StableSet<AtomId> | undefined;
codex-capacity-chair116Bound repeated indexed view membership lookupsCompare195 /** Fixed-size memo for immutable indexed membership, independent of history size. */
196 #membershipSeq = new Float64Array(256).fill(-1);
197 #membershipValue = new Uint8Array(256);
init0Start the project198 #files = new Map<string, FileState>();
199 /** Every file the set wrote in, sorted; worked out the first time it's asked for. */
200 #knownList: string[] | undefined;
201 /** 1 for each atom (by seq) in the set. */
202 #in: Uint8Array;
203 /** Atoms in the set that move lines. */
codex-capacity-chair123Stream mover history when opening persisted viewsCompare204 #movers: AtomId[] | undefined;
205 #hasMoves = false;
init0Start the project206 /** Each moved line's relocation that counts in this set; built on first use. */
207 #relocs: Map<LineId, RelocationInfo> | undefined;
208 /** The same, by n, with the new parent's code. */
209 #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.Compare210 /** The moved lines under each node, by its code, made from the relocations on first use. */
211 #movedInto: Map<number, number[]> | undefined;
212 /** Whether this view's moves are too many to keep, so they're resolved on disk per layout; undefined until asked. */
213 #movesOnDisk: boolean | undefined;
init0Start the project214 /** The latest records asked for: one file's lines, one file's sequence, one file's text. */
215 #linesCache: { path: string; lines: readonly VisibleLine[] } | undefined;
216 #seqCache: { path: string; seq: readonly SeqLine[] } | undefined;
217 #textCache: { path: string; text: string } | undefined;
219 constructor(graph: Graph, set: Iterable<AtomId>) {
codex-capacity-chair109Add opt-in persistent writer state, checked reopen and bounded adoptionCompare220 this.graph = graph;
221 if (set instanceof StableSet) {
222 this.#stable = set;
223 this.#set = set;
224 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.Compare225 // A set kept closed when it was written needs no proof here (abso Capacity).
226 for (const id of isClosedSet(set) ? [] : set) {
codex-capacity-chair109Add opt-in persistent writer state, checked reopen and bounded adoptionCompare227 const atom = graph.atom(id);
228 for (const dependency of atom.deps) {
229 graph.atom(dependency);
230 if (!set.has(dependency))
231 throw new EngineError("not-closed", `set is not closed: ${id} depends on ${dependency}`);
232 }
233 }
codex-capacity-chair123Stream mover history when opening persisted viewsCompare234 for (const id of graph.movers()) {
235 if (set.has(id)) {
236 this.#hasMoves = true;
237 break;
238 }
239 }
240 this.#relocs = this.#hasMoves ? undefined : new Map();
241 this.#relocsN = this.#hasMoves ? undefined : new Map();
codex-capacity-chair109Add opt-in persistent writer state, checked reopen and bounded adoptionCompare242 return;
243 }
init0Start the project244 const inSet = new Uint8Array(graph.size);
245 for (const id of set) {
246 const atom = graph.atom(id);
247 inSet[atom.seq] = 1;
248 }
codex-capacity-chair109Add opt-in persistent writer state, checked reopen and bounded adoptionCompare249 // Validate one atom at a time. Keeping all decoded atoms here defeats
250 // storage-backed Graph reads even though the view only needs membership.
251 for (let seq = 0; seq < inSet.length; seq++) {
252 if (inSet[seq] !== 1) continue;
253 const atom = graph.atom(graph.idOfSeq(seq));
init0Start the project254 for (const d of atom.deps) {
255 if (inSet[graph.atom(d).seq] !== 1)
256 throw new EngineError("not-closed", `set is not closed: ${atom.id} depends on ${d}`);
257 }
258 }
259 this.graph = graph;
260 this.#in = inSet;
261 this.#movers = graph.movers().filter((id) => inSet[graph.atom(id).seq] === 1);
codex-capacity-chair123Stream mover history when opening persisted viewsCompare262 this.#hasMoves = this.#movers.length > 0;
init0Start the project263 this.#relocs = this.#movers.length === 0 ? new Map() : undefined;
264 this.#relocsN = this.#movers.length === 0 ? new Map() : undefined;
265 }
267 /** The set of atoms this view projects. */
268 get set(): AtomSet {
269 if (!this.#set) {
270 const out = new Set<AtomId>();
271 for (let seq = 0; seq < this.#in.length; seq++) if (this.#in[seq] === 1) out.add(this.graph.idOfSeq(seq));
272 this.#set = out;
273 }
274 return this.#set;
275 }
277 /** Whether the atom with this seq is in the set. */
278 #has(seq: number): boolean {
codex-capacity-chair116Bound repeated indexed view membership lookupsCompare279 if (this.#stable) {
280 const slot = seq % this.#membershipSeq.length;
281 if (this.#membershipSeq[slot] === seq) return this.#membershipValue[slot] === 1;
282 const present = this.#stable.has(this.graph.idOfSeq(seq));
283 this.#membershipSeq[slot] = seq;
284 this.#membershipValue[slot] = present ? 1 : 0;
285 return present;
286 }
init0Start the project287 return seq < this.#in.length && this.#in[seq] === 1;
288 }
290 /**
291 * The relocation that counts for each moved line: the newest (by priority)
292 * in the set. Two moves made apart can loop lines into each other, so no
293 * start node reaches them; then the oldest relocation on the loop is
294 * ignored, and the next newest of that line counts, until none loop.
295 */
296 #relocations(): Map<LineId, RelocationInfo> {
297 if (this.#relocs) return this.#relocs;
298 const graph = this.graph;
capacity215Moves resolved over the moved lines alone, and closure over a named draft's own atoms (disk-first 2; abso Capacity), for abso's status and drafts. - view.ts MoveSkeleton: once per graph, and extended as it grows, each mover's moved lines, each moved line's relocations, and for any node the nearest node above it that a move ever relocated (or its file's start), memoised up to 200,000 nodes. A view's relocations and its loop check now hop between moved lines instead of walking every moved line's file up to its start, and fileOf hops the same way. The per-view location memos are gone. On abso's export (1,687 moved lines, 972 movers), status went from 104 s to 41 s under the profiler; agent views no longer re-walk each base's moves. - project.ts #closed opens unions down to their closed parts. An agent in a named draft has the draft's atoms over a closed shared base, one union deeper than #closed looked, so it walked all of shared's atoms and their dependencies. Tests: 97 of 97 across moves, relocation, projection-move-resolution, packed-files, view, drop, queued-moves, named-drafts, stored-closure, stored-membership, version-files, draft-reads-stored and writer storage. tsc clean.Compare299 const skeleton = skeletonOf(graph);
init0Start the project300 const stronger = (a: RelocationInfo, b: RelocationInfo): boolean => graph.comparePriority(a.atom, b.atom) > 0;
codex-capacity-chair126Identify suppressed relocation cycles across persistent readsCompare301 const identity = (r: RelocationInfo): string => JSON.stringify([r.atom, r.k]);
302 const ignored = new Set<string>();
capacity215Moves resolved over the moved lines alone, and closure over a named draft's own atoms (disk-first 2; abso Capacity), for abso's status and drafts. - view.ts MoveSkeleton: once per graph, and extended as it grows, each mover's moved lines, each moved line's relocations, and for any node the nearest node above it that a move ever relocated (or its file's start), memoised up to 200,000 nodes. A view's relocations and its loop check now hop between moved lines instead of walking every moved line's file up to its start, and fileOf hops the same way. The per-view location memos are gone. On abso's export (1,687 moved lines, 972 movers), status went from 104 s to 41 s under the profiler; agent views no longer re-walk each base's moves. - project.ts #closed opens unions down to their closed parts. An agent in a named draft has the draft's atoms over a closed shared base, one union deeper than #closed looked, so it walked all of shared's atoms and their dependencies. Tests: 97 of 97 across moves, relocation, projection-move-resolution, packed-files, view, drop, queued-moves, named-drafts, stored-closure, stored-membership, version-files, draft-reads-stored and writer storage. tsc clean.Compare303 const pick = (n: number): MoveEntry | undefined => {
304 let best: MoveEntry | undefined;
305 for (const e of skeleton.byLine.get(n) ?? []) {
306 if (this.#has(seqOf(e.r.atom)) && !ignored.has(identity(e.r)) && (!best || stronger(e.r, best.r))) best = e;
init0Start the project307 }
308 return best;
309 };
capacity215Moves resolved over the moved lines alone, and closure over a named draft's own atoms (disk-first 2; abso Capacity), for abso's status and drafts. - view.ts MoveSkeleton: once per graph, and extended as it grows, each mover's moved lines, each moved line's relocations, and for any node the nearest node above it that a move ever relocated (or its file's start), memoised up to 200,000 nodes. A view's relocations and its loop check now hop between moved lines instead of walking every moved line's file up to its start, and fileOf hops the same way. The per-view location memos are gone. On abso's export (1,687 moved lines, 972 movers), status went from 104 s to 41 s under the profiler; agent views no longer re-walk each base's moves. - project.ts #closed opens unions down to their closed parts. An agent in a named draft has the draft's atoms over a closed shared base, one union deeper than #closed looked, so it walked all of shared's atoms and their dependencies. Tests: 97 of 97 across moves, relocation, projection-move-resolution, packed-files, view, drop, queued-moves, named-drafts, stored-closure, stored-membership, version-files, draft-reads-stored and writer storage. tsc clean.Compare310 // By the moved line's number, in the order its movers come (seq order, then each mover's moves).
311 const relocs = new Map<number, MoveEntry>();
312 for (const mover of skeleton.movers) {
313 if (!this.#has(mover.seq)) continue;
314 for (const n of mover.lines) {
315 if (!relocs.has(n)) relocs.set(n, pick(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.Compare316 if (graph.hasOrderedChildren && relocs.size > MOVED_LINES_KEPT) throw new TooManyMoves();
init0Start the project317 }
318 }
capacity215Moves resolved over the moved lines alone, and closure over a named draft's own atoms (disk-first 2; abso Capacity), for abso's status and drafts. - view.ts MoveSkeleton: once per graph, and extended as it grows, each mover's moved lines, each moved line's relocations, and for any node the nearest node above it that a move ever relocated (or its file's start), memoised up to 200,000 nodes. A view's relocations and its loop check now hop between moved lines instead of walking every moved line's file up to its start, and fileOf hops the same way. The per-view location memos are gone. On abso's export (1,687 moved lines, 972 movers), status went from 104 s to 41 s under the profiler; agent views no longer re-walk each base's moves. - project.ts #closed opens unions down to their closed parts. An agent in a named draft has the draft's atoms over a closed shared base, one union deeper than #closed looked, so it walked all of shared's atoms and their dependencies. Tests: 97 of 97 across moves, relocation, projection-move-resolution, packed-files, view, drop, queued-moves, named-drafts, stored-closure, stored-membership, version-files, draft-reads-stored and writer storage. tsc clean.Compare319 // From a node, the next node that matters for loops: a line moved in this set, or a file's start.
320 const hop = (code: number): number => {
321 let c = skeleton.climb(code);
322 while (c >= 0 && !relocs.has(c)) c = skeleton.climb(graph.parentCodeOf(c));
323 return c;
324 };
325 const step = (n: number): number => {
326 const e = relocs.get(n);
327 return hop(e ? e.parent : graph.parentCodeOf(n));
328 };
329 // Two moves made apart can loop lines into each other, so no start node reaches them; then the oldest
330 // relocation on the loop is ignored, and the next newest of that line counts, until none loop.
331 const reaches = new Set<number>();
init0Start the project332 for (const line of [...relocs.keys()]) {
333 for (;;) {
capacity215Moves resolved over the moved lines alone, and closure over a named draft's own atoms (disk-first 2; abso Capacity), for abso's status and drafts. - view.ts MoveSkeleton: once per graph, and extended as it grows, each mover's moved lines, each moved line's relocations, and for any node the nearest node above it that a move ever relocated (or its file's start), memoised up to 200,000 nodes. A view's relocations and its loop check now hop between moved lines instead of walking every moved line's file up to its start, and fileOf hops the same way. The per-view location memos are gone. On abso's export (1,687 moved lines, 972 movers), status went from 104 s to 41 s under the profiler; agent views no longer re-walk each base's moves. - project.ts #closed opens unions down to their closed parts. An agent in a named draft has the draft's atoms over a closed shared base, one union deeper than #closed looked, so it walked all of shared's atoms and their dependencies. Tests: 97 of 97 across moves, relocation, projection-move-resolution, packed-files, view, drop, queued-moves, named-drafts, stored-closure, stored-membership, version-files, draft-reads-stored and writer storage. tsc clean.Compare334 const path: number[] = [];
335 const onPath = new Map<number, number>();
336 let cur = line;
init0Start the project337 let loopAt = -1;
capacity215Moves resolved over the moved lines alone, and closure over a named draft's own atoms (disk-first 2; abso Capacity), for abso's status and drafts. - view.ts MoveSkeleton: once per graph, and extended as it grows, each mover's moved lines, each moved line's relocations, and for any node the nearest node above it that a move ever relocated (or its file's start), memoised up to 200,000 nodes. A view's relocations and its loop check now hop between moved lines instead of walking every moved line's file up to its start, and fileOf hops the same way. The per-view location memos are gone. On abso's export (1,687 moved lines, 972 movers), status went from 104 s to 41 s under the profiler; agent views no longer re-walk each base's moves. - project.ts #closed opens unions down to their closed parts. An agent in a named draft has the draft's atoms over a closed shared base, one union deeper than #closed looked, so it walked all of shared's atoms and their dependencies. Tests: 97 of 97 across moves, relocation, projection-move-resolution, packed-files, view, drop, queued-moves, named-drafts, stored-closure, stored-membership, version-files, draft-reads-stored and writer storage. tsc clean.Compare338 while (cur >= 0 && !reaches.has(cur)) {
init0Start the project339 const at = onPath.get(cur);
340 if (at !== undefined) {
341 loopAt = at;
342 break;
343 }
344 onPath.set(cur, path.length);
345 path.push(cur);
capacity215Moves resolved over the moved lines alone, and closure over a named draft's own atoms (disk-first 2; abso Capacity), for abso's status and drafts. - view.ts MoveSkeleton: once per graph, and extended as it grows, each mover's moved lines, each moved line's relocations, and for any node the nearest node above it that a move ever relocated (or its file's start), memoised up to 200,000 nodes. A view's relocations and its loop check now hop between moved lines instead of walking every moved line's file up to its start, and fileOf hops the same way. The per-view location memos are gone. On abso's export (1,687 moved lines, 972 movers), status went from 104 s to 41 s under the profiler; agent views no longer re-walk each base's moves. - project.ts #closed opens unions down to their closed parts. An agent in a named draft has the draft's atoms over a closed shared base, one union deeper than #closed looked, so it walked all of shared's atoms and their dependencies. Tests: 97 of 97 across moves, relocation, projection-move-resolution, packed-files, view, drop, queued-moves, named-drafts, stored-closure, stored-membership, version-files, draft-reads-stored and writer storage. tsc clean.Compare346 cur = step(cur);
init0Start the project347 }
348 if (loopAt < 0) {
349 for (const l of path) reaches.add(l);
350 break;
351 }
capacity215Moves resolved over the moved lines alone, and closure over a named draft's own atoms (disk-first 2; abso Capacity), for abso's status and drafts. - view.ts MoveSkeleton: once per graph, and extended as it grows, each mover's moved lines, each moved line's relocations, and for any node the nearest node above it that a move ever relocated (or its file's start), memoised up to 200,000 nodes. A view's relocations and its loop check now hop between moved lines instead of walking every moved line's file up to its start, and fileOf hops the same way. The per-view location memos are gone. On abso's export (1,687 moved lines, 972 movers), status went from 104 s to 41 s under the profiler; agent views no longer re-walk each base's moves. - project.ts #closed opens unions down to their closed parts. An agent in a named draft has the draft's atoms over a closed shared base, one union deeper than #closed looked, so it walked all of shared's atoms and their dependencies. Tests: 97 of 97 across moves, relocation, projection-move-resolution, packed-files, view, drop, queued-moves, named-drafts, stored-closure, stored-membership, version-files, draft-reads-stored and writer storage. tsc clean.Compare352 let weakest: MoveEntry | undefined;
init0Start the project353 for (const l of path.slice(loopAt)) {
capacity215Moves resolved over the moved lines alone, and closure over a named draft's own atoms (disk-first 2; abso Capacity), for abso's status and drafts. - view.ts MoveSkeleton: once per graph, and extended as it grows, each mover's moved lines, each moved line's relocations, and for any node the nearest node above it that a move ever relocated (or its file's start), memoised up to 200,000 nodes. A view's relocations and its loop check now hop between moved lines instead of walking every moved line's file up to its start, and fileOf hops the same way. The per-view location memos are gone. On abso's export (1,687 moved lines, 972 movers), status went from 104 s to 41 s under the profiler; agent views no longer re-walk each base's moves. - project.ts #closed opens unions down to their closed parts. An agent in a named draft has the draft's atoms over a closed shared base, one union deeper than #closed looked, so it walked all of shared's atoms and their dependencies. Tests: 97 of 97 across moves, relocation, projection-move-resolution, packed-files, view, drop, queued-moves, named-drafts, stored-closure, stored-membership, version-files, draft-reads-stored and writer storage. tsc clean.Compare354 const e = relocs.get(l);
355 if (e && (!weakest || stronger(weakest.r, e.r))) weakest = e;
init0Start the project356 }
capacity215Moves resolved over the moved lines alone, and closure over a named draft's own atoms (disk-first 2; abso Capacity), for abso's status and drafts. - view.ts MoveSkeleton: once per graph, and extended as it grows, each mover's moved lines, each moved line's relocations, and for any node the nearest node above it that a move ever relocated (or its file's start), memoised up to 200,000 nodes. A view's relocations and its loop check now hop between moved lines instead of walking every moved line's file up to its start, and fileOf hops the same way. The per-view location memos are gone. On abso's export (1,687 moved lines, 972 movers), status went from 104 s to 41 s under the profiler; agent views no longer re-walk each base's moves. - project.ts #closed opens unions down to their closed parts. An agent in a named draft has the draft's atoms over a closed shared base, one union deeper than #closed looked, so it walked all of shared's atoms and their dependencies. Tests: 97 of 97 across moves, relocation, projection-move-resolution, packed-files, view, drop, queued-moves, named-drafts, stored-closure, stored-membership, version-files, draft-reads-stored and writer storage. tsc clean.Compare357 ignored.add(identity(weakest!.r));
358 const next = pick(weakest!.n);
359 if (next) relocs.set(weakest!.n, next);
360 else relocs.delete(weakest!.n);
init0Start the project361 }
362 }
capacity215Moves resolved over the moved lines alone, and closure over a named draft's own atoms (disk-first 2; abso Capacity), for abso's status and drafts. - view.ts MoveSkeleton: once per graph, and extended as it grows, each mover's moved lines, each moved line's relocations, and for any node the nearest node above it that a move ever relocated (or its file's start), memoised up to 200,000 nodes. A view's relocations and its loop check now hop between moved lines instead of walking every moved line's file up to its start, and fileOf hops the same way. The per-view location memos are gone. On abso's export (1,687 moved lines, 972 movers), status went from 104 s to 41 s under the profiler; agent views no longer re-walk each base's moves. - project.ts #closed opens unions down to their closed parts. An agent in a named draft has the draft's atoms over a closed shared base, one union deeper than #closed looked, so it walked all of shared's atoms and their dependencies. Tests: 97 of 97 across moves, relocation, projection-move-resolution, packed-files, view, drop, queued-moves, named-drafts, stored-closure, stored-membership, version-files, draft-reads-stored and writer storage. tsc clean.Compare363 this.#relocsN = new Map([...relocs].map(([n, e]) => [n, { r: e.r, parent: e.parent }]));
364 this.#relocs = new Map([...relocs.values()].map((e) => [e.r.line, e.r]));
365 return this.#relocs;
init0Start the project366 }
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.Compare367
368 /**
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 changesCompare369 * Take another view's resolved moves (abso Capacity), when both sets hold the very same atoms that move lines: the
370 * 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.Compare371 */
372 shareMoves(from: View): void {
373 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 changesCompare374 if (this.#relocs || from.#scratchMoves()) return;
375 for (const id of this.graph.movers()) {
376 const seq = seqOf(id);
377 if (this.#has(seq) !== from.#has(seq)) return;
378 }
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 this.#relocs = from.#relocations();
380 this.#relocsN = from.#relocationsN();
381 this.#movesOnDisk = false;
382 this.#movedFrom = from.#movedInFrom();
383 }
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.Compare385 /** Whether moves are resolved on disk for each layout: only a stored graph's view with more than MOVED_LINES_KEPT. */
386 #scratchMoves(): boolean {
387 if (!this.#hasMoves || !this.graph.hasOrderedChildren) return false;
388 if (this.#movesOnDisk === undefined) {
389 try {
390 this.#relocations();
391 this.#movesOnDisk = false;
392 } catch (error) {
393 if (!(error instanceof TooManyMoves)) throw error;
394 this.#movesOnDisk = true;
395 }
396 }
397 return this.#movesOnDisk;
398 }
init0Start the project400 /** The relocations by n, with each new parent's code. */
401 #relocationsN(): Map<number, { readonly r: RelocationInfo; readonly parent: number }> {
402 if (this.#relocsN) return this.#relocsN;
403 const out = new Map<number, { readonly r: RelocationInfo; readonly parent: number }>();
404 for (const [line, r] of this.#relocations())
405 out.set(this.graph.lineN(line), { r, parent: this.graph.codeOf(r.parent)! });
406 this.#relocsN = out;
407 return out;
408 }
410 /** The node a line hangs off in this set: where it was written, or where a move put it. */
411 parentOf(line: LineId): NodeId {
codex-capacity-chair132Bound persistent relocation projection memory with rollback-only scratchCompare412 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.Compare413 if (this.#scratchMoves())
codex-capacity-chair132Bound persistent relocation projection memory with rollback-only scratchCompare414 return this.graph.withProjectionScratch((scratch) =>
415 resolveScratchMoves(this.graph, (id) => this.#has(this.graph.atom(id).seq), scratch).parent(line),
416 );
codex-capacity-chair123Stream mover history when opening persisted viewsCompare417 const r = this.#hasMoves ? this.#relocations().get(line) : undefined;
init0Start the project418 if (r) return r.parent;
419 const parent = this.graph.lineParent(line);
420 if (parent === undefined) throw new EngineError("unknown-line", `no line ${line}`);
421 return parent;
422 }
424 /** Whether any atom in the set moves lines. */
425 hasMoves(): boolean {
codex-capacity-chair123Stream mover history when opening persisted viewsCompare426 return this.#hasMoves;
427 }
428 *#eachMover(): IterableIterator<AtomId> {
429 if (this.#movers) yield* this.#movers;
430 else for (const id of this.graph.movers()) if (this.#stable!.has(id)) yield id;
init0Start the project431 }
433 /** The file a line is in, in this set: the one its chain of parents reaches. */
434 fileOf(line: LineId): string {
435 const n = this.graph.lineN(line);
436 if (n < 0) throw new EngineError("unknown-line", `no line ${line}`);
437 return this.#fileOfN(n);
438 }
440 #fileOfN(n: number): string {
441 const graph = this.graph;
codex-capacity-chair123Stream mover history when opening persisted viewsCompare442 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.Compare443 if (this.#scratchMoves())
codex-capacity-chair132Bound persistent relocation projection memory with rollback-only scratchCompare444 return graph.withProjectionScratch((scratch) => {
445 const moves = resolveScratchMoves(graph, (id) => this.#has(graph.atom(id).seq), scratch);
446 let current = graph.nodeOf(n);
447 while (!isStartNode(current)) current = moves.parent(current);
448 return current.slice(1);
449 });
capacity215Moves resolved over the moved lines alone, and closure over a named draft's own atoms (disk-first 2; abso Capacity), for abso's status and drafts. - view.ts MoveSkeleton: once per graph, and extended as it grows, each mover's moved lines, each moved line's relocations, and for any node the nearest node above it that a move ever relocated (or its file's start), memoised up to 200,000 nodes. A view's relocations and its loop check now hop between moved lines instead of walking every moved line's file up to its start, and fileOf hops the same way. The per-view location memos are gone. On abso's export (1,687 moved lines, 972 movers), status went from 104 s to 41 s under the profiler; agent views no longer re-walk each base's moves. - project.ts #closed opens unions down to their closed parts. An agent in a named draft has the draft's atoms over a closed shared base, one union deeper than #closed looked, so it walked all of shared's atoms and their dependencies. Tests: 97 of 97 across moves, relocation, projection-move-resolution, packed-files, view, drop, queued-moves, named-drafts, stored-closure, stored-membership, version-files, draft-reads-stored and writer storage. tsc clean.Compare450 return this.#fileOfCode(n);
451 }
453 /** The file a node sits in, in this set: up by where lines were written, through the moves that count here. */
454 #fileOfCode(code: number): string {
455 const graph = this.graph;
init0Start the project456 const relocs = this.#relocationsN();
capacity215Moves resolved over the moved lines alone, and closure over a named draft's own atoms (disk-first 2; abso Capacity), for abso's status and drafts. - view.ts MoveSkeleton: once per graph, and extended as it grows, each mover's moved lines, each moved line's relocations, and for any node the nearest node above it that a move ever relocated (or its file's start), memoised up to 200,000 nodes. A view's relocations and its loop check now hop between moved lines instead of walking every moved line's file up to its start, and fileOf hops the same way. The per-view location memos are gone. On abso's export (1,687 moved lines, 972 movers), status went from 104 s to 41 s under the profiler; agent views no longer re-walk each base's moves. - project.ts #closed opens unions down to their closed parts. An agent in a named draft has the draft's atoms over a closed shared base, one union deeper than #closed looked, so it walked all of shared's atoms and their dependencies. Tests: 97 of 97 across moves, relocation, projection-move-resolution, packed-files, view, drop, queued-moves, named-drafts, stored-closure, stored-membership, version-files, draft-reads-stored and writer storage. tsc clean.Compare457 const skeleton = skeletonOf(graph);
458 let c = code;
459 for (;;) {
460 c = skeleton.climb(c);
461 if (c < 0) return graph.nodeOf(c).slice(1);
462 const e = relocs.get(c);
463 c = e ? e.parent : graph.parentCodeOf(c);
init0Start the project464 }
465 }
467 /** The lines hanging off a node in this set, in layout order. */
468 #children(code: number): Child[] {
469 const graph = this.graph;
codex-capacity-chair123Stream mover history when opening persisted viewsCompare470 const relocs = this.#hasMoves ? this.#relocationsN() : undefined;
init0Start the project471 const out: Child[] = [];
codex-capacity-chair130Stream paged child history into layout filteringCompare472 for (const n of graph.eachChildN(code)) {
init0Start the project473 const seq = graph.writerSeqOf(n);
474 if (!this.#has(seq) || relocs?.has(n)) continue;
475 out.push({ n, replaces: graph.replacesN(n) ? 1 : 0, lamport: graph.lamportOfSeq(seq), seq, k: graph.kOf(n) });
476 }
477 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.Compare478 // The lines this set's moves put under each node, from the moves it already resolved: no row read per node
479 // (abso Capacity).
480 if (!this.#movedInto) {
481 this.#movedInto = new Map();
482 for (const [n, { parent }] of relocs) {
483 const into = this.#movedInto.get(parent);
484 if (into) into.push(n);
485 else this.#movedInto.set(parent, [n]);
486 }
487 }
488 for (const n of this.#movedInto.get(code) ?? NO_LINES) {
489 const r = relocs.get(n)!.r;
init0Start the project490 const seq = graph.atom(r.atom).seq;
491 out.push({ n, replaces: 0, lamport: graph.lamportOfSeq(seq), seq, k: r.k });
492 }
493 }
494 // A line's replacements (runs of atoms that deleted it) first, then the
495 // rest; each group in descending priority (lamport, then seq); lines of
496 // one atom keep k order. A replacement already outranks every insertion
497 // after the line that reads it (it depends on them, or conflicts with
498 // them); the grouping also puts it above a `before` insertion, which
499 // doesn't read the line above, so the new text lands in the replaced
500 // line's place. A moved line ranks like an insertion by the moving atom.
501 if (out.length > 1)
502 out.sort((a, b) => b.replaces - a.replaces || b.lamport - a.lamport || b.seq - a.seq || a.k - b.k);
503 return out;
504 }
codex-capacity-chair131Bound persisted no-move layout with ordered successor traversalCompare506 /** Parent/successor traversal keeps no history-sized ancestry or sibling frontier. */
507 *#layoutNodes(start: number): IterableIterator<number> {
508 const graph = this.graph;
509 if (graph.hasOrderedChildren && !this.#hasMoves) {
510 const first = (parent: number, after?: number): number | undefined => {
511 for (const n of graph.orderedChildrenN(parent, after)) if (this.#has(graph.writerSeqOf(n))) return n;
512 return undefined;
513 };
514 let n = first(start);
515 while (n !== undefined) {
516 yield n;
517 const child = first(n);
518 if (child !== undefined) {
519 n = child;
520 continue;
521 }
522 let previous = n;
523 for (;;) {
524 const parent = graph.parentCodeOf(previous);
525 const sibling = first(parent, previous);
526 if (sibling !== undefined) {
527 n = sibling;
528 break;
529 }
530 if (parent === start) {
531 n = undefined;
532 break;
533 }
534 if (parent < 0 || parent >= previous) throw new Error("invalid persistent layout ancestry");
535 previous = parent;
536 }
537 }
538 return;
539 }
init0Start the project540 const stack: number[] = [];
codex-capacity-chair131Bound persisted no-move layout with ordered successor traversalCompare541 const push = (parent: number): void => {
542 const children = this.#children(parent);
543 for (let i = children.length - 1; i >= 0; i--) stack.push(children[i]!.n);
544 };
545 push(start);
546 while (stack.length) {
547 const n = stack.pop()!;
548 yield n;
549 push(n);
550 }
551 }
init0Start the project553 /** 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 stateCompare554 #layout(path: string, complete: boolean): FileState {
init0Start the project555 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.Compare556 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.Compare557 if (this.#scratchMoves())
codex-capacity-chair132Bound persistent relocation projection memory with rollback-only scratchCompare558 return graph.withProjectionScratch((scratch) =>
559 this.#layoutResolved(
560 path,
561 complete,
562 scratchLayoutNodes(graph, (id) => this.#has(graph.atom(id).seq), scratch, `^${path}`),
563 ),
564 );
565 return this.#layoutResolved(path, complete);
566 }
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.Compare568 /** For each path, the files that lines moved into it were written in: worked out once per view. */
569 #movedFrom: Map<string, Set<number>> | undefined;
570 #movedInFrom(): Map<string, Set<number>> {
571 if (this.#movedFrom) return this.#movedFrom;
572 const graph = this.graph;
573 const out = new Map<string, Set<number>>();
574 if (this.#hasMoves) {
575 const relocs = this.#relocationsN();
capacity215Moves resolved over the moved lines alone, and closure over a named draft's own atoms (disk-first 2; abso Capacity), for abso's status and drafts. - view.ts MoveSkeleton: once per graph, and extended as it grows, each mover's moved lines, each moved line's relocations, and for any node the nearest node above it that a move ever relocated (or its file's start), memoised up to 200,000 nodes. A view's relocations and its loop check now hop between moved lines instead of walking every moved line's file up to its start, and fileOf hops the same way. The per-view location memos are gone. On abso's export (1,687 moved lines, 972 movers), status went from 104 s to 41 s under the profiler; agent views no longer re-walk each base's moves. - project.ts #closed opens unions down to their closed parts. An agent in a named draft has the draft's atoms over a closed shared base, one union deeper than #closed looked, so it walked all of shared's atoms and their dependencies. Tests: 97 of 97 across moves, relocation, projection-move-resolution, packed-files, view, drop, queued-moves, named-drafts, stored-closure, stored-membership, version-files, draft-reads-stored and writer storage. tsc clean.Compare576 const fileOf = (code: number): string => this.#fileOfCode(code);
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.Compare577 for (const [n, { parent }] of relocs) {
578 const into = fileOf(parent);
579 let from = out.get(into);
580 if (!from) out.set(into, (from = new Set()));
581 from.add(graph.writtenInIndex(n));
582 }
583 }
584 this.#movedFrom = out;
585 return out;
586 }
588 /**
589 * Lay one file out from its packed history (abso Capacity, Graph.packedLines): the lines written in it, and in the
590 * files its moved-in lines came from, read a page at a time; the same tree and order as #layoutResolved, built in
591 * memory with no read per line.
592 */
593 #layoutPacked(path: string, complete: boolean): FileState {
594 const graph = this.graph;
595 const attrs = this.#attributes(path);
596 const start = graph.startCodeOf(path);
597 if (start === undefined) return { attrs, complete, seq: EMPTY_INTS, vis: EMPTY_INTS, deletedBy: new Map() };
598 const relocs = this.#hasMoves ? this.#relocationsN() : undefined;
599 const files = new Set<number>([-1 - start, ...(this.#movedInFrom().get(path) ?? [])]);
600 const children = new Map<number, Child[]>();
601 const texts = new Map<number, string | null>();
602 const deleters = new Map<number, number[]>();
603 for (const file of files) {
604 const lineTexts = graph.packedTexts(file);
605 for (const [n, parent, seq, k, replaces] of graph.packedLines(file)) {
606 const text = lineTexts.next().value as string | null;
607 if (!this.#has(seq)) continue;
608 const moved = relocs?.get(n);
609 let at = parent;
610 let child: Child = { n, replaces, lamport: graph.lamportOfSeq(seq), seq, k };
611 if (moved) {
612 const mover = graph.atom(moved.r.atom).seq;
613 child = { n, replaces: 0, lamport: graph.lamportOfSeq(mover), seq: mover, k: moved.r.k };
614 at = moved.parent;
615 }
616 const list = children.get(at);
617 if (list) list.push(child);
618 else children.set(at, [child]);
619 texts.set(n, text);
620 }
621 for (const [n, deleter] of graph.packedDeletes(file)) {
622 if (!this.#has(deleter)) continue;
623 const by = deleters.get(n);
624 if (by) by.push(deleter);
625 else deleters.set(n, [deleter]);
626 }
627 }
628 const order = (a: Child, b: Child) =>
629 b.replaces - a.replaces || b.lamport - a.lamport || b.seq - a.seq || a.k - b.k;
630 const priority = (a: number, b: number) => graph.lamportOfSeq(a) - graph.lamportOfSeq(b) || a - b;
631 const seq: number[] = [];
632 const vis: number[] = [];
633 const visText: (string | null)[] = [];
634 const deletedBy = new Map<number, readonly number[]>();
635 const stack: number[] = [];
636 const push = (code: number) => {
637 const list = children.get(code);
638 if (!list) return;
639 if (list.length > 1) list.sort(order);
640 for (let i = list.length - 1; i >= 0; i--) stack.push(list[i]!.n);
641 };
642 push(start);
643 while (stack.length) {
644 const n = stack.pop()!;
645 const by = deleters.get(n);
646 if (by) {
647 if (complete) deletedBy.set(seq.length, by.length > 1 ? by.sort(priority) : by);
648 } else {
649 vis.push(n);
650 visText.push(texts.get(n) ?? null);
651 }
652 if (complete) seq.push(n);
653 push(n);
654 }
655 return { attrs, complete, seq: Int32Array.from(seq), vis: Int32Array.from(vis), deletedBy, visText };
656 }
codex-capacity-chair140Avoid line projection for file attribute queriesCompare658 #attributes(path: string): FileAttrs {
codex-capacity-chair132Bound persistent relocation projection memory with rollback-only scratchCompare659 const graph = this.graph;
init0Start the project660 // For each attribute, the highest-priority setter in the set wins.
661 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.Compare662 const file = graph.packedFiles ? graph.pathIndexOf(path) : undefined;
663 if (graph.packedFiles) {
664 for (const [seq, name, value] of file === undefined ? [] : graph.packedAttrs(file)) {
665 if (!this.#has(seq)) continue;
666 const id = graph.idOfSeq(seq);
667 const best = setters.get(name);
668 if (!best || graph.comparePriority(best.id, id) < 0) setters.set(name, { id, value });
669 }
670 return {
671 exists: setters.get("exists")?.value === "1",
672 exec: setters.get("exec")?.value === "1",
673 link: setters.get("link")?.value ?? null,
674 blob: setters.get("blob")?.value ?? null,
675 };
676 }
codex-capacity-chair119Page per-file atom indexes and stream current-view attribute scansCompare677 for (const id of graph.eachAtomIn(path)) {
init0Start the project678 if (!this.#has(graph.atom(id).seq)) continue;
679 for (const a of graph.atom(id).attrs ?? []) {
680 if (a.file !== path) continue;
681 const best = setters.get(a.name);
682 if (!best || graph.comparePriority(best.id, id) < 0) setters.set(a.name, { id, value: a.value });
683 }
684 }
codex-capacity-chair140Avoid line projection for file attribute queriesCompare685
686 return {
init0Start the project687 exists: setters.get("exists")?.value === "1",
688 exec: setters.get("exec")?.value === "1",
689 link: setters.get("link")?.value ?? null,
690 blob: setters.get("blob")?.value ?? null,
691 };
codex-capacity-chair140Avoid line projection for file attribute queriesCompare692 }
init0Start the project693
codex-capacity-chair132Bound persistent relocation projection memory with rollback-only scratchCompare694 #layoutResolved(path: string, complete: boolean, nodes?: Iterable<number>): FileState {
codex-capacity-chair140Avoid line projection for file attribute queriesCompare695 const graph = this.graph;
696 const attrs = this.#attributes(path);
init0Start the project697 const seq: number[] = [];
698 const vis: number[] = [];
699 const deletedBy = new Map<number, readonly number[]>();
codex-capacity-chair131Bound persisted no-move layout with ordered successor traversalCompare700
init0Start the project701 const start = graph.startCodeOf(path);
702 const priority = (a: number, b: number) => graph.lamportOfSeq(a) - graph.lamportOfSeq(b) || a - b;
codex-capacity-chair132Bound persistent relocation projection memory with rollback-only scratchCompare703 for (const n of nodes ?? (start === undefined ? [] : this.#layoutNodes(start))) {
codex-capacity-chair128Page deletion history and short-circuit current visibilityCompare704 let deleted = false;
705 const by: number[] = [];
706 for (const deleter of graph.eachDeleterSeqOf(n)) {
707 if (!this.#has(deleter)) continue;
708 deleted = true;
709 if (!complete) break;
710 by.push(deleter);
711 }
712 if (deleted) {
713 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 stateCompare714 } else vis.push(n);
715 if (complete) seq.push(n);
init0Start the project716 }
codex-capacity-chair140Avoid line projection for file attribute queriesCompare717
codex-capacity-chair110Keep current-file views and key scans from retaining historical stateCompare718 return { attrs, complete, seq: Int32Array.from(seq), vis: Int32Array.from(vis), deletedBy };
init0Start the project719 }
721 get #known(): string[] {
722 if (!this.#knownList) {
723 const known = new Set<string>();
codex-capacity-chair109Add opt-in persistent writer state, checked reopen and bounded adoptionCompare724 if (this.#stable) {
725 for (const id of this.#stable) for (const file of this.graph.filesOf(id)) known.add(file);
726 } else {
727 for (let seq = 0; seq < this.#in.length; seq++)
728 if (this.#in[seq] === 1) for (const file of this.graph.filesOf(this.graph.idOfSeq(seq))) known.add(file);
729 }
init0Start the project730 this.#knownList = [...known].sort();
731 }
732 return this.#knownList;
733 }
735 /** Files with at least one visible line, sorted. */
736 paths(): string[] {
codex-capacity-chair118Avoid retaining deleted historical paths in indexed current viewsCompare737 if (this.#stable) {
738 const paths: string[] = [];
739 for (const path of this.graph.knownFiles()) {
740 if (this.hasFile(path)) paths.push(path);
741 else this.#files.delete(path);
742 }
743 return paths.sort();
744 }
init0Start the project745 return this.#known.filter((p) => this.hasFile(p));
746 }
748 /** Every file the set has ever written a line in, including fully deleted ones. */
749 knownPaths(): string[] {
750 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.Compare751 }
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 changesCompare753 /** The file line n sits in, in this set: fileOf by the line's number, with no lookup of its id. */
754 fileOfNumber(n: number): string {
755 return this.#fileOfN(n);
756 }
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.Compare758 /** How many visible lines a file has. */
759 visibleCount(path: string): number {
760 return this.#file(path).vis.length;
init0Start the project761 }
763 /** Whether the file exists in this projection (has a visible line). */
764 hasFile(path: string): boolean {
codex-capacity-chair140Avoid line projection for file attribute queriesCompare765 const attrs = this.attrs(path);
766 return attrs.exists || attrs.link !== null || attrs.blob !== null || this.#file(path).vis.length > 0;
init0Start the project767 }
769 /** A file's attributes: kept while empty, executable, a link's target. */
770 attrs(path: string): FileAttrs {
codex-capacity-chair140Avoid line projection for file attribute queriesCompare771 return this.#files.get(path)?.attrs ?? this.#attributes(path);
init0Start the project772 }
774 /** The projected text of a file ("" if it has no visible lines). */
775 text(path: string): string {
776 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.Compare777 const { vis, visText } = this.#file(path);
init0Start the project778 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.Compare779 for (let i = 0; i < vis.length; i++) lines[i] = visText?.[i] ?? this.graph.textOf(vis[i]!);
init0Start the project780 const text = joinLines(lines);
781 this.#textCache = { path, text };
782 return text;
783 }
785 /** 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)Compare786 sameText(path: string, other: ReadView): boolean {
787 if (!(other instanceof View)) {
788 const a = this.lines(path),
789 b = other.lines(path);
790 return a.length === b.length && a.every((line, i) => line.text === b[i]!.text);
791 }
init0Start the project792 const a = this.#file(path).vis;
793 const b = other.#file(path).vis;
794 if (a.length !== b.length) return false;
795 for (let i = 0; i < a.length; i++)
796 if (a[i] !== b[i] && this.graph.textOf(a[i]!) !== this.graph.textOf(b[i]!)) return false;
797 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.Compare798 }
800 *lineChunks(path: string): IterableIterator<() => Iterable<string>> {
801 for (const n of this.#file(path).vis) yield () => this.graph.textChunks(n);
802 }
804 /** Visible lines without retaining their text in the view cache. */
805 *visibleLines(path: string): IterableIterator<VisibleLine> {
806 const graph = this.graph;
807 for (const n of this.#file(path).vis)
808 yield { id: graph.lineIdOf(n), text: graph.textOf(n), atom: graph.idOfSeq(graph.writerSeqOf(n)) };
809 }
811 /** Atom-building line handles; text is loaded only when requested. */
812 buildLines(path: string): readonly VisibleLine[] {
813 const graph = this.graph;
814 const vis = this.#file(path).vis;
815 const lines: VisibleLine[] = new Array(vis.length);
816 for (let i = 0; i < vis.length; i++) {
817 const n = vis[i]!;
818 lines[i] = {
819 id: graph.lineIdOf(n),
820 textChunks: () => graph.textChunks(n),
821 get text() {
822 return graph.textOf(n);
823 },
824 atom: graph.idOfSeq(graph.writerSeqOf(n)),
825 };
826 }
827 return lines;
init0Start the project828 }
830 /** Visible lines with their ids. */
831 lines(path: string): readonly VisibleLine[] {
832 if (this.#linesCache?.path === path) return this.#linesCache.lines;
833 const graph = this.graph;
834 const vis = this.#file(path).vis;
835 const lines: VisibleLine[] = new Array(vis.length);
836 for (let i = 0; i < vis.length; i++) {
837 const n = vis[i]!;
838 lines[i] = { id: graph.lineIdOf(n), text: graph.textOf(n), atom: graph.idOfSeq(graph.writerSeqOf(n)) };
839 }
840 this.#linesCache = { path, lines };
841 return lines;
842 }
844 /** The full linearized sequence of a file, tombstones included. */
845 sequence(path: string): readonly SeqLine[] {
846 if (this.#seqCache?.path === path) return this.#seqCache.seq;
847 const graph = this.graph;
codex-capacity-chair110Keep current-file views and key scans from retaining historical stateCompare848 const f = this.#file(path, true);
init0Start the project849 const out: SeqLine[] = new Array(f.seq.length);
850 for (let i = 0; i < f.seq.length; i++) {
851 const n = f.seq[i]!;
852 const by = f.deletedBy.get(i);
853 out[i] = {
854 id: graph.lineIdOf(n),
855 text: graph.textOf(n),
856 atom: graph.idOfSeq(graph.writerSeqOf(n)),
857 deletedBy: by ? by.map((s) => graph.idOfSeq(s)) : NONE,
858 visible: by === undefined,
859 };
860 }
861 this.#seqCache = { path, seq: out };
862 return out;
863 }
codex-capacity-chair138Find reason-warning neighbors without materializing file historyCompare865 /** Two visible neighbours without retaining the file's historical sequence. */
866 visibleNeighbours(path: string, line: LineId): LineId[] {
867 const graph = this.graph;
868 const target = graph.lineN(line);
869 const start = graph.startCodeOf(path);
870 if (target < 0 || start === undefined) return [];
871 const scan = (nodes: Iterable<number>): LineId[] => {
872 let previous: LineId | undefined;
873 let found = false;
874 for (const n of nodes) {
875 if (n === target) {
876 found = true;
877 continue;
878 }
879 let deleted = false;
880 for (const seq of graph.eachDeleterSeqOf(n))
881 if (this.#has(seq)) {
882 deleted = true;
883 break;
884 }
885 if (deleted) continue;
886 const id = graph.lineIdOf(n);
887 if (found) return previous === undefined ? [id] : [previous, id];
888 previous = id;
889 }
890 return found && previous !== undefined ? [previous] : [];
891 };
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.Compare892 if (this.#scratchMoves())
codex-capacity-chair138Find reason-warning neighbors without materializing file historyCompare893 return graph.withProjectionScratch((scratch) =>
894 scan(scratchLayoutNodes(graph, (id) => this.#has(graph.atom(id).seq), scratch, graph.nodeOf(start))),
895 );
896 return scan(this.#layoutNodes(start));
897 }
init0Start the project899 /** Index of a line in `sequence(path)`, or -1. */
900 sequenceIndex(path: string, line: LineId): number {
codex-capacity-chair110Keep current-file views and key scans from retaining historical stateCompare901 const f = this.#file(path, true);
init0Start the project902 if (!f.seqIndex) {
903 f.seqIndex = new Map();
904 for (let i = 0; i < f.seq.length; i++) f.seqIndex.set(f.seq[i]!, i);
905 }
906 return f.seqIndex.get(this.graph.lineN(line)) ?? -1;
907 }
909 /** Index of a line in `lines(path)` (0-based visible line number), or -1 if not visible. */
910 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 changesCompare911 return this.lineNumberOf(path, this.graph.lineN(line));
912 }
914 /** lineNumber by the line's number, with no lookup of its id. */
915 lineNumberOf(path: string, n: number): number {
init0Start the project916 const f = this.#file(path);
917 if (!f.visIndex) {
918 f.visIndex = new Map();
919 for (let i = 0; i < f.vis.length; i++) f.visIndex.set(f.vis[i]!, i);
920 }
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 changesCompare921 return f.visIndex.get(n) ?? -1;
922 }
924 /** The seq of the atom that wrote each visible line, in order: lines() without ids or text. */
925 visibleWriters(path: string): number[] {
926 const graph = this.graph;
927 return Array.from(this.#file(path).vis, (n) => graph.writerSeqOf(n));
init0Start the project928 }
930 /** All projected text files, path -> text, in path order. Binary files are in `blobs()`. */
931 files(): Record<string, string> {
932 const out: Record<string, string> = {};
933 for (const path of this.paths()) if (this.#file(path).attrs.blob === null) out[path] = this.text(path);
934 return out;
935 }
937 /** Binary files, path -> the SHA-256 of their bytes, in path order. */
938 blobs(): Record<string, string> {
939 const out: Record<string, string> = {};
940 for (const path of this.paths()) {
941 const blob = this.#file(path).attrs.blob;
942 if (blob !== null) out[path] = blob;
943 }
944 return out;
945 }
947 /**
codex-capacity-policy103Test deterministic replay and account view cache weightCompare948 * About how many bytes of retained state this view costs (#46). This uses
949 * approximate ownership costs for containers and wrappers, not V8 heap
950 * measurements. Graph-owned strings and records count only as references.
951 * This method only inspects already-created state: it does not lay out files,
952 * populate lazy caches, enumerate the graph, or count temporary traversal
953 * containers and shared empty singleton payloads as retained view state.
init0Start the project954 */
955 weight(): number {
codex-capacity-policy103Test deterministic replay and account view cache weightCompare956 let n = this.#in.byteLength;
codex-capacity-chair116Bound repeated indexed view membership lookupsCompare957 n += 2 * ARRAY_HEADER_BYTES + this.#membershipSeq.byteLength + this.#membershipValue.byteLength;
codex-capacity-chair123Stream mover history when opening persisted viewsCompare958 if (this.#movers) n += ARRAY_HEADER_BYTES + REFERENCE_BYTES * this.#movers.length;
codex-capacity-policy103Test deterministic replay and account view cache weightCompare959 n += MAP_HEADER_BYTES; // #files exists from construction.
codex-capacity-chair109Add opt-in persistent writer state, checked reopen and bounded adoptionCompare960 if (this.#stable) n += this.#stable.retainedBytes;
961 else if (this.#set) n += OBJECT_BYTES + SET_ENTRY_BYTES * this.#set.size;
codex-capacity-policy103Test deterministic replay and account view cache weightCompare962 if (this.#knownList) n += ARRAY_HEADER_BYTES + REFERENCE_BYTES * this.#knownList.length;
963 if (this.#relocs) n += MAP_HEADER_BYTES + MAP_ENTRY_BYTES * this.#relocs.size;
964 if (this.#relocsN) n += MAP_HEADER_BYTES + (MAP_ENTRY_BYTES + OBJECT_BYTES) * this.#relocsN.size;
965 for (const f of this.#files.values()) {
966 n += MAP_ENTRY_BYTES;
967 if (f !== NO_FILE) {
968 // FileState and FileAttrs are per laid-out file; typed-array
969 // headers are separate from their payload byte lengths below.
970 n += OBJECT_BYTES + OBJECT_BYTES + 2 * ARRAY_HEADER_BYTES;
971 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.Compare972 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 weightCompare973 n += MAP_HEADER_BYTES + (MAP_ENTRY_BYTES + ARRAY_HEADER_BYTES) * f.deletedBy.size;
974 for (const deleters of f.deletedBy.values()) n += REFERENCE_BYTES * deleters.length;
975 if (f.seqIndex) n += MAP_HEADER_BYTES + MAP_ENTRY_BYTES * f.seqIndex.size;
976 if (f.visIndex) n += MAP_HEADER_BYTES + MAP_ENTRY_BYTES * f.visIndex.size;
977 }
978 }
979 if (this.#linesCache)
980 n += OBJECT_BYTES + REFERENCE_BYTES + ARRAY_HEADER_BYTES + 100 * this.#linesCache.lines.length;
981 if (this.#seqCache) {
982 n += OBJECT_BYTES + REFERENCE_BYTES + ARRAY_HEADER_BYTES + 120 * this.#seqCache.seq.length;
983 for (const line of this.#seqCache.seq)
984 if (line.deletedBy !== NONE) n += ARRAY_HEADER_BYTES + REFERENCE_BYTES * line.deletedBy.length;
985 }
986 if (this.#textCache) n += OBJECT_BYTES + REFERENCE_BYTES + ARRAY_HEADER_BYTES + 2 * this.#textCache.text.length;
init0Start the project987 return n;
988 }
codex-capacity-chair110Keep current-file views and key scans from retaining historical stateCompare990 #file(path: string, complete = false): FileState {
init0Start the project991 let state = this.#files.get(path);
codex-capacity-chair110Keep current-file views and key scans from retaining historical stateCompare992 if (!state || (complete && !state.complete)) {
codex-capacity-chair119Page per-file atom indexes and stream current-view attribute scansCompare993 state = this.graph.hasAtomsIn(path) ? this.#layout(path, complete) : NO_FILE;
init0Start the project994 this.#files.set(path, state);
995 }
996 return state;
997 }
1000/** The files of a closed set, path -> text. */
1001export function project(graph: Graph, set: Iterable<AtomId>): Record<string, string> {
1002 return new View(graph, set).files();
1005/** 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)Compare1006export function indexAfter(view: Pick<ReadView, "sequenceIndex">, path: string, node: NodeId): number {
init0Start the project1007 if (isStartNode(node)) return 0;
1008 const i = view.sequenceIndex(path, node);
1009 if (i < 0) throw new EngineError("not-in-view", `line ${node} is not in ${path} in this view`);
1010 return i + 1;