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=133&format=json
497 linescodex-capacity-chair 100%Last change codex-capacity-chair in version 133, 8 versions changed it

You're reading version 133. The newest is 318, and 12 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. 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 }
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 }
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 }
142/** Immutable indexed subtraction retains neither operand's enumerated values. */
143export class StableDifferenceSet<T> extends StableSet<T> {
144 readonly left: StableSet<T>;
145 readonly right: StableSet<T>;
146 constructor(left: StableSet<T>, right: StableSet<T>) {
147 super();
148 this.left = left;
149 this.right = right;
150 }
151 get retainedBytes(): number {
152 return 32 + this.left.retainedBytes + this.right.retainedBytes;
153 }
154 has(value: T): boolean {
155 return this.left.has(value) && !this.right.has(value);
156 }
157 *values(): SetIterator<T> {
158 for (const value of this.left) if (!this.right.has(value)) yield value;
159 }
162/** Preserve indexed history; only the caller's operation-sized overlay is copied. */
163export function unionOverlay<T>(base: ReadonlySet<T>, overlay: Iterable<T>): ReadonlySet<T> {
164 return base instanceof StableSet
165 ? new StableUnionSet(base, new StableOverlaySet(overlay))
166 : new Set([...base, ...overlay]);
169/** Both indexed operands must be immutable for the lifetime of the result. */
170export function differenceSet<T>(left: ReadonlySet<T>, right: ReadonlySet<T>): ReadonlySet<T> {
171 return left instanceof StableSet && right instanceof StableSet
172 ? new StableDifferenceSet(left, right)
173 : new Set([...left].filter((value) => !right.has(value)));
176/** An immutable snapshot for the operation's small overlay, not its history. */
177export class StableOverlaySet<T> extends StableSet<T> {
178 readonly #values: Set<T>;
179 constructor(values: Iterable<T>) {
180 super();
181 this.#values = new Set(values);
182 }
183 get retainedBytes(): number {
184 return 64 + this.#values.size * 32;
185 }
186 has(value: T): boolean {
187 return this.#values.has(value);
188 }
189 values(): SetIterator<T> {
190 return this.#values.values();
191 }
194const indexKey = (key: PropertyKey): key is string =>
195 typeof key === "string" && /^(0|[1-9][0-9]*)$/.test(key) && Number.isSafeInteger(Number(key));
197/** Fixed-size numeric pages; callers retain no pages outside the bounded storage cache. */
198export function storedNumbers(storage: GraphStateStorage, name: string) {
199 const pageSize = 256;
200 const meta = `${name}:meta`;
201 const length = () => (storage.read(meta, "length") as number | undefined) ?? 0;
202 // Older experimental writer indexes must be rebuilt from their canonical log.
203 // Never interpret per-element rows as pages or silently lose existing history.
204 const page = (index: number): number[] => {
205 if (storage.read(meta, "format") !== 2)
206 throw new Error(`writer numeric index ${name} requires canonical-log adoption`);
207 const values = storage.read(`${name}:pages`, String(Math.floor(index / pageSize))) as number[] | undefined;
208 if (!values) throw new Error(`missing writer numeric page in ${name}`);
209 return values;
210 };
211 return {
212 get length() {
213 return length();
214 },
215 at(index: number): number {
216 if (!Number.isSafeInteger(index) || index < 0 || index >= length())
217 throw new Error(`writer numeric index out of bounds in ${name}`);
218 const value = page(index)[index % pageSize];
219 if (value === undefined) throw new Error(`incomplete writer numeric page in ${name}`);
220 return value;
221 },
222 push(value: number): void {
223 if (!Number.isSafeInteger(value)) throw new Error("writer numeric indexes require safe integers");
224 const index = length();
225 if (index > 0 && storage.read(meta, "format") !== 2)
226 throw new Error(`writer numeric index ${name} requires canonical-log adoption`);
227 const offset = index % pageSize;
228 const values = offset === 0 ? [] : page(index);
229 if (values.length !== offset) throw new Error(`invalid writer numeric page length in ${name}`);
230 values.push(value);
231 storage.write(`${name}:pages`, String(Math.floor(index / pageSize)), values);
232 if (index === 0) storage.write(meta, "format", 2);
233 storage.write(meta, "length", index + 1);
234 },
235 set(index: number, value: number): void {
236 if (!Number.isSafeInteger(value)) throw new Error("writer numeric indexes require safe integers");
237 if (!Number.isSafeInteger(index) || index < 0 || index >= length())
238 throw new Error(`writer numeric index out of bounds in ${name}`);
239 const values = page(index);
240 if (index % pageSize >= values.length) throw new Error(`incomplete writer numeric page in ${name}`);
241 values[index % pageSize] = value;
242 storage.write(`${name}:pages`, String(Math.floor(index / pageSize)), values);
243 },
244 };
247/** Array-shaped access without retaining its historical values in memory. */
248export function storedArray<T>(storage: GraphStateStorage, name: string, decode?: (value: T) => T): T[] {
249 const length = () => (storage.read(`${name}:meta`, "length") as number | undefined) ?? 0;
250 const read = (key: string) => {
251 const value = storage.read(name, key) as T;
252 return value === undefined || !decode ? value : decode(value);
253 };
254 return new Proxy([] as T[], {
255 get(target, key, receiver) {
256 if (key === "length") return length();
257 if (indexKey(key)) return Number(key) < length() ? read(key) : undefined;
258 return Reflect.get(target, key, receiver);
259 },
260 set(_target, key, value) {
261 if (key === "length") {
262 if (value !== length()) throw new Error("stored graph arrays cannot be resized directly");
263 return true;
264 }
265 if (!indexKey(key)) throw new Error("invalid stored graph array property");
266 const index = Number(key);
267 const size = length();
268 if (index > size) throw new Error("stored graph arrays cannot contain gaps");
269 storage.write(name, key, value);
270 if (index === size) storage.write(`${name}:meta`, "length", size + 1);
271 return true;
272 },
273 has(target, key) {
274 return indexKey(key) ? Number(key) < length() : Reflect.has(target, key);
275 },
276 ownKeys() {
277 return [...Array.from({ length: length() }, (_, index) => String(index)), "length"];
278 },
279 getOwnPropertyDescriptor(target, key) {
280 if (indexKey(key) && Number(key) < length())
281 return { configurable: true, enumerable: true, writable: true, value: read(key) };
282 return Reflect.getOwnPropertyDescriptor(target, key);
283 },
284 });
287export interface StateMap<K, V> {
288 keys(): IterableIterator<K>;
289 get(key: K): V | undefined;
290 set(key: K, value: V): StateMap<K, V>;
291 has(key: K): boolean;
292 delete(key: K): boolean;
293 values(): IterableIterator<V>;
296/** Append-only per-key lists, retaining at most one fixed-size page per iterator. */
297export function storedLists<V>(
298 storage: GraphStateStorage,
299 name: string,
300 legacyKey = (key: string) => JSON.stringify(["string", key]),
301) {
302 const pageSize = 256;
303 // The previous experimental layout stored one whole historical list per key.
304 const length = (key: string) => {
305 const stored = storage.read(`${name}:lengths`, key) as number | undefined;
306 if (stored === undefined && storage.read(name, legacyKey(key)) !== undefined)
307 throw new Error(`writer list index ${name} requires canonical-log adoption`);
308 const count = stored ?? 0;
309 if (!Number.isSafeInteger(count) || count < 0) throw new Error(`invalid writer list count in ${name}`);
310 return count;
311 };
312 const pageKey = (key: string, page: number) => JSON.stringify([key, page]);
313 const page = (key: string, index: number): V[] => {
314 const values = storage.read(`${name}:pages`, pageKey(key, index)) as V[] | undefined;
315 if (!Array.isArray(values) || values.length < 1 || values.length > pageSize)
316 throw new Error(`missing or invalid writer list page in ${name}`);
317 return values;
318 };
319 return {
320 length,
321 *keys(): IterableIterator<string> {
322 for (const entry of storage.entries(name)) {
323 void entry;
324 throw new Error(`writer list index ${name} requires canonical-log adoption`);
325 }
326 for (const [key] of storage.entries(`${name}:lengths`)) yield key;
327 },
328 *values(key: string): IterableIterator<V> {
329 const count = length(key);
330 for (let start = 0; start < count; start += pageSize) {
331 const values = page(key, start / pageSize);
332 if (values.length !== Math.min(pageSize, count - start))
333 throw new Error(`incomplete writer list page in ${name}`);
334 yield* values;
335 }
336 },
337 append(key: string, value: V): void {
338 const count = length(key);
339 const offset = count % pageSize;
340 const index = Math.floor(count / pageSize);
341 const values = offset === 0 ? [] : page(key, index);
342 if (values.length !== offset) throw new Error(`invalid writer list length in ${name}`);
343 values.push(value);
344 storage.write(`${name}:pages`, pageKey(key, index), values);
345 storage.write(`${name}:lengths`, key, count + 1);
346 },
347 };
350/** Keys are tagged so numeric graph codes cannot collide with string keys. */
351export function storedMap<K extends string | number, V>(storage: GraphStateStorage, name: string): StateMap<K, V> {
352 const keyOf = (key: K) => JSON.stringify([typeof key, key]);
353 const map: StateMap<K, V> = {
354 *keys() {
355 for (const [key] of storage.entries(name)) yield (JSON.parse(key) as [string, K])[1];
356 },
357 get: (key) => storage.read(name, keyOf(key)) as V | undefined,
358 has: (key) => storage.read(name, keyOf(key)) !== undefined,
359 set(key, value) {
360 storage.write(name, keyOf(key), value);
361 return map;
362 },
363 delete(key) {
364 const existed = map.has(key);
365 storage.remove(name, keyOf(key));
366 return existed;
367 },
368 *values() {
369 for (const [, value] of storage.entries(name)) yield value as V;
370 },
371 };
372 return map;
375/**
376 * A Map-compatible persistent index. Iteration follows insertion order and
377 * decodes one row at a time. Returned objects are copies, so mutations need
378 * an explicit set. Hosts wrap a logical multi-index mutation in transaction.
379 */
380export class StoredMap<K extends string | number, V> extends Map<K, V> {
381 readonly #storage: GraphStateStorage;
382 readonly #name: string;
383 readonly #encode: (value: V) => unknown;
384 readonly #decode: (value: unknown) => V;
385 constructor(
386 storage: GraphStateStorage,
387 name: string,
388 codec?: { encode(value: V): unknown; decode(value: unknown): V },
389 ) {
390 super();
391 this.#storage = storage;
392 this.#name = name;
393 this.#encode = codec?.encode ?? ((value) => value);
394 this.#decode = codec?.decode ?? ((value) => value as V);
395 }
396 #key(key: K): string {
397 return JSON.stringify([typeof key, key]);
398 }
399 #row(key: K): { slot: number; value: unknown } | undefined {
400 return this.#storage.read(this.#name, this.#key(key)) as { slot: number; value: unknown } | undefined;
401 }
402 override get size(): number {
403 return (this.#storage.read(`${this.#name}:meta`, "size") as number | undefined) ?? 0;
404 }
405 override has(key: K): boolean {
406 return this.#row(key) !== undefined;
407 }
408 override get(key: K): V | undefined {
409 const row = this.#row(key);
410 return row === undefined ? undefined : this.#decode(row.value);
411 }
412 override set(key: K, value: V): this {
413 const row = this.#row(key);
414 let slot = row?.slot;
415 if (slot === undefined) {
416 const keys = storedArray<K>(this.#storage, `${this.#name}:order`);
417 slot = keys.length;
418 keys.push(key);
419 this.#storage.write(`${this.#name}:meta`, "size", this.size + 1);
420 }
421 this.#storage.write(this.#name, this.#key(key), { slot, value: this.#encode(value) });
422 return this;
423 }
424 override delete(key: K): boolean {
425 if (!this.has(key)) return false;
426 this.#storage.remove(this.#name, this.#key(key));
427 this.#storage.write(`${this.#name}:meta`, "size", this.size - 1);
428 return true;
429 }
430 override clear(): void {
431 for (const key of this.keys()) this.delete(key);
432 }
433 override *entries(): MapIterator<[K, V]> {
434 const keys = storedArray<K>(this.#storage, `${this.#name}:order`);
435 for (let slot = 0; slot < keys.length; slot++) {
436 const key = keys[slot]!;
437 const row = this.#row(key);
438 if (row?.slot === slot) yield [key, this.#decode(row.value)];
439 }
440 }
441 override *keys(): MapIterator<K> {
442 const keys = storedArray<K>(this.#storage, `${this.#name}:order`);
443 for (let slot = 0; slot < keys.length; slot++) {
444 const key = keys[slot]!;
445 if (this.#row(key)?.slot === slot) yield key;
446 }
447 }
448 override *values(): MapIterator<V> {
449 for (const [, value] of this.entries()) yield value;
450 }
451 override [Symbol.iterator](): MapIterator<[K, V]> {
452 return this.entries();
453 }
454 override forEach(callback: (value: V, key: K, map: Map<K, V>) => void, thisArg?: unknown): void {
455 for (const [key, value] of this.entries()) callback.call(thisArg, value, key, this);
456 }
459/** Persistent membership with streaming iteration and no in-memory key cache. */
460export class StoredSet<K extends string | number> extends Set<K> {
461 readonly #map: StoredMap<K, true>;
462 constructor(storage: GraphStateStorage, name: string) {
463 super();
464 this.#map = new StoredMap(storage, name);
465 }
466 override get size(): number {
467 return this.#map.size;
468 }
469 override has(key: K): boolean {
470 return this.#map.has(key);
471 }
472 override add(key: K): this {
473 this.#map.set(key, true);
474 return this;
475 }
476 override delete(key: K): boolean {
477 return this.#map.delete(key);
478 }
479 override clear(): void {
480 this.#map.clear();
481 }
482 override *values(): SetIterator<K> {
483 yield* this.#map.keys();
484 }
485 override keys(): SetIterator<K> {
486 return this.values();
487 }
488 override *entries(): SetIterator<[K, K]> {
489 for (const key of this.values()) yield [key, key];
490 }
491 override [Symbol.iterator](): SetIterator<K> {
492 return this.values();
493 }
494 override forEach(callback: (value: K, key: K, set: Set<K>) => void, thisArg?: unknown): void {
495 for (const key of this.values()) callback.call(thisArg, key, key, this);
496 }