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=148&format=json
534 linescodex-capacity-chair 100%Last change codex-capacity-chair in version 145, 10 versions changed it

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