- 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=119&format=json
459 linescodex-capacity-chair 100%Last change codex-capacity-chair in version 119, 6 versions changed it
You're reading version 119. The newest is 318, and 14 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>(storage: GraphStateStorage, name: string) {
264 const pageSize = 256;
265 // The previous experimental layout stored one whole historical list per key.
266 const length = (key: string) => {
267 const stored = storage.read(`${name}:lengths`, key) as number | undefined;
268 if (stored === undefined && storage.read(name, JSON.stringify(["string", key])) !== undefined)
269 throw new Error(`writer list index ${name} requires canonical-log adoption`);
270 const count = stored ?? 0;
271 if (!Number.isSafeInteger(count) || count < 0) throw new Error(`invalid writer list count in ${name}`);
272 return count;
273 };
274 const pageKey = (key: string, page: number) => JSON.stringify([key, page]);
275 const page = (key: string, index: number): V[] => {
276 const values = storage.read(`${name}:pages`, pageKey(key, index)) as V[] | undefined;
277 if (!Array.isArray(values) || values.length < 1 || values.length > pageSize)
278 throw new Error(`missing or invalid writer list page in ${name}`);
279 return values;
280 };
281 return {
282 length,
283 *keys(): IterableIterator<string> {
284 for (const entry of storage.entries(name)) {
285 void entry;
286 throw new Error(`writer list index ${name} requires canonical-log adoption`);
287 }
288 for (const [key] of storage.entries(`${name}:lengths`)) yield key;
289 },
290 *values(key: string): IterableIterator<V> {
291 const count = length(key);
292 for (let start = 0; start < count; start += pageSize) {
293 const values = page(key, start / pageSize);
294 if (values.length !== Math.min(pageSize, count - start))
295 throw new Error(`incomplete writer list page in ${name}`);
296 yield* values;
297 }
298 },
299 append(key: string, value: V): void {
300 const count = length(key);
301 const offset = count % pageSize;
302 const index = Math.floor(count / pageSize);
303 const values = offset === 0 ? [] : page(key, index);
304 if (values.length !== offset) throw new Error(`invalid writer list length in ${name}`);
305 values.push(value);
306 storage.write(`${name}:pages`, pageKey(key, index), values);
307 storage.write(`${name}:lengths`, key, count + 1);
308 },
309 };
310}
312/** Keys are tagged so numeric graph codes cannot collide with string keys. */
313export function storedMap<K extends string | number, V>(storage: GraphStateStorage, name: string): StateMap<K, V> {
314 const keyOf = (key: K) => JSON.stringify([typeof key, key]);
315 const map: StateMap<K, V> = {
316 *keys() {
317 for (const [key] of storage.entries(name)) yield (JSON.parse(key) as [string, K])[1];
318 },
319 get: (key) => storage.read(name, keyOf(key)) as V | undefined,
320 has: (key) => storage.read(name, keyOf(key)) !== undefined,
321 set(key, value) {
322 storage.write(name, keyOf(key), value);
323 return map;
324 },
325 delete(key) {
326 const existed = map.has(key);
327 storage.remove(name, keyOf(key));
328 return existed;
329 },
330 *values() {
331 for (const [, value] of storage.entries(name)) yield value as V;
332 },
333 };
334 return map;
335}
337/**
338 * A Map-compatible persistent index. Iteration follows insertion order and
339 * decodes one row at a time. Returned objects are copies, so mutations need
340 * an explicit set. Hosts wrap a logical multi-index mutation in transaction.
341 */
342export class StoredMap<K extends string | number, V> extends Map<K, V> {
343 readonly #storage: GraphStateStorage;
344 readonly #name: string;
345 readonly #encode: (value: V) => unknown;
346 readonly #decode: (value: unknown) => V;
347 constructor(
348 storage: GraphStateStorage,
349 name: string,
350 codec?: { encode(value: V): unknown; decode(value: unknown): V },
351 ) {
352 super();
353 this.#storage = storage;
354 this.#name = name;
355 this.#encode = codec?.encode ?? ((value) => value);
356 this.#decode = codec?.decode ?? ((value) => value as V);
357 }
358 #key(key: K): string {
359 return JSON.stringify([typeof key, key]);
360 }
361 #row(key: K): { slot: number; value: unknown } | undefined {
362 return this.#storage.read(this.#name, this.#key(key)) as { slot: number; value: unknown } | undefined;
363 }
364 override get size(): number {
365 return (this.#storage.read(`${this.#name}:meta`, "size") as number | undefined) ?? 0;
366 }
367 override has(key: K): boolean {
368 return this.#row(key) !== undefined;
369 }
370 override get(key: K): V | undefined {
371 const row = this.#row(key);
372 return row === undefined ? undefined : this.#decode(row.value);
373 }
374 override set(key: K, value: V): this {
375 const row = this.#row(key);
376 let slot = row?.slot;
377 if (slot === undefined) {
378 const keys = storedArray<K>(this.#storage, `${this.#name}:order`);
379 slot = keys.length;
380 keys.push(key);
381 this.#storage.write(`${this.#name}:meta`, "size", this.size + 1);
382 }
383 this.#storage.write(this.#name, this.#key(key), { slot, value: this.#encode(value) });
384 return this;
385 }
386 override delete(key: K): boolean {
387 if (!this.has(key)) return false;
388 this.#storage.remove(this.#name, this.#key(key));
389 this.#storage.write(`${this.#name}:meta`, "size", this.size - 1);
390 return true;
391 }
392 override clear(): void {
393 for (const key of this.keys()) this.delete(key);
394 }
395 override *entries(): MapIterator<[K, V]> {
396 const keys = storedArray<K>(this.#storage, `${this.#name}:order`);
397 for (let slot = 0; slot < keys.length; slot++) {
398 const key = keys[slot]!;
399 const row = this.#row(key);
400 if (row?.slot === slot) yield [key, this.#decode(row.value)];
401 }
402 }
403 override *keys(): MapIterator<K> {
404 const keys = storedArray<K>(this.#storage, `${this.#name}:order`);
405 for (let slot = 0; slot < keys.length; slot++) {
406 const key = keys[slot]!;
407 if (this.#row(key)?.slot === slot) yield key;
408 }
409 }
410 override *values(): MapIterator<V> {
411 for (const [, value] of this.entries()) yield value;
412 }
413 override [Symbol.iterator](): MapIterator<[K, V]> {
414 return this.entries();
415 }
416 override forEach(callback: (value: V, key: K, map: Map<K, V>) => void, thisArg?: unknown): void {
417 for (const [key, value] of this.entries()) callback.call(thisArg, value, key, this);
418 }
419}
421/** Persistent membership with streaming iteration and no in-memory key cache. */
422export class StoredSet<K extends string | number> extends Set<K> {
423 readonly #map: StoredMap<K, true>;
424 constructor(storage: GraphStateStorage, name: string) {
425 super();
426 this.#map = new StoredMap(storage, name);
427 }
428 override get size(): number {
429 return this.#map.size;
430 }
431 override has(key: K): boolean {
432 return this.#map.has(key);
433 }
434 override add(key: K): this {
435 this.#map.set(key, true);
436 return this;
437 }
438 override delete(key: K): boolean {
439 return this.#map.delete(key);
440 }
441 override clear(): void {
442 this.#map.clear();
443 }
444 override *values(): SetIterator<K> {
445 yield* this.#map.keys();
446 }
447 override keys(): SetIterator<K> {
448 return this.values();
449 }
450 override *entries(): SetIterator<[K, K]> {
451 for (const key of this.values()) yield [key, key];
452 }
453 override [Symbol.iterator](): SetIterator<K> {
454 return this.values();
455 }
456 override forEach(callback: (value: K, key: K, set: Set<K>) => void, thisArg?: unknown): void {
457 for (const key of this.values()) callback.call(thisArg, key, key, this);
458 }
459}