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=166&format=json
607 linescodex-capacity-chair 100%Last change codex-capacity-chair in version 162, 11 versions changed it

You're reading version 166. The newest is 318, and 9 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>(
286 storage: GraphStateStorage,
287 name: string,
288 decode?: (value: T) => T,
289 encode?: (value: T, key: string) => unknown,
290): T[] {
291 const length = () => (storage.read(`${name}:meta`, "length") as number | undefined) ?? 0;
292 const read = (key: string) => {
293 const value = storage.read(name, key) as T;
294 return value === undefined || !decode ? value : decode(value);
295 };
296 return new Proxy([] as T[], {
297 get(target, key, receiver) {
298 if (key === "length") return length();
299 if (indexKey(key)) return Number(key) < length() ? read(key) : undefined;
300 return Reflect.get(target, key, receiver);
301 },
302 set(_target, key, value) {
303 if (key === "length") {
304 if (value !== length()) throw new Error("stored graph arrays cannot be resized directly");
305 return true;
306 }
307 if (!indexKey(key)) throw new Error("invalid stored graph array property");
308 const index = Number(key);
309 const size = length();
310 if (index > size) throw new Error("stored graph arrays cannot contain gaps");
311 storage.write(name, key, encode ? encode(value, key) : value);
312 if (index === size) storage.write(`${name}:meta`, "length", size + 1);
313 return true;
314 },
315 has(target, key) {
316 return indexKey(key) ? Number(key) < length() : Reflect.has(target, key);
317 },
318 ownKeys() {
319 return [...Array.from({ length: length() }, (_, index) => String(index)), "length"];
320 },
321 getOwnPropertyDescriptor(target, key) {
322 if (indexKey(key) && Number(key) < length())
323 return { configurable: true, enumerable: true, writable: true, value: read(key) };
324 return Reflect.getOwnPropertyDescriptor(target, key);
325 },
326 });
329export interface StateMap<K, V> {
330 keys(): IterableIterator<K>;
331 get(key: K): V | undefined;
332 set(key: K, value: V): StateMap<K, V>;
333 has(key: K): boolean;
334 delete(key: K): boolean;
335 values(): IterableIterator<V>;
338/** Append-only per-key lists, retaining at most one fixed-size page per iterator. */
339export function storedLists<V>(
340 storage: GraphStateStorage,
341 name: string,
342 legacyKey = (key: string) => JSON.stringify(["string", key]),
343) {
344 const pageSize = 256;
345 // The previous experimental layout stored one whole historical list per key.
346 const length = (key: string) => {
347 const stored = storage.read(`${name}:lengths`, key) as number | undefined;
348 if (stored === undefined && storage.read(name, legacyKey(key)) !== undefined)
349 throw new Error(`writer list index ${name} requires canonical-log adoption`);
350 const count = stored ?? 0;
351 if (!Number.isSafeInteger(count) || count < 0) throw new Error(`invalid writer list count in ${name}`);
352 return count;
353 };
354 const pageKey = (key: string, page: number) => JSON.stringify([key, page]);
355 const page = (key: string, index: number): V[] => {
356 const values = storage.read(`${name}:pages`, pageKey(key, index)) as V[] | undefined;
357 if (!Array.isArray(values) || values.length < 1 || values.length > pageSize)
358 throw new Error(`missing or invalid writer list page in ${name}`);
359 return values;
360 };
361 return {
362 length,
363 *keys(): IterableIterator<string> {
364 for (const entry of storage.entries(name)) {
365 void entry;
366 throw new Error(`writer list index ${name} requires canonical-log adoption`);
367 }
368 for (const [key] of storage.entries(`${name}:lengths`)) yield key;
369 },
370 *values(key: string): IterableIterator<V> {
371 const count = length(key);
372 for (let start = 0; start < count; start += pageSize) {
373 const values = page(key, start / pageSize);
374 if (values.length !== Math.min(pageSize, count - start))
375 throw new Error(`incomplete writer list page in ${name}`);
376 yield* values;
377 }
378 },
379 last(key: string): V | undefined {
380 const count = length(key);
381 if (count === 0) return undefined;
382 const values = page(key, Math.floor((count - 1) / pageSize));
383 const expected = ((count - 1) % pageSize) + 1;
384 if (values.length !== expected) throw new Error(`incomplete writer list page in ${name}`);
385 return values[expected - 1];
386 },
387 append(key: string, value: V): void {
388 const count = length(key);
389 const offset = count % pageSize;
390 const index = Math.floor(count / pageSize);
391 const values = offset === 0 ? [] : page(key, index);
392 if (values.length !== offset) throw new Error(`invalid writer list length in ${name}`);
393 values.push(value);
394 storage.write(`${name}:pages`, pageKey(key, index), values);
395 storage.write(`${name}:lengths`, key, count + 1);
396 },
397 };
400/** Keys are tagged so numeric graph codes cannot collide with string keys. */
401export function storedMap<K extends string | number, V>(storage: GraphStateStorage, name: string): StateMap<K, V> {
402 const keyOf = (key: K) => JSON.stringify([typeof key, key]);
403 const map: StateMap<K, V> = {
404 *keys() {
405 for (const [key] of storage.entries(name)) yield (JSON.parse(key) as [string, K])[1];
406 },
407 get: (key) => storage.read(name, keyOf(key)) as V | undefined,
408 has: (key) => storage.read(name, keyOf(key)) !== undefined,
409 set(key, value) {
410 storage.write(name, keyOf(key), value);
411 return map;
412 },
413 delete(key) {
414 const existed = map.has(key);
415 storage.remove(name, keyOf(key));
416 return existed;
417 },
418 *values() {
419 for (const [, value] of storage.entries(name)) yield value as V;
420 },
421 };
422 return map;
425/**
426 * A Map-compatible persistent index. Iteration follows insertion order and
427 * decodes one row at a time. Returned objects are copies, so mutations need
428 * an explicit set. Hosts wrap a logical multi-index mutation in transaction.
429 */
430export class StoredMap<K extends string | number, V> extends Map<K, V> {
431 readonly #storage: GraphStateStorage;
432 readonly #name: string;
433 readonly #encode: (value: V) => unknown;
434 readonly #decode: (value: unknown) => V;
435 constructor(
436 storage: GraphStateStorage,
437 name: string,
438 codec?: { encode(value: V): unknown; decode(value: unknown): V },
439 ) {
440 super();
441 this.#storage = storage;
442 this.#name = name;
443 this.#encode = codec?.encode ?? ((value) => value);
444 this.#decode = codec?.decode ?? ((value) => value as V);
445 }
446 #key(key: K): string {
447 return JSON.stringify([typeof key, key]);
448 }
449 #row(key: K): { slot: number; value: unknown } | undefined {
450 return this.#storage.read(this.#name, this.#key(key)) as { slot: number; value: unknown } | undefined;
451 }
452 override get size(): number {
453 return (this.#storage.read(`${this.#name}:meta`, "size") as number | undefined) ?? 0;
454 }
455 override has(key: K): boolean {
456 return this.#row(key) !== undefined;
457 }
458 override get(key: K): V | undefined {
459 const row = this.#row(key);
460 return row === undefined ? undefined : this.#decode(row.value);
461 }
462 override set(key: K, value: V): this {
463 const row = this.#row(key);
464 let slot = row?.slot;
465 if (slot === undefined) {
466 const keys = storedArray<K>(this.#storage, `${this.#name}:order`);
467 slot = keys.length;
468 keys.push(key);
469 this.#storage.write(`${this.#name}:meta`, "size", this.size + 1);
470 }
471 this.#storage.write(this.#name, this.#key(key), { slot, value: this.#encode(value) });
472 return this;
473 }
474 override delete(key: K): boolean {
475 if (!this.has(key)) return false;
476 this.#storage.remove(this.#name, this.#key(key));
477 this.#storage.write(`${this.#name}:meta`, "size", this.size - 1);
478 return true;
479 }
480 override clear(): void {
481 for (const key of this.keys()) this.delete(key);
482 }
483 override *entries(): MapIterator<[K, V]> {
484 const keys = storedArray<K>(this.#storage, `${this.#name}:order`);
485 for (let slot = 0; slot < keys.length; slot++) {
486 const key = keys[slot]!;
487 const row = this.#row(key);
488 if (row?.slot === slot) yield [key, this.#decode(row.value)];
489 }
490 }
491 override *keys(): MapIterator<K> {
492 const keys = storedArray<K>(this.#storage, `${this.#name}:order`);
493 for (let slot = 0; slot < keys.length; slot++) {
494 const key = keys[slot]!;
495 if (this.#row(key)?.slot === slot) yield key;
496 }
497 }
498 override *values(): MapIterator<V> {
499 for (const [, value] of this.entries()) yield value;
500 }
501 override [Symbol.iterator](): MapIterator<[K, V]> {
502 return this.entries();
503 }
504 override forEach(callback: (value: V, key: K, map: Map<K, V>) => void, thisArg?: unknown): void {
505 for (const [key, value] of this.entries()) callback.call(thisArg, value, key, this);
506 }
509/** Persistent membership with streaming iteration and no in-memory key cache. */
510export class StoredSet<K extends string | number> extends Set<K> {
511 readonly #map: StoredMap<K, true>;
512 constructor(storage: GraphStateStorage, name: string) {
513 super();
514 this.#map = new StoredMap(storage, name);
515 }
516 override get size(): number {
517 return this.#map.size;
518 }
519 override has(key: K): boolean {
520 return this.#map.has(key);
521 }
522 override add(key: K): this {
523 this.#map.set(key, true);
524 return this;
525 }
526 override delete(key: K): boolean {
527 return this.#map.delete(key);
528 }
529 override clear(): void {
530 this.#map.clear();
531 }
532 override *values(): SetIterator<K> {
533 yield* this.#map.keys();
534 }
535 override keys(): SetIterator<K> {
536 return this.values();
537 }
538 override *entries(): SetIterator<[K, K]> {
539 for (const key of this.values()) yield [key, key];
540 }
541 override [Symbol.iterator](): SetIterator<K> {
542 return this.values();
543 }
544 override forEach(callback: (value: K, key: K, set: Set<K>) => void, thisArg?: unknown): void {
545 for (const key of this.values()) callback.call(thisArg, key, key, this);
546 }
549/** Read-only array access to individually stored values, without copying the list. */
550export function readonlyStoredArray<T>(
551 storage: GraphStateStorage,
552 name: string,
553 decode?: (value: unknown, index: number) => T,
554): readonly T[] {
555 const length = () => {
556 const count = storage.read(`${name}:meta`, "length");
557 if (!Number.isSafeInteger(count) || (count as number) < 0) throw Error("invalid stored list length");
558 return count as number;
559 };
560 length();
561 return new Proxy([] as T[], {
562 get(target, key, receiver) {
563 if (key === "length") return length();
564 if (indexKey(key)) {
565 if (Number(key) >= length()) return undefined;
566 const raw = storage.read(name, key);
567 const value = raw === undefined ? undefined : decode ? decode(raw, Number(key)) : (raw as T);
568 if (value === undefined) throw Error("missing stored list element");
569 return value && typeof value === "object" ? Object.freeze(value) : value;
570 }
571 return Reflect.get(target, key, receiver);
572 },
573 has(target, key) {
574 return indexKey(key) ? Number(key) < length() : Reflect.has(target, key);
575 },
576 ownKeys() {
577 return [...Array.from({ length: length() }, (_, index) => String(index)), "length"];
578 },
579 getOwnPropertyDescriptor(target, key) {
580 if (key === "length") return { ...Reflect.getOwnPropertyDescriptor(target, key)!, value: length() };
581 if (indexKey(key) && Number(key) < length()) {
582 const raw = storage.read(name, key);
583 const value = raw === undefined ? undefined : decode ? decode(raw, Number(key)) : (raw as T);
584 if (value === undefined) throw Error("missing stored list element");
585 return {
586 configurable: true,
587 enumerable: true,
588 writable: false,
589 value: value && typeof value === "object" ? Object.freeze(value) : value,
590 };
591 }
592 return Reflect.getOwnPropertyDescriptor(target, key);
593 },
594 preventExtensions() {
595 throw Error("stored list is read-only");
596 },
597 set() {
598 throw Error("stored list is read-only");
599 },
600 deleteProperty() {
601 throw Error("stored list is read-only");
602 },
603 defineProperty() {
604 throw Error("stored list is read-only");
605 },
606 });