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/state-source.ts --version 261 --json
JSON
/christopher/abso-core/blame/src/engine/state-source.ts?version=261&format=json
747 linescodex-capacity-chair 80% · capacity 20%Last change capacity in version 260,

747 lines from 25 changes in 17 versions.

codex-capacity-chair109Add opt-in persistent writer state, checked reopen and bounded adoptionCompare1/**
2 * Indexed graph storage. Values must be copied on write and read: a caller
3 * mutating a returned list must not silently change persisted state. Hosts
4 * provide transactions that roll back every write when the callback throws.
5 * The namespace belongs to one graph and must not be shared by concurrent
6 * Graph instances. Opening a graph does not scan its stored collections.
7 */
8export interface GraphStateStorage {
9 read(collection: string, key: string): unknown;
10 write(collection: string, key: string, value: unknown): void;
11 remove(collection: string, key: string): void;
12 entries(collection: string): Iterable<readonly [string, unknown]>;
13 transaction<T>(body: () => T): T;
codex-capacity-chair111Bound persistent writer read caching and verify rollback isolationCompare16/**
codex-capacity-chair136Avoid JSON decoding for bounded numeric cache pages and scalar metadataCompare17 * Operation-local read cache with fixed payload and entry limits. Private numeric
18 * pages, immutable scalars and serialized objects preserve the copy contract. Discard it after an outer host
codex-capacity-chair111Bound persistent writer read caching and verify rollback isolationCompare19 * rollback or any mutation made through another storage instance.
20 */
codex-capacity-chair136Avoid JSON decoding for bounded numeric cache pages and scalar metadataCompare21type CachedValue = { bytes: number } & (
22 | { kind: "scalar"; value: string | number | boolean | null | undefined }
23 | { kind: "numbers"; value: readonly number[] }
24 | { kind: "json"; json: string }
25);
codex-capacity-chair111Bound persistent writer read caching and verify rollback isolationCompare27export class CachedStateStorage implements GraphStateStorage {
28 readonly #source: GraphStateStorage;
codex-capacity-chair136Avoid JSON decoding for bounded numeric cache pages and scalar metadataCompare29 readonly #cache = new Map<string, CachedValue>();
codex-capacity-chair111Bound persistent writer read caching and verify rollback isolationCompare30 readonly #maxBytes: number;
31 readonly #maxEntries: number;
32 #bytes = 0;
capacity253The writer's row cache survives projection scratch and big rows (abso Capacity, issue 664). - CachedStateStorage dropped its whole cache whenever a transaction rolled back. Every projection scratch scope ends in a rollback on purpose, so the cache emptied many times within a call and at every call of a kept reader. A rollback now drops only the keys written or removed in that transaction (and any read back after), and a scope's own scratch rows; a nested commit's keys go with an outer rollback. - A row bigger than a per-row limit is read but not kept (the writer passes 16 KB). abso's 109 agents, each with all the news it was told, are 4.3 MB of rows read on every call, and they pushed every small page out of the 4 MB cache. On a fresh abso adoption (my machine), asked again: where 229 to 237 ms after its second ask (was 0.32 to 0.46 s), drafts 198 ms (0.31 s), collisions 207 ms. A full run matches 33 of 33 answers; held heap at most 39.8 MB. Tests: state-cache (new: a rollback drops only what its transaction wrote, a nested commit's writes go with an outer rollback; a row over the limit isn't kept and pushes nothing out). projection-scratch's check now expects the canonical value written before a scratch scope to stay cached. All of src/engine/test (294) and worker/project/test (349) pass. codex-capacity-policy has older unpushed changes in lines 1 to 25 of state-source.ts (and a new test file); this touches the class body only.Compare33 /**
34 * The keys written or removed in each open transaction, innermost last (abso Capacity). A rollback drops only those:
35 * every projection scratch scope ends in a rollback, and dropping the whole cache there read the same rows from
36 * storage again within a call and on every call of a kept reader.
37 */
38 readonly #touched: Set<string>[] = [];
39 /**
40 * The biggest one row may be and still be kept (abso Capacity). A few big rows read on every call (each agent with
41 * all the news it was told: 4.3 MB for abso's 109 agents) otherwise push every small page out of the cache.
42 */
43 readonly #maxEntryBytes: number;
capacity260The writer cache stops reading layout pages straight through (abso Capacity, issue 664). 258 read file-lines, file-texts and file-deletes pages straight through the writer cache. A kept reader didn't gain from it (an agent's tree's time was elsewhere: counting authors line by line, fixed in the same version), and adoption, which lays the same files out in a fresh view for each version, lost the cache it relied on: a fresh abso adoption took 17.4 min with it against 11.6 min without (my machine). The option, its wiring and its test are gone; 258's told buckets and author counting stay. Tests: all of src/engine/test and worker/project/test pass.Compare44 constructor(source: GraphStateStorage, maxBytes = 1_048_576, maxEntries = 4096, maxEntryBytes = maxBytes) {
capacity253The writer's row cache survives projection scratch and big rows (abso Capacity, issue 664). - CachedStateStorage dropped its whole cache whenever a transaction rolled back. Every projection scratch scope ends in a rollback on purpose, so the cache emptied many times within a call and at every call of a kept reader. A rollback now drops only the keys written or removed in that transaction (and any read back after), and a scope's own scratch rows; a nested commit's keys go with an outer rollback. - A row bigger than a per-row limit is read but not kept (the writer passes 16 KB). abso's 109 agents, each with all the news it was told, are 4.3 MB of rows read on every call, and they pushed every small page out of the 4 MB cache. On a fresh abso adoption (my machine), asked again: where 229 to 237 ms after its second ask (was 0.32 to 0.46 s), drafts 198 ms (0.31 s), collisions 207 ms. A full run matches 33 of 33 answers; held heap at most 39.8 MB. Tests: state-cache (new: a rollback drops only what its transaction wrote, a nested commit's writes go with an outer rollback; a row over the limit isn't kept and pushes nothing out). projection-scratch's check now expects the canonical value written before a scratch scope to stay cached. All of src/engine/test (294) and worker/project/test (349) pass. codex-capacity-policy has older unpushed changes in lines 1 to 25 of state-source.ts (and a new test file); this touches the class body only.Compare45 if (
46 !Number.isSafeInteger(maxBytes) ||
47 maxBytes < 0 ||
48 !Number.isSafeInteger(maxEntries) ||
49 maxEntries < 0 ||
50 !Number.isSafeInteger(maxEntryBytes) ||
51 maxEntryBytes < 0
52 )
codex-capacity-chair111Bound persistent writer read caching and verify rollback isolationCompare53 throw new Error("invalid writer cache limits");
54 this.#source = source;
55 this.#maxBytes = maxBytes;
56 this.#maxEntries = maxEntries;
capacity253The writer's row cache survives projection scratch and big rows (abso Capacity, issue 664). - CachedStateStorage dropped its whole cache whenever a transaction rolled back. Every projection scratch scope ends in a rollback on purpose, so the cache emptied many times within a call and at every call of a kept reader. A rollback now drops only the keys written or removed in that transaction (and any read back after), and a scope's own scratch rows; a nested commit's keys go with an outer rollback. - A row bigger than a per-row limit is read but not kept (the writer passes 16 KB). abso's 109 agents, each with all the news it was told, are 4.3 MB of rows read on every call, and they pushed every small page out of the 4 MB cache. On a fresh abso adoption (my machine), asked again: where 229 to 237 ms after its second ask (was 0.32 to 0.46 s), drafts 198 ms (0.31 s), collisions 207 ms. A full run matches 33 of 33 answers; held heap at most 39.8 MB. Tests: state-cache (new: a rollback drops only what its transaction wrote, a nested commit's writes go with an outer rollback; a row over the limit isn't kept and pushes nothing out). projection-scratch's check now expects the canonical value written before a scratch scope to stay cached. All of src/engine/test (294) and worker/project/test (349) pass. codex-capacity-policy has older unpushed changes in lines 1 to 25 of state-source.ts (and a new test file); this touches the class body only.Compare57 this.#maxEntryBytes = Math.min(maxEntryBytes, maxBytes);
codex-capacity-chair111Bound persistent writer read caching and verify rollback isolationCompare58 }
59 get retainedBytes(): number {
60 return this.#bytes;
61 }
62 get retainedEntries(): number {
63 return this.#cache.size;
64 }
65 clear(): void {
66 this.#cache.clear();
67 this.#bytes = 0;
68 }
69 #drop(key: string): void {
70 const previous = this.#cache.get(key);
71 if (previous) {
72 this.#cache.delete(key);
73 this.#bytes -= previous.bytes;
74 }
75 }
76 read(collection: string, key: string): unknown {
77 const cacheKey = JSON.stringify([collection, key]);
78 const hit = this.#cache.get(cacheKey);
79 if (hit) {
80 this.#cache.delete(cacheKey);
81 this.#cache.set(cacheKey, hit);
codex-capacity-chair136Avoid JSON decoding for bounded numeric cache pages and scalar metadataCompare82 if (hit.kind === "scalar") return hit.value;
83 if (hit.kind === "numbers") return hit.value.slice();
codex-capacity-chair111Bound persistent writer read caching and verify rollback isolationCompare84 return (JSON.parse(hit.json) as { value?: unknown }).value;
85 }
86 const value = this.#source.read(collection, key);
codex-capacity-chair136Avoid JSON decoding for bounded numeric cache pages and scalar metadataCompare87 const overhead = 2 * cacheKey.length + 160;
88 let entry: CachedValue;
89 if (
90 value === undefined ||
91 value === null ||
92 typeof value === "string" ||
93 typeof value === "boolean" ||
94 (typeof value === "number" && Number.isFinite(value))
95 ) {
96 entry = { kind: "scalar", value, bytes: overhead + (typeof value === "string" ? 2 * value.length : 16) };
97 } else if (
98 Array.isArray(value) &&
99 value.length <= 256 &&
100 Object.keys(value).length === value.length &&
101 value.every(Number.isSafeInteger)
102 ) {
103 // Store one private, bounded numeric page. Public reads still receive a
104 // fresh copy; neither the source result nor a reader can mutate the cache.
105 entry = { kind: "numbers", value: value.slice(), bytes: overhead + 32 + value.length * 8 };
106 } else {
107 const json = JSON.stringify({ value });
108 entry = { kind: "json", json, bytes: overhead + 2 * json.length };
109 }
codex-capacity-chair145Cache successful integer writes within existing storage limits (#16)Compare110 this.#remember(cacheKey, entry);
capacity253The writer's row cache survives projection scratch and big rows (abso Capacity, issue 664). - CachedStateStorage dropped its whole cache whenever a transaction rolled back. Every projection scratch scope ends in a rollback on purpose, so the cache emptied many times within a call and at every call of a kept reader. A rollback now drops only the keys written or removed in that transaction (and any read back after), and a scope's own scratch rows; a nested commit's keys go with an outer rollback. - A row bigger than a per-row limit is read but not kept (the writer passes 16 KB). abso's 109 agents, each with all the news it was told, are 4.3 MB of rows read on every call, and they pushed every small page out of the 4 MB cache. On a fresh abso adoption (my machine), asked again: where 229 to 237 ms after its second ask (was 0.32 to 0.46 s), drafts 198 ms (0.31 s), collisions 207 ms. A full run matches 33 of 33 answers; held heap at most 39.8 MB. Tests: state-cache (new: a rollback drops only what its transaction wrote, a nested commit's writes go with an outer rollback; a row over the limit isn't kept and pushes nothing out). projection-scratch's check now expects the canonical value written before a scratch scope to stay cached. All of src/engine/test (294) and worker/project/test (349) pass. codex-capacity-policy has older unpushed changes in lines 1 to 25 of state-source.ts (and a new test file); this touches the class body only.Compare111 // A projection scope's own rows are never read again once it ends in its rollback: forget them with it.
112 if (collection.startsWith("projection-scratch:")) this.#touched.at(-1)?.add(cacheKey);
codex-capacity-chair111Bound persistent writer read caching and verify rollback isolationCompare113 return value;
codex-capacity-chair145Cache successful integer writes within existing storage limits (#16)Compare114 }
115 #remember(cacheKey: string, entry: CachedValue): void {
116 this.#drop(cacheKey);
codex-capacity-chair136Avoid JSON decoding for bounded numeric cache pages and scalar metadataCompare117 // Payload accounting is bounded, not a measurement of actual isolate heap.
capacity253The writer's row cache survives projection scratch and big rows (abso Capacity, issue 664). - CachedStateStorage dropped its whole cache whenever a transaction rolled back. Every projection scratch scope ends in a rollback on purpose, so the cache emptied many times within a call and at every call of a kept reader. A rollback now drops only the keys written or removed in that transaction (and any read back after), and a scope's own scratch rows; a nested commit's keys go with an outer rollback. - A row bigger than a per-row limit is read but not kept (the writer passes 16 KB). abso's 109 agents, each with all the news it was told, are 4.3 MB of rows read on every call, and they pushed every small page out of the 4 MB cache. On a fresh abso adoption (my machine), asked again: where 229 to 237 ms after its second ask (was 0.32 to 0.46 s), drafts 198 ms (0.31 s), collisions 207 ms. A full run matches 33 of 33 answers; held heap at most 39.8 MB. Tests: state-cache (new: a rollback drops only what its transaction wrote, a nested commit's writes go with an outer rollback; a row over the limit isn't kept and pushes nothing out). projection-scratch's check now expects the canonical value written before a scratch scope to stay cached. All of src/engine/test (294) and worker/project/test (349) pass. codex-capacity-policy has older unpushed changes in lines 1 to 25 of state-source.ts (and a new test file); this touches the class body only.Compare118 if (entry.bytes <= this.#maxEntryBytes && this.#maxEntries > 0) {
codex-capacity-chair136Avoid JSON decoding for bounded numeric cache pages and scalar metadataCompare119 while (this.#bytes + entry.bytes > this.#maxBytes || this.#cache.size >= this.#maxEntries)
codex-capacity-chair111Bound persistent writer read caching and verify rollback isolationCompare120 this.#drop(this.#cache.keys().next().value!);
codex-capacity-chair136Avoid JSON decoding for bounded numeric cache pages and scalar metadataCompare121 this.#cache.set(cacheKey, entry);
122 this.#bytes += entry.bytes;
codex-capacity-chair111Bound persistent writer read caching and verify rollback isolationCompare123 }
124 }
125 write(collection: string, key: string, value: unknown): void {
codex-capacity-chair145Cache successful integer writes within existing storage limits (#16)Compare126 const cacheKey = JSON.stringify([collection, key]);
127 this.#drop(cacheKey);
capacity253The writer's row cache survives projection scratch and big rows (abso Capacity, issue 664). - CachedStateStorage dropped its whole cache whenever a transaction rolled back. Every projection scratch scope ends in a rollback on purpose, so the cache emptied many times within a call and at every call of a kept reader. A rollback now drops only the keys written or removed in that transaction (and any read back after), and a scope's own scratch rows; a nested commit's keys go with an outer rollback. - A row bigger than a per-row limit is read but not kept (the writer passes 16 KB). abso's 109 agents, each with all the news it was told, are 4.3 MB of rows read on every call, and they pushed every small page out of the 4 MB cache. On a fresh abso adoption (my machine), asked again: where 229 to 237 ms after its second ask (was 0.32 to 0.46 s), drafts 198 ms (0.31 s), collisions 207 ms. A full run matches 33 of 33 answers; held heap at most 39.8 MB. Tests: state-cache (new: a rollback drops only what its transaction wrote, a nested commit's writes go with an outer rollback; a row over the limit isn't kept and pushes nothing out). projection-scratch's check now expects the canonical value written before a scratch scope to stay cached. All of src/engine/test (294) and worker/project/test (349) pass. codex-capacity-policy has older unpushed changes in lines 1 to 25 of state-source.ts (and a new test file); this touches the class body only.Compare128 this.#touched.at(-1)?.add(cacheKey);
codex-capacity-chair111Bound persistent writer read caching and verify rollback isolationCompare129 this.#source.write(collection, key, value);
codex-capacity-chair145Cache successful integer writes within existing storage limits (#16)Compare130 // Allocation counters are immutable scalars. Keep successful writes within
131 // the existing cache budget instead of immediately reading them back.
132 if (typeof value === "number" && Number.isSafeInteger(value) && !Object.is(value, -0))
133 this.#remember(cacheKey, { kind: "scalar", value, bytes: 2 * cacheKey.length + 176 });
codex-capacity-chair111Bound persistent writer read caching and verify rollback isolationCompare134 }
135 remove(collection: string, key: string): void {
capacity253The writer's row cache survives projection scratch and big rows (abso Capacity, issue 664). - CachedStateStorage dropped its whole cache whenever a transaction rolled back. Every projection scratch scope ends in a rollback on purpose, so the cache emptied many times within a call and at every call of a kept reader. A rollback now drops only the keys written or removed in that transaction (and any read back after), and a scope's own scratch rows; a nested commit's keys go with an outer rollback. - A row bigger than a per-row limit is read but not kept (the writer passes 16 KB). abso's 109 agents, each with all the news it was told, are 4.3 MB of rows read on every call, and they pushed every small page out of the 4 MB cache. On a fresh abso adoption (my machine), asked again: where 229 to 237 ms after its second ask (was 0.32 to 0.46 s), drafts 198 ms (0.31 s), collisions 207 ms. A full run matches 33 of 33 answers; held heap at most 39.8 MB. Tests: state-cache (new: a rollback drops only what its transaction wrote, a nested commit's writes go with an outer rollback; a row over the limit isn't kept and pushes nothing out). projection-scratch's check now expects the canonical value written before a scratch scope to stay cached. All of src/engine/test (294) and worker/project/test (349) pass. codex-capacity-policy has older unpushed changes in lines 1 to 25 of state-source.ts (and a new test file); this touches the class body only.Compare136 const cacheKey = JSON.stringify([collection, key]);
137 this.#drop(cacheKey);
138 this.#touched.at(-1)?.add(cacheKey);
codex-capacity-chair111Bound persistent writer read caching and verify rollback isolationCompare139 this.#source.remove(collection, key);
140 }
141 entries(collection: string): Iterable<readonly [string, unknown]> {
142 return this.#source.entries(collection);
143 }
144 transaction<T>(body: () => T): T {
capacity253The writer's row cache survives projection scratch and big rows (abso Capacity, issue 664). - CachedStateStorage dropped its whole cache whenever a transaction rolled back. Every projection scratch scope ends in a rollback on purpose, so the cache emptied many times within a call and at every call of a kept reader. A rollback now drops only the keys written or removed in that transaction (and any read back after), and a scope's own scratch rows; a nested commit's keys go with an outer rollback. - A row bigger than a per-row limit is read but not kept (the writer passes 16 KB). abso's 109 agents, each with all the news it was told, are 4.3 MB of rows read on every call, and they pushed every small page out of the 4 MB cache. On a fresh abso adoption (my machine), asked again: where 229 to 237 ms after its second ask (was 0.32 to 0.46 s), drafts 198 ms (0.31 s), collisions 207 ms. A full run matches 33 of 33 answers; held heap at most 39.8 MB. Tests: state-cache (new: a rollback drops only what its transaction wrote, a nested commit's writes go with an outer rollback; a row over the limit isn't kept and pushes nothing out). projection-scratch's check now expects the canonical value written before a scratch scope to stay cached. All of src/engine/test (294) and worker/project/test (349) pass. codex-capacity-policy has older unpushed changes in lines 1 to 25 of state-source.ts (and a new test file); this touches the class body only.Compare145 const touched = new Set<string>();
146 this.#touched.push(touched);
codex-capacity-chair111Bound persistent writer read caching and verify rollback isolationCompare147 try {
capacity253The writer's row cache survives projection scratch and big rows (abso Capacity, issue 664). - CachedStateStorage dropped its whole cache whenever a transaction rolled back. Every projection scratch scope ends in a rollback on purpose, so the cache emptied many times within a call and at every call of a kept reader. A rollback now drops only the keys written or removed in that transaction (and any read back after), and a scope's own scratch rows; a nested commit's keys go with an outer rollback. - A row bigger than a per-row limit is read but not kept (the writer passes 16 KB). abso's 109 agents, each with all the news it was told, are 4.3 MB of rows read on every call, and they pushed every small page out of the 4 MB cache. On a fresh abso adoption (my machine), asked again: where 229 to 237 ms after its second ask (was 0.32 to 0.46 s), drafts 198 ms (0.31 s), collisions 207 ms. A full run matches 33 of 33 answers; held heap at most 39.8 MB. Tests: state-cache (new: a rollback drops only what its transaction wrote, a nested commit's writes go with an outer rollback; a row over the limit isn't kept and pushes nothing out). projection-scratch's check now expects the canonical value written before a scratch scope to stay cached. All of src/engine/test (294) and worker/project/test (349) pass. codex-capacity-policy has older unpushed changes in lines 1 to 25 of state-source.ts (and a new test file); this touches the class body only.Compare148 const result = this.#source.transaction(body);
149 this.#touched.pop();
150 // Committed into the outer transaction, which may still roll back.
151 const outer = this.#touched.at(-1);
152 if (outer) for (const key of touched) outer.add(key);
153 return result;
codex-capacity-chair111Bound persistent writer read caching and verify rollback isolationCompare154 } catch (error) {
capacity253The writer's row cache survives projection scratch and big rows (abso Capacity, issue 664). - CachedStateStorage dropped its whole cache whenever a transaction rolled back. Every projection scratch scope ends in a rollback on purpose, so the cache emptied many times within a call and at every call of a kept reader. A rollback now drops only the keys written or removed in that transaction (and any read back after), and a scope's own scratch rows; a nested commit's keys go with an outer rollback. - A row bigger than a per-row limit is read but not kept (the writer passes 16 KB). abso's 109 agents, each with all the news it was told, are 4.3 MB of rows read on every call, and they pushed every small page out of the 4 MB cache. On a fresh abso adoption (my machine), asked again: where 229 to 237 ms after its second ask (was 0.32 to 0.46 s), drafts 198 ms (0.31 s), collisions 207 ms. A full run matches 33 of 33 answers; held heap at most 39.8 MB. Tests: state-cache (new: a rollback drops only what its transaction wrote, a nested commit's writes go with an outer rollback; a row over the limit isn't kept and pushes nothing out). projection-scratch's check now expects the canonical value written before a scratch scope to stay cached. All of src/engine/test (294) and worker/project/test (349) pass. codex-capacity-policy has older unpushed changes in lines 1 to 25 of state-source.ts (and a new test file); this touches the class body only.Compare155 this.#touched.pop();
156 // What the transaction wrote, and anything read back after it wrote it, is gone with the rollback.
157 for (const key of touched) this.#drop(key);
codex-capacity-chair111Bound persistent writer read caching and verify rollback isolationCompare158 throw error;
159 }
160 }
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.Compare163/**
164 * Sets known to be closed under dependencies (abso Capacity): every atom's deps are in the set. A view or a project
165 * given one skips proving it again, which read every atom and every dependency in the history.
166 */
167const closedSets = new WeakSet<object>();
168export function markClosed<S extends ReadonlySet<unknown>>(set: S): S {
169 closedSets.add(set);
170 return set;
172export function isClosedSet(set: unknown): boolean {
173 return typeof set === "object" && set !== null && closedSets.has(set);
codex-capacity-chair109Add opt-in persistent writer state, checked reopen and bounded adoptionCompare176/** Immutable membership whose implementation does not retain its enumerated keys. */
177export abstract class StableSet<T> implements ReadonlySet<T> {
178 abstract has(value: T): boolean;
179 abstract values(): SetIterator<T>;
180 /** Only resident membership data; external storage is not charged as heap. */
181 abstract readonly retainedBytes: number;
182 get [Symbol.toStringTag](): string {
183 return "Set";
184 }
185 get size(): number {
186 let count = 0;
187 for (const _ of this) count++;
188 return count;
189 }
190 keys(): SetIterator<T> {
191 return this.values();
192 }
193 *entries(): SetIterator<[T, T]> {
194 for (const value of this) yield [value, value];
195 }
196 [Symbol.iterator](): SetIterator<T> {
197 return this.values();
198 }
199 forEach(callback: (value: T, key: T, set: ReadonlySet<T>) => void, thisArg?: unknown): void {
200 for (const value of this) callback.call(thisArg, value, value, this);
201 }
204/** Both operands must be immutable for the lifetime of this union. */
205export class StableUnionSet<T> extends StableSet<T> {
206 readonly #left: StableSet<T>;
207 readonly #right: StableSet<T>;
208 constructor(left: StableSet<T>, right: StableSet<T>) {
209 super();
210 this.#left = left;
211 this.#right = right;
212 }
213 get retainedBytes(): number {
214 return 32 + this.#left.retainedBytes + this.#right.retainedBytes;
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.Compare215 }
216 get left(): StableSet<T> {
217 return this.#left;
218 }
219 get right(): StableSet<T> {
220 return this.#right;
codex-capacity-chair109Add opt-in persistent writer state, checked reopen and bounded adoptionCompare221 }
222 has(value: T): boolean {
223 return this.#left.has(value) || this.#right.has(value);
224 }
225 *values(): SetIterator<T> {
226 yield* this.#left;
227 for (const value of this.#right) if (!this.#left.has(value)) yield value;
228 }
codex-capacity-chair133Keep persistent publish membership indexed through conflict checksCompare231/** Immutable indexed subtraction retains neither operand's enumerated values. */
232export class StableDifferenceSet<T> extends StableSet<T> {
233 readonly left: StableSet<T>;
234 readonly right: StableSet<T>;
235 constructor(left: StableSet<T>, right: StableSet<T>) {
236 super();
237 this.left = left;
238 this.right = right;
239 }
240 get retainedBytes(): number {
241 return 32 + this.left.retainedBytes + this.right.retainedBytes;
242 }
243 has(value: T): boolean {
244 return this.left.has(value) && !this.right.has(value);
245 }
246 *values(): SetIterator<T> {
247 for (const value of this.left) if (!this.right.has(value)) yield value;
248 }
251/** Preserve indexed history; only the caller's operation-sized overlay is copied. */
252export function unionOverlay<T>(base: ReadonlySet<T>, overlay: Iterable<T>): ReadonlySet<T> {
253 return base instanceof StableSet
254 ? new StableUnionSet(base, new StableOverlaySet(overlay))
255 : new Set([...base, ...overlay]);
258/** Both indexed operands must be immutable for the lifetime of the result. */
259export function differenceSet<T>(left: ReadonlySet<T>, right: ReadonlySet<T>): ReadonlySet<T> {
260 return left instanceof StableSet && right instanceof StableSet
261 ? new StableDifferenceSet(left, right)
262 : new Set([...left].filter((value) => !right.has(value)));
codex-capacity-chair109Add opt-in persistent writer state, checked reopen and bounded adoptionCompare265/** An immutable snapshot for the operation's small overlay, not its history. */
266export class StableOverlaySet<T> extends StableSet<T> {
267 readonly #values: Set<T>;
268 constructor(values: Iterable<T>) {
269 super();
270 this.#values = new Set(values);
271 }
272 get retainedBytes(): number {
273 return 64 + this.#values.size * 32;
274 }
275 has(value: T): boolean {
276 return this.#values.has(value);
277 }
278 values(): SetIterator<T> {
279 return this.#values.values();
280 }
283const indexKey = (key: PropertyKey): key is string =>
284 typeof key === "string" && /^(0|[1-9][0-9]*)$/.test(key) && Number.isSafeInteger(Number(key));
codex-capacity-chair113Page disk-first numeric graph indexes under bounded storage cacheCompare286/** Fixed-size numeric pages; callers retain no pages outside the bounded storage cache. */
287export function storedNumbers(storage: GraphStateStorage, name: string) {
288 const pageSize = 256;
289 const meta = `${name}:meta`;
290 const length = () => (storage.read(meta, "length") as number | undefined) ?? 0;
291 // Older experimental writer indexes must be rebuilt from their canonical log.
292 // Never interpret per-element rows as pages or silently lose existing history.
293 const page = (index: number): number[] => {
294 if (storage.read(meta, "format") !== 2)
295 throw new Error(`writer numeric index ${name} requires canonical-log adoption`);
296 const values = storage.read(`${name}:pages`, String(Math.floor(index / pageSize))) as number[] | undefined;
297 if (!values) throw new Error(`missing writer numeric page in ${name}`);
298 return values;
299 };
300 return {
301 get length() {
302 return length();
303 },
304 at(index: number): number {
305 if (!Number.isSafeInteger(index) || index < 0 || index >= length())
306 throw new Error(`writer numeric index out of bounds in ${name}`);
307 const value = page(index)[index % pageSize];
308 if (value === undefined) throw new Error(`incomplete writer numeric page in ${name}`);
309 return value;
310 },
311 push(value: number): void {
312 if (!Number.isSafeInteger(value)) throw new Error("writer numeric indexes require safe integers");
313 const index = length();
314 if (index > 0 && storage.read(meta, "format") !== 2)
315 throw new Error(`writer numeric index ${name} requires canonical-log adoption`);
316 const offset = index % pageSize;
317 const values = offset === 0 ? [] : page(index);
318 if (values.length !== offset) throw new Error(`invalid writer numeric page length in ${name}`);
319 values.push(value);
320 storage.write(`${name}:pages`, String(Math.floor(index / pageSize)), values);
321 if (index === 0) storage.write(meta, "format", 2);
322 storage.write(meta, "length", index + 1);
323 },
324 set(index: number, value: number): void {
325 if (!Number.isSafeInteger(value)) throw new Error("writer numeric indexes require safe integers");
326 if (!Number.isSafeInteger(index) || index < 0 || index >= length())
327 throw new Error(`writer numeric index out of bounds in ${name}`);
328 const values = page(index);
329 if (index % pageSize >= values.length) throw new Error(`incomplete writer numeric page in ${name}`);
330 values[index % pageSize] = value;
331 storage.write(`${name}:pages`, String(Math.floor(index / pageSize)), values);
332 },
333 };
codex-capacity-chair109Add opt-in persistent writer state, checked reopen and bounded adoptionCompare336/** Array-shaped access without retaining its historical values in memory. */
codex-capacity-chair162Add reviewed disk-first history and indexed graph storage for core issue 16; retain runtime activation gateCompare337export function storedArray<T>(
338 storage: GraphStateStorage,
339 name: string,
340 decode?: (value: T) => T,
341 encode?: (value: T, key: string) => unknown,
342): T[] {
codex-capacity-chair109Add opt-in persistent writer state, checked reopen and bounded adoptionCompare343 const length = () => (storage.read(`${name}:meta`, "length") as number | undefined) ?? 0;
344 const read = (key: string) => {
345 const value = storage.read(name, key) as T;
346 return value === undefined || !decode ? value : decode(value);
347 };
348 return new Proxy([] as T[], {
349 get(target, key, receiver) {
350 if (key === "length") return length();
351 if (indexKey(key)) return Number(key) < length() ? read(key) : undefined;
352 return Reflect.get(target, key, receiver);
353 },
354 set(_target, key, value) {
355 if (key === "length") {
356 if (value !== length()) throw new Error("stored graph arrays cannot be resized directly");
357 return true;
358 }
359 if (!indexKey(key)) throw new Error("invalid stored graph array property");
360 const index = Number(key);
361 const size = length();
362 if (index > size) throw new Error("stored graph arrays cannot contain gaps");
codex-capacity-chair162Add reviewed disk-first history and indexed graph storage for core issue 16; retain runtime activation gateCompare363 storage.write(name, key, encode ? encode(value, key) : value);
codex-capacity-chair109Add opt-in persistent writer state, checked reopen and bounded adoptionCompare364 if (index === size) storage.write(`${name}:meta`, "length", size + 1);
365 return true;
366 },
367 has(target, key) {
368 return indexKey(key) ? Number(key) < length() : Reflect.has(target, key);
369 },
370 ownKeys() {
371 return [...Array.from({ length: length() }, (_, index) => String(index)), "length"];
372 },
373 getOwnPropertyDescriptor(target, key) {
374 if (indexKey(key) && Number(key) < length())
375 return { configurable: true, enumerable: true, writable: true, value: read(key) };
376 return Reflect.getOwnPropertyDescriptor(target, key);
377 },
378 });
381export interface StateMap<K, V> {
codex-capacity-chair118Avoid retaining deleted historical paths in indexed current viewsCompare382 keys(): IterableIterator<K>;
codex-capacity-chair109Add opt-in persistent writer state, checked reopen and bounded adoptionCompare383 get(key: K): V | undefined;
384 set(key: K, value: V): StateMap<K, V>;
385 has(key: K): boolean;
386 delete(key: K): boolean;
387 values(): IterableIterator<V>;
codex-capacity-chair119Page per-file atom indexes and stream current-view attribute scansCompare390/** Append-only per-key lists, retaining at most one fixed-size page per iterator. */
codex-capacity-chair120Page persistent claim indexes and stream dependency queriesCompare391export function storedLists<V>(
392 storage: GraphStateStorage,
393 name: string,
394 legacyKey = (key: string) => JSON.stringify(["string", key]),
395) {
codex-capacity-chair119Page per-file atom indexes and stream current-view attribute scansCompare396 const pageSize = 256;
397 // The previous experimental layout stored one whole historical list per key.
398 const length = (key: string) => {
399 const stored = storage.read(`${name}:lengths`, key) as number | undefined;
codex-capacity-chair120Page persistent claim indexes and stream dependency queriesCompare400 if (stored === undefined && storage.read(name, legacyKey(key)) !== undefined)
codex-capacity-chair119Page per-file atom indexes and stream current-view attribute scansCompare401 throw new Error(`writer list index ${name} requires canonical-log adoption`);
402 const count = stored ?? 0;
403 if (!Number.isSafeInteger(count) || count < 0) throw new Error(`invalid writer list count in ${name}`);
404 return count;
405 };
406 const pageKey = (key: string, page: number) => JSON.stringify([key, page]);
407 const page = (key: string, index: number): V[] => {
408 const values = storage.read(`${name}:pages`, pageKey(key, index)) as V[] | undefined;
409 if (!Array.isArray(values) || values.length < 1 || values.length > pageSize)
410 throw new Error(`missing or invalid writer list page in ${name}`);
411 return values;
412 };
413 return {
414 length,
415 *keys(): IterableIterator<string> {
416 for (const entry of storage.entries(name)) {
417 void entry;
418 throw new Error(`writer list index ${name} requires canonical-log adoption`);
419 }
420 for (const [key] of storage.entries(`${name}:lengths`)) yield key;
421 },
422 *values(key: string): IterableIterator<V> {
423 const count = length(key);
424 for (let start = 0; start < count; start += pageSize) {
425 const values = page(key, start / pageSize);
426 if (values.length !== Math.min(pageSize, count - start))
427 throw new Error(`incomplete writer list page in ${name}`);
428 yield* values;
429 }
codex-capacity-chair162Add reviewed disk-first history and indexed graph storage for core issue 16; retain runtime activation gateCompare430 },
431 last(key: string): V | undefined {
432 const count = length(key);
433 if (count === 0) return undefined;
434 const values = page(key, Math.floor((count - 1) / pageSize));
435 const expected = ((count - 1) % pageSize) + 1;
436 if (values.length !== expected) throw new Error(`incomplete writer list page in ${name}`);
437 return values[expected - 1];
codex-capacity-chair119Page per-file atom indexes and stream current-view attribute scansCompare438 },
439 append(key: string, value: V): void {
440 const count = length(key);
441 const offset = count % pageSize;
442 const index = Math.floor(count / pageSize);
443 const values = offset === 0 ? [] : page(key, index);
444 if (values.length !== offset) throw new Error(`invalid writer list length in ${name}`);
445 values.push(value);
446 storage.write(`${name}:pages`, pageKey(key, index), values);
447 storage.write(`${name}:lengths`, key, count + 1);
448 },
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.Compare449 /** Append several values, writing each page they touch once. */
450 appendAll(key: string, more: readonly V[]): void {
451 if (more.length === 0) return;
452 const count = length(key);
453 let index = Math.floor(count / pageSize);
454 let values = count % pageSize === 0 ? [] : page(key, index);
455 if (values.length !== count % pageSize) throw new Error(`invalid writer list length in ${name}`);
456 for (const value of more) {
457 if (values.length === pageSize) {
458 storage.write(`${name}:pages`, pageKey(key, index++), values);
459 values = [];
460 }
461 values.push(value);
462 }
463 storage.write(`${name}:pages`, pageKey(key, index), values);
464 storage.write(`${name}:lengths`, key, count + more.length);
465 },
codex-capacity-chair119Page per-file atom indexes and stream current-view attribute scansCompare466 };
codex-capacity-chair109Add opt-in persistent writer state, checked reopen and bounded adoptionCompare469/** Keys are tagged so numeric graph codes cannot collide with string keys. */
470export function storedMap<K extends string | number, V>(storage: GraphStateStorage, name: string): StateMap<K, V> {
471 const keyOf = (key: K) => JSON.stringify([typeof key, key]);
472 const map: StateMap<K, V> = {
codex-capacity-chair118Avoid retaining deleted historical paths in indexed current viewsCompare473 *keys() {
474 for (const [key] of storage.entries(name)) yield (JSON.parse(key) as [string, K])[1];
475 },
codex-capacity-chair109Add opt-in persistent writer state, checked reopen and bounded adoptionCompare476 get: (key) => storage.read(name, keyOf(key)) as V | undefined,
477 has: (key) => storage.read(name, keyOf(key)) !== undefined,
478 set(key, value) {
479 storage.write(name, keyOf(key), value);
480 return map;
481 },
482 delete(key) {
483 const existed = map.has(key);
484 storage.remove(name, keyOf(key));
485 return existed;
486 },
487 *values() {
488 for (const [, value] of storage.entries(name)) yield value as V;
489 },
490 };
491 return map;
494/**
495 * A Map-compatible persistent index. Iteration follows insertion order and
496 * decodes one row at a time. Returned objects are copies, so mutations need
497 * an explicit set. Hosts wrap a logical multi-index mutation in transaction.
498 */
499export class StoredMap<K extends string | number, V> extends Map<K, V> {
500 readonly #storage: GraphStateStorage;
501 readonly #name: string;
502 readonly #encode: (value: V) => unknown;
503 readonly #decode: (value: unknown) => V;
504 constructor(
505 storage: GraphStateStorage,
506 name: string,
507 codec?: { encode(value: V): unknown; decode(value: unknown): V },
508 ) {
509 super();
510 this.#storage = storage;
511 this.#name = name;
512 this.#encode = codec?.encode ?? ((value) => value);
513 this.#decode = codec?.decode ?? ((value) => value as V);
514 }
515 #key(key: K): string {
516 return JSON.stringify([typeof key, key]);
517 }
518 #row(key: K): { slot: number; value: unknown } | undefined {
519 return this.#storage.read(this.#name, this.#key(key)) as { slot: number; value: unknown } | undefined;
520 }
521 override get size(): number {
522 return (this.#storage.read(`${this.#name}:meta`, "size") as number | undefined) ?? 0;
523 }
524 override has(key: K): boolean {
525 return this.#row(key) !== undefined;
526 }
527 override get(key: K): V | undefined {
528 const row = this.#row(key);
529 return row === undefined ? undefined : this.#decode(row.value);
530 }
531 override set(key: K, value: V): this {
532 const row = this.#row(key);
533 let slot = row?.slot;
534 if (slot === undefined) {
535 const keys = storedArray<K>(this.#storage, `${this.#name}:order`);
536 slot = keys.length;
537 keys.push(key);
538 this.#storage.write(`${this.#name}:meta`, "size", this.size + 1);
539 }
540 this.#storage.write(this.#name, this.#key(key), { slot, value: this.#encode(value) });
541 return this;
542 }
543 override delete(key: K): boolean {
544 if (!this.has(key)) return false;
545 this.#storage.remove(this.#name, this.#key(key));
546 this.#storage.write(`${this.#name}:meta`, "size", this.size - 1);
547 return true;
548 }
549 override clear(): void {
550 for (const key of this.keys()) this.delete(key);
551 }
552 override *entries(): MapIterator<[K, V]> {
553 const keys = storedArray<K>(this.#storage, `${this.#name}:order`);
554 for (let slot = 0; slot < keys.length; slot++) {
555 const key = keys[slot]!;
556 const row = this.#row(key);
557 if (row?.slot === slot) yield [key, this.#decode(row.value)];
558 }
559 }
560 override *keys(): MapIterator<K> {
codex-capacity-chair110Keep current-file views and key scans from retaining historical stateCompare561 const keys = storedArray<K>(this.#storage, `${this.#name}:order`);
562 for (let slot = 0; slot < keys.length; slot++) {
563 const key = keys[slot]!;
564 if (this.#row(key)?.slot === slot) yield key;
565 }
codex-capacity-chair109Add opt-in persistent writer state, checked reopen and bounded adoptionCompare566 }
567 override *values(): MapIterator<V> {
568 for (const [, value] of this.entries()) yield value;
569 }
570 override [Symbol.iterator](): MapIterator<[K, V]> {
571 return this.entries();
572 }
573 override forEach(callback: (value: V, key: K, map: Map<K, V>) => void, thisArg?: unknown): void {
574 for (const [key, value] of this.entries()) callback.call(thisArg, value, key, this);
575 }
578/** Persistent membership with streaming iteration and no in-memory key cache. */
579export class StoredSet<K extends string | number> extends Set<K> {
580 readonly #map: StoredMap<K, true>;
581 constructor(storage: GraphStateStorage, name: string) {
582 super();
583 this.#map = new StoredMap(storage, name);
584 }
585 override get size(): number {
586 return this.#map.size;
587 }
588 override has(key: K): boolean {
589 return this.#map.has(key);
590 }
591 override add(key: K): this {
592 this.#map.set(key, true);
593 return this;
594 }
595 override delete(key: K): boolean {
596 return this.#map.delete(key);
597 }
598 override clear(): void {
599 this.#map.clear();
600 }
601 override *values(): SetIterator<K> {
602 yield* this.#map.keys();
603 }
604 override keys(): SetIterator<K> {
605 return this.values();
606 }
607 override *entries(): SetIterator<[K, K]> {
608 for (const key of this.values()) yield [key, key];
609 }
610 override [Symbol.iterator](): SetIterator<K> {
611 return this.values();
612 }
613 override forEach(callback: (value: K, key: K, set: Set<K>) => void, thisArg?: unknown): void {
614 for (const key of this.values()) callback.call(thisArg, key, key, this);
615 }
codex-capacity-chair162Add reviewed disk-first history and indexed graph storage for core issue 16; retain runtime activation gateCompare616}
618/** Read-only array access to individually stored values, without copying the list. */
capacity239An atom's long lists kept 256 values to a row (list format 2; disk-first 2; abso Capacity). Collisions reads every key each draft atom writes. An atom's lists over 256 values were stored a row per value (readonlyStoredArray). On website, collisions read 75,000 of those rows (a draft deleting a big file has thousands of keys). - New atoms store such lists 256 values to a row (writePagedArray) and mark it listFormat 2. readonlyPagedArray reads them a page at a time, in order or by index. - An atom stored before keeps listFormat 1 and its row per value, and reads as before. The format is per atom record, so old and new atoms sit side by side. Only atoms stored from this version on, or a fresh adoption, get pages. On website adopted fresh, cold, one opened writer: collisions 9.6 s to 4.7 s (79,000 reads to 3,900), matching replay (0.4 s). Adoption took 87 s instead of 119 s. Tests: graph-atom-list-pages (new: a new atom's list is paged and reads whole; an atom rewritten as list format 1 reads whole). graph-atom-list-rollback now injects its failure on the list's second page. Every engine test (290 of 290), every worker/project test (341 of 341); tsc and biome clean.Compare619/** How many values an atom's long list keeps to a row (readonlyPagedArray). */
620export const LIST_PAGE = 256;
622/** Write a list as readonlyPagedArray reads it: its values LIST_PAGE to a row, and its length. */
623export function writePagedArray(storage: GraphStateStorage, name: string, values: readonly unknown[]): void {
624 for (let start = 0; start < values.length; start += LIST_PAGE)
625 storage.write(`${name}:pages`, String(start / LIST_PAGE), values.slice(start, start + LIST_PAGE));
626 storage.write(`${name}:meta`, "length", values.length);
629/**
630 * A stored list read a page of LIST_PAGE values at a time (abso Capacity): an atom's long lists, which
631 * readonlyStoredArray reads a row per value. Collisions read every key a draft's atoms write; a draft deleting a big
632 * file has thousands, and that was a row each.
633 */
634export function readonlyPagedArray<T>(storage: GraphStateStorage, name: string): readonly T[] {
635 const length = () => {
636 const count = storage.read(`${name}:meta`, "length");
637 if (!Number.isSafeInteger(count) || (count as number) < 0) throw Error("invalid stored list length");
638 return count as number;
639 };
640 length();
641 let held = -1;
642 let page: readonly unknown[] = [];
643 const at = (index: number): T => {
644 const p = Math.floor(index / LIST_PAGE);
645 if (p !== held) {
646 const raw = storage.read(`${name}:pages`, String(p));
647 if (!Array.isArray(raw)) throw Error("missing stored list page");
648 page = raw;
649 held = p;
650 }
651 const value = page[index % LIST_PAGE];
652 if (value === undefined) throw Error("missing stored list element");
653 return (value && typeof value === "object" ? Object.freeze(value) : value) as T;
654 };
655 function* inOrder(): IterableIterator<T> {
656 const count = length();
657 for (let index = 0; index < count; index++) yield at(index);
658 }
659 return new Proxy([] as T[], {
660 get(target, key, receiver) {
661 if (key === "length") return length();
662 if (key === Symbol.iterator || key === "values") return inOrder;
663 if (indexKey(key)) return Number(key) >= length() ? undefined : at(Number(key));
664 return Reflect.get(target, key, receiver);
665 },
666 has(target, key) {
667 return indexKey(key) ? Number(key) < length() : Reflect.has(target, key);
668 },
669 ownKeys() {
670 return [...Array.from({ length: length() }, (_, index) => String(index)), "length"];
671 },
672 getOwnPropertyDescriptor(target, key) {
673 if (indexKey(key) && Number(key) < length())
674 return { configurable: true, enumerable: true, writable: false, value: at(Number(key)) };
675 return Reflect.getOwnPropertyDescriptor(target, key);
676 },
677 set() {
678 throw Error("stored lists are read-only");
679 },
680 });
codex-capacity-chair162Add reviewed disk-first history and indexed graph storage for core issue 16; retain runtime activation gateCompare683export function readonlyStoredArray<T>(
684 storage: GraphStateStorage,
685 name: string,
686 decode?: (value: unknown, index: number) => T,
687): readonly T[] {
688 const length = () => {
689 const count = storage.read(`${name}:meta`, "length");
690 if (!Number.isSafeInteger(count) || (count as number) < 0) throw Error("invalid stored list length");
691 return count as number;
692 };
693 length();
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 changesCompare694 const at = (index: number): T => {
695 const raw = storage.read(name, String(index));
696 const value = raw === undefined ? undefined : decode ? decode(raw, index) : (raw as T);
697 if (value === undefined) throw Error("missing stored list element");
698 return value && typeof value === "object" ? (Object.freeze(value) as T) : value;
699 };
700 // In order, with the length read once (abso Capacity): the array iterator reads it again before every element, a
701 // second disk read per element of a list too long for the cache.
702 function* inOrder(): IterableIterator<T> {
703 const count = length();
704 for (let index = 0; index < count; index++) yield at(index);
705 }
codex-capacity-chair162Add reviewed disk-first history and indexed graph storage for core issue 16; retain runtime activation gateCompare706 return new Proxy([] as T[], {
707 get(target, key, receiver) {
708 if (key === "length") return length();
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 changesCompare709 if (key === Symbol.iterator || key === "values") return inOrder;
710 if (indexKey(key)) return Number(key) >= length() ? undefined : at(Number(key));
codex-capacity-chair162Add reviewed disk-first history and indexed graph storage for core issue 16; retain runtime activation gateCompare711 return Reflect.get(target, key, receiver);
712 },
713 has(target, key) {
714 return indexKey(key) ? Number(key) < length() : Reflect.has(target, key);
715 },
716 ownKeys() {
717 return [...Array.from({ length: length() }, (_, index) => String(index)), "length"];
718 },
719 getOwnPropertyDescriptor(target, key) {
720 if (key === "length") return { ...Reflect.getOwnPropertyDescriptor(target, key)!, value: length() };
721 if (indexKey(key) && Number(key) < length()) {
722 const raw = storage.read(name, key);
723 const value = raw === undefined ? undefined : decode ? decode(raw, Number(key)) : (raw as T);
724 if (value === undefined) throw Error("missing stored list element");
725 return {
726 configurable: true,
727 enumerable: true,
728 writable: false,
729 value: value && typeof value === "object" ? Object.freeze(value) : value,
730 };
731 }
732 return Reflect.getOwnPropertyDescriptor(target, key);
733 },
734 preventExtensions() {
735 throw Error("stored list is read-only");
736 },
737 set() {
738 throw Error("stored list is read-only");
739 },
740 deleteProperty() {
741 throw Error("stored list is read-only");
742 },
743 defineProperty() {
744 throw Error("stored list is read-only");
745 },
746 });
codex-capacity-chair109Add opt-in persistent writer state, checked reopen and bounded adoptionCompare747}