- MCP
- blame on this site's /mcp
- CLI
- abso blame src/engine/state-source.ts --version 231 --json
- JSON
- /christopher/abso-core/blame/src/engine/state-source.ts?version=231&format=json
650 linescodex-capacity-chair 92% · capacity 8%Last change capacity in version 212,
650 lines from 16 changes in 14 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;
14}
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;
33 constructor(source: GraphStateStorage, maxBytes = 1_048_576, maxEntries = 4096) {
34 if (!Number.isSafeInteger(maxBytes) || maxBytes < 0 || !Number.isSafeInteger(maxEntries) || maxEntries < 0)
35 throw new Error("invalid writer cache limits");
36 this.#source = source;
37 this.#maxBytes = maxBytes;
38 this.#maxEntries = maxEntries;
39 }
40 get retainedBytes(): number {
41 return this.#bytes;
42 }
43 get retainedEntries(): number {
44 return this.#cache.size;
45 }
46 clear(): void {
47 this.#cache.clear();
48 this.#bytes = 0;
49 }
50 #drop(key: string): void {
51 const previous = this.#cache.get(key);
52 if (previous) {
53 this.#cache.delete(key);
54 this.#bytes -= previous.bytes;
55 }
56 }
57 read(collection: string, key: string): unknown {
58 const cacheKey = JSON.stringify([collection, key]);
59 const hit = this.#cache.get(cacheKey);
60 if (hit) {
61 this.#cache.delete(cacheKey);
62 this.#cache.set(cacheKey, hit);
codex-capacity-chair136Avoid JSON decoding for bounded numeric cache pages and scalar metadataCompare63 if (hit.kind === "scalar") return hit.value;
64 if (hit.kind === "numbers") return hit.value.slice();
codex-capacity-chair111Bound persistent writer read caching and verify rollback isolationCompare65 return (JSON.parse(hit.json) as { value?: unknown }).value;
66 }
67 const value = this.#source.read(collection, key);
codex-capacity-chair136Avoid JSON decoding for bounded numeric cache pages and scalar metadataCompare68 const overhead = 2 * cacheKey.length + 160;
69 let entry: CachedValue;
70 if (
71 value === undefined ||
72 value === null ||
73 typeof value === "string" ||
74 typeof value === "boolean" ||
75 (typeof value === "number" && Number.isFinite(value))
76 ) {
77 entry = { kind: "scalar", value, bytes: overhead + (typeof value === "string" ? 2 * value.length : 16) };
78 } else if (
79 Array.isArray(value) &&
80 value.length <= 256 &&
81 Object.keys(value).length === value.length &&
82 value.every(Number.isSafeInteger)
83 ) {
84 // Store one private, bounded numeric page. Public reads still receive a
85 // fresh copy; neither the source result nor a reader can mutate the cache.
86 entry = { kind: "numbers", value: value.slice(), bytes: overhead + 32 + value.length * 8 };
87 } else {
88 const json = JSON.stringify({ value });
89 entry = { kind: "json", json, bytes: overhead + 2 * json.length };
90 }
codex-capacity-chair145Cache successful integer writes within existing storage limits (#16)Compare91 this.#remember(cacheKey, entry);
codex-capacity-chair111Bound persistent writer read caching and verify rollback isolationCompare92 return value;
codex-capacity-chair145Cache successful integer writes within existing storage limits (#16)Compare93 }
94 #remember(cacheKey: string, entry: CachedValue): void {
95 this.#drop(cacheKey);
codex-capacity-chair136Avoid JSON decoding for bounded numeric cache pages and scalar metadataCompare96 // Payload accounting is bounded, not a measurement of actual isolate heap.
97 if (entry.bytes <= this.#maxBytes && this.#maxEntries > 0) {
98 while (this.#bytes + entry.bytes > this.#maxBytes || this.#cache.size >= this.#maxEntries)
codex-capacity-chair111Bound persistent writer read caching and verify rollback isolationCompare99 this.#drop(this.#cache.keys().next().value!);
codex-capacity-chair136Avoid JSON decoding for bounded numeric cache pages and scalar metadataCompare100 this.#cache.set(cacheKey, entry);
101 this.#bytes += entry.bytes;
codex-capacity-chair111Bound persistent writer read caching and verify rollback isolationCompare102 }
103 }
104 write(collection: string, key: string, value: unknown): void {
codex-capacity-chair145Cache successful integer writes within existing storage limits (#16)Compare105 const cacheKey = JSON.stringify([collection, key]);
106 this.#drop(cacheKey);
codex-capacity-chair111Bound persistent writer read caching and verify rollback isolationCompare107 this.#source.write(collection, key, value);
codex-capacity-chair145Cache successful integer writes within existing storage limits (#16)Compare108 // Allocation counters are immutable scalars. Keep successful writes within
109 // the existing cache budget instead of immediately reading them back.
110 if (typeof value === "number" && Number.isSafeInteger(value) && !Object.is(value, -0))
111 this.#remember(cacheKey, { kind: "scalar", value, bytes: 2 * cacheKey.length + 176 });
codex-capacity-chair111Bound persistent writer read caching and verify rollback isolationCompare112 }
113 remove(collection: string, key: string): void {
114 this.#drop(JSON.stringify([collection, key]));
115 this.#source.remove(collection, key);
116 }
117 entries(collection: string): Iterable<readonly [string, unknown]> {
118 return this.#source.entries(collection);
119 }
120 transaction<T>(body: () => T): T {
121 try {
122 return this.#source.transaction(body);
123 } catch (error) {
124 this.clear();
125 throw error;
126 }
127 }
128}
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.Compare130/**
131 * Sets known to be closed under dependencies (abso Capacity): every atom's deps are in the set. A view or a project
132 * given one skips proving it again, which read every atom and every dependency in the history.
133 */
134const closedSets = new WeakSet<object>();
135export function markClosed<S extends ReadonlySet<unknown>>(set: S): S {
136 closedSets.add(set);
137 return set;
138}
139export function isClosedSet(set: unknown): boolean {
140 return typeof set === "object" && set !== null && closedSets.has(set);
141}
codex-capacity-chair109Add opt-in persistent writer state, checked reopen and bounded adoptionCompare143/** Immutable membership whose implementation does not retain its enumerated keys. */
144export abstract class StableSet<T> implements ReadonlySet<T> {
145 abstract has(value: T): boolean;
146 abstract values(): SetIterator<T>;
147 /** Only resident membership data; external storage is not charged as heap. */
148 abstract readonly retainedBytes: number;
149 get [Symbol.toStringTag](): string {
150 return "Set";
151 }
152 get size(): number {
153 let count = 0;
154 for (const _ of this) count++;
155 return count;
156 }
157 keys(): SetIterator<T> {
158 return this.values();
159 }
160 *entries(): SetIterator<[T, T]> {
161 for (const value of this) yield [value, value];
162 }
163 [Symbol.iterator](): SetIterator<T> {
164 return this.values();
165 }
166 forEach(callback: (value: T, key: T, set: ReadonlySet<T>) => void, thisArg?: unknown): void {
167 for (const value of this) callback.call(thisArg, value, value, this);
168 }
169}
171/** Both operands must be immutable for the lifetime of this union. */
172export class StableUnionSet<T> extends StableSet<T> {
173 readonly #left: StableSet<T>;
174 readonly #right: StableSet<T>;
175 constructor(left: StableSet<T>, right: StableSet<T>) {
176 super();
177 this.#left = left;
178 this.#right = right;
179 }
180 get retainedBytes(): number {
181 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.Compare182 }
183 get left(): StableSet<T> {
184 return this.#left;
185 }
186 get right(): StableSet<T> {
187 return this.#right;
codex-capacity-chair109Add opt-in persistent writer state, checked reopen and bounded adoptionCompare188 }
189 has(value: T): boolean {
190 return this.#left.has(value) || this.#right.has(value);
191 }
192 *values(): SetIterator<T> {
193 yield* this.#left;
194 for (const value of this.#right) if (!this.#left.has(value)) yield value;
195 }
196}
codex-capacity-chair133Keep persistent publish membership indexed through conflict checksCompare198/** Immutable indexed subtraction retains neither operand's enumerated values. */
199export class StableDifferenceSet<T> extends StableSet<T> {
200 readonly left: StableSet<T>;
201 readonly right: StableSet<T>;
202 constructor(left: StableSet<T>, right: StableSet<T>) {
203 super();
204 this.left = left;
205 this.right = right;
206 }
207 get retainedBytes(): number {
208 return 32 + this.left.retainedBytes + this.right.retainedBytes;
209 }
210 has(value: T): boolean {
211 return this.left.has(value) && !this.right.has(value);
212 }
213 *values(): SetIterator<T> {
214 for (const value of this.left) if (!this.right.has(value)) yield value;
215 }
216}
218/** Preserve indexed history; only the caller's operation-sized overlay is copied. */
219export function unionOverlay<T>(base: ReadonlySet<T>, overlay: Iterable<T>): ReadonlySet<T> {
220 return base instanceof StableSet
221 ? new StableUnionSet(base, new StableOverlaySet(overlay))
222 : new Set([...base, ...overlay]);
223}
225/** Both indexed operands must be immutable for the lifetime of the result. */
226export function differenceSet<T>(left: ReadonlySet<T>, right: ReadonlySet<T>): ReadonlySet<T> {
227 return left instanceof StableSet && right instanceof StableSet
228 ? new StableDifferenceSet(left, right)
229 : new Set([...left].filter((value) => !right.has(value)));
230}
codex-capacity-chair109Add opt-in persistent writer state, checked reopen and bounded adoptionCompare232/** An immutable snapshot for the operation's small overlay, not its history. */
233export class StableOverlaySet<T> extends StableSet<T> {
234 readonly #values: Set<T>;
235 constructor(values: Iterable<T>) {
236 super();
237 this.#values = new Set(values);
238 }
239 get retainedBytes(): number {
240 return 64 + this.#values.size * 32;
241 }
242 has(value: T): boolean {
243 return this.#values.has(value);
244 }
245 values(): SetIterator<T> {
246 return this.#values.values();
247 }
248}
250const indexKey = (key: PropertyKey): key is string =>
251 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 cacheCompare253/** Fixed-size numeric pages; callers retain no pages outside the bounded storage cache. */
254export function storedNumbers(storage: GraphStateStorage, name: string) {
255 const pageSize = 256;
256 const meta = `${name}:meta`;
257 const length = () => (storage.read(meta, "length") as number | undefined) ?? 0;
258 // Older experimental writer indexes must be rebuilt from their canonical log.
259 // Never interpret per-element rows as pages or silently lose existing history.
260 const page = (index: number): number[] => {
261 if (storage.read(meta, "format") !== 2)
262 throw new Error(`writer numeric index ${name} requires canonical-log adoption`);
263 const values = storage.read(`${name}:pages`, String(Math.floor(index / pageSize))) as number[] | undefined;
264 if (!values) throw new Error(`missing writer numeric page in ${name}`);
265 return values;
266 };
267 return {
268 get length() {
269 return length();
270 },
271 at(index: number): number {
272 if (!Number.isSafeInteger(index) || index < 0 || index >= length())
273 throw new Error(`writer numeric index out of bounds in ${name}`);
274 const value = page(index)[index % pageSize];
275 if (value === undefined) throw new Error(`incomplete writer numeric page in ${name}`);
276 return value;
277 },
278 push(value: number): void {
279 if (!Number.isSafeInteger(value)) throw new Error("writer numeric indexes require safe integers");
280 const index = length();
281 if (index > 0 && storage.read(meta, "format") !== 2)
282 throw new Error(`writer numeric index ${name} requires canonical-log adoption`);
283 const offset = index % pageSize;
284 const values = offset === 0 ? [] : page(index);
285 if (values.length !== offset) throw new Error(`invalid writer numeric page length in ${name}`);
286 values.push(value);
287 storage.write(`${name}:pages`, String(Math.floor(index / pageSize)), values);
288 if (index === 0) storage.write(meta, "format", 2);
289 storage.write(meta, "length", index + 1);
290 },
291 set(index: number, value: number): void {
292 if (!Number.isSafeInteger(value)) throw new Error("writer numeric indexes require safe integers");
293 if (!Number.isSafeInteger(index) || index < 0 || index >= length())
294 throw new Error(`writer numeric index out of bounds in ${name}`);
295 const values = page(index);
296 if (index % pageSize >= values.length) throw new Error(`incomplete writer numeric page in ${name}`);
297 values[index % pageSize] = value;
298 storage.write(`${name}:pages`, String(Math.floor(index / pageSize)), values);
299 },
300 };
301}
codex-capacity-chair109Add opt-in persistent writer state, checked reopen and bounded adoptionCompare303/** 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 gateCompare304export function storedArray<T>(
305 storage: GraphStateStorage,
306 name: string,
307 decode?: (value: T) => T,
308 encode?: (value: T, key: string) => unknown,
309): T[] {
codex-capacity-chair109Add opt-in persistent writer state, checked reopen and bounded adoptionCompare310 const length = () => (storage.read(`${name}:meta`, "length") as number | undefined) ?? 0;
311 const read = (key: string) => {
312 const value = storage.read(name, key) as T;
313 return value === undefined || !decode ? value : decode(value);
314 };
315 return new Proxy([] as T[], {
316 get(target, key, receiver) {
317 if (key === "length") return length();
318 if (indexKey(key)) return Number(key) < length() ? read(key) : undefined;
319 return Reflect.get(target, key, receiver);
320 },
321 set(_target, key, value) {
322 if (key === "length") {
323 if (value !== length()) throw new Error("stored graph arrays cannot be resized directly");
324 return true;
325 }
326 if (!indexKey(key)) throw new Error("invalid stored graph array property");
327 const index = Number(key);
328 const size = length();
329 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 gateCompare330 storage.write(name, key, encode ? encode(value, key) : value);
codex-capacity-chair109Add opt-in persistent writer state, checked reopen and bounded adoptionCompare331 if (index === size) storage.write(`${name}:meta`, "length", size + 1);
332 return true;
333 },
334 has(target, key) {
335 return indexKey(key) ? Number(key) < length() : Reflect.has(target, key);
336 },
337 ownKeys() {
338 return [...Array.from({ length: length() }, (_, index) => String(index)), "length"];
339 },
340 getOwnPropertyDescriptor(target, key) {
341 if (indexKey(key) && Number(key) < length())
342 return { configurable: true, enumerable: true, writable: true, value: read(key) };
343 return Reflect.getOwnPropertyDescriptor(target, key);
344 },
345 });
346}
348export interface StateMap<K, V> {
codex-capacity-chair118Avoid retaining deleted historical paths in indexed current viewsCompare349 keys(): IterableIterator<K>;
codex-capacity-chair109Add opt-in persistent writer state, checked reopen and bounded adoptionCompare350 get(key: K): V | undefined;
351 set(key: K, value: V): StateMap<K, V>;
352 has(key: K): boolean;
353 delete(key: K): boolean;
354 values(): IterableIterator<V>;
355}
codex-capacity-chair119Page per-file atom indexes and stream current-view attribute scansCompare357/** Append-only per-key lists, retaining at most one fixed-size page per iterator. */
codex-capacity-chair120Page persistent claim indexes and stream dependency queriesCompare358export function storedLists<V>(
359 storage: GraphStateStorage,
360 name: string,
361 legacyKey = (key: string) => JSON.stringify(["string", key]),
362) {
codex-capacity-chair119Page per-file atom indexes and stream current-view attribute scansCompare363 const pageSize = 256;
364 // The previous experimental layout stored one whole historical list per key.
365 const length = (key: string) => {
366 const stored = storage.read(`${name}:lengths`, key) as number | undefined;
codex-capacity-chair120Page persistent claim indexes and stream dependency queriesCompare367 if (stored === undefined && storage.read(name, legacyKey(key)) !== undefined)
codex-capacity-chair119Page per-file atom indexes and stream current-view attribute scansCompare368 throw new Error(`writer list index ${name} requires canonical-log adoption`);
369 const count = stored ?? 0;
370 if (!Number.isSafeInteger(count) || count < 0) throw new Error(`invalid writer list count in ${name}`);
371 return count;
372 };
373 const pageKey = (key: string, page: number) => JSON.stringify([key, page]);
374 const page = (key: string, index: number): V[] => {
375 const values = storage.read(`${name}:pages`, pageKey(key, index)) as V[] | undefined;
376 if (!Array.isArray(values) || values.length < 1 || values.length > pageSize)
377 throw new Error(`missing or invalid writer list page in ${name}`);
378 return values;
379 };
380 return {
381 length,
382 *keys(): IterableIterator<string> {
383 for (const entry of storage.entries(name)) {
384 void entry;
385 throw new Error(`writer list index ${name} requires canonical-log adoption`);
386 }
387 for (const [key] of storage.entries(`${name}:lengths`)) yield key;
388 },
389 *values(key: string): IterableIterator<V> {
390 const count = length(key);
391 for (let start = 0; start < count; start += pageSize) {
392 const values = page(key, start / pageSize);
393 if (values.length !== Math.min(pageSize, count - start))
394 throw new Error(`incomplete writer list page in ${name}`);
395 yield* values;
396 }
codex-capacity-chair162Add reviewed disk-first history and indexed graph storage for core issue 16; retain runtime activation gateCompare397 },
398 last(key: string): V | undefined {
399 const count = length(key);
400 if (count === 0) return undefined;
401 const values = page(key, Math.floor((count - 1) / pageSize));
402 const expected = ((count - 1) % pageSize) + 1;
403 if (values.length !== expected) throw new Error(`incomplete writer list page in ${name}`);
404 return values[expected - 1];
codex-capacity-chair119Page per-file atom indexes and stream current-view attribute scansCompare405 },
406 append(key: string, value: V): void {
407 const count = length(key);
408 const offset = count % pageSize;
409 const index = Math.floor(count / pageSize);
410 const values = offset === 0 ? [] : page(key, index);
411 if (values.length !== offset) throw new Error(`invalid writer list length in ${name}`);
412 values.push(value);
413 storage.write(`${name}:pages`, pageKey(key, index), values);
414 storage.write(`${name}:lengths`, key, count + 1);
415 },
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.Compare416 /** Append several values, writing each page they touch once. */
417 appendAll(key: string, more: readonly V[]): void {
418 if (more.length === 0) return;
419 const count = length(key);
420 let index = Math.floor(count / pageSize);
421 let values = count % pageSize === 0 ? [] : page(key, index);
422 if (values.length !== count % pageSize) throw new Error(`invalid writer list length in ${name}`);
423 for (const value of more) {
424 if (values.length === pageSize) {
425 storage.write(`${name}:pages`, pageKey(key, index++), values);
426 values = [];
427 }
428 values.push(value);
429 }
430 storage.write(`${name}:pages`, pageKey(key, index), values);
431 storage.write(`${name}:lengths`, key, count + more.length);
432 },
codex-capacity-chair119Page per-file atom indexes and stream current-view attribute scansCompare433 };
434}
codex-capacity-chair109Add opt-in persistent writer state, checked reopen and bounded adoptionCompare436/** Keys are tagged so numeric graph codes cannot collide with string keys. */
437export function storedMap<K extends string | number, V>(storage: GraphStateStorage, name: string): StateMap<K, V> {
438 const keyOf = (key: K) => JSON.stringify([typeof key, key]);
439 const map: StateMap<K, V> = {
codex-capacity-chair118Avoid retaining deleted historical paths in indexed current viewsCompare440 *keys() {
441 for (const [key] of storage.entries(name)) yield (JSON.parse(key) as [string, K])[1];
442 },
codex-capacity-chair109Add opt-in persistent writer state, checked reopen and bounded adoptionCompare443 get: (key) => storage.read(name, keyOf(key)) as V | undefined,
444 has: (key) => storage.read(name, keyOf(key)) !== undefined,
445 set(key, value) {
446 storage.write(name, keyOf(key), value);
447 return map;
448 },
449 delete(key) {
450 const existed = map.has(key);
451 storage.remove(name, keyOf(key));
452 return existed;
453 },
454 *values() {
455 for (const [, value] of storage.entries(name)) yield value as V;
456 },
457 };
458 return map;
459}
461/**
462 * A Map-compatible persistent index. Iteration follows insertion order and
463 * decodes one row at a time. Returned objects are copies, so mutations need
464 * an explicit set. Hosts wrap a logical multi-index mutation in transaction.
465 */
466export class StoredMap<K extends string | number, V> extends Map<K, V> {
467 readonly #storage: GraphStateStorage;
468 readonly #name: string;
469 readonly #encode: (value: V) => unknown;
470 readonly #decode: (value: unknown) => V;
471 constructor(
472 storage: GraphStateStorage,
473 name: string,
474 codec?: { encode(value: V): unknown; decode(value: unknown): V },
475 ) {
476 super();
477 this.#storage = storage;
478 this.#name = name;
479 this.#encode = codec?.encode ?? ((value) => value);
480 this.#decode = codec?.decode ?? ((value) => value as V);
481 }
482 #key(key: K): string {
483 return JSON.stringify([typeof key, key]);
484 }
485 #row(key: K): { slot: number; value: unknown } | undefined {
486 return this.#storage.read(this.#name, this.#key(key)) as { slot: number; value: unknown } | undefined;
487 }
488 override get size(): number {
489 return (this.#storage.read(`${this.#name}:meta`, "size") as number | undefined) ?? 0;
490 }
491 override has(key: K): boolean {
492 return this.#row(key) !== undefined;
493 }
494 override get(key: K): V | undefined {
495 const row = this.#row(key);
496 return row === undefined ? undefined : this.#decode(row.value);
497 }
498 override set(key: K, value: V): this {
499 const row = this.#row(key);
500 let slot = row?.slot;
501 if (slot === undefined) {
502 const keys = storedArray<K>(this.#storage, `${this.#name}:order`);
503 slot = keys.length;
504 keys.push(key);
505 this.#storage.write(`${this.#name}:meta`, "size", this.size + 1);
506 }
507 this.#storage.write(this.#name, this.#key(key), { slot, value: this.#encode(value) });
508 return this;
509 }
510 override delete(key: K): boolean {
511 if (!this.has(key)) return false;
512 this.#storage.remove(this.#name, this.#key(key));
513 this.#storage.write(`${this.#name}:meta`, "size", this.size - 1);
514 return true;
515 }
516 override clear(): void {
517 for (const key of this.keys()) this.delete(key);
518 }
519 override *entries(): MapIterator<[K, V]> {
520 const keys = storedArray<K>(this.#storage, `${this.#name}:order`);
521 for (let slot = 0; slot < keys.length; slot++) {
522 const key = keys[slot]!;
523 const row = this.#row(key);
524 if (row?.slot === slot) yield [key, this.#decode(row.value)];
525 }
526 }
527 override *keys(): MapIterator<K> {
codex-capacity-chair110Keep current-file views and key scans from retaining historical stateCompare528 const keys = storedArray<K>(this.#storage, `${this.#name}:order`);
529 for (let slot = 0; slot < keys.length; slot++) {
530 const key = keys[slot]!;
531 if (this.#row(key)?.slot === slot) yield key;
532 }
codex-capacity-chair109Add opt-in persistent writer state, checked reopen and bounded adoptionCompare533 }
534 override *values(): MapIterator<V> {
535 for (const [, value] of this.entries()) yield value;
536 }
537 override [Symbol.iterator](): MapIterator<[K, V]> {
538 return this.entries();
539 }
540 override forEach(callback: (value: V, key: K, map: Map<K, V>) => void, thisArg?: unknown): void {
541 for (const [key, value] of this.entries()) callback.call(thisArg, value, key, this);
542 }
543}
545/** Persistent membership with streaming iteration and no in-memory key cache. */
546export class StoredSet<K extends string | number> extends Set<K> {
547 readonly #map: StoredMap<K, true>;
548 constructor(storage: GraphStateStorage, name: string) {
549 super();
550 this.#map = new StoredMap(storage, name);
551 }
552 override get size(): number {
553 return this.#map.size;
554 }
555 override has(key: K): boolean {
556 return this.#map.has(key);
557 }
558 override add(key: K): this {
559 this.#map.set(key, true);
560 return this;
561 }
562 override delete(key: K): boolean {
563 return this.#map.delete(key);
564 }
565 override clear(): void {
566 this.#map.clear();
567 }
568 override *values(): SetIterator<K> {
569 yield* this.#map.keys();
570 }
571 override keys(): SetIterator<K> {
572 return this.values();
573 }
574 override *entries(): SetIterator<[K, K]> {
575 for (const key of this.values()) yield [key, key];
576 }
577 override [Symbol.iterator](): SetIterator<K> {
578 return this.values();
579 }
580 override forEach(callback: (value: K, key: K, set: Set<K>) => void, thisArg?: unknown): void {
581 for (const key of this.values()) callback.call(thisArg, key, key, this);
582 }
codex-capacity-chair162Add reviewed disk-first history and indexed graph storage for core issue 16; retain runtime activation gateCompare583}
585/** Read-only array access to individually stored values, without copying the list. */
586export function readonlyStoredArray<T>(
587 storage: GraphStateStorage,
588 name: string,
589 decode?: (value: unknown, index: number) => T,
590): readonly T[] {
591 const length = () => {
592 const count = storage.read(`${name}:meta`, "length");
593 if (!Number.isSafeInteger(count) || (count as number) < 0) throw Error("invalid stored list length");
594 return count as number;
595 };
596 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 changesCompare597 const at = (index: number): T => {
598 const raw = storage.read(name, String(index));
599 const value = raw === undefined ? undefined : decode ? decode(raw, index) : (raw as T);
600 if (value === undefined) throw Error("missing stored list element");
601 return value && typeof value === "object" ? (Object.freeze(value) as T) : value;
602 };
603 // In order, with the length read once (abso Capacity): the array iterator reads it again before every element, a
604 // second disk read per element of a list too long for the cache.
605 function* inOrder(): IterableIterator<T> {
606 const count = length();
607 for (let index = 0; index < count; index++) yield at(index);
608 }
codex-capacity-chair162Add reviewed disk-first history and indexed graph storage for core issue 16; retain runtime activation gateCompare609 return new Proxy([] as T[], {
610 get(target, key, receiver) {
611 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 changesCompare612 if (key === Symbol.iterator || key === "values") return inOrder;
613 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 gateCompare614 return Reflect.get(target, key, receiver);
615 },
616 has(target, key) {
617 return indexKey(key) ? Number(key) < length() : Reflect.has(target, key);
618 },
619 ownKeys() {
620 return [...Array.from({ length: length() }, (_, index) => String(index)), "length"];
621 },
622 getOwnPropertyDescriptor(target, key) {
623 if (key === "length") return { ...Reflect.getOwnPropertyDescriptor(target, key)!, value: length() };
624 if (indexKey(key) && Number(key) < length()) {
625 const raw = storage.read(name, key);
626 const value = raw === undefined ? undefined : decode ? decode(raw, Number(key)) : (raw as T);
627 if (value === undefined) throw Error("missing stored list element");
628 return {
629 configurable: true,
630 enumerable: true,
631 writable: false,
632 value: value && typeof value === "object" ? Object.freeze(value) : value,
633 };
634 }
635 return Reflect.getOwnPropertyDescriptor(target, key);
636 },
637 preventExtensions() {
638 throw Error("stored list is read-only");
639 },
640 set() {
641 throw Error("stored list is read-only");
642 },
643 deleteProperty() {
644 throw Error("stored list is read-only");
645 },
646 defineProperty() {
647 throw Error("stored list is read-only");
648 },
649 });