{"draft":null,"from":20,"to":318,"files":[{"path":"src/engine/state-source.ts","added":757,"removed":0,"diff":"--- /dev/null\n+++ b/src/engine/state-source.ts\n@@ -0,0 +1,757 @@\n+/**\n+ * Indexed graph storage. Values must be copied on write and read: a caller\n+ * mutating a returned list must not silently change persisted state. Hosts\n+ * provide transactions that roll back every write when the callback throws.\n+ * The namespace belongs to one graph and must not be shared by concurrent\n+ * Graph instances. Opening a graph does not scan its stored collections.\n+ */\n+export interface GraphStateStorage {\n+\tread(collection: string, key: string): unknown;\n+\twrite(collection: string, key: string, value: unknown): void;\n+\tremove(collection: string, key: string): void;\n+\tentries(collection: string): Iterable<readonly [string, unknown]>;\n+\ttransaction<T>(body: () => T): T;\n+}\n+\n+/**\n+ * Operation-local read cache with fixed payload and entry limits. Private numeric\n+ * pages, immutable scalars and serialized objects preserve the copy contract. Discard it after an outer host\n+ * rollback or any mutation made through another storage instance.\n+ */\n+type CachedValue = { bytes: number } & (\n+\t| { kind: \"scalar\"; value: string | number | boolean | null | undefined }\n+\t| { kind: \"numbers\"; value: readonly number[] }\n+\t| { kind: \"json\"; json: string }\n+);\n+\n+export class CachedStateStorage implements GraphStateStorage {\n+\treadonly #source: GraphStateStorage;\n+\treadonly #cache = new Map<string, CachedValue>();\n+\treadonly #maxBytes: number;\n+\treadonly #maxEntries: number;\n+\t#bytes = 0;\n+\t/**\n+\t * The keys written or removed in each open transaction, innermost last (abso Capacity). A rollback drops only those:\n+\t * every projection scratch scope ends in a rollback, and dropping the whole cache there read the same rows from\n+\t * storage again within a call and on every call of a kept reader.\n+\t */\n+\treadonly #touched: Set<string>[] = [];\n+\t/**\n+\t * The biggest one row may be and still be kept (abso Capacity). A few big rows read on every call (each agent with\n+\t * all the news it was told: 4.3 MB for abso's 109 agents) otherwise push every small page out of the cache.\n+\t */\n+\treadonly #maxEntryBytes: number;\n+\tconstructor(source: GraphStateStorage, maxBytes = 1_048_576, maxEntries = 4096, maxEntryBytes = maxBytes) {\n+\t\tif (\n+\t\t\t!Number.isSafeInteger(maxBytes) ||\n+\t\t\tmaxBytes < 0 ||\n+\t\t\t!Number.isSafeInteger(maxEntries) ||\n+\t\t\tmaxEntries < 0 ||\n+\t\t\t!Number.isSafeInteger(maxEntryBytes) ||\n+\t\t\tmaxEntryBytes < 0\n+\t\t)\n+\t\t\tthrow new Error(\"invalid writer cache limits\");\n+\t\tthis.#source = source;\n+\t\tthis.#maxBytes = maxBytes;\n+\t\tthis.#maxEntries = maxEntries;\n+\t\tthis.#maxEntryBytes = Math.min(maxEntryBytes, maxBytes);\n+\t}\n+\tget retainedBytes(): number {\n+\t\treturn this.#bytes;\n+\t}\n+\tget retainedEntries(): number {\n+\t\treturn this.#cache.size;\n+\t}\n+\tclear(): void {\n+\t\tthis.#cache.clear();\n+\t\tthis.#bytes = 0;\n+\t}\n+\t#drop(key: string): void {\n+\t\tconst previous = this.#cache.get(key);\n+\t\tif (previous) {\n+\t\t\tthis.#cache.delete(key);\n+\t\t\tthis.#bytes -= previous.bytes;\n+\t\t}\n+\t}\n+\tread(collection: string, key: string): unknown {\n+\t\tconst cacheKey = JSON.stringify([collection, key]);\n+\t\tconst hit = this.#cache.get(cacheKey);\n+\t\tif (hit) {\n+\t\t\tthis.#cache.delete(cacheKey);\n+\t\t\tthis.#cache.set(cacheKey, hit);\n+\t\t\tif (hit.kind === \"scalar\") return hit.value;\n+\t\t\tif (hit.kind === \"numbers\") return hit.value.slice();\n+\t\t\treturn (JSON.parse(hit.json) as { value?: unknown }).value;\n+\t\t}\n+\t\tconst value = this.#source.read(collection, key);\n+\t\tconst overhead = 2 * cacheKey.length + 160;\n+\t\tlet entry: CachedValue;\n+\t\tif (\n+\t\t\tvalue === undefined ||\n+\t\t\tvalue === null ||\n+\t\t\ttypeof value === \"string\" ||\n+\t\t\ttypeof value === \"boolean\" ||\n+\t\t\t(typeof value === \"number\" && Number.isFinite(value))\n+\t\t) {\n+\t\t\tentry = { kind: \"scalar\", value, bytes: overhead + (typeof value === \"string\" ? 2 * value.length : 16) };\n+\t\t} else if (\n+\t\t\tArray.isArray(value) &&\n+\t\t\tvalue.length <= 256 &&\n+\t\t\tObject.keys(value).length === value.length &&\n+\t\t\tvalue.every(Number.isSafeInteger)\n+\t\t) {\n+\t\t\t// Store one private, bounded numeric page. Public reads still receive a\n+\t\t\t// fresh copy; neither the source result nor a reader can mutate the cache.\n+\t\t\tentry = { kind: \"numbers\", value: value.slice(), bytes: overhead + 32 + value.length * 8 };\n+\t\t} else {\n+\t\t\tconst json = JSON.stringify({ value });\n+\t\t\tentry = { kind: \"json\", json, bytes: overhead + 2 * json.length };\n+\t\t}\n+\t\tthis.#remember(cacheKey, entry);\n+\t\t// A projection scope's own rows are never read again once it ends in its rollback: forget them with it.\n+\t\tif (collection.startsWith(\"projection-scratch:\")) this.#touched.at(-1)?.add(cacheKey);\n+\t\treturn value;\n+\t}\n+\t#remember(cacheKey: string, entry: CachedValue): void {\n+\t\tthis.#drop(cacheKey);\n+\t\t// Payload accounting is bounded, not a measurement of actual isolate heap.\n+\t\tif (entry.bytes <= this.#maxEntryBytes && this.#maxEntries > 0) {\n+\t\t\twhile (this.#bytes + entry.bytes > this.#maxBytes || this.#cache.size >= this.#maxEntries)\n+\t\t\t\tthis.#drop(this.#cache.keys().next().value!);\n+\t\t\tthis.#cache.set(cacheKey, entry);\n+\t\t\tthis.#bytes += entry.bytes;\n+\t\t}\n+\t}\n+\twrite(collection: string, key: string, value: unknown): void {\n+\t\tconst cacheKey = JSON.stringify([collection, key]);\n+\t\tthis.#drop(cacheKey);\n+\t\tthis.#touched.at(-1)?.add(cacheKey);\n+\t\tthis.#source.write(collection, key, value);\n+\t\t// Allocation counters are immutable scalars. Keep successful writes within\n+\t\t// the existing cache budget instead of immediately reading them back.\n+\t\tif (typeof value === \"number\" && Number.isSafeInteger(value) && !Object.is(value, -0))\n+\t\t\tthis.#remember(cacheKey, { kind: \"scalar\", value, bytes: 2 * cacheKey.length + 176 });\n+\t}\n+\tremove(collection: string, key: string): void {\n+\t\tconst cacheKey = JSON.stringify([collection, key]);\n+\t\tthis.#drop(cacheKey);\n+\t\tthis.#touched.at(-1)?.add(cacheKey);\n+\t\tthis.#source.remove(collection, key);\n+\t}\n+\tentries(collection: string): Iterable<readonly [string, unknown]> {\n+\t\treturn this.#source.entries(collection);\n+\t}\n+\ttransaction<T>(body: () => T): T {\n+\t\tconst touched = new Set<string>();\n+\t\tthis.#touched.push(touched);\n+\t\ttry {\n+\t\t\tconst result = this.#source.transaction(body);\n+\t\t\tthis.#touched.pop();\n+\t\t\t// Committed into the outer transaction, which may still roll back.\n+\t\t\tconst outer = this.#touched.at(-1);\n+\t\t\tif (outer) for (const key of touched) outer.add(key);\n+\t\t\treturn result;\n+\t\t} catch (error) {\n+\t\t\tthis.#touched.pop();\n+\t\t\t// What the transaction wrote, and anything read back after it wrote it, is gone with the rollback.\n+\t\t\tfor (const key of touched) this.#drop(key);\n+\t\t\tthrow error;\n+\t\t}\n+\t}\n+}\n+\n+/**\n+ * Sets known to be closed under dependencies (abso Capacity): every atom's deps are in the set. A view or a project\n+ * given one skips proving it again, which read every atom and every dependency in the history.\n+ */\n+const closedSets = new WeakSet<object>();\n+export function markClosed<S extends ReadonlySet<unknown>>(set: S): S {\n+\tclosedSets.add(set);\n+\treturn set;\n+}\n+export function isClosedSet(set: unknown): boolean {\n+\treturn typeof set === \"object\" && set !== null && closedSets.has(set);\n+}\n+\n+/** Immutable membership whose implementation does not retain its enumerated keys. */\n+export abstract class StableSet<T> implements ReadonlySet<T> {\n+\tabstract has(value: T): boolean;\n+\tabstract values(): SetIterator<T>;\n+\t/** Only resident membership data; external storage is not charged as heap. */\n+\tabstract readonly retainedBytes: number;\n+\tget [Symbol.toStringTag](): string {\n+\t\treturn \"Set\";\n+\t}\n+\tget size(): number {\n+\t\tlet count = 0;\n+\t\tfor (const _ of this) count++;\n+\t\treturn count;\n+\t}\n+\tkeys(): SetIterator<T> {\n+\t\treturn this.values();\n+\t}\n+\t*entries(): SetIterator<[T, T]> {\n+\t\tfor (const value of this) yield [value, value];\n+\t}\n+\t[Symbol.iterator](): SetIterator<T> {\n+\t\treturn this.values();\n+\t}\n+\tforEach(callback: (value: T, key: T, set: ReadonlySet<T>) => void, thisArg?: unknown): void {\n+\t\tfor (const value of this) callback.call(thisArg, value, value, this);\n+\t}\n+}\n+\n+/** Both operands must be immutable for the lifetime of this union. */\n+export class StableUnionSet<T> extends StableSet<T> {\n+\treadonly #left: StableSet<T>;\n+\treadonly #right: StableSet<T>;\n+\tconstructor(left: StableSet<T>, right: StableSet<T>) {\n+\t\tsuper();\n+\t\tthis.#left = left;\n+\t\tthis.#right = right;\n+\t}\n+\tget retainedBytes(): number {\n+\t\treturn 32 + this.#left.retainedBytes + this.#right.retainedBytes;\n+\t}\n+\tget left(): StableSet<T> {\n+\t\treturn this.#left;\n+\t}\n+\tget right(): StableSet<T> {\n+\t\treturn this.#right;\n+\t}\n+\thas(value: T): boolean {\n+\t\treturn this.#left.has(value) || this.#right.has(value);\n+\t}\n+\t*values(): SetIterator<T> {\n+\t\tyield* this.#left;\n+\t\tfor (const value of this.#right) if (!this.#left.has(value)) yield value;\n+\t}\n+}\n+\n+/** Immutable indexed subtraction retains neither operand's enumerated values. */\n+export class StableDifferenceSet<T> extends StableSet<T> {\n+\treadonly left: StableSet<T>;\n+\treadonly right: StableSet<T>;\n+\tconstructor(left: StableSet<T>, right: StableSet<T>) {\n+\t\tsuper();\n+\t\tthis.left = left;\n+\t\tthis.right = right;\n+\t}\n+\tget retainedBytes(): number {\n+\t\treturn 32 + this.left.retainedBytes + this.right.retainedBytes;\n+\t}\n+\thas(value: T): boolean {\n+\t\treturn this.left.has(value) && !this.right.has(value);\n+\t}\n+\t*values(): SetIterator<T> {\n+\t\tfor (const value of this.left) if (!this.right.has(value)) yield value;\n+\t}\n+}\n+\n+/** Preserve indexed history; only the caller's operation-sized overlay is copied. */\n+export function unionOverlay<T>(base: ReadonlySet<T>, overlay: Iterable<T>): ReadonlySet<T> {\n+\treturn base instanceof StableSet\n+\t\t? new StableUnionSet(base, new StableOverlaySet(overlay))\n+\t\t: new Set([...base, ...overlay]);\n+}\n+\n+/** Both indexed operands must be immutable for the lifetime of the result. */\n+export function differenceSet<T>(left: ReadonlySet<T>, right: ReadonlySet<T>): ReadonlySet<T> {\n+\treturn left instanceof StableSet && right instanceof StableSet\n+\t\t? new StableDifferenceSet(left, right)\n+\t\t: new Set([...left].filter((value) => !right.has(value)));\n+}\n+\n+/** An immutable snapshot for the operation's small overlay, not its history. */\n+export class StableOverlaySet<T> extends StableSet<T> {\n+\treadonly #values: Set<T>;\n+\tconstructor(values: Iterable<T>) {\n+\t\tsuper();\n+\t\tthis.#values = new Set(values);\n+\t}\n+\tget retainedBytes(): number {\n+\t\treturn 64 + this.#values.size * 32;\n+\t}\n+\thas(value: T): boolean {\n+\t\treturn this.#values.has(value);\n+\t}\n+\tvalues(): SetIterator<T> {\n+\t\treturn this.#values.values();\n+\t}\n+}\n+\n+const indexKey = (key: PropertyKey): key is string =>\n+\ttypeof key === \"string\" && /^(0|[1-9][0-9]*)$/.test(key) && Number.isSafeInteger(Number(key));\n+\n+/** Fixed-size numeric pages; callers retain no pages outside the bounded storage cache. */\n+export function storedNumbers(storage: GraphStateStorage, name: string) {\n+\tconst pageSize = 256;\n+\tconst meta = `${name}:meta`;\n+\tconst length = () => (storage.read(meta, \"length\") as number | undefined) ?? 0;\n+\t// Older experimental writer indexes must be rebuilt from their canonical log.\n+\t// Never interpret per-element rows as pages or silently lose existing history.\n+\tconst page = (index: number): number[] => {\n+\t\tif (storage.read(meta, \"format\") !== 2)\n+\t\t\tthrow new Error(`writer numeric index ${name} requires canonical-log adoption`);\n+\t\tconst values = storage.read(`${name}:pages`, String(Math.floor(index / pageSize))) as number[] | undefined;\n+\t\tif (!values) throw new Error(`missing writer numeric page in ${name}`);\n+\t\treturn values;\n+\t};\n+\treturn {\n+\t\tget length() {\n+\t\t\treturn length();\n+\t\t},\n+\t\tat(index: number): number {\n+\t\t\tif (!Number.isSafeInteger(index) || index < 0 || index >= length())\n+\t\t\t\tthrow new Error(`writer numeric index out of bounds in ${name}`);\n+\t\t\tconst value = page(index)[index % pageSize];\n+\t\t\tif (value === undefined) throw new Error(`incomplete writer numeric page in ${name}`);\n+\t\t\treturn value;\n+\t\t},\n+\t\tpush(value: number): void {\n+\t\t\tif (!Number.isSafeInteger(value)) throw new Error(\"writer numeric indexes require safe integers\");\n+\t\t\tconst index = length();\n+\t\t\tif (index > 0 && storage.read(meta, \"format\") !== 2)\n+\t\t\t\tthrow new Error(`writer numeric index ${name} requires canonical-log adoption`);\n+\t\t\tconst offset = index % pageSize;\n+\t\t\tconst values = offset === 0 ? [] : page(index);\n+\t\t\tif (values.length !== offset) throw new Error(`invalid writer numeric page length in ${name}`);\n+\t\t\tvalues.push(value);\n+\t\t\tstorage.write(`${name}:pages`, String(Math.floor(index / pageSize)), values);\n+\t\t\tif (index === 0) storage.write(meta, \"format\", 2);\n+\t\t\tstorage.write(meta, \"length\", index + 1);\n+\t\t},\n+\t\tset(index: number, value: number): void {\n+\t\t\tif (!Number.isSafeInteger(value)) throw new Error(\"writer numeric indexes require safe integers\");\n+\t\t\tif (!Number.isSafeInteger(index) || index < 0 || index >= length())\n+\t\t\t\tthrow new Error(`writer numeric index out of bounds in ${name}`);\n+\t\t\tconst values = page(index);\n+\t\t\tif (index % pageSize >= values.length) throw new Error(`incomplete writer numeric page in ${name}`);\n+\t\t\tvalues[index % pageSize] = value;\n+\t\t\tstorage.write(`${name}:pages`, String(Math.floor(index / pageSize)), values);\n+\t\t},\n+\t};\n+}\n+\n+/** Array-shaped access without retaining its historical values in memory. */\n+export function storedArray<T>(\n+\tstorage: GraphStateStorage,\n+\tname: string,\n+\tdecode?: (value: T) => T,\n+\tencode?: (value: T, key: string) => unknown,\n+): T[] {\n+\tconst length = () => (storage.read(`${name}:meta`, \"length\") as number | undefined) ?? 0;\n+\tconst read = (key: string) => {\n+\t\tconst value = storage.read(name, key) as T;\n+\t\treturn value === undefined || !decode ? value : decode(value);\n+\t};\n+\treturn new Proxy([] as T[], {\n+\t\tget(target, key, receiver) {\n+\t\t\tif (key === \"length\") return length();\n+\t\t\t// No length read first (abso Capacity): set writes the row and the length together and nothing shrinks, so no\n+\t\t\t// row lies past the length. Half of a cold layout's reads were this length.\n+\t\t\tif (indexKey(key)) return read(key);\n+\t\t\treturn Reflect.get(target, key, receiver);\n+\t\t},\n+\t\tset(_target, key, value) {\n+\t\t\tif (key === \"length\") {\n+\t\t\t\tif (value !== length()) throw new Error(\"stored graph arrays cannot be resized directly\");\n+\t\t\t\treturn true;\n+\t\t\t}\n+\t\t\tif (!indexKey(key)) throw new Error(\"invalid stored graph array property\");\n+\t\t\tconst index = Number(key);\n+\t\t\tconst size = length();\n+\t\t\tif (index > size) throw new Error(\"stored graph arrays cannot contain gaps\");\n+\t\t\tstorage.write(name, key, encode ? encode(value, key) : value);\n+\t\t\tif (index === size) storage.write(`${name}:meta`, \"length\", size + 1);\n+\t\t\treturn true;\n+\t\t},\n+\t\thas(target, key) {\n+\t\t\treturn indexKey(key) ? Number(key) < length() : Reflect.has(target, key);\n+\t\t},\n+\t\townKeys() {\n+\t\t\treturn [...Array.from({ length: length() }, (_, index) => String(index)), \"length\"];\n+\t\t},\n+\t\tgetOwnPropertyDescriptor(target, key) {\n+\t\t\tif (indexKey(key) && Number(key) < length())\n+\t\t\t\treturn { configurable: true, enumerable: true, writable: true, value: read(key) };\n+\t\t\treturn Reflect.getOwnPropertyDescriptor(target, key);\n+\t\t},\n+\t});\n+}\n+\n+export interface StateMap<K, V> {\n+\tkeys(): IterableIterator<K>;\n+\tget(key: K): V | undefined;\n+\tset(key: K, value: V): StateMap<K, V>;\n+\thas(key: K): boolean;\n+\tdelete(key: K): boolean;\n+\tvalues(): IterableIterator<V>;\n+}\n+\n+/** Append-only per-key lists, retaining at most one fixed-size page per iterator. */\n+export function storedLists<V>(\n+\tstorage: GraphStateStorage,\n+\tname: string,\n+\tlegacyKey = (key: string) => JSON.stringify([\"string\", key]),\n+) {\n+\tconst pageSize = 256;\n+\t// The previous experimental layout stored one whole historical list per key.\n+\tconst length = (key: string) => {\n+\t\tconst stored = storage.read(`${name}:lengths`, key) as number | undefined;\n+\t\tif (stored === undefined && storage.read(name, legacyKey(key)) !== undefined)\n+\t\t\tthrow new Error(`writer list index ${name} requires canonical-log adoption`);\n+\t\tconst count = stored ?? 0;\n+\t\tif (!Number.isSafeInteger(count) || count < 0) throw new Error(`invalid writer list count in ${name}`);\n+\t\treturn count;\n+\t};\n+\tconst pageKey = (key: string, page: number) => JSON.stringify([key, page]);\n+\tconst page = (key: string, index: number): V[] => {\n+\t\tconst values = storage.read(`${name}:pages`, pageKey(key, index)) as V[] | undefined;\n+\t\tif (!Array.isArray(values) || values.length < 1 || values.length > pageSize)\n+\t\t\tthrow new Error(`missing or invalid writer list page in ${name}`);\n+\t\treturn values;\n+\t};\n+\treturn {\n+\t\tlength,\n+\t\t*keys(): IterableIterator<string> {\n+\t\t\tfor (const entry of storage.entries(name)) {\n+\t\t\t\tvoid entry;\n+\t\t\t\tthrow new Error(`writer list index ${name} requires canonical-log adoption`);\n+\t\t\t}\n+\t\t\tfor (const [key] of storage.entries(`${name}:lengths`)) yield key;\n+\t\t},\n+\t\t/** Values [index * PAGE, (index + 1) * PAGE) of `key`'s list: one page, not the whole list (abso Capacity). */\n+\t\tpageAt(key: string, index: number): readonly V[] {\n+\t\t\tconst count = length(key);\n+\t\t\tconst values = page(key, index);\n+\t\t\tif (values.length !== Math.min(pageSize, count - index * pageSize))\n+\t\t\t\tthrow new Error(`incomplete writer list page in ${name}`);\n+\t\t\treturn values;\n+\t\t},\n+\t\t*values(key: string): IterableIterator<V> {\n+\t\t\tconst count = length(key);\n+\t\t\tfor (let start = 0; start < count; start += pageSize) {\n+\t\t\t\tconst values = page(key, start / pageSize);\n+\t\t\t\tif (values.length !== Math.min(pageSize, count - start))\n+\t\t\t\t\tthrow new Error(`incomplete writer list page in ${name}`);\n+\t\t\t\tyield* values;\n+\t\t\t}\n+\t\t},\n+\t\tlast(key: string): V | undefined {\n+\t\t\tconst count = length(key);\n+\t\t\tif (count === 0) return undefined;\n+\t\t\tconst values = page(key, Math.floor((count - 1) / pageSize));\n+\t\t\tconst expected = ((count - 1) % pageSize) + 1;\n+\t\t\tif (values.length !== expected) throw new Error(`incomplete writer list page in ${name}`);\n+\t\t\treturn values[expected - 1];\n+\t\t},\n+\t\tappend(key: string, value: V): void {\n+\t\t\tconst count = length(key);\n+\t\t\tconst offset = count % pageSize;\n+\t\t\tconst index = Math.floor(count / pageSize);\n+\t\t\tconst values = offset === 0 ? [] : page(key, index);\n+\t\t\tif (values.length !== offset) throw new Error(`invalid writer list length in ${name}`);\n+\t\t\tvalues.push(value);\n+\t\t\tstorage.write(`${name}:pages`, pageKey(key, index), values);\n+\t\t\tstorage.write(`${name}:lengths`, key, count + 1);\n+\t\t},\n+\t\t/** Append several values, writing each page they touch once. */\n+\t\tappendAll(key: string, more: readonly V[]): void {\n+\t\t\tif (more.length === 0) return;\n+\t\t\tconst count = length(key);\n+\t\t\tlet index = Math.floor(count / pageSize);\n+\t\t\tlet values = count % pageSize === 0 ? [] : page(key, index);\n+\t\t\tif (values.length !== count % pageSize) throw new Error(`invalid writer list length in ${name}`);\n+\t\t\tfor (const value of more) {\n+\t\t\t\tif (values.length === pageSize) {\n+\t\t\t\t\tstorage.write(`${name}:pages`, pageKey(key, index++), values);\n+\t\t\t\t\tvalues = [];\n+\t\t\t\t}\n+\t\t\t\tvalues.push(value);\n+\t\t\t}\n+\t\t\tstorage.write(`${name}:pages`, pageKey(key, index), values);\n+\t\t\tstorage.write(`${name}:lengths`, key, count + more.length);\n+\t\t},\n+\t};\n+}\n+\n+/** Keys are tagged so numeric graph codes cannot collide with string keys. */\n+export function storedMap<K extends string | number, V>(storage: GraphStateStorage, name: string): StateMap<K, V> {\n+\tconst keyOf = (key: K) => JSON.stringify([typeof key, key]);\n+\tconst map: StateMap<K, V> = {\n+\t\t*keys() {\n+\t\t\tfor (const [key] of storage.entries(name)) yield (JSON.parse(key) as [string, K])[1];\n+\t\t},\n+\t\tget: (key) => storage.read(name, keyOf(key)) as V | undefined,\n+\t\thas: (key) => storage.read(name, keyOf(key)) !== undefined,\n+\t\tset(key, value) {\n+\t\t\tstorage.write(name, keyOf(key), value);\n+\t\t\treturn map;\n+\t\t},\n+\t\tdelete(key) {\n+\t\t\tconst existed = map.has(key);\n+\t\t\tstorage.remove(name, keyOf(key));\n+\t\t\treturn existed;\n+\t\t},\n+\t\t*values() {\n+\t\t\tfor (const [, value] of storage.entries(name)) yield value as V;\n+\t\t},\n+\t};\n+\treturn map;\n+}\n+\n+/**\n+ * A Map-compatible persistent index. Iteration follows insertion order and\n+ * decodes one row at a time. Returned objects are copies, so mutations need\n+ * an explicit set. Hosts wrap a logical multi-index mutation in transaction.\n+ */\n+export class StoredMap<K extends string | number, V> extends Map<K, V> {\n+\treadonly #storage: GraphStateStorage;\n+\treadonly #name: string;\n+\treadonly #encode: (value: V) => unknown;\n+\treadonly #decode: (value: unknown) => V;\n+\tconstructor(\n+\t\tstorage: GraphStateStorage,\n+\t\tname: string,\n+\t\tcodec?: { encode(value: V): unknown; decode(value: unknown): V },\n+\t) {\n+\t\tsuper();\n+\t\tthis.#storage = storage;\n+\t\tthis.#name = name;\n+\t\tthis.#encode = codec?.encode ?? ((value) => value);\n+\t\tthis.#decode = codec?.decode ?? ((value) => value as V);\n+\t}\n+\t#key(key: K): string {\n+\t\treturn JSON.stringify([typeof key, key]);\n+\t}\n+\t#row(key: K): { slot: number; value: unknown } | undefined {\n+\t\treturn this.#storage.read(this.#name, this.#key(key)) as { slot: number; value: unknown } | undefined;\n+\t}\n+\toverride get size(): number {\n+\t\treturn (this.#storage.read(`${this.#name}:meta`, \"size\") as number | undefined) ?? 0;\n+\t}\n+\toverride has(key: K): boolean {\n+\t\treturn this.#row(key) !== undefined;\n+\t}\n+\toverride get(key: K): V | undefined {\n+\t\tconst row = this.#row(key);\n+\t\treturn row === undefined ? undefined : this.#decode(row.value);\n+\t}\n+\toverride set(key: K, value: V): this {\n+\t\tconst row = this.#row(key);\n+\t\tlet slot = row?.slot;\n+\t\tif (slot === undefined) {\n+\t\t\tconst keys = storedArray<K>(this.#storage, `${this.#name}:order`);\n+\t\t\tslot = keys.length;\n+\t\t\tkeys.push(key);\n+\t\t\tthis.#storage.write(`${this.#name}:meta`, \"size\", this.size + 1);\n+\t\t}\n+\t\tthis.#storage.write(this.#name, this.#key(key), { slot, value: this.#encode(value) });\n+\t\treturn this;\n+\t}\n+\toverride delete(key: K): boolean {\n+\t\tif (!this.has(key)) return false;\n+\t\tthis.#storage.remove(this.#name, this.#key(key));\n+\t\tthis.#storage.write(`${this.#name}:meta`, \"size\", this.size - 1);\n+\t\treturn true;\n+\t}\n+\toverride clear(): void {\n+\t\tfor (const key of this.keys()) this.delete(key);\n+\t}\n+\toverride *entries(): MapIterator<[K, V]> {\n+\t\tconst keys = storedArray<K>(this.#storage, `${this.#name}:order`);\n+\t\tfor (let slot = 0; slot < keys.length; slot++) {\n+\t\t\tconst key = keys[slot]!;\n+\t\t\tconst row = this.#row(key);\n+\t\t\tif (row?.slot === slot) yield [key, this.#decode(row.value)];\n+\t\t}\n+\t}\n+\toverride *keys(): MapIterator<K> {\n+\t\tconst keys = storedArray<K>(this.#storage, `${this.#name}:order`);\n+\t\tfor (let slot = 0; slot < keys.length; slot++) {\n+\t\t\tconst key = keys[slot]!;\n+\t\t\tif (this.#row(key)?.slot === slot) yield key;\n+\t\t}\n+\t}\n+\toverride *values(): MapIterator<V> {\n+\t\tfor (const [, value] of this.entries()) yield value;\n+\t}\n+\toverride [Symbol.iterator](): MapIterator<[K, V]> {\n+\t\treturn this.entries();\n+\t}\n+\toverride forEach(callback: (value: V, key: K, map: Map<K, V>) => void, thisArg?: unknown): void {\n+\t\tfor (const [key, value] of this.entries()) callback.call(thisArg, value, key, this);\n+\t}\n+}\n+\n+/** Persistent membership with streaming iteration and no in-memory key cache. */\n+export class StoredSet<K extends string | number> extends Set<K> {\n+\treadonly #map: StoredMap<K, true>;\n+\tconstructor(storage: GraphStateStorage, name: string) {\n+\t\tsuper();\n+\t\tthis.#map = new StoredMap(storage, name);\n+\t}\n+\toverride get size(): number {\n+\t\treturn this.#map.size;\n+\t}\n+\toverride has(key: K): boolean {\n+\t\treturn this.#map.has(key);\n+\t}\n+\toverride add(key: K): this {\n+\t\tthis.#map.set(key, true);\n+\t\treturn this;\n+\t}\n+\toverride delete(key: K): boolean {\n+\t\treturn this.#map.delete(key);\n+\t}\n+\toverride clear(): void {\n+\t\tthis.#map.clear();\n+\t}\n+\toverride *values(): SetIterator<K> {\n+\t\tyield* this.#map.keys();\n+\t}\n+\toverride keys(): SetIterator<K> {\n+\t\treturn this.values();\n+\t}\n+\toverride *entries(): SetIterator<[K, K]> {\n+\t\tfor (const key of this.values()) yield [key, key];\n+\t}\n+\toverride [Symbol.iterator](): SetIterator<K> {\n+\t\treturn this.values();\n+\t}\n+\toverride forEach(callback: (value: K, key: K, set: Set<K>) => void, thisArg?: unknown): void {\n+\t\tfor (const key of this.values()) callback.call(thisArg, key, key, this);\n+\t}\n+}\n+\n+/** Read-only array access to individually stored values, without copying the list. */\n+/** How many values an atom's long list keeps to a row (readonlyPagedArray). */\n+export const LIST_PAGE = 256;\n+\n+/** Write a list as readonlyPagedArray reads it: its values LIST_PAGE to a row, and its length. */\n+export function writePagedArray(storage: GraphStateStorage, name: string, values: readonly unknown[]): void {\n+\tfor (let start = 0; start < values.length; start += LIST_PAGE)\n+\t\tstorage.write(`${name}:pages`, String(start / LIST_PAGE), values.slice(start, start + LIST_PAGE));\n+\tstorage.write(`${name}:meta`, \"length\", values.length);\n+}\n+\n+/**\n+ * A stored list read a page of LIST_PAGE values at a time (abso Capacity): an atom's long lists, which\n+ * readonlyStoredArray reads a row per value. Collisions read every key a draft's atoms write; a draft deleting a big\n+ * file has thousands, and that was a row each.\n+ */\n+export function readonlyPagedArray<T>(storage: GraphStateStorage, name: string): readonly T[] {\n+\tconst length = () => {\n+\t\tconst count = storage.read(`${name}:meta`, \"length\");\n+\t\tif (!Number.isSafeInteger(count) || (count as number) < 0) throw Error(\"invalid stored list length\");\n+\t\treturn count as number;\n+\t};\n+\tlength();\n+\tlet held = -1;\n+\tlet page: readonly unknown[] = [];\n+\tconst at = (index: number): T => {\n+\t\tconst p = Math.floor(index / LIST_PAGE);\n+\t\tif (p !== held) {\n+\t\t\tconst raw = storage.read(`${name}:pages`, String(p));\n+\t\t\tif (!Array.isArray(raw)) throw Error(\"missing stored list page\");\n+\t\t\tpage = raw;\n+\t\t\theld = p;\n+\t\t}\n+\t\tconst value = page[index % LIST_PAGE];\n+\t\tif (value === undefined) throw Error(\"missing stored list element\");\n+\t\treturn (value && typeof value === \"object\" ? Object.freeze(value) : value) as T;\n+\t};\n+\tfunction* inOrder(): IterableIterator<T> {\n+\t\tconst count = length();\n+\t\tfor (let index = 0; index < count; index++) yield at(index);\n+\t}\n+\treturn new Proxy([] as T[], {\n+\t\tget(target, key, receiver) {\n+\t\t\tif (key === \"length\") return length();\n+\t\t\tif (key === Symbol.iterator || key === \"values\") return inOrder;\n+\t\t\tif (indexKey(key)) return Number(key) >= length() ? undefined : at(Number(key));\n+\t\t\treturn Reflect.get(target, key, receiver);\n+\t\t},\n+\t\thas(target, key) {\n+\t\t\treturn indexKey(key) ? Number(key) < length() : Reflect.has(target, key);\n+\t\t},\n+\t\townKeys() {\n+\t\t\treturn [...Array.from({ length: length() }, (_, index) => String(index)), \"length\"];\n+\t\t},\n+\t\tgetOwnPropertyDescriptor(target, key) {\n+\t\t\tif (indexKey(key) && Number(key) < length())\n+\t\t\t\treturn { configurable: true, enumerable: true, writable: false, value: at(Number(key)) };\n+\t\t\treturn Reflect.getOwnPropertyDescriptor(target, key);\n+\t\t},\n+\t\tset() {\n+\t\t\tthrow Error(\"stored lists are read-only\");\n+\t\t},\n+\t});\n+}\n+\n+export function readonlyStoredArray<T>(\n+\tstorage: GraphStateStorage,\n+\tname: string,\n+\tdecode?: (value: unknown, index: number) => T,\n+): readonly T[] {\n+\tconst length = () => {\n+\t\tconst count = storage.read(`${name}:meta`, \"length\");\n+\t\tif (!Number.isSafeInteger(count) || (count as number) < 0) throw Error(\"invalid stored list length\");\n+\t\treturn count as number;\n+\t};\n+\tlength();\n+\tconst at = (index: number): T => {\n+\t\tconst raw = storage.read(name, String(index));\n+\t\tconst value = raw === undefined ? undefined : decode ? decode(raw, index) : (raw as T);\n+\t\tif (value === undefined) throw Error(\"missing stored list element\");\n+\t\treturn value && typeof value === \"object\" ? (Object.freeze(value) as T) : value;\n+\t};\n+\t// In order, with the length read once (abso Capacity): the array iterator reads it again before every element, a\n+\t// second disk read per element of a list too long for the cache.\n+\tfunction* inOrder(): IterableIterator<T> {\n+\t\tconst count = length();\n+\t\tfor (let index = 0; index < count; index++) yield at(index);\n+\t}\n+\treturn new Proxy([] as T[], {\n+\t\tget(target, key, receiver) {\n+\t\t\tif (key === \"length\") return length();\n+\t\t\tif (key === Symbol.iterator || key === \"values\") return inOrder;\n+\t\t\tif (indexKey(key)) return Number(key) >= length() ? undefined : at(Number(key));\n+\t\t\treturn Reflect.get(target, key, receiver);\n+\t\t},\n+\t\thas(target, key) {\n+\t\t\treturn indexKey(key) ? Number(key) < length() : Reflect.has(target, key);\n+\t\t},\n+\t\townKeys() {\n+\t\t\treturn [...Array.from({ length: length() }, (_, index) => String(index)), \"length\"];\n+\t\t},\n+\t\tgetOwnPropertyDescriptor(target, key) {\n+\t\t\tif (key === \"length\") return { ...Reflect.getOwnPropertyDescriptor(target, key)!, value: length() };\n+\t\t\tif (indexKey(key) && Number(key) < length()) {\n+\t\t\t\tconst raw = storage.read(name, key);\n+\t\t\t\tconst value = raw === undefined ? undefined : decode ? decode(raw, Number(key)) : (raw as T);\n+\t\t\t\tif (value === undefined) throw Error(\"missing stored list element\");\n+\t\t\t\treturn {\n+\t\t\t\t\tconfigurable: true,\n+\t\t\t\t\tenumerable: true,\n+\t\t\t\t\twritable: false,\n+\t\t\t\t\tvalue: value && typeof value === \"object\" ? Object.freeze(value) : value,\n+\t\t\t\t};\n+\t\t\t}\n+\t\t\treturn Reflect.getOwnPropertyDescriptor(target, key);\n+\t\t},\n+\t\tpreventExtensions() {\n+\t\t\tthrow Error(\"stored list is read-only\");\n+\t\t},\n+\t\tset() {\n+\t\t\tthrow Error(\"stored list is read-only\");\n+\t\t},\n+\t\tdeleteProperty() {\n+\t\t\tthrow Error(\"stored list is read-only\");\n+\t\t},\n+\t\tdefineProperty() {\n+\t\t\tthrow Error(\"stored list is read-only\");\n+\t\t},\n+\t});\n+}"}],"unmatched":[]}