- 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=111&format=json
355 linescodex-capacity-chair 100%Last change codex-capacity-chair in version 111, 3 versions changed it
You're reading version 111. The newest is 318, and 17 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/** Array-shaped access without retaining its historical values in memory. */
164export function storedArray<T>(storage: GraphStateStorage, name: string, decode?: (value: T) => T): T[] {
165 const length = () => (storage.read(`${name}:meta`, "length") as number | undefined) ?? 0;
166 const read = (key: string) => {
167 const value = storage.read(name, key) as T;
168 return value === undefined || !decode ? value : decode(value);
169 };
170 return new Proxy([] as T[], {
171 get(target, key, receiver) {
172 if (key === "length") return length();
173 if (indexKey(key)) return Number(key) < length() ? read(key) : undefined;
174 return Reflect.get(target, key, receiver);
175 },
176 set(_target, key, value) {
177 if (key === "length") {
178 if (value !== length()) throw new Error("stored graph arrays cannot be resized directly");
179 return true;
180 }
181 if (!indexKey(key)) throw new Error("invalid stored graph array property");
182 const index = Number(key);
183 const size = length();
184 if (index > size) throw new Error("stored graph arrays cannot contain gaps");
185 storage.write(name, key, value);
186 if (index === size) storage.write(`${name}:meta`, "length", size + 1);
187 return true;
188 },
189 has(target, key) {
190 return indexKey(key) ? Number(key) < length() : Reflect.has(target, key);
191 },
192 ownKeys() {
193 return [...Array.from({ length: length() }, (_, index) => String(index)), "length"];
194 },
195 getOwnPropertyDescriptor(target, key) {
196 if (indexKey(key) && Number(key) < length())
197 return { configurable: true, enumerable: true, writable: true, value: read(key) };
198 return Reflect.getOwnPropertyDescriptor(target, key);
199 },
200 });
201}
203export interface StateMap<K, V> {
204 get(key: K): V | undefined;
205 set(key: K, value: V): StateMap<K, V>;
206 has(key: K): boolean;
207 delete(key: K): boolean;
208 values(): IterableIterator<V>;
209}
211/** Keys are tagged so numeric graph codes cannot collide with string keys. */
212export function storedMap<K extends string | number, V>(storage: GraphStateStorage, name: string): StateMap<K, V> {
213 const keyOf = (key: K) => JSON.stringify([typeof key, key]);
214 const map: StateMap<K, V> = {
215 get: (key) => storage.read(name, keyOf(key)) as V | undefined,
216 has: (key) => storage.read(name, keyOf(key)) !== undefined,
217 set(key, value) {
218 storage.write(name, keyOf(key), value);
219 return map;
220 },
221 delete(key) {
222 const existed = map.has(key);
223 storage.remove(name, keyOf(key));
224 return existed;
225 },
226 *values() {
227 for (const [, value] of storage.entries(name)) yield value as V;
228 },
229 };
230 return map;
231}
233/**
234 * A Map-compatible persistent index. Iteration follows insertion order and
235 * decodes one row at a time. Returned objects are copies, so mutations need
236 * an explicit set. Hosts wrap a logical multi-index mutation in transaction.
237 */
238export class StoredMap<K extends string | number, V> extends Map<K, V> {
239 readonly #storage: GraphStateStorage;
240 readonly #name: string;
241 readonly #encode: (value: V) => unknown;
242 readonly #decode: (value: unknown) => V;
243 constructor(
244 storage: GraphStateStorage,
245 name: string,
246 codec?: { encode(value: V): unknown; decode(value: unknown): V },
247 ) {
248 super();
249 this.#storage = storage;
250 this.#name = name;
251 this.#encode = codec?.encode ?? ((value) => value);
252 this.#decode = codec?.decode ?? ((value) => value as V);
253 }
254 #key(key: K): string {
255 return JSON.stringify([typeof key, key]);
256 }
257 #row(key: K): { slot: number; value: unknown } | undefined {
258 return this.#storage.read(this.#name, this.#key(key)) as { slot: number; value: unknown } | undefined;
259 }
260 override get size(): number {
261 return (this.#storage.read(`${this.#name}:meta`, "size") as number | undefined) ?? 0;
262 }
263 override has(key: K): boolean {
264 return this.#row(key) !== undefined;
265 }
266 override get(key: K): V | undefined {
267 const row = this.#row(key);
268 return row === undefined ? undefined : this.#decode(row.value);
269 }
270 override set(key: K, value: V): this {
271 const row = this.#row(key);
272 let slot = row?.slot;
273 if (slot === undefined) {
274 const keys = storedArray<K>(this.#storage, `${this.#name}:order`);
275 slot = keys.length;
276 keys.push(key);
277 this.#storage.write(`${this.#name}:meta`, "size", this.size + 1);
278 }
279 this.#storage.write(this.#name, this.#key(key), { slot, value: this.#encode(value) });
280 return this;
281 }
282 override delete(key: K): boolean {
283 if (!this.has(key)) return false;
284 this.#storage.remove(this.#name, this.#key(key));
285 this.#storage.write(`${this.#name}:meta`, "size", this.size - 1);
286 return true;
287 }
288 override clear(): void {
289 for (const key of this.keys()) this.delete(key);
290 }
291 override *entries(): MapIterator<[K, V]> {
292 const keys = storedArray<K>(this.#storage, `${this.#name}:order`);
293 for (let slot = 0; slot < keys.length; slot++) {
294 const key = keys[slot]!;
295 const row = this.#row(key);
296 if (row?.slot === slot) yield [key, this.#decode(row.value)];
297 }
298 }
299 override *keys(): MapIterator<K> {
300 const keys = storedArray<K>(this.#storage, `${this.#name}:order`);
301 for (let slot = 0; slot < keys.length; slot++) {
302 const key = keys[slot]!;
303 if (this.#row(key)?.slot === slot) yield key;
304 }
305 }
306 override *values(): MapIterator<V> {
307 for (const [, value] of this.entries()) yield value;
308 }
309 override [Symbol.iterator](): MapIterator<[K, V]> {
310 return this.entries();
311 }
312 override forEach(callback: (value: V, key: K, map: Map<K, V>) => void, thisArg?: unknown): void {
313 for (const [key, value] of this.entries()) callback.call(thisArg, value, key, this);
314 }
315}
317/** Persistent membership with streaming iteration and no in-memory key cache. */
318export class StoredSet<K extends string | number> extends Set<K> {
319 readonly #map: StoredMap<K, true>;
320 constructor(storage: GraphStateStorage, name: string) {
321 super();
322 this.#map = new StoredMap(storage, name);
323 }
324 override get size(): number {
325 return this.#map.size;
326 }
327 override has(key: K): boolean {
328 return this.#map.has(key);
329 }
330 override add(key: K): this {
331 this.#map.set(key, true);
332 return this;
333 }
334 override delete(key: K): boolean {
335 return this.#map.delete(key);
336 }
337 override clear(): void {
338 this.#map.clear();
339 }
340 override *values(): SetIterator<K> {
341 yield* this.#map.keys();
342 }
343 override keys(): SetIterator<K> {
344 return this.values();
345 }
346 override *entries(): SetIterator<[K, K]> {
347 for (const key of this.values()) yield [key, key];
348 }
349 override [Symbol.iterator](): SetIterator<K> {
350 return this.values();
351 }
352 override forEach(callback: (value: K, key: K, set: Set<K>) => void, thisArg?: unknown): void {
353 for (const key of this.values()) callback.call(thisArg, key, key, this);
354 }
355}