- MCP
- code on this site's /mcp
- CLI
- none: the JSON below is the answer
- JSON
- /christopher/abso-core/files/src/engine/state-source.ts?version=129&format=json
463 linescodex-capacity-chair 100%Last change codex-capacity-chair in version 120, 7 versions changed it
You're reading version 129. The newest is 318, and 13 versions since then changed this file.
codex-capacity-policy has unpushed changes at lines 1–25no start notelast edit
1/**
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}
16/**
17 * Operation-local read cache with fixed payload and entry limits. Serialized
18 * values preserve the storage copy contract. Discard it after an outer host
19 * rollback or any mutation made through another storage instance.
20 */
21export class CachedStateStorage implements GraphStateStorage {
22 readonly #source: GraphStateStorage;
23 readonly #cache = new Map<string, { json: string; bytes: number }>();
24 readonly #maxBytes: number;
25 readonly #maxEntries: number;
26 #bytes = 0;
27 constructor(source: GraphStateStorage, maxBytes = 1_048_576, maxEntries = 4096) {
28 if (!Number.isSafeInteger(maxBytes) || maxBytes < 0 || !Number.isSafeInteger(maxEntries) || maxEntries < 0)
29 throw new Error("invalid writer cache limits");
30 this.#source = source;
31 this.#maxBytes = maxBytes;
32 this.#maxEntries = maxEntries;
33 }
34 get retainedBytes(): number {
35 return this.#bytes;
36 }
37 get retainedEntries(): number {
38 return this.#cache.size;
39 }
40 clear(): void {
41 this.#cache.clear();
42 this.#bytes = 0;
43 }
44 #drop(key: string): void {
45 const previous = this.#cache.get(key);
46 if (previous) {
47 this.#cache.delete(key);
48 this.#bytes -= previous.bytes;
49 }
50 }
51 read(collection: string, key: string): unknown {
52 const cacheKey = JSON.stringify([collection, key]);
53 const hit = this.#cache.get(cacheKey);
54 if (hit) {
55 this.#cache.delete(cacheKey);
56 this.#cache.set(cacheKey, hit);
57 return (JSON.parse(hit.json) as { value?: unknown }).value;
58 }
59 const value = this.#source.read(collection, key);
60 const json = JSON.stringify({ value });
61 // Charge two bytes per UTF-16 unit and a conservative fixed entry cost.
62 // This bounds retained payload; it is not an isolate heap measurement.
63 const bytes = 2 * (json.length + cacheKey.length) + 128;
64 if (bytes <= this.#maxBytes && this.#maxEntries > 0) {
65 while (this.#bytes + bytes > this.#maxBytes || this.#cache.size >= this.#maxEntries)
66 this.#drop(this.#cache.keys().next().value!);
67 this.#cache.set(cacheKey, { json, bytes });
68 this.#bytes += bytes;
69 }
70 return value;
71 }
72 write(collection: string, key: string, value: unknown): void {
73 this.#drop(JSON.stringify([collection, key]));
74 this.#source.write(collection, key, value);
75 }
76 remove(collection: string, key: string): void {
77 this.#drop(JSON.stringify([collection, key]));
78 this.#source.remove(collection, key);
79 }
80 entries(collection: string): Iterable<readonly [string, unknown]> {
81 return this.#source.entries(collection);
82 }
83 transaction<T>(body: () => T): T {
84 try {
85 return this.#source.transaction(body);
86 } catch (error) {
87 this.clear();
88 throw error;
89 }
90 }
91}
93/** Immutable membership whose implementation does not retain its enumerated keys. */
94export abstract class StableSet<T> implements ReadonlySet<T> {
95 abstract has(value: T): boolean;
96 abstract values(): SetIterator<T>;
97 /** Only resident membership data; external storage is not charged as heap. */
98 abstract readonly retainedBytes: number;
99 get [Symbol.toStringTag](): string {
100 return "Set";
101 }
102 get size(): number {
103 let count = 0;
104 for (const _ of this) count++;
105 return count;
106 }
107 keys(): SetIterator<T> {
108 return this.values();
109 }
110 *entries(): SetIterator<[T, T]> {
111 for (const value of this) yield [value, value];
112 }
113 [Symbol.iterator](): SetIterator<T> {
114 return this.values();
115 }
116 forEach(callback: (value: T, key: T, set: ReadonlySet<T>) => void, thisArg?: unknown): void {
117 for (const value of this) callback.call(thisArg, value, value, this);
118 }
119}
121/** Both operands must be immutable for the lifetime of this union. */
122export class StableUnionSet<T> extends StableSet<T> {
123 readonly #left: StableSet<T>;
124 readonly #right: StableSet<T>;
125 constructor(left: StableSet<T>, right: StableSet<T>) {
126 super();
127 this.#left = left;
128 this.#right = right;
129 }
130 get retainedBytes(): number {
131 return 32 + this.#left.retainedBytes + this.#right.retainedBytes;
132 }
133 has(value: T): boolean {
134 return this.#left.has(value) || this.#right.has(value);
135 }
136 *values(): SetIterator<T> {
137 yield* this.#left;
138 for (const value of this.#right) if (!this.#left.has(value)) yield value;
139 }
140}
142/** An immutable snapshot for the operation's small overlay, not its history. */
143export class StableOverlaySet<T> extends StableSet<T> {
144 readonly #values: Set<T>;
145 constructor(values: Iterable<T>) {
146 super();
147 this.#values = new Set(values);
148 }
149 get retainedBytes(): number {
150 return 64 + this.#values.size * 32;
151 }
152 has(value: T): boolean {
153 return this.#values.has(value);
154 }
155 values(): SetIterator<T> {
156 return this.#values.values();
157 }
158}
160const indexKey = (key: PropertyKey): key is string =>
161 typeof key === "string" && /^(0|[1-9][0-9]*)$/.test(key) && Number.isSafeInteger(Number(key));
163/** Fixed-size numeric pages; callers retain no pages outside the bounded storage cache. */
164export function storedNumbers(storage: GraphStateStorage, name: string) {
165 const pageSize = 256;
166 const meta = `${name}:meta`;
167 const length = () => (storage.read(meta, "length") as number | undefined) ?? 0;
168 // Older experimental writer indexes must be rebuilt from their canonical log.
169 // Never interpret per-element rows as pages or silently lose existing history.
170 const page = (index: number): number[] => {
171 if (storage.read(meta, "format") !== 2)
172 throw new Error(`writer numeric index ${name} requires canonical-log adoption`);
173 const values = storage.read(`${name}:pages`, String(Math.floor(index / pageSize))) as number[] | undefined;
174 if (!values) throw new Error(`missing writer numeric page in ${name}`);
175 return values;
176 };
177 return {
178 get length() {
179 return length();
180 },
181 at(index: number): number {
182 if (!Number.isSafeInteger(index) || index < 0 || index >= length())
183 throw new Error(`writer numeric index out of bounds in ${name}`);
184 const value = page(index)[index % pageSize];
185 if (value === undefined) throw new Error(`incomplete writer numeric page in ${name}`);
186 return value;
187 },
188 push(value: number): void {
189 if (!Number.isSafeInteger(value)) throw new Error("writer numeric indexes require safe integers");
190 const index = length();
191 if (index > 0 && storage.read(meta, "format") !== 2)
192 throw new Error(`writer numeric index ${name} requires canonical-log adoption`);
193 const offset = index % pageSize;
194 const values = offset === 0 ? [] : page(index);
195 if (values.length !== offset) throw new Error(`invalid writer numeric page length in ${name}`);
196 values.push(value);
197 storage.write(`${name}:pages`, String(Math.floor(index / pageSize)), values);
198 if (index === 0) storage.write(meta, "format", 2);
199 storage.write(meta, "length", index + 1);
200 },
201 set(index: number, value: number): void {
202 if (!Number.isSafeInteger(value)) throw new Error("writer numeric indexes require safe integers");
203 if (!Number.isSafeInteger(index) || index < 0 || index >= length())
204 throw new Error(`writer numeric index out of bounds in ${name}`);
205 const values = page(index);
206 if (index % pageSize >= values.length) throw new Error(`incomplete writer numeric page in ${name}`);
207 values[index % pageSize] = value;
208 storage.write(`${name}:pages`, String(Math.floor(index / pageSize)), values);
209 },
210 };
211}
213/** Array-shaped access without retaining its historical values in memory. */
214export function storedArray<T>(storage: GraphStateStorage, name: string, decode?: (value: T) => T): T[] {
215 const length = () => (storage.read(`${name}:meta`, "length") as number | undefined) ?? 0;
216 const read = (key: string) => {
217 const value = storage.read(name, key) as T;
218 return value === undefined || !decode ? value : decode(value);
219 };
220 return new Proxy([] as T[], {
221 get(target, key, receiver) {
222 if (key === "length") return length();
223 if (indexKey(key)) return Number(key) < length() ? read(key) : undefined;
224 return Reflect.get(target, key, receiver);
225 },
226 set(_target, key, value) {
227 if (key === "length") {
228 if (value !== length()) throw new Error("stored graph arrays cannot be resized directly");
229 return true;
230 }
231 if (!indexKey(key)) throw new Error("invalid stored graph array property");
232 const index = Number(key);
233 const size = length();
234 if (index > size) throw new Error("stored graph arrays cannot contain gaps");
235 storage.write(name, key, value);
236 if (index === size) storage.write(`${name}:meta`, "length", size + 1);
237 return true;
238 },
239 has(target, key) {
240 return indexKey(key) ? Number(key) < length() : Reflect.has(target, key);
241 },
242 ownKeys() {
243 return [...Array.from({ length: length() }, (_, index) => String(index)), "length"];
244 },
245 getOwnPropertyDescriptor(target, key) {
246 if (indexKey(key) && Number(key) < length())
247 return { configurable: true, enumerable: true, writable: true, value: read(key) };
248 return Reflect.getOwnPropertyDescriptor(target, key);
249 },
250 });
251}
253export interface StateMap<K, V> {
254 keys(): IterableIterator<K>;
255 get(key: K): V | undefined;
256 set(key: K, value: V): StateMap<K, V>;
257 has(key: K): boolean;
258 delete(key: K): boolean;
259 values(): IterableIterator<V>;
260}
262/** Append-only per-key lists, retaining at most one fixed-size page per iterator. */
263export function storedLists<V>(
264 storage: GraphStateStorage,
265 name: string,
266 legacyKey = (key: string) => JSON.stringify(["string", key]),
267) {
268 const pageSize = 256;
269 // The previous experimental layout stored one whole historical list per key.
270 const length = (key: string) => {
271 const stored = storage.read(`${name}:lengths`, key) as number | undefined;
272 if (stored === undefined && storage.read(name, legacyKey(key)) !== undefined)
273 throw new Error(`writer list index ${name} requires canonical-log adoption`);
274 const count = stored ?? 0;
275 if (!Number.isSafeInteger(count) || count < 0) throw new Error(`invalid writer list count in ${name}`);
276 return count;
277 };
278 const pageKey = (key: string, page: number) => JSON.stringify([key, page]);
279 const page = (key: string, index: number): V[] => {
280 const values = storage.read(`${name}:pages`, pageKey(key, index)) as V[] | undefined;
281 if (!Array.isArray(values) || values.length < 1 || values.length > pageSize)
282 throw new Error(`missing or invalid writer list page in ${name}`);
283 return values;
284 };
285 return {
286 length,
287 *keys(): IterableIterator<string> {
288 for (const entry of storage.entries(name)) {
289 void entry;
290 throw new Error(`writer list index ${name} requires canonical-log adoption`);
291 }
292 for (const [key] of storage.entries(`${name}:lengths`)) yield key;
293 },
294 *values(key: string): IterableIterator<V> {
295 const count = length(key);
296 for (let start = 0; start < count; start += pageSize) {
297 const values = page(key, start / pageSize);
298 if (values.length !== Math.min(pageSize, count - start))
299 throw new Error(`incomplete writer list page in ${name}`);
300 yield* values;
301 }
302 },
303 append(key: string, value: V): void {
304 const count = length(key);
305 const offset = count % pageSize;
306 const index = Math.floor(count / pageSize);
307 const values = offset === 0 ? [] : page(key, index);
308 if (values.length !== offset) throw new Error(`invalid writer list length in ${name}`);
309 values.push(value);
310 storage.write(`${name}:pages`, pageKey(key, index), values);
311 storage.write(`${name}:lengths`, key, count + 1);
312 },
313 };
314}
316/** Keys are tagged so numeric graph codes cannot collide with string keys. */
317export function storedMap<K extends string | number, V>(storage: GraphStateStorage, name: string): StateMap<K, V> {
318 const keyOf = (key: K) => JSON.stringify([typeof key, key]);
319 const map: StateMap<K, V> = {
320 *keys() {
321 for (const [key] of storage.entries(name)) yield (JSON.parse(key) as [string, K])[1];
322 },
323 get: (key) => storage.read(name, keyOf(key)) as V | undefined,
324 has: (key) => storage.read(name, keyOf(key)) !== undefined,
325 set(key, value) {
326 storage.write(name, keyOf(key), value);
327 return map;
328 },
329 delete(key) {
330 const existed = map.has(key);
331 storage.remove(name, keyOf(key));
332 return existed;
333 },
334 *values() {
335 for (const [, value] of storage.entries(name)) yield value as V;
336 },
337 };
338 return map;
339}
341/**
342 * A Map-compatible persistent index. Iteration follows insertion order and
343 * decodes one row at a time. Returned objects are copies, so mutations need
344 * an explicit set. Hosts wrap a logical multi-index mutation in transaction.
345 */
346export class StoredMap<K extends string | number, V> extends Map<K, V> {
347 readonly #storage: GraphStateStorage;
348 readonly #name: string;
349 readonly #encode: (value: V) => unknown;
350 readonly #decode: (value: unknown) => V;
351 constructor(
352 storage: GraphStateStorage,
353 name: string,
354 codec?: { encode(value: V): unknown; decode(value: unknown): V },
355 ) {
356 super();
357 this.#storage = storage;
358 this.#name = name;
359 this.#encode = codec?.encode ?? ((value) => value);
360 this.#decode = codec?.decode ?? ((value) => value as V);
361 }
362 #key(key: K): string {
363 return JSON.stringify([typeof key, key]);
364 }
365 #row(key: K): { slot: number; value: unknown } | undefined {
366 return this.#storage.read(this.#name, this.#key(key)) as { slot: number; value: unknown } | undefined;
367 }
368 override get size(): number {
369 return (this.#storage.read(`${this.#name}:meta`, "size") as number | undefined) ?? 0;
370 }
371 override has(key: K): boolean {
372 return this.#row(key) !== undefined;
373 }
374 override get(key: K): V | undefined {
375 const row = this.#row(key);
376 return row === undefined ? undefined : this.#decode(row.value);
377 }
378 override set(key: K, value: V): this {
379 const row = this.#row(key);
380 let slot = row?.slot;
381 if (slot === undefined) {
382 const keys = storedArray<K>(this.#storage, `${this.#name}:order`);
383 slot = keys.length;
384 keys.push(key);
385 this.#storage.write(`${this.#name}:meta`, "size", this.size + 1);
386 }
387 this.#storage.write(this.#name, this.#key(key), { slot, value: this.#encode(value) });
388 return this;
389 }
390 override delete(key: K): boolean {
391 if (!this.has(key)) return false;
392 this.#storage.remove(this.#name, this.#key(key));
393 this.#storage.write(`${this.#name}:meta`, "size", this.size - 1);
394 return true;
395 }
396 override clear(): void {
397 for (const key of this.keys()) this.delete(key);
398 }
399 override *entries(): MapIterator<[K, V]> {
400 const keys = storedArray<K>(this.#storage, `${this.#name}:order`);
401 for (let slot = 0; slot < keys.length; slot++) {
402 const key = keys[slot]!;
403 const row = this.#row(key);
404 if (row?.slot === slot) yield [key, this.#decode(row.value)];
405 }
406 }
407 override *keys(): MapIterator<K> {
408 const keys = storedArray<K>(this.#storage, `${this.#name}:order`);
409 for (let slot = 0; slot < keys.length; slot++) {
410 const key = keys[slot]!;
411 if (this.#row(key)?.slot === slot) yield key;
412 }
413 }
414 override *values(): MapIterator<V> {
415 for (const [, value] of this.entries()) yield value;
416 }
417 override [Symbol.iterator](): MapIterator<[K, V]> {
418 return this.entries();
419 }
420 override forEach(callback: (value: V, key: K, map: Map<K, V>) => void, thisArg?: unknown): void {
421 for (const [key, value] of this.entries()) callback.call(thisArg, value, key, this);
422 }
423}
425/** Persistent membership with streaming iteration and no in-memory key cache. */
426export class StoredSet<K extends string | number> extends Set<K> {
427 readonly #map: StoredMap<K, true>;
428 constructor(storage: GraphStateStorage, name: string) {
429 super();
430 this.#map = new StoredMap(storage, name);
431 }
432 override get size(): number {
433 return this.#map.size;
434 }
435 override has(key: K): boolean {
436 return this.#map.has(key);
437 }
438 override add(key: K): this {
439 this.#map.set(key, true);
440 return this;
441 }
442 override delete(key: K): boolean {
443 return this.#map.delete(key);
444 }
445 override clear(): void {
446 this.#map.clear();
447 }
448 override *values(): SetIterator<K> {
449 yield* this.#map.keys();
450 }
451 override keys(): SetIterator<K> {
452 return this.values();
453 }
454 override *entries(): SetIterator<[K, K]> {
455 for (const key of this.values()) yield [key, key];
456 }
457 override [Symbol.iterator](): SetIterator<K> {
458 return this.values();
459 }
460 override forEach(callback: (value: K, key: K, set: Set<K>) => void, thisArg?: unknown): void {
461 for (const key of this.values()) callback.call(thisArg, key, key, this);
462 }
463}