- 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=113&format=json
405 linescodex-capacity-chair 100%Last change codex-capacity-chair in version 113, 4 versions changed it
You're reading version 113. The newest is 318, and 16 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 get(key: K): V | undefined;
255 set(key: K, value: V): StateMap<K, V>;
256 has(key: K): boolean;
257 delete(key: K): boolean;
258 values(): IterableIterator<V>;
259}
261/** Keys are tagged so numeric graph codes cannot collide with string keys. */
262export function storedMap<K extends string | number, V>(storage: GraphStateStorage, name: string): StateMap<K, V> {
263 const keyOf = (key: K) => JSON.stringify([typeof key, key]);
264 const map: StateMap<K, V> = {
265 get: (key) => storage.read(name, keyOf(key)) as V | undefined,
266 has: (key) => storage.read(name, keyOf(key)) !== undefined,
267 set(key, value) {
268 storage.write(name, keyOf(key), value);
269 return map;
270 },
271 delete(key) {
272 const existed = map.has(key);
273 storage.remove(name, keyOf(key));
274 return existed;
275 },
276 *values() {
277 for (const [, value] of storage.entries(name)) yield value as V;
278 },
279 };
280 return map;
281}
283/**
284 * A Map-compatible persistent index. Iteration follows insertion order and
285 * decodes one row at a time. Returned objects are copies, so mutations need
286 * an explicit set. Hosts wrap a logical multi-index mutation in transaction.
287 */
288export class StoredMap<K extends string | number, V> extends Map<K, V> {
289 readonly #storage: GraphStateStorage;
290 readonly #name: string;
291 readonly #encode: (value: V) => unknown;
292 readonly #decode: (value: unknown) => V;
293 constructor(
294 storage: GraphStateStorage,
295 name: string,
296 codec?: { encode(value: V): unknown; decode(value: unknown): V },
297 ) {
298 super();
299 this.#storage = storage;
300 this.#name = name;
301 this.#encode = codec?.encode ?? ((value) => value);
302 this.#decode = codec?.decode ?? ((value) => value as V);
303 }
304 #key(key: K): string {
305 return JSON.stringify([typeof key, key]);
306 }
307 #row(key: K): { slot: number; value: unknown } | undefined {
308 return this.#storage.read(this.#name, this.#key(key)) as { slot: number; value: unknown } | undefined;
309 }
310 override get size(): number {
311 return (this.#storage.read(`${this.#name}:meta`, "size") as number | undefined) ?? 0;
312 }
313 override has(key: K): boolean {
314 return this.#row(key) !== undefined;
315 }
316 override get(key: K): V | undefined {
317 const row = this.#row(key);
318 return row === undefined ? undefined : this.#decode(row.value);
319 }
320 override set(key: K, value: V): this {
321 const row = this.#row(key);
322 let slot = row?.slot;
323 if (slot === undefined) {
324 const keys = storedArray<K>(this.#storage, `${this.#name}:order`);
325 slot = keys.length;
326 keys.push(key);
327 this.#storage.write(`${this.#name}:meta`, "size", this.size + 1);
328 }
329 this.#storage.write(this.#name, this.#key(key), { slot, value: this.#encode(value) });
330 return this;
331 }
332 override delete(key: K): boolean {
333 if (!this.has(key)) return false;
334 this.#storage.remove(this.#name, this.#key(key));
335 this.#storage.write(`${this.#name}:meta`, "size", this.size - 1);
336 return true;
337 }
338 override clear(): void {
339 for (const key of this.keys()) this.delete(key);
340 }
341 override *entries(): MapIterator<[K, V]> {
342 const keys = storedArray<K>(this.#storage, `${this.#name}:order`);
343 for (let slot = 0; slot < keys.length; slot++) {
344 const key = keys[slot]!;
345 const row = this.#row(key);
346 if (row?.slot === slot) yield [key, this.#decode(row.value)];
347 }
348 }
349 override *keys(): MapIterator<K> {
350 const keys = storedArray<K>(this.#storage, `${this.#name}:order`);
351 for (let slot = 0; slot < keys.length; slot++) {
352 const key = keys[slot]!;
353 if (this.#row(key)?.slot === slot) yield key;
354 }
355 }
356 override *values(): MapIterator<V> {
357 for (const [, value] of this.entries()) yield value;
358 }
359 override [Symbol.iterator](): MapIterator<[K, V]> {
360 return this.entries();
361 }
362 override forEach(callback: (value: V, key: K, map: Map<K, V>) => void, thisArg?: unknown): void {
363 for (const [key, value] of this.entries()) callback.call(thisArg, value, key, this);
364 }
365}
367/** Persistent membership with streaming iteration and no in-memory key cache. */
368export class StoredSet<K extends string | number> extends Set<K> {
369 readonly #map: StoredMap<K, true>;
370 constructor(storage: GraphStateStorage, name: string) {
371 super();
372 this.#map = new StoredMap(storage, name);
373 }
374 override get size(): number {
375 return this.#map.size;
376 }
377 override has(key: K): boolean {
378 return this.#map.has(key);
379 }
380 override add(key: K): this {
381 this.#map.set(key, true);
382 return this;
383 }
384 override delete(key: K): boolean {
385 return this.#map.delete(key);
386 }
387 override clear(): void {
388 this.#map.clear();
389 }
390 override *values(): SetIterator<K> {
391 yield* this.#map.keys();
392 }
393 override keys(): SetIterator<K> {
394 return this.values();
395 }
396 override *entries(): SetIterator<[K, K]> {
397 for (const key of this.values()) yield [key, key];
398 }
399 override [Symbol.iterator](): SetIterator<K> {
400 return this.values();
401 }
402 override forEach(callback: (value: K, key: K, set: Set<K>) => void, thisArg?: unknown): void {
403 for (const key of this.values()) callback.call(thisArg, key, key, this);
404 }
405}