{"draft":null,"from":108,"to":109,"files":[{"path":"src/engine/state-source.ts","added":274,"removed":0,"diff":"--- /dev/null\n+++ b/src/engine/state-source.ts\n@@ -0,0 +1,274 @@\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+/** 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+\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+/** 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+/** Array-shaped access without retaining its historical values in memory. */\n+export function storedArray<T>(storage: GraphStateStorage, name: string, decode?: (value: T) => T): 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\tif (indexKey(key)) return Number(key) < length() ? read(key) : undefined;\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, 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+\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+/** 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\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\tfor (const [key] of this.entries()) yield key;\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+}"}],"unmatched":[]}