Skip to content

abso-core

Public

abso is version control for agents: the client, the engine and a server you can run on your own Cloudflare account.

Check passed
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=136&format=json
525 linescodex-capacity-chair 100%Last change codex-capacity-chair in version 136, 9 versions changed it

You're reading version 136. The newest is 318, and 11 versions since then changed this file. Go to the newestCompare with 318

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;
16/**
17 * 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
19 * rollback or any mutation made through another storage instance.
20 */
21type CachedValue = { bytes: number } & (
22 | { kind: "scalar"; value: string | number | boolean | null | undefined }
23 | { kind: "numbers"; value: readonly number[] }
24 | { kind: "json"; json: string }
25);
27export class CachedStateStorage implements GraphStateStorage {
28 readonly #source: GraphStateStorage;
29 readonly #cache = new Map<string, CachedValue>();
30 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);
63 if (hit.kind === "scalar") return hit.value;
64 if (hit.kind === "numbers") return hit.value.slice();
65 return (JSON.parse(hit.json) as { value?: unknown }).value;
66 }
67 const value = this.#source.read(collection, key);
68 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 }
91 // Payload accounting is bounded, not a measurement of actual isolate heap.
92 if (entry.bytes <= this.#maxBytes && this.#maxEntries > 0) {
93 while (this.#bytes + entry.bytes > this.#maxBytes || this.#cache.size >= this.#maxEntries)
94 this.#drop(this.#cache.keys().next().value!);
95 this.#cache.set(cacheKey, entry);
96 this.#bytes += entry.bytes;
97 }
98 return value;
99 }
100 write(collection: string, key: string, value: unknown): void {
101 this.#drop(JSON.stringify([collection, key]));
102 this.#source.write(collection, key, value);
103 }
104 remove(collection: string, key: string): void {
105 this.#drop(JSON.stringify([collection, key]));
106 this.#source.remove(collection, key);
107 }
108 entries(collection: string): Iterable<readonly [string, unknown]> {
109 return this.#source.entries(collection);
110 }
111 transaction<T>(body: () => T): T {
112 try {
113 return this.#source.transaction(body);
114 } catch (error) {
115 this.clear();
116 throw error;
117 }
118 }
121/** Immutable membership whose implementation does not retain its enumerated keys. */
122export abstract class StableSet<T> implements ReadonlySet<T> {
123 abstract has(value: T): boolean;
124 abstract values(): SetIterator<T>;
125 /** Only resident membership data; external storage is not charged as heap. */
126 abstract readonly retainedBytes: number;
127 get [Symbol.toStringTag](): string {
128 return "Set";
129 }
130 get size(): number {
131 let count = 0;
132 for (const _ of this) count++;
133 return count;
134 }
135 keys(): SetIterator<T> {
136 return this.values();
137 }
138 *entries(): SetIterator<[T, T]> {
139 for (const value of this) yield [value, value];
140 }
141 [Symbol.iterator](): SetIterator<T> {
142 return this.values();
143 }
144 forEach(callback: (value: T, key: T, set: ReadonlySet<T>) => void, thisArg?: unknown): void {
145 for (const value of this) callback.call(thisArg, value, value, this);
146 }
149/** Both operands must be immutable for the lifetime of this union. */
150export class StableUnionSet<T> extends StableSet<T> {
151 readonly #left: StableSet<T>;
152 readonly #right: StableSet<T>;
153 constructor(left: StableSet<T>, right: StableSet<T>) {
154 super();
155 this.#left = left;
156 this.#right = right;
157 }
158 get retainedBytes(): number {
159 return 32 + this.#left.retainedBytes + this.#right.retainedBytes;
160 }
161 has(value: T): boolean {
162 return this.#left.has(value) || this.#right.has(value);
163 }
164 *values(): SetIterator<T> {
165 yield* this.#left;
166 for (const value of this.#right) if (!this.#left.has(value)) yield value;
167 }
170/** Immutable indexed subtraction retains neither operand's enumerated values. */
171export class StableDifferenceSet<T> extends StableSet<T> {
172 readonly left: StableSet<T>;
173 readonly right: StableSet<T>;
174 constructor(left: StableSet<T>, right: StableSet<T>) {
175 super();
176 this.left = left;
177 this.right = right;
178 }
179 get retainedBytes(): number {
180 return 32 + this.left.retainedBytes + this.right.retainedBytes;
181 }
182 has(value: T): boolean {
183 return this.left.has(value) && !this.right.has(value);
184 }
185 *values(): SetIterator<T> {
186 for (const value of this.left) if (!this.right.has(value)) yield value;
187 }
190/** Preserve indexed history; only the caller's operation-sized overlay is copied. */
191export function unionOverlay<T>(base: ReadonlySet<T>, overlay: Iterable<T>): ReadonlySet<T> {
192 return base instanceof StableSet
193 ? new StableUnionSet(base, new StableOverlaySet(overlay))
194 : new Set([...base, ...overlay]);
197/** Both indexed operands must be immutable for the lifetime of the result. */
198export function differenceSet<T>(left: ReadonlySet<T>, right: ReadonlySet<T>): ReadonlySet<T> {
199 return left instanceof StableSet && right instanceof StableSet
200 ? new StableDifferenceSet(left, right)
201 : new Set([...left].filter((value) => !right.has(value)));
204/** An immutable snapshot for the operation's small overlay, not its history. */
205export class StableOverlaySet<T> extends StableSet<T> {
206 readonly #values: Set<T>;
207 constructor(values: Iterable<T>) {
208 super();
209 this.#values = new Set(values);
210 }
211 get retainedBytes(): number {
212 return 64 + this.#values.size * 32;
213 }
214 has(value: T): boolean {
215 return this.#values.has(value);
216 }
217 values(): SetIterator<T> {
218 return this.#values.values();
219 }
222const indexKey = (key: PropertyKey): key is string =>
223 typeof key === "string" && /^(0|[1-9][0-9]*)$/.test(key) && Number.isSafeInteger(Number(key));
225/** Fixed-size numeric pages; callers retain no pages outside the bounded storage cache. */
226export function storedNumbers(storage: GraphStateStorage, name: string) {
227 const pageSize = 256;
228 const meta = `${name}:meta`;
229 const length = () => (storage.read(meta, "length") as number | undefined) ?? 0;
230 // Older experimental writer indexes must be rebuilt from their canonical log.
231 // Never interpret per-element rows as pages or silently lose existing history.
232 const page = (index: number): number[] => {
233 if (storage.read(meta, "format") !== 2)
234 throw new Error(`writer numeric index ${name} requires canonical-log adoption`);
235 const values = storage.read(`${name}:pages`, String(Math.floor(index / pageSize))) as number[] | undefined;
236 if (!values) throw new Error(`missing writer numeric page in ${name}`);
237 return values;
238 };
239 return {
240 get length() {
241 return length();
242 },
243 at(index: number): number {
244 if (!Number.isSafeInteger(index) || index < 0 || index >= length())
245 throw new Error(`writer numeric index out of bounds in ${name}`);
246 const value = page(index)[index % pageSize];
247 if (value === undefined) throw new Error(`incomplete writer numeric page in ${name}`);
248 return value;
249 },
250 push(value: number): void {
251 if (!Number.isSafeInteger(value)) throw new Error("writer numeric indexes require safe integers");
252 const index = length();
253 if (index > 0 && storage.read(meta, "format") !== 2)
254 throw new Error(`writer numeric index ${name} requires canonical-log adoption`);
255 const offset = index % pageSize;
256 const values = offset === 0 ? [] : page(index);
257 if (values.length !== offset) throw new Error(`invalid writer numeric page length in ${name}`);
258 values.push(value);
259 storage.write(`${name}:pages`, String(Math.floor(index / pageSize)), values);
260 if (index === 0) storage.write(meta, "format", 2);
261 storage.write(meta, "length", index + 1);
262 },
263 set(index: number, value: number): void {
264 if (!Number.isSafeInteger(value)) throw new Error("writer numeric indexes require safe integers");
265 if (!Number.isSafeInteger(index) || index < 0 || index >= length())
266 throw new Error(`writer numeric index out of bounds in ${name}`);
267 const values = page(index);
268 if (index % pageSize >= values.length) throw new Error(`incomplete writer numeric page in ${name}`);
269 values[index % pageSize] = value;
270 storage.write(`${name}:pages`, String(Math.floor(index / pageSize)), values);
271 },
272 };
275/** Array-shaped access without retaining its historical values in memory. */
276export function storedArray<T>(storage: GraphStateStorage, name: string, decode?: (value: T) => T): T[] {
277 const length = () => (storage.read(`${name}:meta`, "length") as number | undefined) ?? 0;
278 const read = (key: string) => {
279 const value = storage.read(name, key) as T;
280 return value === undefined || !decode ? value : decode(value);
281 };
282 return new Proxy([] as T[], {
283 get(target, key, receiver) {
284 if (key === "length") return length();
285 if (indexKey(key)) return Number(key) < length() ? read(key) : undefined;
286 return Reflect.get(target, key, receiver);
287 },
288 set(_target, key, value) {
289 if (key === "length") {
290 if (value !== length()) throw new Error("stored graph arrays cannot be resized directly");
291 return true;
292 }
293 if (!indexKey(key)) throw new Error("invalid stored graph array property");
294 const index = Number(key);
295 const size = length();
296 if (index > size) throw new Error("stored graph arrays cannot contain gaps");
297 storage.write(name, key, value);
298 if (index === size) storage.write(`${name}:meta`, "length", size + 1);
299 return true;
300 },
301 has(target, key) {
302 return indexKey(key) ? Number(key) < length() : Reflect.has(target, key);
303 },
304 ownKeys() {
305 return [...Array.from({ length: length() }, (_, index) => String(index)), "length"];
306 },
307 getOwnPropertyDescriptor(target, key) {
308 if (indexKey(key) && Number(key) < length())
309 return { configurable: true, enumerable: true, writable: true, value: read(key) };
310 return Reflect.getOwnPropertyDescriptor(target, key);
311 },
312 });
315export interface StateMap<K, V> {
316 keys(): IterableIterator<K>;
317 get(key: K): V | undefined;
318 set(key: K, value: V): StateMap<K, V>;
319 has(key: K): boolean;
320 delete(key: K): boolean;
321 values(): IterableIterator<V>;
324/** Append-only per-key lists, retaining at most one fixed-size page per iterator. */
325export function storedLists<V>(
326 storage: GraphStateStorage,
327 name: string,
328 legacyKey = (key: string) => JSON.stringify(["string", key]),
329) {
330 const pageSize = 256;
331 // The previous experimental layout stored one whole historical list per key.
332 const length = (key: string) => {
333 const stored = storage.read(`${name}:lengths`, key) as number | undefined;
334 if (stored === undefined && storage.read(name, legacyKey(key)) !== undefined)
335 throw new Error(`writer list index ${name} requires canonical-log adoption`);
336 const count = stored ?? 0;
337 if (!Number.isSafeInteger(count) || count < 0) throw new Error(`invalid writer list count in ${name}`);
338 return count;
339 };
340 const pageKey = (key: string, page: number) => JSON.stringify([key, page]);
341 const page = (key: string, index: number): V[] => {
342 const values = storage.read(`${name}:pages`, pageKey(key, index)) as V[] | undefined;
343 if (!Array.isArray(values) || values.length < 1 || values.length > pageSize)
344 throw new Error(`missing or invalid writer list page in ${name}`);
345 return values;
346 };
347 return {
348 length,
349 *keys(): IterableIterator<string> {
350 for (const entry of storage.entries(name)) {
351 void entry;
352 throw new Error(`writer list index ${name} requires canonical-log adoption`);
353 }
354 for (const [key] of storage.entries(`${name}:lengths`)) yield key;
355 },
356 *values(key: string): IterableIterator<V> {
357 const count = length(key);
358 for (let start = 0; start < count; start += pageSize) {
359 const values = page(key, start / pageSize);
360 if (values.length !== Math.min(pageSize, count - start))
361 throw new Error(`incomplete writer list page in ${name}`);
362 yield* values;
363 }
364 },
365 append(key: string, value: V): void {
366 const count = length(key);
367 const offset = count % pageSize;
368 const index = Math.floor(count / pageSize);
369 const values = offset === 0 ? [] : page(key, index);
370 if (values.length !== offset) throw new Error(`invalid writer list length in ${name}`);
371 values.push(value);
372 storage.write(`${name}:pages`, pageKey(key, index), values);
373 storage.write(`${name}:lengths`, key, count + 1);
374 },
375 };
378/** Keys are tagged so numeric graph codes cannot collide with string keys. */
379export function storedMap<K extends string | number, V>(storage: GraphStateStorage, name: string): StateMap<K, V> {
380 const keyOf = (key: K) => JSON.stringify([typeof key, key]);
381 const map: StateMap<K, V> = {
382 *keys() {
383 for (const [key] of storage.entries(name)) yield (JSON.parse(key) as [string, K])[1];
384 },
385 get: (key) => storage.read(name, keyOf(key)) as V | undefined,
386 has: (key) => storage.read(name, keyOf(key)) !== undefined,
387 set(key, value) {
388 storage.write(name, keyOf(key), value);
389 return map;
390 },
391 delete(key) {
392 const existed = map.has(key);
393 storage.remove(name, keyOf(key));
394 return existed;
395 },
396 *values() {
397 for (const [, value] of storage.entries(name)) yield value as V;
398 },
399 };
400 return map;
403/**
404 * A Map-compatible persistent index. Iteration follows insertion order and
405 * decodes one row at a time. Returned objects are copies, so mutations need
406 * an explicit set. Hosts wrap a logical multi-index mutation in transaction.
407 */
408export class StoredMap<K extends string | number, V> extends Map<K, V> {
409 readonly #storage: GraphStateStorage;
410 readonly #name: string;
411 readonly #encode: (value: V) => unknown;
412 readonly #decode: (value: unknown) => V;
413 constructor(
414 storage: GraphStateStorage,
415 name: string,
416 codec?: { encode(value: V): unknown; decode(value: unknown): V },
417 ) {
418 super();
419 this.#storage = storage;
420 this.#name = name;
421 this.#encode = codec?.encode ?? ((value) => value);
422 this.#decode = codec?.decode ?? ((value) => value as V);
423 }
424 #key(key: K): string {
425 return JSON.stringify([typeof key, key]);
426 }
427 #row(key: K): { slot: number; value: unknown } | undefined {
428 return this.#storage.read(this.#name, this.#key(key)) as { slot: number; value: unknown } | undefined;
429 }
430 override get size(): number {
431 return (this.#storage.read(`${this.#name}:meta`, "size") as number | undefined) ?? 0;
432 }
433 override has(key: K): boolean {
434 return this.#row(key) !== undefined;
435 }
436 override get(key: K): V | undefined {
437 const row = this.#row(key);
438 return row === undefined ? undefined : this.#decode(row.value);
439 }
440 override set(key: K, value: V): this {
441 const row = this.#row(key);
442 let slot = row?.slot;
443 if (slot === undefined) {
444 const keys = storedArray<K>(this.#storage, `${this.#name}:order`);
445 slot = keys.length;
446 keys.push(key);
447 this.#storage.write(`${this.#name}:meta`, "size", this.size + 1);
448 }
449 this.#storage.write(this.#name, this.#key(key), { slot, value: this.#encode(value) });
450 return this;
451 }
452 override delete(key: K): boolean {
453 if (!this.has(key)) return false;
454 this.#storage.remove(this.#name, this.#key(key));
455 this.#storage.write(`${this.#name}:meta`, "size", this.size - 1);
456 return true;
457 }
458 override clear(): void {
459 for (const key of this.keys()) this.delete(key);
460 }
461 override *entries(): MapIterator<[K, V]> {
462 const keys = storedArray<K>(this.#storage, `${this.#name}:order`);
463 for (let slot = 0; slot < keys.length; slot++) {
464 const key = keys[slot]!;
465 const row = this.#row(key);
466 if (row?.slot === slot) yield [key, this.#decode(row.value)];
467 }
468 }
469 override *keys(): MapIterator<K> {
470 const keys = storedArray<K>(this.#storage, `${this.#name}:order`);
471 for (let slot = 0; slot < keys.length; slot++) {
472 const key = keys[slot]!;
473 if (this.#row(key)?.slot === slot) yield key;
474 }
475 }
476 override *values(): MapIterator<V> {
477 for (const [, value] of this.entries()) yield value;
478 }
479 override [Symbol.iterator](): MapIterator<[K, V]> {
480 return this.entries();
481 }
482 override forEach(callback: (value: V, key: K, map: Map<K, V>) => void, thisArg?: unknown): void {
483 for (const [key, value] of this.entries()) callback.call(thisArg, value, key, this);
484 }
487/** Persistent membership with streaming iteration and no in-memory key cache. */
488export class StoredSet<K extends string | number> extends Set<K> {
489 readonly #map: StoredMap<K, true>;
490 constructor(storage: GraphStateStorage, name: string) {
491 super();
492 this.#map = new StoredMap(storage, name);
493 }
494 override get size(): number {
495 return this.#map.size;
496 }
497 override has(key: K): boolean {
498 return this.#map.has(key);
499 }
500 override add(key: K): this {
501 this.#map.set(key, true);
502 return this;
503 }
504 override delete(key: K): boolean {
505 return this.#map.delete(key);
506 }
507 override clear(): void {
508 this.#map.clear();
509 }
510 override *values(): SetIterator<K> {
511 yield* this.#map.keys();
512 }
513 override keys(): SetIterator<K> {
514 return this.values();
515 }
516 override *entries(): SetIterator<[K, K]> {
517 for (const key of this.values()) yield [key, key];
518 }
519 override [Symbol.iterator](): SetIterator<K> {
520 return this.values();
521 }
522 override forEach(callback: (value: K, key: K, set: Set<K>) => void, thisArg?: unknown): void {
523 for (const key of this.values()) callback.call(thisArg, key, key, this);
524 }