{"version":109,"agent":"codex-capacity-chair","message":"Add opt-in persistent writer state, checked reopen and bounded adoption","time":1791825459416,"timeIso":"2026-10-12T17:17:39.416Z","changes":29,"change":1284,"files":["src/engine/graph.ts","src/engine/state-source.ts","src/engine/test/state-source.test.ts","src/engine/test/storage-helper.ts","src/engine/test/view.test.ts","src/engine/view.ts","worker/project/apply-entry.ts","worker/project/change-records.ts","worker/project/notes.ts","worker/project/project-types.ts","worker/project/project.ts","worker/project/spaces.ts","worker/project/test/project-writer-storage.test.ts","worker/project/test/stored-membership.test.ts","worker/project/test/writer-adoption.test.ts","worker/project/writer-agents.ts"],"draft":null,"diff":[{"path":"src/engine/graph.ts","added":113,"removed":32,"diff":"--- a/src/engine/graph.ts\n+++ b/src/engine/graph.ts\n@@ -15,6 +15,7 @@\n \tseqOf,\n \tstartNode,\n } from \"./keys.ts\";\n+import { type GraphStateStorage, type StateMap, storedArray, storedMap } from \"./state-source.ts\";\n import {\n \tATTR_NAMES,\n \ttype Atom,\n@@ -76,21 +77,25 @@\n  * are two (#46): most keys name one atom, and a list for each costs more than\n  * the value.\n  */\n-function pushOne<K, V>(map: Map<K, V | V[]>, key: K, value: V): void {\n+function pushOne<K, V>(map: StateMap<K, V | V[]>, key: K, value: V): void {\n \tconst had = map.get(key);\n \tif (had === undefined) map.set(key, value);\n-\telse if (Array.isArray(had)) had.push(value);\n-\telse map.set(key, [had, value]);\n+\telse if (Array.isArray(had)) {\n+\t\thad.push(value);\n+\t\tmap.set(key, had);\n+\t} else map.set(key, [had, value]);\n }\n \n function listOf<V>(had: V | V[] | undefined): readonly V[] {\n \treturn had === undefined ? EMPTY : Array.isArray(had) ? had : [had];\n }\n \n-function pushIndex<K, V>(map: Map<K, V[]>, key: K, value: V): void {\n+function pushIndex<K, V>(map: StateMap<K, V[]>, key: K, value: V): void {\n \tconst list = map.get(key);\n-\tif (list) list.push(value);\n-\telse map.set(key, [value]);\n+\tif (list) {\n+\t\tlist.push(value);\n+\t\tmap.set(key, list);\n+\t} else map.set(key, [value]);\n }\n \n const EMPTY: readonly never[] = Object.freeze([]);\n@@ -176,7 +181,14 @@\n }\n \n /** A growable array of 32-bit integers: a line's fields cost 4 bytes each, not an object and its strings (#46). */\n-class Ints {\n+interface NumberIndex {\n+\treadonly length: number;\n+\tpush(n: number): void;\n+\tat(i: number): number;\n+\tset(i: number, n: number): void;\n+}\n+\n+class Ints implements NumberIndex {\n \t#buf: Int32Array | Uint8Array;\n \t/** bytes: values 0-255 only, one byte each. */\n \tconstructor(bytes = false) {\n@@ -232,6 +244,7 @@\n }\n \n export class Graph {\n+\treadonly #storage?: GraphStateStorage;\n \t#atoms: Atom[] = [];\n \t#lamport: number[] = [];\n \t// Lines, packed (#46): line n is the k-th line atom seq wrote, n = #lineBase[seq] + k. Each holds its\n@@ -239,12 +252,14 @@\n \t// path's index for a file's start). Its text stays in the atom. Ids and LineInfo objects are made only\n \t// when asked for, so a line costs about 16 bytes here instead of a record, its id and its parent's id.\n \t#lineBase: number[] = [];\n-\t#lineAtom = new Ints();\n-\t#lineFile = new Ints();\n-\t#lineParent = new Ints();\n+\t#lineAtom: NumberIndex = new Ints();\n+\t#lineFile: NumberIndex = new Ints();\n+\t#lineParent: NumberIndex = new Ints();\n \t/** Lines' text, when the graph keeps it; without it, it comes from `texts` (#46, text on disk). */\n \t#lineText: string[] | undefined = [];\n-\t#lineTotal = 0;\n+\tget #lineTotal(): number {\n+\t\treturn this.#lineAtom.length;\n+\t}\n \t/** Where an atom's lines' text is when the graph doesn't keep it: each run's lines, by the atom's seq. */\n \t#texts: ((seq: number) => readonly (readonly string[])[]) | undefined;\n \t/** Recently read atoms' text, flattened, most recent last, up to TEXT_CACHE characters. */\n@@ -257,13 +272,69 @@\n \t * atom's text when a line of it is asked for, keeping the most recent.\n \t */\n \tconstructor(\n-\t\toptions: { texts?: (seq: number) => readonly (readonly string[])[]; lists?: (seq: number) => AtomLists } = {},\n+\t\toptions: {\n+\t\t\ttexts?: (seq: number) => readonly (readonly string[])[];\n+\t\t\tlists?: (seq: number) => AtomLists;\n+\t\t\tstorage?: GraphStateStorage;\n+\t\t} = {},\n \t) {\n \t\tif (options.texts) {\n \t\t\tthis.#texts = options.texts;\n \t\t\tthis.#lineText = undefined;\n \t\t}\n \t\tif (options.lists) this.#lists = options.lists;\n+\t\tthis.#storage = options.storage;\n+\t\tif (options.storage) {\n+\t\t\tconst storage = options.storage;\n+\t\t\tconst numbers = (name: string): NumberIndex => {\n+\t\t\t\tconst values = storedArray<number>(storage, name);\n+\t\t\t\treturn {\n+\t\t\t\t\tget length() {\n+\t\t\t\t\t\treturn values.length;\n+\t\t\t\t\t},\n+\t\t\t\t\tpush: (value) => {\n+\t\t\t\t\t\tvalues.push(value);\n+\t\t\t\t\t},\n+\t\t\t\t\tat: (index) => values[index]!,\n+\t\t\t\t\tset: (index, value) => {\n+\t\t\t\t\t\tvalues[index] = value;\n+\t\t\t\t\t},\n+\t\t\t\t};\n+\t\t\t};\n+\t\t\tthis.#atoms = storedArray<Atom>(storage, \"atoms\", (atom) =>\n+\t\t\t\tfreezeAtom(\n+\t\t\t\t\tatom,\n+\t\t\t\t\t(id) => id,\n+\t\t\t\t\t(author) => author,\n+\t\t\t\t),\n+\t\t\t);\n+\t\t\tthis.#lamport = storedArray(storage, \"lamport\");\n+\t\t\tthis.#lineBase = storedArray(storage, \"line-base\");\n+\t\t\tthis.#paths = storedArray(storage, \"paths\");\n+\t\t\tthis.#movers = storedArray(storage, \"movers\");\n+\t\t\tthis.#atomFiles = storedArray(storage, \"atom-files\");\n+\t\t\tthis.#atomDeletes = storedArray(storage, \"atom-deletes\");\n+\t\t\tthis.#lineAtom = numbers(\"line-atom\");\n+\t\t\tthis.#lineFile = numbers(\"line-file\");\n+\t\t\tthis.#lineParent = numbers(\"line-parent\");\n+\t\t\tthis.#deleter = numbers(\"deleter\");\n+\t\t\tthis.#replacing = numbers(\"replacing\");\n+\t\t\tthis.#lineText = storedArray(storage, \"line-text\");\n+\t\t\tthis.#pathIndex = storedMap(storage, \"path-index\");\n+\t\t\tthis.#moreDeleters = storedMap(storage, \"more-deleters\");\n+\t\t\tthis.#writers = storedMap(storage, \"writers\");\n+\t\t\tthis.#readers = storedMap(storage, \"readers\");\n+\t\t\tthis.#holders = storedMap(storage, \"holders\");\n+\t\t\tthis.#dependents = storedMap(storage, \"dependents\");\n+\t\t\tthis.#resolvers = storedMap(storage, \"resolvers\");\n+\t\t\tthis.#together = storedMap(storage, \"together\");\n+\t\t\tthis.#fileAtoms = storedMap(storage, \"file-atoms\");\n+\t\t\tthis.#runStarts = storedMap(storage, \"run-starts\");\n+\t\t\tthis.#relocations = storedMap(storage, \"relocations\");\n+\t\t\tthis.#relocatedTo = storedMap(storage, \"relocated-to\");\n+\t\t\tthis.#relocatedToCode = storedMap(storage, \"relocated-to-code\");\n+\t\t\tthis.#labels = storedMap(storage, \"labels\");\n+\t\t}\n \t}\n \n \t/** Where an atom's key and delete lists are when the graph doesn't keep them (#46): the stored atom. */\n@@ -352,30 +423,30 @@\n \t\treturn this.#textOf(seq)[n - this.#lineBase[seq]!]!;\n \t}\n \t#paths: string[] = [];\n-\t#pathIndex = new Map<string, number>();\n+\t#pathIndex: StateMap<string, number> = new Map();\n \t/** The first atom that deletes each line (its seq), or -1; a line deleted by more than one has the rest in #moreDeleters. */\n-\t#deleter = new Ints();\n-\t#moreDeleters = new Map<number, number[]>();\n-\t#writers = new Map<Key | number, AtomId | AtomId[]>();\n-\t#readers = new Map<Key | number, AtomId | AtomId[]>();\n-\t#holders = new Map<Key | number, AtomId | AtomId[]>();\n-\t#dependents = new Map<AtomId, AtomId | AtomId[]>();\n-\t#resolvers = new Map<AtomId, AtomId | AtomId[]>();\n-\t#together = new Map<AtomId, TogetherLink[]>();\n-\t#fileAtoms = new Map<string, AtomId[]>();\n+\t#deleter: NumberIndex = new Ints();\n+\t#moreDeleters: StateMap<number, number[]> = new Map();\n+\t#writers: StateMap<Key | number, AtomId | AtomId[]> = new Map();\n+\t#readers: StateMap<Key | number, AtomId | AtomId[]> = new Map();\n+\t#holders: StateMap<Key | number, AtomId | AtomId[]> = new Map();\n+\t#dependents: StateMap<AtomId, AtomId | AtomId[]> = new Map();\n+\t#resolvers: StateMap<AtomId, AtomId | AtomId[]> = new Map();\n+\t#together: StateMap<AtomId, TogetherLink[]> = new Map();\n+\t#fileAtoms: StateMap<string, AtomId[]> = new Map();\n \t/** First lines of runs (their n), by the node they were written after: a line's n, or -1 - a path's index. */\n-\t#runStarts = new Map<number, number | number[]>();\n+\t#runStarts: StateMap<number, number | number[]> = new Map();\n \t/** 1 for the first line of a run whose atom deleted the line it hangs off: the run replaces it. */\n-\t#replacing = new Ints(true);\n-\t#relocations = new Map<LineId, RelocationInfo[]>();\n-\t#relocatedTo = new Map<NodeId, RelocationInfo[]>();\n+\t#replacing: NumberIndex = new Ints(true);\n+\t#relocations: StateMap<LineId, RelocationInfo[]> = new Map();\n+\t#relocatedTo: StateMap<NodeId, RelocationInfo[]> = new Map();\n \t/** The same relocations by node code (a line's n, or -1 - a path's index), for views laid out by number. */\n-\t#relocatedToCode = new Map<number, RelocationInfo[]>();\n+\t#relocatedToCode: StateMap<number, RelocationInfo[]> = new Map();\n \t#movers: AtomId[] = [];\n \t#atomFiles: (readonly string[])[] = [];\n \t/** Each atom's deleted lines by n, packed (#46), or undefined when it deletes none. */\n-\t#atomDeletes: (Int32Array | undefined)[] = [];\n-\t#labels = new Map<string, Label>();\n+\t#atomDeletes: (readonly number[] | Int32Array | undefined)[] = [];\n+\t#labels: StateMap<string, Label> = new Map();\n \t/** Each author's name kept once (#46). */\n \t#authors = new Map<string, string>();\n \n@@ -776,6 +847,11 @@\n \t * The atom is frozen. Adding to the graph does not add it to any set.\n \t */\n \tadd(atom: Atom): void {\n+\t\tif (this.#storage) this.#storage.transaction(() => this.#add(atom));\n+\t\telse this.#add(atom);\n+\t}\n+\n+\t#add(atom: Atom): void {\n \t\tvalidateShape(atom);\n \t\tconst seq = this.#atoms.length;\n \t\tconst bad = (why: string): never => {\n@@ -850,6 +926,7 @@\n \t\t\tatom,\n \t\t\t(id) => this.#atoms[seqOf(id)]!.id,\n \t\t\t(author) => {\n+\t\t\t\tif (this.#storage) return author;\n \t\t\t\tlet a = this.#authors.get(author);\n \t\t\t\tif (a === undefined) this.#authors.set(author, (a = author));\n \t\t\t\treturn a;\n@@ -857,7 +934,7 @@\n \t\t\tthis.#texts ? this.#reader(seq) : undefined,\n \t\t\tthis.#lists ? this.#listReader(seq) : undefined,\n \t\t);\n-\t\tthis.#atoms.push(frozen);\n+\t\tthis.#atoms.push(this.#storage ? atom : frozen);\n \t\tlet lam = 0;\n \t\tfor (const d of deps) lam = Math.max(lam, this.lamport(d) + 1);\n \t\tthis.#lamport.push(lam);\n@@ -866,7 +943,7 @@\n \t\t// The atom as given: with lists kept elsewhere, the frozen one reads them back from the log.\n \t\tconst deletes = atom.deletes.length > 0 ? new Set(atom.deletes) : undefined;\n \t\tconst deletedN = atom.deletes.map((line) => this.#lineN(line));\n-\t\tthis.#atomDeletes.push(deletedN.length > 0 ? Int32Array.from(deletedN) : undefined);\n+\t\tthis.#atomDeletes.push(deletedN.length > 0 ? (this.#storage ? deletedN : Int32Array.from(deletedN)) : undefined);\n \t\tthis.#lineBase.push(this.#lineTotal);\n \t\tfor (const run of atom.inserts) {\n \t\t\tconst file = this.#pathOf(run.file);\n@@ -874,7 +951,7 @@\n \t\t\tconst first = this.#lineTotal;\n \t\t\tpushOne(this.#runStarts, parent, first);\n \t\t\tfor (let i = 0; i < run.lines.length; i++) {\n-\t\t\t\tconst n = this.#lineTotal++;\n+\t\t\t\tconst n = this.#lineTotal;\n \t\t\t\tthis.#lineAtom.push(seq);\n \t\t\t\tthis.#lineFile.push(file);\n \t\t\t\tthis.#lineParent.push(parent);\n@@ -974,6 +1051,10 @@\n \t * their base instead, so their contents don't change.\n \t */\n \tremoveLabel(name: string): boolean {\n+\t\treturn this.#storage ? this.#storage.transaction(() => this.#removeLabel(name)) : this.#removeLabel(name);\n+\t}\n+\n+\t#removeLabel(name: string): boolean {\n \t\tconst gone = this.#labels.get(name);\n \t\tif (!gone) return false;\n \t\tthis.#labels.delete(name);"},{"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+}"},{"path":"src/engine/test/state-source.test.ts","added":96,"removed":0,"diff":"--- /dev/null\n+++ b/src/engine/test/state-source.test.ts\n@@ -0,0 +1,96 @@\n+import assert from \"node:assert/strict\";\n+import { test } from \"node:test\";\n+import { checkDraft, Graph, View } from \"../index.ts\";\n+import { lines, Repo } from \"./helpers.ts\";\n+import { SqlState } from \"./storage-helper.ts\";\n+\n+test(\"stored graph reopens without replay and preserves moves, conflicts and new edits\", () => {\n+\tconst oracle = Repo.init({ \"a.txt\": lines(\"one\", \"two\", \"three\"), \"b.txt\": \"\" });\n+\toracle.edit({ edits: [{ file: \"a.txt\", old: \"two\", new: \"TWO\" }] });\n+\toracle.edit({ move: { file: \"a.txt\", start: 1, end: 2, to: \"b.txt\", at: 0 } });\n+\tconst storage = new SqlState();\n+\tconst original = new Graph({ storage });\n+\tfor (const atom of oracle.graph.atoms()) original.add(atom);\n+\toriginal.setLabel({ name: \"saved\", head: \"a2\", title: \"Saved\", message: \"\" });\n+\tconst reads = storage.reads;\n+\tconst reopened = new Graph({ storage });\n+\tassert.equal(storage.reads, reads, \"opening does not hydrate historical collections\");\n+\tassert.equal(storage.scans, 0);\n+\tassert.equal(reopened.size, oracle.graph.size);\n+\tassert.equal(reopened.lineCount, oracle.graph.lineCount);\n+\tassert.deepEqual([...reopened.movers()], [...oracle.graph.movers()]);\n+\tfor (const atom of oracle.graph.atoms()) {\n+\t\tassert.deepEqual(reopened.filesOf(atom.id), oracle.graph.filesOf(atom.id));\n+\t\tfor (const move of atom.moves ?? []) {\n+\t\t\tassert.deepEqual(reopened.relocationsOf(move.line), oracle.graph.relocationsOf(move.line));\n+\t\t\tassert.deepEqual(reopened.relocatedTo(move.parent), oracle.graph.relocatedTo(move.parent));\n+\t\t\tassert.equal(reopened.codeOf(move.parent), oracle.graph.codeOf(move.parent));\n+\t\t}\n+\t}\n+\tassert.deepEqual(new View(reopened, oracle.shared).files(), oracle.files());\n+\tassert.equal(reopened.label(\"saved\")?.head, \"a2\");\n+\tconst draft = oracle.draft({ edits: [{ file: \"a.txt\", old: \"one\", new: \"ONE\" }] });\n+\tassert.deepEqual(checkDraft(reopened, oracle.shared, draft), oracle.check(draft));\n+\toracle.graph.add(draft);\n+\treopened.add(draft);\n+\toracle.shared.add(draft.id);\n+\tassert.deepEqual(new View(new Graph({ storage }), oracle.shared).files(), oracle.files());\n+\tfor (let n = 0; n < oracle.graph.lineCount; n++) {\n+\t\tconst id = oracle.graph.lineIdOf(n);\n+\t\tassert.deepEqual(reopened.line(id), oracle.graph.line(id));\n+\t\tassert.deepEqual(reopened.deletersOf(id), oracle.graph.deletersOf(id));\n+\t}\n+\tassert.ok(Object.isFrozen(reopened.atom(\"a0\")));\n+\tstorage.db.close();\n+});\n+\n+test(\"stored indexes retain multiple claimants and preserve a real divergent conflict\", () => {\n+\tconst oracle = Repo.init({ \"a.txt\": lines(\"one\", \"two\", \"three\") });\n+\toracle.edit({ edits: [{ file: \"a.txt\", old: \"one\", new: \"ONE\" }], author: \"left\" });\n+\tconst right = oracle.draft({ edits: [{ file: \"a.txt\", old: \"one\", new: \"uno\" }], author: \"right\" }, [\"a0\"]);\n+\tconst storage = new SqlState();\n+\tconst graph = new Graph({ storage });\n+\tfor (const atom of oracle.graph.atoms()) graph.add(atom);\n+\tassert.equal(oracle.check(right).conflicts.length, 1);\n+\tassert.deepEqual(checkDraft(new Graph({ storage }), oracle.shared, right), oracle.check(right));\n+\tgraph.add(right);\n+\toracle.graph.add(right);\n+\tassert.deepEqual(new Graph({ storage }).writersOf(\"L:a0.0\"), oracle.graph.writersOf(\"L:a0.0\"));\n+\tassert.deepEqual(new Graph({ storage }).deletedLines(right.id), oracle.graph.deletedLines(right.id));\n+\tstorage.db.close();\n+});\n+\n+test(\"failed stored append rolls back all graph indexes and can be retried\", () => {\n+\tconst oracle = Repo.init({ \"a.txt\": lines(\"one\", \"two\") });\n+\tconst storage = new SqlState();\n+\tconst graph = new Graph({ storage });\n+\tgraph.add(oracle.graph.atom(\"a0\"));\n+\tconst before = JSON.stringify(graph.toJSON());\n+\tconst draft = oracle.draft({ edits: [{ file: \"a.txt\", old: \"one\", new: \"ONE\" }] });\n+\tstorage.failWrite = storage.writes + 10;\n+\tassert.throws(() => graph.add(draft), /injected storage failure/);\n+\tassert.equal(JSON.stringify(graph.toJSON()), before);\n+\tassert.equal(JSON.stringify(new Graph({ storage }).toJSON()), before);\n+\tstorage.failWrite = Infinity;\n+\tgraph.add(draft);\n+\tassert.equal(new Graph({ storage }).size, 2);\n+\tstorage.db.close();\n+});\n+\n+test(\"removing a stored label rolls back dependent rewrites on failure\", () => {\n+\tconst oracle = Repo.init({ \"a.txt\": lines(\"one\") });\n+\tconst storage = new SqlState();\n+\tconst graph = new Graph({ storage });\n+\tgraph.add(oracle.graph.atom(\"a0\"));\n+\tgraph.setLabel({ name: \"base\", head: \"a0\", title: \"Base\", message: \"\" });\n+\tgraph.setLabel({ name: \"child\", head: \"a0\", base: \"base\", title: \"Child\", message: \"\" });\n+\tconst before = graph.labels();\n+\tstorage.failWrite = storage.writes + 1;\n+\tassert.throws(() => graph.removeLabel(\"base\"), /injected storage failure/);\n+\tassert.deepEqual(new Graph({ storage }).labels(), before);\n+\tstorage.failWrite = Infinity;\n+\tassert.equal(graph.removeLabel(\"base\"), true);\n+\tassert.equal(new Graph({ storage }).label(\"base\"), undefined);\n+\tassert.equal(new Graph({ storage }).label(\"child\")?.base, \"a0\");\n+\tstorage.db.close();\n+});"},{"path":"src/engine/test/storage-helper.ts","added":43,"removed":0,"diff":"--- /dev/null\n+++ b/src/engine/test/storage-helper.ts\n@@ -0,0 +1,43 @@\n+import { DatabaseSync } from \"node:sqlite\";\n+import type { GraphStateStorage } from \"../state-source.ts\";\n+\n+export class SqlState implements GraphStateStorage {\n+\treadonly db = new DatabaseSync(\":memory:\");\n+\treads = 0;\n+\twrites = 0;\n+\tscans = 0;\n+\tfailWrite = Infinity;\n+\tconstructor() {\n+\t\tthis.db.exec(\"CREATE TABLE state (collection TEXT, key TEXT, value TEXT, PRIMARY KEY(collection,key))\");\n+\t}\n+\tread(collection: string, key: string): unknown {\n+\t\tthis.reads++;\n+\t\tconst row = this.db.prepare(\"SELECT value FROM state WHERE collection = ? AND key = ?\").get(collection, key);\n+\t\treturn row ? JSON.parse(row.value as string).value : undefined;\n+\t}\n+\twrite(collection: string, key: string, value: unknown): void {\n+\t\tif (++this.writes === this.failWrite) throw new Error(\"injected storage failure\");\n+\t\tthis.db.prepare(\"INSERT OR REPLACE INTO state VALUES (?, ?, ?)\").run(collection, key, JSON.stringify({ value }));\n+\t}\n+\tremove(collection: string, key: string): void {\n+\t\tthis.db.prepare(\"DELETE FROM state WHERE collection = ? AND key = ?\").run(collection, key);\n+\t}\n+\t*entries(collection: string): Iterable<readonly [string, unknown]> {\n+\t\tthis.scans++;\n+\t\tfor (const row of this.db\n+\t\t\t.prepare(\"SELECT key, value FROM state WHERE collection = ? ORDER BY key\")\n+\t\t\t.iterate(collection))\n+\t\t\tyield [row.key as string, JSON.parse(row.value as string).value];\n+\t}\n+\ttransaction<T>(body: () => T): T {\n+\t\tthis.db.exec(\"SAVEPOINT graph_change\");\n+\t\ttry {\n+\t\t\tconst value = body();\n+\t\t\tthis.db.exec(\"RELEASE graph_change\");\n+\t\t\treturn value;\n+\t\t} catch (error) {\n+\t\t\tthis.db.exec(\"ROLLBACK TO graph_change; RELEASE graph_change\");\n+\t\t\tthrow error;\n+\t\t}\n+\t}\n+}"},{"path":"src/engine/test/view.test.ts","added":29,"removed":0,"diff":"--- a/src/engine/test/view.test.ts\n+++ b/src/engine/test/view.test.ts\n@@ -3,9 +3,38 @@\n import assert from \"node:assert/strict\";\n import { describe, it } from \"node:test\";\n import { buildBase, conflicts, Graph, project, View } from \"../index.ts\";\n+import { StableOverlaySet, StableSet } from \"../state-source.ts\";\n+import type { AtomId } from \"../types.ts\";\n import { lines, Repo } from \"./helpers.ts\";\n \n describe(\"View\", () => {\n+\tit(\"immutable indexed membership avoids a history-sized bitmap and remains a snapshot\", () => {\n+\t\tclass RangeMembership extends StableSet<AtomId> {\n+\t\t\treadonly retainedBytes = 64;\n+\t\t\treadonly count: number;\n+\t\t\tconstructor(count: number) {\n+\t\t\t\tsuper();\n+\t\t\t\tthis.count = count;\n+\t\t\t}\n+\t\t\thas(id: AtomId): boolean {\n+\t\t\t\treturn /^a[0-9]+$/.test(id) && Number(id.slice(1)) < this.count;\n+\t\t\t}\n+\t\t\t*values(): SetIterator<AtomId> {\n+\t\t\t\tfor (let i = 0; i < this.count; i++) yield `a${i}`;\n+\t\t\t}\n+\t\t}\n+\t\tconst repo = Repo.init({ \"a.txt\": \"0\\n\" });\n+\t\tfor (let i = 1; i <= 40; i++) repo.edit({ edits: [{ file: \"a.txt\", old: `${i - 1}\\n`, new: `${i}\\n` }] });\n+\t\tconst first = new View(repo.graph, new RangeMembership(repo.graph.size));\n+\t\tconst weight = first.weight();\n+\t\tfor (let i = 41; i <= 80; i++) repo.edit({ edits: [{ file: \"a.txt\", old: `${i - 1}\\n`, new: `${i}\\n` }] });\n+\t\tconst second = new View(repo.graph, new RangeMembership(repo.graph.size));\n+\t\tassert.equal(second.weight(), weight, \"membership resident size does not increase with historical atom count\");\n+\t\tassert.equal(first.text(\"a.txt\"), \"40\\n\");\n+\t\tassert.equal(second.text(\"a.txt\"), \"80\\n\");\n+\t\tassert.equal(first.set.has(\"a80\"), false);\n+\t\tassert.throws(() => new View(repo.graph, new StableOverlaySet<AtomId>([\"a1\"])), /not closed/);\n+\t});\n \tit(\"keeps deleted lines as tombstones in the full sequence\", () => {\n \t\tconst repo = Repo.init({ \"f.txt\": lines(\"one\", \"two\", \"three\") });\n \t\tconst del = repo.edit({ edits: [{ file: \"f.txt\", old: \"two\\n\", new: \"\" }] });"},{"path":"src/engine/view.ts","added":37,"removed":8,"diff":"--- a/src/engine/view.ts\n+++ b/src/engine/view.ts\n@@ -11,6 +11,7 @@\n \n import type { Graph, RelocationInfo } from \"./graph.ts\";\n import { isStartNode } from \"./keys.ts\";\n+import { StableSet } from \"./state-source.ts\";\n import { joinLines } from \"./text.ts\";\n import { type AtomId, type AtomSet, EngineError, type LineId, type NodeId } from \"./types.ts\";\n \n@@ -90,7 +91,8 @@\n export class View {\n \treadonly graph: Graph;\n \t/** The set, made from #in the first time it's asked for: a view keeps a byte per atom, not a copy of the set (#46). */\n-\t#set: Set<AtomId> | undefined;\n+\t#set: AtomSet | undefined;\n+\treadonly #stable: StableSet<AtomId> | undefined;\n \t#files = new Map<string, FileState>();\n \t/** Every file the set wrote in, sorted; worked out the first time it's asked for. */\n \t#knownList: string[] | undefined;\n@@ -109,14 +111,34 @@\n \t#textCache: { path: string; text: string } | undefined;\n \n \tconstructor(graph: Graph, set: Iterable<AtomId>) {\n+\t\tthis.graph = graph;\n+\t\tif (set instanceof StableSet) {\n+\t\t\tthis.#stable = set;\n+\t\t\tthis.#set = set;\n+\t\t\tthis.#in = new Uint8Array(0);\n+\t\t\tfor (const id of set) {\n+\t\t\t\tconst atom = graph.atom(id);\n+\t\t\t\tfor (const dependency of atom.deps) {\n+\t\t\t\t\tgraph.atom(dependency);\n+\t\t\t\t\tif (!set.has(dependency))\n+\t\t\t\t\t\tthrow new EngineError(\"not-closed\", `set is not closed: ${id} depends on ${dependency}`);\n+\t\t\t\t}\n+\t\t\t}\n+\t\t\tthis.#movers = graph.movers().filter((id) => set.has(id));\n+\t\t\tthis.#relocs = this.#movers.length === 0 ? new Map() : undefined;\n+\t\t\tthis.#relocsN = this.#movers.length === 0 ? new Map() : undefined;\n+\t\t\treturn;\n+\t\t}\n \t\tconst inSet = new Uint8Array(graph.size);\n-\t\tconst atoms: { readonly id: AtomId; readonly deps: readonly AtomId[] }[] = [];\n \t\tfor (const id of set) {\n \t\t\tconst atom = graph.atom(id);\n \t\t\tinSet[atom.seq] = 1;\n-\t\t\tatoms.push(atom);\n \t\t}\n-\t\tfor (const atom of atoms) {\n+\t\t// Validate one atom at a time. Keeping all decoded atoms here defeats\n+\t\t// storage-backed Graph reads even though the view only needs membership.\n+\t\tfor (let seq = 0; seq < inSet.length; seq++) {\n+\t\t\tif (inSet[seq] !== 1) continue;\n+\t\t\tconst atom = graph.atom(graph.idOfSeq(seq));\n \t\t\tfor (const d of atom.deps) {\n \t\t\t\tif (inSet[graph.atom(d).seq] !== 1)\n \t\t\t\t\tthrow new EngineError(\"not-closed\", `set is not closed: ${atom.id} depends on ${d}`);\n@@ -141,6 +163,7 @@\n \n \t/** Whether the atom with this seq is in the set. */\n \t#has(seq: number): boolean {\n+\t\tif (this.#stable) return this.#stable.has(this.graph.idOfSeq(seq));\n \t\treturn seq < this.#in.length && this.#in[seq] === 1;\n \t}\n \n@@ -272,7 +295,8 @@\n \t\tif (relocs) {\n \t\t\tfor (const r of graph.relocatedToCode(code)) {\n \t\t\t\tconst n = graph.lineN(r.line);\n-\t\t\t\tif (relocs.get(n)?.r !== r) continue;\n+\t\t\t\tconst selected = relocs.get(n)?.r;\n+\t\t\t\tif (!selected || selected.atom !== r.atom || selected.k !== r.k) continue;\n \t\t\t\tconst seq = graph.atom(r.atom).seq;\n \t\t\t\tout.push({ n, replaces: 0, lamport: graph.lamportOfSeq(seq), seq, k: r.k });\n \t\t\t}\n@@ -336,8 +360,12 @@\n \tget #known(): string[] {\n \t\tif (!this.#knownList) {\n \t\t\tconst known = new Set<string>();\n-\t\t\tfor (let seq = 0; seq < this.#in.length; seq++)\n-\t\t\t\tif (this.#in[seq] === 1) for (const file of this.graph.filesOf(this.graph.idOfSeq(seq))) known.add(file);\n+\t\t\tif (this.#stable) {\n+\t\t\t\tfor (const id of this.#stable) for (const file of this.graph.filesOf(id)) known.add(file);\n+\t\t\t} else {\n+\t\t\t\tfor (let seq = 0; seq < this.#in.length; seq++)\n+\t\t\t\t\tif (this.#in[seq] === 1) for (const file of this.graph.filesOf(this.graph.idOfSeq(seq))) known.add(file);\n+\t\t\t}\n \t\t\tthis.#knownList = [...known].sort();\n \t\t}\n \t\treturn this.#knownList;\n@@ -470,7 +498,8 @@\n \t\tn += ARRAY_HEADER_BYTES + REFERENCE_BYTES * this.#movers.length;\n \t\tn += MAP_HEADER_BYTES; // #files exists from construction.\n \t\tn += MAP_HEADER_BYTES; // #fileOf exists from construction.\n-\t\tif (this.#set) n += OBJECT_BYTES + SET_ENTRY_BYTES * this.#set.size;\n+\t\tif (this.#stable) n += this.#stable.retainedBytes;\n+\t\telse if (this.#set) n += OBJECT_BYTES + SET_ENTRY_BYTES * this.#set.size;\n \t\tif (this.#knownList) n += ARRAY_HEADER_BYTES + REFERENCE_BYTES * this.#knownList.length;\n \t\tif (this.#relocs) n += MAP_HEADER_BYTES + MAP_ENTRY_BYTES * this.#relocs.size;\n \t\tif (this.#relocsN) n += MAP_HEADER_BYTES + (MAP_ENTRY_BYTES + OBJECT_BYTES) * this.#relocsN.size;"},{"path":"worker/project/apply-entry.ts","added":12,"removed":2,"diff":"--- a/worker/project/apply-entry.ts\n+++ b/worker/project/apply-entry.ts\n@@ -141,12 +141,21 @@\n \t\t\tconst { type: _, ...note } = entry;\n \t\t\thost.notes.set(entry.id, { ...note, lines: [...entry.lines], at });\n \t\t\thost.setLastNote(Math.max(host.lastNote(), entry.id));\n-\t\t\tif (entry.change !== undefined && host.changes.has(entry.change)) host.changes.get(entry.change)!.last = at;\n+\t\t\tif (entry.change !== undefined) {\n+\t\t\t\tconst change = host.changes.get(entry.change);\n+\t\t\t\tif (change) {\n+\t\t\t\t\tchange.last = at;\n+\t\t\t\t\thost.changes.set(entry.change, change);\n+\t\t\t\t}\n+\t\t\t}\n \t\t\tbreak;\n \t\t}\n \t\tcase \"note-closed\": {\n \t\t\tconst note = host.notes.get(entry.id);\n-\t\t\tif (note) note.closed = { agent: entry.agent, how: entry.how, time: entry.time };\n+\t\t\tif (note) {\n+\t\t\t\tnote.closed = { agent: entry.agent, how: entry.how, time: entry.time };\n+\t\t\t\thost.notes.set(entry.id, note);\n+\t\t\t}\n \t\t\tbreak;\n \t\t}\n \t\tcase \"pulled\":\n@@ -249,6 +258,7 @@\n \t\t\t\t\t\tfiles: [...new Set(entry.collisions.map((c) => c.file))].sort(),\n \t\t\t\t\t});\n \t\t\t\t\trec.last = at;\n+\t\t\t\t\thost.changes.set(id, rec);\n \t\t\t\t}\n \t\t\t}\n \t\t\tbreak;"},{"path":"worker/project/change-records.ts","added":2,"removed":0,"diff":"--- a/worker/project/change-records.ts\n+++ b/worker/project/change-records.ts\n@@ -73,6 +73,7 @@\n \t\trec.note = { text: agent.starting.text, files: [...agent.starting.files] };\n \t\tif (agent.starting.issue !== undefined) rec.issue = agent.starting.issue;\n \t}\n+\thost.changes.set(id, rec);\n \treturn rec;\n }\n \n@@ -101,6 +102,7 @@\n \thost.versionChange.set(`${draft ?? \"\"} ${entry.version}`, id);\n \tif (entry.type === \"publish\") for (const s of entry.settled ?? []) rec.settled.push({ ...s, version: entry.version });\n \trec.last = at;\n+\thost.changes.set(id, rec);\n \tif (old) {\n \t\tdelete agent.starting;\n \t\tdelete agent.noteAt;"},{"path":"worker/project/notes.ts","added":2,"removed":1,"diff":"--- a/worker/project/notes.ts\n+++ b/worker/project/notes.ts\n@@ -321,5 +321,6 @@\n \t\tif (a) host.queueNews(a, [noteClosedItem(agentName, how, id, note)], entries);\n \t}\n \thost.flush(entries);\n-\treturn host.noteAnswer(note);\n+\t// Storage-backed maps return snapshots; apply may replace the stored row.\n+\treturn host.noteAnswer(host.notes.get(id)!);\n }"},{"path":"worker/project/project-types.ts","added":9,"removed":0,"diff":"--- a/worker/project/project-types.ts\n+++ b/worker/project/project-types.ts\n@@ -1,4 +1,5 @@\n import type { Atom, AtomId, LineId } from \"../../src/engine/index.ts\";\n+import type { GraphStateStorage } from \"../../src/engine/state-source.ts\";\n import type { Kept, MarkedRegion } from \"./markers.ts\";\n /** Whole files: path -> text, or null for a deleted file. */\n export type Files = Record<string, string | null>;\n@@ -565,6 +566,14 @@\n \n /** What the project needs from the store of binary files' bytes. */\n export interface ProjectOptions {\n+\t/**\n+\t * Writer indexes for a fresh project or adoption into an empty namespace.\n+\t * The host must wrap each operation and canonical log append in the same\n+\t * storage transaction, and discard this Project if it rolls back. This is\n+\t * not the checkpoint reopen API: use Project.openWriter for an existing\n+\t * committed namespace, with its authoritative canonical log length.\n+\t */\n+\twriterStorage?: GraphStateStorage;\n \t/** Whether the bytes for a SHA-256 have been uploaded. Without it, no blob is held, so binary files are refused. */\n \thasBlob?: (sha256: string) => boolean;\n \t/** The time now, for start notes that end after 2 hours idle (#44). Without it, the newest entry's time. */"},{"path":"worker/project/project.ts","added":261,"removed":11,"diff":"--- a/worker/project/project.ts\n+++ b/worker/project/project.ts\n@@ -13,6 +13,14 @@\n // unit. Every agent works in one space at a time.\n \n import { type Atom, type AtomId, EngineError, Graph, type LineId, type View } from \"../../src/engine/index.ts\";\n+import {\n+\ttype GraphStateStorage,\n+\tStableOverlaySet,\n+\tStableSet,\n+\tStableUnionSet,\n+\tStoredMap,\n+\tstoredArray,\n+} from \"../../src/engine/state-source.ts\";\n import { type AddDraftHost, addDraft as hostedAddDraft } from \"./add-draft.ts\";\n import { type AmendHost, amend as hostedAmend } from \"./amend.ts\";\n import { type AnnounceHost, announce as hostedAnnounce, announcePerson as hostedAnnouncePerson } from \"./announce.ts\";\n@@ -191,6 +199,7 @@\n \twholeRules as hostedWholeRules,\n \ttype WholeHost,\n } from \"./whole-files.ts\";\n+import { WriterAgents } from \"./writer-agents.ts\";\n \n export { MemoryStore } from \"./memory-store.ts\";\n export { checkReadPath, pathProblem } from \"./path-rules.ts\";\n@@ -204,9 +213,21 @@\n \n /** A start note lasts this long after the agent's last activity (#44). */\n const NOTE_IDLE = 2 * 60 * 60 * 1000;\n+const WRITER_REOPEN = Symbol(\"verified writer checkpoint\");\n+export interface WriterSource {\n+\treadonly generation: number;\n+\treadonly logLength: number;\n+\treadonly sharedVersion: number;\n+}\n+interface WriterAdoption {\n+\tsource: WriterSource;\n+\tnext: number;\n+\tready: boolean;\n+}\n \n export class Project {\n \treadonly #store: ProjectStore;\n+\treadonly #writerStorage?: GraphStateStorage;\n \treadonly #graph: Graph;\n \t/** Views laid out from atom sets, cached under a byte budget (views.ts). */\n \treadonly #views: ViewCache;\n@@ -248,7 +269,16 @@\n \t/** For each version of shared, the log position of the entry that made it (#41). */\n \treadonly #versionAt: number[] = [];\n \t/** The newest time any applied entry carries: the clock when none was given. */\n-\t#lastTime = 0;\n+\t#lastTimeMemory = 0;\n+\tget #lastTime(): number {\n+\t\treturn this.#writerStorage\n+\t\t\t? ((this.#writerStorage.read(\"project:meta\", \"lastTime\") as number | undefined) ?? 0)\n+\t\t\t: this.#lastTimeMemory;\n+\t}\n+\tset #lastTime(value: number) {\n+\t\tif (this.#writerStorage) this.#writerStorage.write(\"project:meta\", \"lastTime\", value);\n+\t\telse this.#lastTimeMemory = value;\n+\t}\n \t/** Every change (#44), by id. */\n \treadonly #changes = new Map<number, ChangeRecord>();\n \t/** Each version's change, by \"<draft or ''> <version>\" (#44): what a note on its lines belongs to. */\n@@ -260,12 +290,39 @@\n \t/** The merge queue (#39), in order: publishes to shared waiting for their batch's check. */\n \t#queue: QueuedPublish[] = [];\n \t/** The newest note's id (#44). */\n-\t#lastNote = 0;\n-\t#queuedId = 0;\n+\t#lastNoteMemory = 0;\n+\tget #lastNote(): number {\n+\t\treturn this.#writerStorage\n+\t\t\t? ((this.#writerStorage.read(\"project:meta\", \"lastNote\") as number | undefined) ?? 0)\n+\t\t\t: this.#lastNoteMemory;\n+\t}\n+\tset #lastNote(value: number) {\n+\t\tif (this.#writerStorage) this.#writerStorage.write(\"project:meta\", \"lastNote\", value);\n+\t\telse this.#lastNoteMemory = value;\n+\t}\n+\t#queuedIdMemory = 0;\n+\tget #queuedId(): number {\n+\t\treturn this.#writerStorage\n+\t\t\t? ((this.#writerStorage.read(\"project:meta\", \"queuedId\") as number | undefined) ?? 0)\n+\t\t\t: this.#queuedIdMemory;\n+\t}\n+\tset #queuedId(value: number) {\n+\t\tif (this.#writerStorage) this.#writerStorage.write(\"project:meta\", \"queuedId\", value);\n+\t\telse this.#queuedIdMemory = value;\n+\t}\n \t/** Queued ids in the batch being checked now: not in the log, only for refusing an unqueue mid-check. */\n \t#checking = new Set<number>();\n \t/** How many entries the store holds: the log position of the next one (#41, the website's feed and replay). */\n-\t#stored = 0;\n+\t#storedMemory = 0;\n+\tget #stored(): number {\n+\t\treturn this.#writerStorage\n+\t\t\t? ((this.#writerStorage.read(\"project:meta\", \"stored\") as number | undefined) ?? 0)\n+\t\t\t: this.#storedMemory;\n+\t}\n+\tset #stored(value: number) {\n+\t\tif (this.#writerStorage) this.#writerStorage.write(\"project:meta\", \"stored\", value);\n+\t\telse this.#storedMemory = value;\n+\t}\n \t/** Names on the lines a change replaced, by \"<atom> <last replaced line>\" (atoms never change). */\n \t#rule?: DefinitionRule;\n \tget #definitionRule(): DefinitionRule {\n@@ -273,13 +330,53 @@\n \t\treturn this.#rule;\n \t}\n \t/** The newest announcement's id (announcements are news entries keyed \"announce <id>\"). */\n-\t#announced = 0;\n+\t#announcedMemory = 0;\n+\tget #announced(): number {\n+\t\treturn this.#writerStorage\n+\t\t\t? ((this.#writerStorage.read(\"project:meta\", \"announced\") as number | undefined) ?? 0)\n+\t\t\t: this.#announcedMemory;\n+\t}\n+\tset #announced(value: number) {\n+\t\tif (this.#writerStorage) this.#writerStorage.write(\"project:meta\", \"announced\", value);\n+\t\telse this.#announcedMemory = value;\n+\t}\n \t#loading = false;\n \n \treadonly #hasBlob: (sha256: string) => boolean;\n \n-\tconstructor(store: ProjectStore, options: ProjectOptions = {}) {\n+\tconstructor(store: ProjectStore, options: ProjectOptions = {}, checkpoint?: typeof WRITER_REOPEN) {\n \t\tthis.#store = store;\n+\t\tthis.#writerStorage = options.writerStorage;\n+\t\tif (options.writerStorage) {\n+\t\t\tconst storage = options.writerStorage;\n+\t\t\t// A stored Graph cannot be replayed over itself. Check before any\n+\t\t\t// constructor writes so an accidental reopen preserves the namespace.\n+\t\t\tif (\n+\t\t\t\tcheckpoint !== WRITER_REOPEN &&\n+\t\t\t\t((storage.read(\"atoms:meta\", \"length\") as number | undefined) ||\n+\t\t\t\t\t(storage.read('membership:\"\":versions:meta', \"length\") as number | undefined))\n+\t\t\t)\n+\t\t\t\tthrow new Error(\"writer indexes already contain history; Project checkpoint reopen is required\");\n+\t\t\tthis.#membership = new Membership(storage);\n+\t\t\tthis.#atomAt = storedArray(storage, \"project:atom-at\");\n+\t\t\tthis.#timeAt = storedArray(storage, \"project:time-at\");\n+\t\t\tthis.#versionAt = storedArray(storage, \"project:version-at\");\n+\t\t\tthis.#notes = new StoredMap(storage, \"project:notes\");\n+\t\t\tthis.#changes = new StoredMap(storage, \"project:changes\");\n+\t\t\tthis.#labels = new StoredMap(storage, \"project:labels\");\n+\t\t\tthis.#versionChange = new StoredMap(storage, \"project:version-change\");\n+\t\t\tthis.#refusals = storedArray(storage, \"project:refusals\");\n+\t\t\tthis.#agents = new WriterAgents(storage);\n+\t\t\tif (checkpoint === WRITER_REOPEN) {\n+\t\t\t\tthis.#mods = storage.read(\"project:meta\", \"mods\") as string[];\n+\t\t\t\tthis.#queue = storage.read(\"project:meta\", \"queue\") as QueuedPublish[];\n+\t\t\t\tconst tells = storage.read(\"project:meta\", \"tells\") as [\n+\t\t\t\t\tnumber,\n+\t\t\t\t\tOmit<TellRecord, \"heard\"> & { heard: [string, { at: number | undefined } | null][] },\n+\t\t\t\t][];\n+\t\t\t\tthis.#tells = new Map(tells.map(([id, tell]) => [id, { ...tell, heard: new Map(tell.heard) }]));\n+\t\t\t}\n+\t\t}\n \t\tthis.#hasBlob = options.hasBlob ?? (() => false);\n \t\tthis.#now = options.now;\n \t\tthis.#whole = options.whole;\n@@ -301,9 +398,11 @@\n \t\t\tthrow new Error(`log entry ${at} holds no atom ${seq}`);\n \t\t};\n \t\t// Line text and each atom's deletes and claim keys stay in the log (#46), read back when asked for.\n-\t\tthis.#graph = entryAt\n-\t\t\t? new Graph({ texts: (seq) => stored(seq).inserts.map((r) => r.lines), lists: (seq) => stored(seq) })\n-\t\t\t: new Graph();\n+\t\tthis.#graph = options.writerStorage\n+\t\t\t? new Graph({ storage: options.writerStorage })\n+\t\t\t: entryAt\n+\t\t\t\t? new Graph({ texts: (seq) => stored(seq).inserts.map((r) => r.lines), lists: (seq) => stored(seq) })\n+\t\t\t\t: new Graph();\n \t\tthis.#views = new ViewCache(this.#graph);\n \t\tthis.#paths = new PathIndex({\n \t\t\tgraph: this.#graph,\n@@ -330,12 +429,135 @@\n \t\tfor (const entry of entries) {\n \t\t\tproject.#apply(entry);\n \t\t\tproject.#stored++;\n+\t\t\tproject.#persistMutable();\n \t\t}\n \t\tproject.#loading = false;\n+\t\tproject.#writeCheckpoint();\n \t\treturn project;\n \t}\n \n+\t/** Reopen committed writer indexes. The host supplies the authoritative canonical log length. */\n+\tstatic openWriter(\n+\t\tstore: ProjectStore,\n+\t\tstorage: GraphStateStorage,\n+\t\tlogLength: number,\n+\t\toptions: Omit<ProjectOptions, \"writerStorage\"> = {},\n+\t): Project {\n+\t\tconst adoption = storage.read(\"project:meta\", \"adoption\") as WriterAdoption | undefined;\n+\t\tif (adoption && !adoption.ready) throw new Error(\"writer adoption is incomplete\");\n+\t\treturn Project.#openWriter(store, storage, logLength, options);\n+\t}\n+\n+\tstatic #openWriter(\n+\t\tstore: ProjectStore,\n+\t\tstorage: GraphStateStorage,\n+\t\tlogLength: number,\n+\t\toptions: Omit<ProjectOptions, \"writerStorage\">,\n+\t): Project {\n+\t\tconst checkpoint = storage.read(\"project:meta\", \"checkpoint\") as\n+\t\t\t| { format: number; logLength: number; atoms: number; version: number }\n+\t\t\t| undefined;\n+\t\tconst length = (name: string) => (storage.read(`${name}:meta`, \"length\") as number | undefined) ?? 0;\n+\t\tif (\n+\t\t\t!Number.isSafeInteger(logLength) ||\n+\t\t\tlogLength < 1 ||\n+\t\t\tcheckpoint?.format !== 1 ||\n+\t\t\tcheckpoint.logLength !== logLength ||\n+\t\t\tstorage.read(\"project:meta\", \"stored\") !== logLength ||\n+\t\t\tlength(\"project:time-at\") !== logLength ||\n+\t\t\tlength(\"atoms\") !== checkpoint.atoms ||\n+\t\t\tlength(\"project:atom-at\") !== checkpoint.atoms ||\n+\t\t\tlength('membership:\"\":versions') !== checkpoint.version + 1 ||\n+\t\t\tlength(\"project:version-at\") !== checkpoint.version + 1 ||\n+\t\t\t![\"mods\", \"queue\", \"tells\"].every((key) => Array.isArray(storage.read(\"project:meta\", key)))\n+\t\t)\n+\t\t\tthrow new Error(\"writer checkpoint does not match the canonical log and indexes\");\n+\t\treturn new Project(store, { ...options, writerStorage: storage }, WRITER_REOPEN);\n+\t}\n+\n \t/**\n+\t * Derive one bounded page from the host's canonical frames. The host reads\n+\t * those frames from its own log and revalidates the source inside this same\n+\t * transaction. Partial adoption cannot be opened for normal operations.\n+\t */\n+\tstatic adoptWriterPage(\n+\t\tstorage: GraphStateStorage,\n+\t\tinput: {\n+\t\t\tsource: WriterSource;\n+\t\t\tfrom: number;\n+\t\t\tframes: Iterable<{ seq: number; json: string }>;\n+\t\t\tmaxEntries: number;\n+\t\t\tmaxBytes: number;\n+\t\t\tcurrentSource(): WriterSource;\n+\t\t},\n+\t\toptions: Omit<ProjectOptions, \"writerStorage\"> = {},\n+\t): { next: number; ready: boolean; entries: number; bytes: number } {\n+\t\tconst same = (a: WriterSource, b: WriterSource) =>\n+\t\t\ta.generation === b.generation && a.logLength === b.logLength && a.sharedVersion === b.sharedVersion;\n+\t\tif (\n+\t\t\t![input.source.generation, input.source.logLength, input.source.sharedVersion, input.from].every(\n+\t\t\t\t(n) => Number.isSafeInteger(n) && n >= 0,\n+\t\t\t) ||\n+\t\t\tinput.source.logLength < 1 ||\n+\t\t\t!Number.isSafeInteger(input.maxEntries) ||\n+\t\t\tinput.maxEntries < 1 ||\n+\t\t\tinput.maxEntries > 256 ||\n+\t\t\t!Number.isSafeInteger(input.maxBytes) ||\n+\t\t\tinput.maxBytes < 1 ||\n+\t\t\tinput.maxBytes > 8_000_000\n+\t\t)\n+\t\t\tthrow new Error(\"invalid writer adoption bounds or source\");\n+\t\treturn storage.transaction(() => {\n+\t\t\tif (!same(input.currentSource(), input.source))\n+\t\t\t\tthrow new Error(\"canonical source changed before writer adoption\");\n+\t\t\tconst previous = storage.read(\"project:meta\", \"adoption\") as WriterAdoption | undefined;\n+\t\t\tif (\n+\t\t\t\t(previous && (!same(previous.source, input.source) || previous.ready || previous.next !== input.from)) ||\n+\t\t\t\t(!previous && input.from !== 0)\n+\t\t\t)\n+\t\t\t\tthrow new Error(\"writer adoption source or cursor does not match\");\n+\t\t\tconst noAppend: ProjectStore = {\n+\t\t\t\tappend: () => {\n+\t\t\t\t\tthrow new Error(\"adoption must never append canonical history\");\n+\t\t\t\t},\n+\t\t\t};\n+\t\t\tconst project = previous\n+\t\t\t\t? Project.#openWriter(noAppend, storage, input.from, options)\n+\t\t\t\t: new Project(noAppend, { ...options, writerStorage: storage });\n+\t\t\tproject.#loading = true;\n+\t\t\tlet count = 0;\n+\t\t\tlet bytes = 0;\n+\t\t\tfor (const frame of input.frames) {\n+\t\t\t\tif (\n+\t\t\t\t\tcount >= input.maxEntries ||\n+\t\t\t\t\tframe.seq !== input.from + count ||\n+\t\t\t\t\tframe.seq >= input.source.logLength ||\n+\t\t\t\t\ttypeof frame.json !== \"string\" ||\n+\t\t\t\t\tframe.json.length > input.maxBytes - bytes\n+\t\t\t\t)\n+\t\t\t\t\tthrow new Error(\"writer adoption page exceeds bounds or has a noncontiguous frame\");\n+\t\t\t\tbytes += new TextEncoder().encode(frame.json).byteLength;\n+\t\t\t\tif (bytes > input.maxBytes) throw new Error(\"writer adoption page exceeds byte bound\");\n+\t\t\t\tproject.#apply(JSON.parse(frame.json) as Entry);\n+\t\t\t\tproject.#stored++;\n+\t\t\t\tproject.#persistMutable();\n+\t\t\t\tcount++;\n+\t\t\t}\n+\t\t\tif (count === 0) throw new Error(\"writer adoption page must advance\");\n+\t\t\tproject.#loading = false;\n+\t\t\tconst next = input.from + count;\n+\t\t\tconst ready = next === input.source.logLength;\n+\t\t\tif (!same(input.currentSource(), input.source))\n+\t\t\t\tthrow new Error(\"canonical source changed during writer adoption\");\n+\t\t\tif (ready && project.version !== input.source.sharedVersion)\n+\t\t\t\tthrow new Error(\"adopted shared version differs from canonical source\");\n+\t\t\tproject.#writeCheckpoint();\n+\t\t\tstorage.write(\"project:meta\", \"adoption\", { source: input.source, next, ready } satisfies WriterAdoption);\n+\t\t\treturn { next, ready, entries: count, bytes };\n+\t\t});\n+\t}\n+\n+\t/**\n \t * Apply more stored entries to a copy loaded for reading (#41, replay):\n \t * scrubbing forward applies only what's new. Never for the live project.\n \t */\n@@ -1267,11 +1489,34 @@\n \t#flush(_entries: readonly Entry[]): void {\n \t\tif (this.#pending.length === 0) return;\n \t\tconst out = this.#pending;\n-\t\tthis.#pending = [];\n \t\tthis.#store.append(out);\n+\t\tthis.#persistMutable();\n+\t\tthis.#pending = [];\n \t\tthis.#stored += out.length;\n+\t\tthis.#writeCheckpoint();\n \t}\n \n+\t#writeCheckpoint(): void {\n+\t\tthis.#writerStorage?.write(\"project:meta\", \"checkpoint\", {\n+\t\t\tformat: 1,\n+\t\t\tlogLength: this.#stored,\n+\t\t\tatoms: this.#graph.size,\n+\t\t\tversion: this.version,\n+\t\t});\n+\t}\n+\n+\t#persistMutable(): void {\n+\t\tif (!this.#writerStorage) return;\n+\t\tif (this.#agents instanceof WriterAgents) this.#agents.flush();\n+\t\tthis.#writerStorage.write(\"project:meta\", \"mods\", this.#mods);\n+\t\tthis.#writerStorage.write(\"project:meta\", \"queue\", this.#queue);\n+\t\tthis.#writerStorage.write(\n+\t\t\t\"project:meta\",\n+\t\t\t\"tells\",\n+\t\t\t[...this.#tells].map(([id, tell]) => [id, { ...tell, heard: [...tell.heard] }]),\n+\t\t);\n+\t}\n+\n \t/**\n \t * The agent an entry names. Before every applied entry was stored, a call\n \t * that joined an agent and then threw could leave the join out of the log\n@@ -2217,7 +2462,12 @@\n \t}\n \n \t#agentView(agent: AgentState): View {\n-\t\treturn this.#viewKeyed(this.#agentViewKey(agent), () => this.#agentSet(agent));\n+\t\treturn this.#viewKeyed(this.#agentViewKey(agent), () => {\n+\t\t\tconst base = this.#at(this.#spaceOf(agent), agent.base);\n+\t\t\treturn base instanceof StableSet\n+\t\t\t\t? new StableUnionSet(base, new StableOverlaySet(agent.mine))\n+\t\t\t\t: new Set([...base, ...agent.mine]);\n+\t\t});\n \t}\n \n \t/** An agent's view, keyed by what the set is made of, not by sorting every atom in it (#46): that cost more than the work. */"},{"path":"worker/project/spaces.ts","added":151,"removed":4,"diff":"--- a/worker/project/spaces.ts\n+++ b/worker/project/spaces.ts\n@@ -4,6 +4,14 @@\n // live here once.\n \n import type { AtomId } from \"../../src/engine/index.ts\";\n+import {\n+\ttype GraphStateStorage,\n+\tStableSet,\n+\tStableUnionSet,\n+\tStoredMap,\n+\tStoredSet,\n+\tstoredArray,\n+} from \"../../src/engine/state-source.ts\";\n import type { Entry } from \"./project.ts\";\n \n export const SHARED = \"\";\n@@ -27,6 +35,8 @@\n \n export /** Shared ('') or a named draft. */\n interface Space {\n+\t/** Storage-backed spaces append the historical membership index here. */\n+\tindexVersion?: (version: Published) => void;\n \treadonly name: string;\n \treadonly versions: Published[];\n \t/** Every atom published into this space (for shared, everything in it). */\n@@ -39,7 +49,19 @@\n \tstartedAt?: number;\n }\n \n-export function newSpace(name: string): Space {\n+export function newSpace(name: string, storage?: GraphStateStorage): Space {\n+\tif (storage) {\n+\t\tconst prefix = `membership:${JSON.stringify(name)}`;\n+\t\treturn {\n+\t\t\tname,\n+\t\t\tindexVersion: (version) => indexMembership(storage, prefix, version),\n+\t\t\tversions: storedArray(storage, `${prefix}:versions`),\n+\t\t\town: new StoredSet(storage, `${prefix}:own`),\n+\t\t\tpublishedIn: new StoredMap(storage, `${prefix}:published`),\n+\t\t\tdroppedIn: new StoredMap(storage, `${prefix}:dropped`),\n+\t\t\tatCache: new Map(),\n+\t\t};\n+\t}\n \treturn { name, versions: [], own: new Set(), publishedIn: new Map(), droppedIn: new Map(), atCache: new Map() };\n }\n \n@@ -53,8 +75,95 @@\n \t\tspace.own.delete(id);\n \t\tspace.droppedIn.set(id, version.version);\n \t}\n+\tspace.indexVersion?.(version);\n }\n \n+interface MembershipEvent {\n+\tversion: number;\n+\tpresent: boolean;\n+\tslot: number;\n+\tatom: AtomId;\n+}\n+\n+function membershipEvent(\n+\tstorage: GraphStateStorage,\n+\tprefix: string,\n+\tatom: AtomId,\n+\tversion: number,\n+): MembershipEvent | undefined {\n+\tconst events = storedArray<MembershipEvent>(storage, `${prefix}:events:${atom}`);\n+\tlet lo = 0;\n+\tlet hi = events.length;\n+\twhile (lo < hi) {\n+\t\tconst mid = lo + Math.floor((hi - lo) / 2);\n+\t\tif (events[mid]!.version <= version) lo = mid + 1;\n+\t\telse hi = mid;\n+\t}\n+\treturn lo === 0 ? undefined : events[lo - 1];\n+}\n+\n+function indexMembership(storage: GraphStateStorage, prefix: string, version: Published): void {\n+\tconst order = storedArray<MembershipEvent>(storage, `${prefix}:events`);\n+\tfor (const [ids, present] of [\n+\t\t[version.atoms, true],\n+\t\t[version.dropped ?? [], false],\n+\t] as const) {\n+\t\tfor (const atom of ids) {\n+\t\t\tconst previous = membershipEvent(storage, prefix, atom, version.version);\n+\t\t\tif ((previous?.present ?? false) === present) continue;\n+\t\t\tconst event = { atom, version: version.version, present, slot: order.length };\n+\t\t\tstoredArray<MembershipEvent>(storage, `${prefix}:events:${atom}`).push(event);\n+\t\t\torder.push(event);\n+\t\t}\n+\t}\n+}\n+\n+/** Immutable historical shared membership; iteration reads one event at a time. */\n+class StoredVersionSet extends StableSet<AtomId> {\n+\treadonly retainedBytes = 64;\n+\treadonly #storage: GraphStateStorage;\n+\treadonly #prefix: string;\n+\treadonly #version: number;\n+\tconstructor(storage: GraphStateStorage, prefix: string, version: number) {\n+\t\tsuper();\n+\t\tthis.#storage = storage;\n+\t\tthis.#prefix = prefix;\n+\t\tthis.#version = version;\n+\t}\n+\tget [Symbol.toStringTag](): string {\n+\t\treturn \"Set\";\n+\t}\n+\thas(atom: AtomId): boolean {\n+\t\treturn membershipEvent(this.#storage, this.#prefix, atom, this.#version)?.present ?? false;\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+\t*values(): SetIterator<AtomId> {\n+\t\tconst events = storedArray<MembershipEvent>(this.#storage, `${this.#prefix}:events`);\n+\t\tfor (const event of events) {\n+\t\t\tif (event.version > this.#version) break;\n+\t\t\tif (!event.present) continue;\n+\t\t\tconst selected = membershipEvent(this.#storage, this.#prefix, event.atom, this.#version);\n+\t\t\tif (selected?.slot === event.slot) yield event.atom;\n+\t\t}\n+\t}\n+\tkeys(): SetIterator<AtomId> {\n+\t\treturn this.values();\n+\t}\n+\t*entries(): SetIterator<[AtomId, AtomId]> {\n+\t\tfor (const atom of this) yield [atom, atom];\n+\t}\n+\t[Symbol.iterator](): SetIterator<AtomId> {\n+\t\treturn this.values();\n+\t}\n+\tforEach(callback: (value: AtomId, key: AtomId, set: ReadonlySet<AtomId>) => void, thisArg?: unknown): void {\n+\t\tfor (const atom of this) callback.call(thisArg, atom, atom, this);\n+\t}\n+}\n+\n export function last(space: Space): number {\n \treturn space.versions.length - 1;\n }\n@@ -65,7 +174,26 @@\n \n /** Every space, and each one's contents at any of its versions. */\n export class Membership {\n-\treadonly spaces = new Map<string, Space>([[SHARED, newSpace(SHARED)]]);\n+\treadonly spaces: Map<string, Space>;\n+\treadonly #storage?: GraphStateStorage;\n+\tconstructor(storage?: GraphStateStorage) {\n+\t\tthis.#storage = storage;\n+\t\tif (!storage) {\n+\t\t\tthis.spaces = new Map([[SHARED, newSpace(SHARED)]]);\n+\t\t\treturn;\n+\t\t}\n+\t\tthis.spaces = new StoredMap(storage, \"membership:spaces\", {\n+\t\t\tencode: (space) => ({ name: space.name, startedAt: space.startedAt }),\n+\t\t\tdecode: (value) => {\n+\t\t\t\tconst meta = value as { name: string; startedAt?: number };\n+\t\t\t\treturn {\n+\t\t\t\t\t...newSpace(meta.name, storage),\n+\t\t\t\t\t...(meta.startedAt === undefined ? {} : { startedAt: meta.startedAt }),\n+\t\t\t\t};\n+\t\t\t},\n+\t\t});\n+\t\tif (!this.spaces.has(SHARED)) storage.transaction(() => this.spaces.set(SHARED, newSpace(SHARED, storage)));\n+\t}\n \n \tget shared(): Space {\n \t\treturn this.spaces.get(SHARED)!;\n@@ -73,6 +201,11 @@\n \n \t/** What an entry (at log position `at`) does to membership; other kinds change none. */\n \tapply(entry: Entry, at: number): void {\n+\t\tif (this.#storage) this.#storage.transaction(() => this.#apply(entry, at));\n+\t\telse this.#apply(entry, at);\n+\t}\n+\n+\t#apply(entry: Entry, at: number): void {\n \t\tswitch (entry.type) {\n \t\t\tcase \"init\":\n \t\t\t\taddVersion(this.shared, {\n@@ -108,13 +241,15 @@\n \t\t\t\t});\n \t\t\t\tbreak;\n \t\t\tcase \"amend\": {\n-\t\t\t\tconst p = this.spaces.get(entry.space ?? SHARED)!.versions[entry.version]!;\n+\t\t\t\tconst space = this.spaces.get(entry.space ?? SHARED)!;\n+\t\t\t\tconst p = space.versions[entry.version]!;\n \t\t\t\tp.originalMessage ??= p.message;\n \t\t\t\tp.message = entry.message;\n+\t\t\t\tspace.versions[entry.version] = p;\n \t\t\t\tbreak;\n \t\t\t}\n \t\t\tcase \"space\": {\n-\t\t\t\tconst space = newSpace(entry.name);\n+\t\t\t\tconst space = newSpace(entry.name, this.#storage);\n \t\t\t\tspace.startedAt = at;\n \t\t\t\tthis.spaces.set(entry.name, space);\n \t\t\t\taddVersion(space, {\n@@ -170,6 +305,18 @@\n \t * next version is applied. A caller that keeps it across an apply copies it first.\n \t */\n \tat(space: Space, version: number): ReadonlySet<AtomId> {\n+\t\tif (this.#storage) {\n+\t\t\tconst own = new StoredVersionSet(this.#storage, `membership:${JSON.stringify(space.name)}`, version);\n+\t\t\tif (space.name === SHARED) return own;\n+\t\t\t// Named drafts add local atoms over an immutable shared base; drop\n+\t\t\t// entries target shared, never a named draft's local membership.\n+\t\t\tconst base = new StoredVersionSet(\n+\t\t\t\tthis.#storage,\n+\t\t\t\t`membership:${JSON.stringify(SHARED)}`,\n+\t\t\t\tspace.versions[version]!.sharedBase!,\n+\t\t\t);\n+\t\t\treturn new StableUnionSet(base, own);\n+\t\t}\n \t\tif (space.name === SHARED && version === last(space)) return space.own;\n \t\tlet set = space.atCache.get(version);\n \t\tif (!set) {"},{"path":"worker/project/test/project-writer-storage.test.ts","added":142,"removed":0,"diff":"--- /dev/null\n+++ b/worker/project/test/project-writer-storage.test.ts\n@@ -0,0 +1,142 @@\n+import assert from \"node:assert/strict\";\n+import { test } from \"node:test\";\n+import { storedArray } from \"../../../src/engine/state-source.ts\";\n+import { SqlState } from \"../../../src/engine/test/storage-helper.ts\";\n+import { MemoryStore, Project } from \"../project.ts\";\n+import type { Entry, ProjectStore } from \"../project-types.ts\";\n+\n+function setup() {\n+\tconst storage = new SqlState();\n+\tconst entries = storedArray<Entry>(storage, \"canonical-log\");\n+\tlet failAppend = false;\n+\tconst store: ProjectStore = {\n+\t\tappend(batch) {\n+\t\t\tfor (const entry of batch) {\n+\t\t\t\tentries.push(entry);\n+\t\t\t\tif (failAppend) throw new Error(\"injected canonical append failure\");\n+\t\t\t}\n+\t\t},\n+\t};\n+\treturn {\n+\t\tstorage,\n+\t\tentries,\n+\t\tstore,\n+\t\tfail: () => {\n+\t\t\tfailAppend = true;\n+\t\t},\n+\t\trecover: () => {\n+\t\t\tfailAppend = false;\n+\t\t},\n+\t};\n+}\n+\n+test(\"actual Project record and publish use persistent graph, membership and positional indexes\", (t) => {\n+\tt.mock.method(Date, \"now\", () => 100);\n+\tconst { storage, entries, store } = setup();\n+\tlet project = new Project(store, { writerStorage: storage });\n+\tt.mock.method(Project, \"load\", () => {\n+\t\tthrow new Error(\"checkpoint path must not replay the log\");\n+\t});\n+\tconst oracleLog = new MemoryStore();\n+\tconst oracle = new Project(oracleLog);\n+\tconst run = <T>(operation: (p: Project) => T) => {\n+\t\tconst expected = operation(oracle);\n+\t\tconst actual = storage.transaction(() => operation(project));\n+\t\tassert.deepEqual(actual, expected);\n+\t\tassert.deepEqual(project.files(), oracle.files());\n+\t\tassert.deepEqual(project.changes(0), oracle.changes(0));\n+\t\tassert.deepEqual(project.notes({ file: \"a.txt\" }), oracle.notes({ file: \"a.txt\" }));\n+\t\tassert.deepEqual([...entries], oracleLog.entries);\n+\t\tproject = Project.openWriter(store, storage, entries.length);\n+\t\tassert.deepEqual(project.files(), oracle.files(), \"reopened checkpoint preserves published files\");\n+\t\tassert.deepEqual(\n+\t\t\tproject.status(),\n+\t\t\toracle.status(),\n+\t\t\t\"reopened checkpoint preserves agents, drafts and history state\",\n+\t\t);\n+\t};\n+\trun((p) => p.init({ \"a.txt\": \"one\\ntwo\\n\", \"b.txt\": \"alpha\\n\" }, 0));\n+\trun((p) => p.record(\"writer\", { \"a.txt\": \"ONE\\ntwo\\n\" }, 1));\n+\trun((p) => p.publish(\"writer\", \"Edit\", 2));\n+\trun((p) => p.note(\"writer\", { file: \"a.txt\", from: 1, to: 1, text: \"Review this\", kind: \"objection\" }, 2));\n+\trun((p) => p.record(\"writer\", { \"a.txt\": \"ONE\\ntwo\\n\" }, 3));\n+\trun((p) => p.record(\"left\", { \"a.txt\": \"LEFT\\ntwo\\n\" }, 4));\n+\trun((p) => p.record(\"right\", { \"a.txt\": \"RIGHT\\ntwo\\n\" }, 5));\n+\trun((p) => p.publish(\"left\", \"Left\", 6));\n+\trun((p) => p.publish(\"right\", \"Right\", 7));\n+\trun((p) => p.closeNote(\"writer\", 1, \"resolved\", 8));\n+\trun((p) => p.switchTo(\"writer\", \"branch\", 9));\n+\trun((p) => p.record(\"writer\", { \"b.txt\": \"BETA\\n\" }, 10));\n+\trun((p) => p.publish(\"writer\", \"Branch edit\", 11));\n+\trun((p) => p.land(\"writer\", \"Land branch\", 12));\n+\trun((p) => p.announce(\"writer\", \"Please review\", [\"left\"], 13));\n+\trun((p) => p.news(\"left\"));\n+\tassert.deepEqual(project.position({ version: 1 }), oracle.position({ version: 1 }));\n+\tassert.deepEqual(project.position({ time: 3 }), oracle.position({ time: 3 }));\n+\tassert.throws(() => new Project(store, { writerStorage: storage }), /checkpoint reopen is required/);\n+\tassert.throws(() => Project.openWriter(store, storage, entries.length + 1), /does not match/);\n+\tstorage.db.close();\n+});\n+\n+test(\"queued publish survives checkpoint reopen and lands with the same candidate\", () => {\n+\tconst { storage, entries, store } = setup();\n+\tlet project = new Project(store, { writerStorage: storage });\n+\tproject.checkerReady = true;\n+\tstorage.transaction(() => project.init({ \"avcs.json\": '{\"queue\":true}\\n', \"a.txt\": \"one\\n\" }, 0));\n+\tstorage.transaction(() => project.record(\"writer\", { \"a.txt\": \"ONE\\n\" }, 1));\n+\tconst queued = storage.transaction(() => project.publish(\"writer\", \"Queued edit\", 2));\n+\tassert.ok(queued.ok && \"queued\" in queued);\n+\tconst before = project.queueCandidate(1);\n+\tproject = Project.openWriter(store, storage, entries.length);\n+\tproject.checkerReady = true;\n+\tassert.deepEqual(project.queueCandidate(1), before);\n+\tstorage.transaction(() => project.queueLand(1, 3));\n+\tconst reopened = Project.openWriter(store, storage, entries.length);\n+\tassert.equal(reopened.files()[\"a.txt\"], \"ONE\\n\");\n+\tassert.deepEqual(reopened.queue().items, []);\n+\tstorage.db.close();\n+});\n+\n+test(\"failure after log append rolls back the log and persistent Project counters\", (t) => {\n+\tconst { storage, entries, store } = setup();\n+\tconst project = new Project(store, { writerStorage: storage });\n+\tstorage.transaction(() => project.init({ \"a.txt\": \"one\\n\" }, 0));\n+\tconst snapshot = () => storage.db.prepare(\"SELECT * FROM state ORDER BY collection, key\").all();\n+\tconst before = snapshot();\n+\tconst length = entries.length;\n+\tconst write = storage.write.bind(storage);\n+\tt.mock.method(storage, \"write\", (collection: string, key: string, value: unknown) => {\n+\t\tif (collection === \"project:meta\" && key === \"stored\") {\n+\t\t\tassert.ok(entries.length > length, \"the failure occurs after the canonical append\");\n+\t\t\tthrow new Error(\"injected checkpoint counter failure\");\n+\t\t}\n+\t\twrite(collection, key, value);\n+\t});\n+\tassert.throws(\n+\t\t() => storage.transaction(() => project.record(\"writer\", { \"a.txt\": \"ONE\\n\" }, 1)),\n+\t\t/checkpoint counter failure/,\n+\t);\n+\tassert.deepEqual(snapshot(), before);\n+\tstorage.db.close();\n+});\n+\n+test(\"outer transaction rolls back canonical append and every Project writer index\", () => {\n+\tconst { storage, store, entries, fail, recover } = setup();\n+\tconst project = new Project(store, { writerStorage: storage });\n+\tstorage.transaction(() => project.init({ \"a.txt\": \"one\\n\" }, 0));\n+\tconst snapshot = () => storage.db.prepare(\"SELECT * FROM state ORDER BY collection, key\").all();\n+\tconst before = snapshot();\n+\tfail();\n+\tassert.throws(\n+\t\t() => storage.transaction(() => project.record(\"writer\", { \"a.txt\": \"ONE\\n\" }, 1)),\n+\t\t/canonical append failure/,\n+\t);\n+\tassert.deepEqual(snapshot(), before, \"log, graph, membership and positional state roll back together\");\n+\t// Discard the failed in-memory instance and retry from the committed root.\n+\trecover();\n+\tconst reopened = Project.openWriter(store, storage, entries.length);\n+\tstorage.transaction(() => reopened.record(\"writer\", { \"a.txt\": \"ONE\\n\" }, 1));\n+\tstorage.transaction(() => reopened.publish(\"writer\", \"Retry\", 2));\n+\tassert.deepEqual(Project.openWriter(store, storage, entries.length).files(), { \"a.txt\": \"ONE\\n\" });\n+\tstorage.db.close();\n+});"},{"path":"worker/project/test/stored-membership.test.ts","added":129,"removed":0,"diff":"--- /dev/null\n+++ b/worker/project/test/stored-membership.test.ts\n@@ -0,0 +1,129 @@\n+import assert from \"node:assert/strict\";\n+import { test } from \"node:test\";\n+import { StoredMap, StoredSet } from \"../../../src/engine/state-source.ts\";\n+import { SqlState } from \"../../../src/engine/test/storage-helper.ts\";\n+import { MemoryStore, Project } from \"../project.ts\";\n+import { Membership } from \"../spaces.ts\";\n+\n+test(\"persistent collections preserve insertion order, deletion, reinsert and undefined values\", () => {\n+\tconst storage = new SqlState();\n+\tconst map = new StoredMap<string, number | undefined>(storage, \"map\");\n+\tmap.set(\"z\", 1).set(\"a\", undefined).set(\"m\", 3);\n+\tmap.delete(\"z\");\n+\tmap.set(\"z\", 4);\n+\tconst reopened = new StoredMap<string, number | undefined>(storage, \"map\");\n+\tassert.equal(reopened.size, 3);\n+\tassert.equal(reopened.has(\"a\"), true);\n+\tassert.deepEqual(\n+\t\t[...reopened],\n+\t\t[\n+\t\t\t[\"a\", undefined],\n+\t\t\t[\"m\", 3],\n+\t\t\t[\"z\", 4],\n+\t\t],\n+\t);\n+\tconst set = new StoredSet<string>(storage, \"set\");\n+\tset.add(\"z\").add(\"a\").add(\"z\");\n+\tassert.deepEqual([...new StoredSet<string>(storage, \"set\")], [\"z\", \"a\"]);\n+\tstorage.db.close();\n+});\n+\n+test(\"membership reopens stored versions and preserves historical drop and amendment semantics\", () => {\n+\tconst log = new MemoryStore();\n+\tconst project = new Project(log);\n+\tproject.init({ \"a.txt\": \"one\\ntwo\\n\" }, 0);\n+\tproject.record(\"writer\", { \"a.txt\": \"ONE\\ntwo\\n\" }, 1);\n+\tassert.equal(project.publish(\"writer\", \"First edit\", 2).ok, true);\n+\tproject.drop(\"writer\", [1], \"Undo\", 3);\n+\tconst oracle = new Membership();\n+\tconst storage = new SqlState();\n+\tconst stored = new Membership(storage);\n+\tfor (const [at, entry] of log.entries.entries()) {\n+\t\toracle.apply(entry, at);\n+\t\tstored.apply(entry, at);\n+\t}\n+\tconst reads = storage.reads;\n+\tconst reopened = new Membership(storage);\n+\tassert.equal(storage.reads - reads, 1, \"reopen only checks the space directory; it does not read version history\");\n+\tassert.equal(storage.scans, 0);\n+\tassert.deepEqual([...reopened.shared.versions], oracle.shared.versions);\n+\tassert.deepEqual([...reopened.shared.own], [...oracle.shared.own]);\n+\tassert.deepEqual([...reopened.shared.publishedIn], [...oracle.shared.publishedIn]);\n+\tassert.deepEqual([...reopened.shared.droppedIn], [...oracle.shared.droppedIn]);\n+\tfor (let version = 0; version < oracle.shared.versions.length; version++) {\n+\t\tassert.deepEqual([...reopened.at(reopened.shared, version)], [...oracle.at(oracle.shared, version)]);\n+\t}\n+\tconst amend = { type: \"amend\" as const, agent: \"writer\", version: 1, message: \"Corrected\", time: 4 };\n+\treopened.apply(amend, log.entries.length);\n+\tconst again = new Membership(storage);\n+\tassert.equal(again.shared.versions[1]?.message, \"Corrected\");\n+\tassert.equal(again.shared.versions[1]?.originalMessage, \"First edit\");\n+\tstorage.db.close();\n+});\n+\n+test(\"membership application rolls back its version and every index together\", () => {\n+\tconst log = new MemoryStore();\n+\tconst project = new Project(log);\n+\tproject.init({ \"a.txt\": \"one\\n\" }, 0);\n+\tconst storage = new SqlState();\n+\tconst membership = new Membership(storage);\n+\tstorage.failWrite = storage.writes + 5;\n+\tassert.throws(() => membership.apply(log.entries[0]!, 0), /injected storage failure/);\n+\tconst reopened = new Membership(storage);\n+\tassert.equal(reopened.shared.versions.length, 0);\n+\tassert.equal(reopened.shared.own.size, 0);\n+\tassert.equal(reopened.shared.publishedIn.size, 0);\n+\tstorage.failWrite = Infinity;\n+\treopened.apply(log.entries[0]!, 0);\n+\tassert.equal(new Membership(storage).shared.versions.length, 1);\n+\tstorage.db.close();\n+});\n+\n+test(\"stored membership preserves named draft bases and land across reopen\", () => {\n+\tconst log = new MemoryStore();\n+\tconst project = new Project(log);\n+\tproject.init({ \"a.txt\": \"one\\n\" }, 0);\n+\tproject.switchTo(\"writer\", \"branch\", 1);\n+\tproject.record(\"writer\", { \"a.txt\": \"ONE\\n\" }, 2);\n+\tassert.equal(project.publish(\"writer\", \"Branch edit\", 3).ok, true);\n+\tassert.equal(project.land(\"writer\", \"Land\", 4).ok, true);\n+\tconst storage = new SqlState();\n+\tconst oracle = new Membership();\n+\tconst stored = new Membership(storage);\n+\tfor (const [at, entry] of log.entries.entries()) {\n+\t\toracle.apply(entry, at);\n+\t\tstored.apply(entry, at);\n+\t}\n+\tconst reopened = new Membership(storage);\n+\tfor (const [name, space] of oracle.spaces) {\n+\t\tconst actual = reopened.spaces.get(name)!;\n+\t\tassert.equal(actual.startedAt, space.startedAt);\n+\t\tassert.deepEqual([...actual.versions], space.versions);\n+\t\tfor (let version = 0; version < space.versions.length; version++)\n+\t\t\tassert.deepEqual([...reopened.at(actual, version)], [...oracle.at(space, version)]);\n+\t}\n+\tstorage.db.close();\n+});\n+\n+test(\"opening an old shared membership does not hydrate its atom set\", () => {\n+\tconst log = new MemoryStore();\n+\tconst project = new Project(log);\n+\tproject.init({ \"a.txt\": \"zero\\n\" }, 0);\n+\tfor (let i = 1; i <= 40; i++) {\n+\t\tproject.record(\"writer\", { \"a.txt\": `${i}\\n` }, i * 2);\n+\t\tassert.equal(project.publish(\"writer\", `Edit ${i}`, i * 2 + 1).ok, true);\n+\t}\n+\tconst storage = new SqlState();\n+\tconst membership = new Membership(storage);\n+\tfor (const [at, entry] of log.entries.entries()) membership.apply(entry, at);\n+\tconst reopened = new Membership(storage);\n+\tconst shared = reopened.shared;\n+\tconst reads = storage.reads;\n+\tconst old = reopened.at(shared, 20);\n+\tassert.equal(storage.reads - reads, 0, \"opening a historical membership does not read historical state\");\n+\tassert.equal(old.size, 41);\n+\tassert.equal(old.has(\"a0\"), true);\n+\tassert.equal(old.has(\"a79\"), false);\n+\tassert.equal(shared.atCache.size, 0, \"storage-backed shared history never fills the in-memory set cache\");\n+\tstorage.db.close();\n+});"},{"path":"worker/project/test/writer-adoption.test.ts","added":101,"removed":0,"diff":"--- /dev/null\n+++ b/worker/project/test/writer-adoption.test.ts\n@@ -0,0 +1,101 @@\n+import assert from \"node:assert/strict\";\n+import { test } from \"node:test\";\n+import { SqlState } from \"../../../src/engine/test/storage-helper.ts\";\n+import { MemoryStore, Project, type WriterSource } from \"../project.ts\";\n+\n+function history() {\n+\tconst log = new MemoryStore();\n+\tconst project = new Project(log);\n+\tproject.init({ \"a.txt\": \"zero\\n\" }, 0);\n+\tfor (let i = 1; i <= 8; i++) {\n+\t\tproject.record(\"writer\", { \"a.txt\": `${i}\\n` }, i * 2);\n+\t\tproject.publish(\"writer\", `Edit ${i}`, i * 2 + 1);\n+\t}\n+\tconst source: WriterSource = { generation: 8, logLength: log.entries.length, sharedVersion: project.version };\n+\tconst frames = log.entries.map((entry, seq) => ({ seq, json: JSON.stringify(entry) }));\n+\treturn { log, project, source, frames };\n+}\n+\n+test(\"nonempty canonical history adopts in bounded restartable pages without Project.load\", (t) => {\n+\tconst { log, project: oracle, source, frames } = history();\n+\tt.mock.method(Project, \"load\", () => {\n+\t\tthrow new Error(\"full replay is forbidden\");\n+\t});\n+\tconst storage = new SqlState();\n+\tconst before = JSON.stringify(log.entries);\n+\tlet next = 0;\n+\twhile (next < frames.length) {\n+\t\tconst result = Project.adoptWriterPage(storage, {\n+\t\t\tsource,\n+\t\t\tfrom: next,\n+\t\t\tframes: frames.slice(next, next + 2),\n+\t\t\tmaxEntries: 2,\n+\t\t\tmaxBytes: 16_384,\n+\t\t\tcurrentSource: () => source,\n+\t\t});\n+\t\tassert.ok(result.entries <= 2 && result.bytes <= 16_384);\n+\t\tnext = result.next;\n+\t\tif (!result.ready) assert.throws(() => Project.openWriter(log, storage, next), /adoption is incomplete/);\n+\t}\n+\tassert.equal(JSON.stringify(log.entries), before, \"adoption never rewrites or appends canonical entries\");\n+\tconst reopened = Project.openWriter(log, storage, log.entries.length);\n+\tassert.deepEqual(reopened.files(), oracle.files());\n+\tassert.deepEqual(reopened.status(), oracle.status());\n+\tassert.deepEqual(reopened.changes(0), oracle.changes(0));\n+\tstorage.transaction(() => reopened.record(\"writer\", { \"a.txt\": \"after adoption\\n\" }, 30));\n+\tstorage.transaction(() => reopened.publish(\"writer\", \"After adoption\", 31));\n+\tassert.equal(Project.openWriter(log, storage, log.entries.length).files()[\"a.txt\"], \"after adoption\\n\");\n+\tstorage.db.close();\n+});\n+\n+test(\"adoption rejects stale source and rolls back a page if the source changes before commit\", () => {\n+\tconst { source, frames } = history();\n+\tconst storage = new SqlState();\n+\tconst snapshot = () => storage.db.prepare(\"SELECT * FROM state ORDER BY collection, key\").all();\n+\tconst input = { source, from: 0, frames: frames.slice(0, 2), maxEntries: 2, maxBytes: 16_384 };\n+\tlet calls = 0;\n+\tassert.throws(\n+\t\t() =>\n+\t\t\tProject.adoptWriterPage(storage, {\n+\t\t\t\t...input,\n+\t\t\t\tcurrentSource: () => (++calls === 1 ? source : { ...source, generation: source.generation + 1 }),\n+\t\t\t}),\n+\t\t/source changed during/,\n+\t);\n+\tassert.deepEqual(snapshot(), []);\n+\tProject.adoptWriterPage(storage, { ...input, currentSource: () => source });\n+\tconst before = snapshot();\n+\tassert.throws(\n+\t\t() => Project.adoptWriterPage(storage, { ...input, currentSource: () => source }),\n+\t\t/cursor does not match/,\n+\t);\n+\tassert.throws(\n+\t\t() =>\n+\t\t\tProject.adoptWriterPage(storage, {\n+\t\t\t\t...input,\n+\t\t\t\tfrom: 2,\n+\t\t\t\tsource: { ...source, generation: 9 },\n+\t\t\t\tcurrentSource: () => ({ ...source, generation: 9 }),\n+\t\t\t}),\n+\t\t/source or cursor/,\n+\t);\n+\tassert.deepEqual(snapshot(), before);\n+\tstorage.db.close();\n+});\n+\n+test(\"oversized and noncontiguous adoption pages leave no partial indexes\", () => {\n+\tconst { source, frames } = history();\n+\tfor (const page of [\n+\t\t{ frames: frames.slice(0, 2), maxEntries: 1, maxBytes: 16_384 },\n+\t\t{ frames: frames.slice(0, 2), maxEntries: 2, maxBytes: 1 },\n+\t\t{ frames: [frames[0]!, frames[2]!], maxEntries: 2, maxBytes: 16_384 },\n+\t]) {\n+\t\tconst storage = new SqlState();\n+\t\tassert.throws(\n+\t\t\t() => Project.adoptWriterPage(storage, { source, from: 0, currentSource: () => source, ...page }),\n+\t\t\t/bounds|bound|noncontiguous/,\n+\t\t);\n+\t\tassert.deepEqual(storage.db.prepare(\"SELECT * FROM state\").all(), []);\n+\t\tstorage.db.close();\n+\t}\n+});"},{"path":"worker/project/writer-agents.ts","added":54,"removed":0,"diff":"--- /dev/null\n+++ b/worker/project/writer-agents.ts\n@@ -0,0 +1,54 @@\n+import { type GraphStateStorage, StoredMap } from \"../../src/engine/state-source.ts\";\n+import type { AgentState } from \"./project-types.ts\";\n+\n+type StoredAgent = Omit<AgentState, \"told\" | \"parked\"> & {\n+\ttold: string[];\n+\tparked: [string, { base: number; mine: AgentState[\"mine\"] }][];\n+};\n+\n+/**\n+ * Identity map for agents touched by the current operation. Project's existing\n+ * reducers share mutable agent references, so copies cannot be substituted\n+ * halfway through an operation. Flush those rows with the canonical append,\n+ * then drop the references. Opening this map does not load any agents.\n+ */\n+export class WriterAgents extends StoredMap<string, AgentState> {\n+\treadonly #touched = new Map<string, AgentState>();\n+\tconstructor(storage: GraphStateStorage) {\n+\t\tsuper(storage, \"project:agents\", {\n+\t\t\tencode: (agent) => ({ ...agent, told: [...agent.told], parked: [...agent.parked] }),\n+\t\t\tdecode: (value) => {\n+\t\t\t\tconst agent = value as StoredAgent;\n+\t\t\t\treturn { ...agent, told: new Set(agent.told), parked: new Map(agent.parked) };\n+\t\t\t},\n+\t\t});\n+\t}\n+\toverride get(key: string): AgentState | undefined {\n+\t\tlet value = this.#touched.get(key);\n+\t\tif (!value) {\n+\t\t\tvalue = super.get(key);\n+\t\t\tif (value) this.#touched.set(key, value);\n+\t\t}\n+\t\treturn value;\n+\t}\n+\toverride set(key: string, value: AgentState): this {\n+\t\tsuper.set(key, value);\n+\t\tthis.#touched.set(key, value);\n+\t\treturn this;\n+\t}\n+\toverride delete(key: string): boolean {\n+\t\tthis.#touched.delete(key);\n+\t\treturn super.delete(key);\n+\t}\n+\toverride *entries(): MapIterator<[string, AgentState]> {\n+\t\tfor (const [key, stored] of super.entries()) {\n+\t\t\tlet value = this.#touched.get(key);\n+\t\t\tif (!value) this.#touched.set(key, (value = stored));\n+\t\t\tyield [key, value];\n+\t\t}\n+\t}\n+\tflush(): void {\n+\t\tfor (const [key, value] of this.#touched) super.set(key, value);\n+\t\tthis.#touched.clear();\n+\t}\n+}"}],"ci":null}