{"version":162,"agent":"codex-capacity-chair","message":"Add reviewed disk-first history and indexed graph storage for core issue 16; retain runtime activation gate","time":1791945013341,"timeIso":"2026-10-14T02:30:13.341Z","changes":75,"change":2341,"files":["client/src/api.ts","client/test/api-request-id.test.ts","server/README.md","server/src/decoded-frames.ts","server/src/disk-first-runtime.ts","server/src/engine-project.ts","server/src/history-host.ts","server/src/history-state.ts","server/src/json-chunk-cursor.ts","server/src/json-events.ts","server/src/project-object.ts","server/src/projection-store.ts","server/src/router.ts","server/src/stored-json-view.ts","server/src/stored-json.ts","server/src/writer-host.ts","server/test/atom-list-history.test.ts","server/test/decoded-adoption-bounds.test.ts","server/test/decoded-entry-adoption.test.ts","server/test/decoded-frames.test.ts","server/test/disk-first-runtime.test.ts","server/test/frame-chunks.test.ts","server/test/history-host.test.ts","server/test/history-recovery.test.ts","server/test/history-state.test.ts","server/test/json-chunk-cursor.test.ts","server/test/json-events.test.ts","server/test/long-text-history.test.ts","server/test/project-object-disk-first.test.ts","server/test/router.test.ts","server/test/stored-json-view.test.ts","server/test/stored-json.test.ts","server/test/streamed-history-host.test.ts","server/test/streamed-large-frame.test.ts","server/test/streamed-large-history.test.ts","server/test/streamed-writer-adoption.test.ts","server/test/writer-host.test.ts","src/engine/experimental/projection-atom-index.ts","src/engine/experimental/projection-locator.ts","src/engine/experimental/projection-marker.ts","src/engine/experimental/projection-priority.ts","src/engine/experimental/projection-sequence.ts","src/engine/graph.ts","src/engine/state-source.ts","src/engine/stored-text.ts","src/engine/test/graph-atom-list-integrity.test.ts","src/engine/test/graph-atom-list-rollback.test.ts","src/engine/test/graph-atom-lists.test.ts","src/engine/test/graph-deletion-pages.test.ts","src/engine/test/graph-deletion-rollback.test.ts","src/engine/test/graph-index-dedup.test.ts","src/engine/test/graph-insertion-integrity.test.ts","src/engine/test/graph-insertion-runs.test.ts","src/engine/test/graph-insertion-storage.test.ts","src/engine/test/graph-long-text.test.ts","src/engine/test/graph-move-write-membership.test.ts","src/engine/test/graph-replacement-membership.test.ts","src/engine/test/graph-validation-scratch.test.ts","src/engine/test/projection-locator.test.ts","src/engine/test/projection-marker.test.ts","src/engine/test/projection-priority.test.ts","src/engine/test/stored-list-array.test.ts","src/engine/test/stored-list-integrity.test.ts","src/engine/test/stored-text.test.ts","worker/project/collisions.ts","worker/project/land.ts","worker/project/news.ts","worker/project/project.ts","worker/project/projection-provider.ts","worker/project/test/collision-streaming.test.ts","worker/project/test/land-streaming.test.ts","worker/project/test/news-lazy.test.ts","worker/project/test/reviewers.test.ts","worker/project/test/where-many-agents.test.ts","worker/project/where.ts"],"draft":null,"diff":[{"path":"client/src/api.ts","added":6,"removed":1,"diff":"--- a/client/src/api.ts\n+++ b/client/src/api.ts\n@@ -2,6 +2,7 @@\n // except `run`, which sends a tar.gz and reads the answer as a stream of JSON\n // lines (box-run.ts).\n \n+import { randomUUID } from \"node:crypto\";\n import { setDefaultResultOrder } from \"node:dns\";\n import type {\n \tChangeAnswer,\n@@ -201,6 +202,7 @@\n \t\tif (this.config.visitor && method !== \"GET\")\n \t\t\tthrow new ApiError(`${path}: a folder that reads signed out sends only reads`);\n \t\tconst sent = body === undefined ? undefined : JSON.stringify(body);\n+\t\tconst requestId = method === \"POST\" ? randomUUID() : undefined;\n \t\tconst timeoutMs = Math.max(atLeastMs, timeoutFor(this.timeoutMs, sent));\n \t\t// A connection that never opened is tried once more, IPv4 first (#37, GAME - UI/UX: one IPv6\n \t\t// address timed out, and the same command went through seconds later). Nothing went out, so\n@@ -209,7 +211,10 @@\n \t\t\ttry {\n \t\t\t\tres = await this.send(this.url(path, server), {\n \t\t\t\t\tmethod,\n-\t\t\t\t\theaders: this.headers(sent === undefined ? undefined : \"application/json\"),\n+\t\t\t\t\theaders: {\n+\t\t\t\t\t\t...this.headers(sent === undefined ? undefined : \"application/json\"),\n+\t\t\t\t\t\t...(requestId ? { \"Idempotency-Key\": requestId } : {}),\n+\t\t\t\t\t},\n \t\t\t\t\t...(sent === undefined ? {} : { body: sent }),\n \t\t\t\t\tsignal: AbortSignal.timeout(timeoutMs),\n \t\t\t\t});"},{"path":"client/test/api-request-id.test.ts","added":20,"removed":0,"diff":"--- /dev/null\n+++ b/client/test/api-request-id.test.ts\n@@ -0,0 +1,20 @@\n+import assert from \"node:assert/strict\";\n+import { test } from \"node:test\";\n+import { Api } from \"../src/api.ts\";\n+\n+test(\"a logical JSON write retains its UUID across connection retry and later writes get new IDs\", async (t) => {\n+\tconst api = new Api({ server: \"https://example.invalid\", project: \"test\", agent: \"alice\" } as never);\n+\tconst ids: (string | null)[] = [];\n+\tt.mock.method(api, \"send\", async (_url: string, init: RequestInit) => {\n+\t\tids.push(new Headers(init.headers).get(\"Idempotency-Key\"));\n+\t\tif (ids.length === 1) throw Object.assign(Error(\"not connected\"), { cause: { code: \"ECONNREFUSED\" } });\n+\t\treturn Response.json({ ok: true });\n+\t});\n+\tawait api.json(\"POST\", \"/a/alice/record\", { files: {} });\n+\tawait api.json(\"POST\", \"/a/alice/record\", { files: {} });\n+\tawait api.json(\"GET\", \"/status\");\n+\tassert.match(ids[0]!, /^[0-9a-f-]{36}$/);\n+\tassert.equal(ids[1], ids[0]);\n+\tassert.notEqual(ids[2], ids[0]);\n+\tassert.equal(ids[3], null);\n+});"},{"path":"server/README.md","added":13,"removed":0,"diff":"--- a/server/README.md\n+++ b/server/README.md\n@@ -101,3 +101,16 @@\n   oversized projects, and runs the alarm that pushes out to Artifacts and takes plain git pushes in.\n - `src/issues/`: issues, asks and news.\n - The engine itself is `src/engine/` at the repository's root, the same one the client uses.\n+\n+### Experimental disk-first rollback floor\n+\n+Disk-first runtime format 4 is required before compressed projection-priority pages, chunked retry receipts chunked atom-text references or indexed atom-list references are written. Preparation upgrades a format-1, format-2 or format-3 namespace atomically. Older runtimes refuse that namespace before reading or writing; rolling back the executable does not make its derived data readable.\n+\n+To return to an older runtime, keep writes disabled and rebuild its derived writer, projection and historical namespaces from the canonical log using a compatible implementation. Do not lower the format marker in place. Preserve retry receipts or explicitly resolve outstanding retries before changing their storage format. This is an activation boundary, not authorization to delete project data. The canonical log is unchanged by the format upgrade.\n+\n+\n+Runtime format 3 also fences chunked atom-text references. Runtimes that only understand format 2 must refuse these derived namespaces. Do not lower the marker to roll back; rebuild compatible derived state while preserving canonical history and retry receipts.\n+\n+Format 4 additionally fences atom-list references. A format-3 executable must refuse a format-4 namespace; it cannot safely interpret the placeholder arrays.\n+\n+Format 5 additionally fences indexed insertion runs and lines. Preparation accepts recognized formats 1 through 4 and upgrades atomically. Older executables must refuse format 5. Never lower the marker to roll back."},{"path":"server/src/decoded-frames.ts","added":68,"removed":0,"diff":"--- /dev/null\n+++ b/server/src/decoded-frames.ts\n@@ -0,0 +1,68 @@\n+import { CachedStateStorage } from \"../../src/engine/state-source.ts\";\n+import type { WriterAdoptionFrame } from \"../../worker/project/project.ts\";\n+import type { Entry } from \"../../worker/project/project-types.ts\";\n+import type { SqliteLog, SqliteStorage } from \"./engine-project.ts\";\n+import { StoredJson, storeJson } from \"./stored-json.ts\";\n+import { storedJsonView } from \"./stored-json-view.ts\";\n+import { SqliteWriterState, writerFrameChunksDigest } from \"./writer-host.ts\";\n+\n+/** Keep decoded views alive through the complete page checkpoint, then remove their rows. */\n+export function withDecodedFrames<T>(\n+\tstorage: SqliteStorage,\n+\tnamespace: string,\n+\tlog: SqliteLog,\n+\tinput: { from: number; to: number; maxEntries: number; maxBytes: number; digest: string },\n+\tconsume: (frames: Iterable<WriterAdoptionFrame>) => T,\n+): { result: T; digest: string } {\n+\tif (\n+\t\t![input.from, input.to, input.maxEntries, input.maxBytes].every(Number.isSafeInteger) ||\n+\t\tinput.from < 0 ||\n+\t\tinput.to < input.from ||\n+\t\tinput.maxEntries < 1 ||\n+\t\tinput.maxEntries > 256 ||\n+\t\tinput.maxBytes < 1\n+\t)\n+\t\tthrow Error(\"invalid decoded frame page bounds\");\n+\treturn storage.transactionSync(() => {\n+\t\tSqliteWriterState.initialize(storage);\n+\t\tconst state = new SqliteWriterState(storage, namespace);\n+\t\t// Temporary nodes are immutable after parsing; cap retained reads for the whole page.\n+\t\tconst reads = new CachedStateStorage(state, 64 * 1024, 256);\n+\t\tif (\n+\t\t\tstorage.sql.exec(\"SELECT 1 AS present FROM writer_state WHERE namespace = ? LIMIT 1\", namespace).toArray().length\n+\t\t)\n+\t\t\tthrow Error(\"decoded frame namespace is occupied\");\n+\t\tlet digest = input.digest;\n+\t\tlet active = true;\n+\t\tconst frames = function* (): IterableIterator<WriterAdoptionFrame> {\n+\t\t\tlet bytes = 0;\n+\t\t\tfor (let seq = input.from; seq < input.to && seq < input.from + input.maxEntries; seq++) {\n+\t\t\t\tif (!active) throw Error(\"decoded frame page has ended\");\n+\t\t\t\tconst size = log.frameBytes(seq);\n+\t\t\t\tif (size > input.maxBytes - bytes) {\n+\t\t\t\t\tif (bytes) return;\n+\t\t\t\t\tthrow Error(\"decoded frame exceeds page byte bound\");\n+\t\t\t\t}\n+\t\t\t\tdigest = writerFrameChunksDigest(digest, seq, log.frameChunks(seq));\n+\t\t\t\tstoreJson(state, String(seq), log.frameChunks(seq));\n+\t\t\t\tbytes += size;\n+\t\t\t\tyield { seq, bytes: size, entry: storedJsonView(new StoredJson(reads, String(seq))) as Entry };\n+\t\t\t}\n+\t\t};\n+\t\ttry {\n+\t\t\tconst result = consume(frames());\n+\t\t\tif (\n+\t\t\t\tresult &&\n+\t\t\t\ttypeof result === \"object\" &&\n+\t\t\t\t(typeof (result as { then?: unknown }).then === \"function\" ||\n+\t\t\t\t\ttypeof (result as { next?: unknown }).next === \"function\")\n+\t\t\t)\n+\t\t\t\tthrow Error(\"decoded frame consumption must finish synchronously\");\n+\t\t\treturn { result: structuredClone(result), digest };\n+\t\t} finally {\n+\t\t\tactive = false;\n+\t\t\treads.clear();\n+\t\t\tstorage.sql.exec(\"DELETE FROM writer_state WHERE namespace = ?\", namespace);\n+\t\t}\n+\t});\n+}"},{"path":"server/src/disk-first-runtime.ts","added":98,"removed":14,"diff":"--- a/server/src/disk-first-runtime.ts\n+++ b/server/src/disk-first-runtime.ts\n@@ -1,12 +1,14 @@\n+import { createHash } from \"node:crypto\";\n import { canonicalJson } from \"../../worker/project/operation-protocol.ts\";\n import { Project, type WriterSource } from \"../../worker/project/project.ts\";\n import type { ProjectOptions } from \"../../worker/project/project-types.ts\";\n import { EngineProject, SqliteLog, type SqliteStorage } from \"./engine-project.ts\";\n+import { SqliteHistoryHost } from \"./history-host.ts\";\n import { SqliteProjectionStore } from \"./projection-store.ts\";\n import { SqliteWriterHost, SqliteWriterState } from \"./writer-host.ts\";\n \n type Services = Pick<ProjectOptions, \"hasBlob\" | \"whole\">;\n-type Progress = { ready: boolean; phase: \"empty\" | \"writer\" | \"projection\" | \"ready\"; next: number };\n+type Progress = { ready: boolean; phase: \"empty\" | \"writer\" | \"projection\" | \"history\" | \"ready\"; next: number };\n \n /** One synchronous page or call per invocation. No object retains a loaded Project.\n  * The owner schedules subsequent pages and supplies fresh authorization for every call. */\n@@ -15,10 +17,12 @@\n \treadonly #namespace: string;\n \treadonly #projection: SqliteProjectionStore;\n \treadonly #services: Services;\n+\treadonly #history: SqliteHistoryHost;\n \tconstructor(storage: SqliteStorage, database: string, namespace: string, services: Services = {}) {\n \t\tthis.#storage = storage;\n \t\tthis.#namespace = namespace;\n \t\tthis.#services = services;\n+\t\tthis.#history = new SqliteHistoryHost(storage, `${namespace}:history`);\n \t\tthis.#projection = new SqliteProjectionStore(\n \t\t\t{\n \t\t\t\tdatabase,\n@@ -31,11 +35,57 @@\n \t\t);\n \t}\n \t#host() {\n-\t\treturn new SqliteWriterHost(this.#storage, this.#namespace, this.#projection, { indexProjectionAtoms: true });\n+\t\treturn new SqliteWriterHost(this.#storage, this.#namespace, this.#projection, {\n+\t\t\tindexProjectionAtoms: true,\n+\t\t\thistory: this.#history,\n+\t\t});\n \t}\n \t#state() {\n \t\treturn new SqliteWriterState(this.#storage, this.#namespace);\n \t}\n+\t#saveReceipt(state: SqliteWriterState, id: string, identity: string, result: unknown) {\n+\t\t// Receipt payloads can exceed the graph-state value bound. Keep each stored\n+\t\t// piece small without increasing that bound for engine state.\n+\t\tconst json = JSON.stringify({ result });\n+\t\tconst characters = 64 * 1024;\n+\t\tconst parts = Math.ceil(json.length / characters);\n+\t\tfor (let part = 0; part < parts; part++)\n+\t\t\tstate.write(`runtime:receipt:${id}`, String(part), json.slice(part * characters, (part + 1) * characters));\n+\t\tstate.write(\"runtime:receipts\", id, {\n+\t\t\tformat: 3,\n+\t\t\tidentity,\n+\t\t\tparts,\n+\t\t\tcharacters: json.length,\n+\t\t\tdigest: createHash(\"sha256\").update(json).digest(\"hex\"),\n+\t\t});\n+\t}\n+\t#receiptResult<T>(\n+\t\tstate: SqliteWriterState,\n+\t\tid: string,\n+\t\treceipt: { format: number; result?: T; parts?: number; characters?: number; digest?: string },\n+\t): T {\n+\t\tif (receipt.format === 2) return structuredClone(receipt.result) as T;\n+\t\tif (\n+\t\t\treceipt.format !== 3 ||\n+\t\t\t!Number.isSafeInteger(receipt.parts) ||\n+\t\t\treceipt.parts! < 1 ||\n+\t\t\t!Number.isSafeInteger(receipt.characters) ||\n+\t\t\treceipt.characters! < 1 ||\n+\t\t\treceipt.parts !== Math.ceil(receipt.characters! / (64 * 1024))\n+\t\t)\n+\t\t\tthrow Error(\"invalid receipt header\");\n+\t\tlet json = \"\";\n+\t\tfor (let part = 0; part < receipt.parts!; part++) {\n+\t\t\tconst chunk = state.read(`runtime:receipt:${id}`, String(part));\n+\t\t\tif (typeof chunk !== \"string\" || chunk.length !== Math.min(64 * 1024, receipt.characters! - part * 64 * 1024))\n+\t\t\t\tthrow Error(\"incomplete receipt payload\");\n+\t\t\tjson += chunk;\n+\t\t}\n+\t\tif (createHash(\"sha256\").update(json).digest(\"hex\") !== receipt.digest)\n+\t\t\tthrow Error(\"receipt payload digest mismatch\");\n+\t\treturn (JSON.parse(json) as { result: T }).result;\n+\t}\n+\n \t#validate(validate: () => void) {\n \t\tconst result: unknown = validate();\n \t\tif (result && (typeof result === \"object\" || typeof result === \"function\") && \"then\" in result)\n@@ -45,19 +95,34 @@\n \t\tSqliteWriterState.initialize(this.#storage);\n \t\tconst state = this.#state();\n \t\tconst format = state.read(\"runtime\", \"format\");\n-\t\tif (format !== undefined && format !== 1) throw Error(\"unsupported disk-first runtime format\");\n-\t\tif (format === undefined) state.write(\"runtime\", \"format\", 1);\n+\t\tif (format !== undefined && format !== 1 && format !== 2 && format !== 3 && format !== 4 && format !== 5)\n+\t\t\tthrow Error(\"unsupported disk-first runtime format\");\n+\t\t// Format 5 additionally fences indexed insertion runs and lines from older readers.\n+\t\t// Never lower this marker in place.\n+\t\tif (format !== 5) state.write(\"runtime\", \"format\", 5);\n \t\treturn state;\n \t}\n \t/** Initializes an empty canonical log without replay. Existing history must be adopted. */\n-\tinitialize<T>(operation: (calls: EngineProject) => T, validate: () => void): T {\n+\tinitialize<T>(\n+\t\toperation: (calls: EngineProject) => T,\n+\t\tvalidate: () => void,\n+\t\trequest?: { id: string; identity: unknown },\n+\t): T {\n \t\treturn this.#storage.transactionSync(() => {\n \t\t\tthis.#validate(validate);\n \t\t\tconst log = new SqliteLog(this.#storage);\n \t\t\tif (log.seq() !== 0) throw Error(\"disk-first initialization requires an empty log\");\n+\t\t\tif (request && (!request.id || request.id.length > 128)) throw Error(\"invalid disk-first request identity\");\n \t\t\tconst project = new Project(log, { ...this.#services, now: () => Date.now(), shapes: log.shapes() });\n \t\t\tconst result = structuredClone(operation(new EngineProject(project)));\n \t\t\tthis.#validate(validate);\n+\t\t\tif (request && log.seq() > 0)\n+\t\t\t\tthis.#saveReceipt(\n+\t\t\t\t\tthis.#setup(),\n+\t\t\t\t\trequest.id,\n+\t\t\t\t\tcreateHash(\"sha256\").update(canonicalJson(request.identity)).digest(\"hex\"),\n+\t\t\t\t\tresult,\n+\t\t\t\t);\n \t\t\treturn result;\n \t\t});\n \t}\n@@ -75,6 +140,12 @@\n \t\t\tif (ready !== undefined && ready !== true) throw Error(\"invalid runtime readiness marker\");\n \t\t\tif (ready === true) {\n \t\t\t\tconst root = host.root();\n+\t\t\t\tconst history = this.#history.prepare(log, root, () => host.root(), validate);\n+\t\t\t\tif (!history.ready) {\n+\t\t\t\t\tstate.remove(\"runtime\", \"history-ready\");\n+\t\t\t\t\treturn { ready: false, phase: \"history\", next: history.next };\n+\t\t\t\t}\n+\t\t\t\tstate.write(\"runtime\", \"history-ready\", true);\n \t\t\t\tconst scope = this.#projection.open({ state, log, root });\n \t\t\t\tscope.close();\n \t\t\t\tthis.#validate(validate);\n@@ -91,7 +162,7 @@\n \t\t\t\t\t\tfrom: cursor?.next ?? 0,\n \t\t\t\t\t\tdigest: cursor?.digest ?? \"\",\n \t\t\t\t\t\tmaxEntries: 32,\n-\t\t\t\t\t\tmaxBytes: 1_048_576,\n+\t\t\t\t\t\tmaxBytes: log.adoptionPageBytes(cursor?.next ?? 0),\n \t\t\t\t\t},\n \t\t\t\t\tvalidate,\n \t\t\t\t);\n@@ -108,8 +179,13 @@\n \t\t\t\tmaxSteps: 32,\n \t\t\t});\n \t\t\tthis.#validate(validate);\n-\t\t\tif (page.ready) state.write(\"runtime\", \"ready\", true);\n-\t\t\treturn { ready: page.ready, phase: page.ready ? \"ready\" : \"projection\", next: root.logLength };\n+\t\t\tif (!page.ready) return { ready: false, phase: \"projection\", next: root.logLength };\n+\t\t\tconst history = this.#history.prepare(log, root, () => host.root(), validate);\n+\t\t\tif (history.ready) {\n+\t\t\t\tstate.write(\"runtime\", \"ready\", true);\n+\t\t\t\tstate.write(\"runtime\", \"history-ready\", true);\n+\t\t\t}\n+\t\t\treturn { ready: history.ready, phase: history.ready ? \"ready\" : \"history\", next: history.next };\n \t\t});\n \t}\n \t#requireReady() {\n@@ -118,7 +194,11 @@\n \t\t\t\t.length === 0\n \t\t)\n \t\t\tthrow Error(\"disk-first adoption is not complete\");\n-\t\tif (this.#state().read(\"runtime\", \"format\") !== 1 || this.#state().read(\"runtime\", \"ready\") !== true)\n+\t\tif (\n+\t\t\tthis.#state().read(\"runtime\", \"format\") !== 5 ||\n+\t\t\tthis.#state().read(\"runtime\", \"ready\") !== true ||\n+\t\t\tthis.#state().read(\"runtime\", \"history-ready\") !== true\n+\t\t)\n \t\t\tthrow Error(\"disk-first adoption is not complete\");\n \t}\n \tread<T>(operation: (calls: EngineProject) => T, validate: () => void): T {\n@@ -143,13 +223,17 @@\n \t\t\tconst host = this.#host();\n \t\t\thost.root();\n \t\t\tif (request && (!request.id || request.id.length > 128)) throw Error(\"invalid disk-first request identity\");\n-\t\t\tconst identity = request ? canonicalJson(request.identity) : undefined;\n+\t\t\tconst identity = request ? createHash(\"sha256\").update(canonicalJson(request.identity)).digest(\"hex\") : undefined;\n \t\t\tif (request) {\n-\t\t\t\tconst receipt = state.read(\"runtime:receipts\", request.id) as { identity: string; result: T } | undefined;\n+\t\t\t\tconst receipt = state.read(\"runtime:receipts\", request.id) as\n+\t\t\t\t\t| { format: number; identity: string; result: T }\n+\t\t\t\t\t| undefined;\n \t\t\t\tif (receipt) {\n-\t\t\t\t\tif (receipt.identity !== identity) throw Error(\"disk-first request identity was reused\");\n+\t\t\t\t\tif (receipt.format !== 2 && receipt.format !== 3) throw Error(\"unsupported disk-first receipt format\");\n+\t\t\t\t\tif (receipt.identity !== identity)\n+\t\t\t\t\t\tthrow Object.assign(Error(\"disk-first request identity was reused\"), { code: \"request-reused\" });\n \t\t\t\t\tthis.#validate(validate);\n-\t\t\t\t\treturn structuredClone(receipt.result);\n+\t\t\t\t\treturn this.#receiptResult<T>(state, request.id, receipt);\n \t\t\t\t}\n \t\t\t}\n \t\t\treturn host.runCalls({\n@@ -159,7 +243,7 @@\n \t\t\t\tcheckerReady: false,\n \t\t\t\toperation: (calls) => structuredClone(operation(calls)),\n \t\t\t\tcommitReceipt: (result) => {\n-\t\t\t\t\tif (request) state.write(\"runtime:receipts\", request.id, { identity, result });\n+\t\t\t\t\tif (request) this.#saveReceipt(state, request.id, identity!, result);\n \t\t\t\t},\n \t\t\t});\n \t\t});"},{"path":"server/src/engine-project.ts","added":55,"removed":1,"diff":"--- a/server/src/engine-project.ts\n+++ b/server/src/engine-project.ts\n@@ -96,6 +96,23 @@\n \t}\n \n \t/** Reject an oversized canonical frame before loading its text into JavaScript. */\n+\tframeBytes(seq: number): number {\n+\t\tif (!Number.isSafeInteger(seq) || seq < 0) throw Error(\"invalid canonical frame position\");\n+\t\tconst size = this.storage.sql\n+\t\t\t.exec(\n+\t\t\t\t\"SELECT COUNT(*) AS parts, COALESCE(SUM(LENGTH(CAST(text AS BLOB))), 0) AS bytes FROM log WHERE seq = ?\",\n+\t\t\t\tseq,\n+\t\t\t)\n+\t\t\t.toArray()[0] as { parts: number; bytes: number };\n+\t\tif (!size || size.parts < 1 || size.parts > 256 || size.bytes < 1 || !Number.isSafeInteger(size.bytes))\n+\t\t\tthrow Error(\"canonical frame exceeds hard decoding bound or is missing\");\n+\t\treturn size.bytes;\n+\t}\n+\t/** A larger first frame gets its own budget; later frames are deferred. */\n+\tadoptionPageBytes(from: number): number {\n+\t\treturn Math.max(1_048_576, this.frameBytes(from));\n+\t}\n+\n \tboundedFrame(seq: number, maxBytes: number): string {\n \t\tif (\n \t\t\t!Number.isSafeInteger(seq) ||\n@@ -122,6 +139,26 @@\n \t\treturn rows.map((row) => row.text).join(\"\");\n \t}\n \n+\t/** Stream one canonical frame without retaining its complete JSON text. */\n+\t*frameChunks(seq: number): IterableIterator<string> {\n+\t\tif (!Number.isSafeInteger(seq) || seq < 0) throw Error(\"invalid canonical frame position\");\n+\t\tlet expected = 0;\n+\t\tfor (;;) {\n+\t\t\tconst rows = this.storage.sql\n+\t\t\t\t.exec(\"SELECT part, text FROM log WHERE seq = ? AND part >= ? ORDER BY part LIMIT 1\", seq, expected)\n+\t\t\t\t.toArray() as { part: number; text: string }[];\n+\t\t\tif (!rows.length) {\n+\t\t\t\tif (!expected) throw Error(\"canonical frame is missing\");\n+\t\t\t\treturn;\n+\t\t\t}\n+\t\t\tconst row = rows[0]!;\n+\t\t\tif (row.part !== expected || row.text.length > LOG_PART_CHARACTERS)\n+\t\t\t\tthrow Error(\"canonical frame parts are incomplete or oversized\");\n+\t\t\texpected++;\n+\t\t\tyield row.text;\n+\t\t}\n+\t}\n+\n \t/** Refreshes the in-memory cursor after an enclosing transaction rolls back. */\n \trefreshSequence(): void {\n \t\tconst rows = this.storage.sql.exec(\"SELECT COALESCE(MAX(seq), -1) AS last FROM log\").toArray() as {\n@@ -524,11 +561,18 @@\n \t/** Reads stored entries by log position, for the feed and replay (#41); absent, those answer 501. */\n \tprivate readonly read: ((from: number, limit: number) => Entry[]) | undefined;\n \tprivate readonly store: SqliteLog | undefined;\n+\tprivate readonly historical: (<T>(at: number, operation: (project: Project) => T) => T) | undefined;\n \n-\tconstructor(project: Project, read?: (from: number, limit: number) => Entry[], store?: SqliteLog) {\n+\tconstructor(\n+\t\tproject: Project,\n+\t\tread?: (from: number, limit: number) => Entry[],\n+\t\tstore?: SqliteLog,\n+\t\thistorical?: <T>(at: number, operation: (project: Project) => T) => T,\n+\t) {\n \t\tthis.project = project;\n \t\tthis.read = read;\n \t\tthis.store = store;\n+\t\tthis.historical = historical;\n \t}\n \n \t/** The project's events from log position `from` (#41): reading consumes nothing. */\n@@ -638,6 +682,11 @@\n \t\treturn this.replica;\n \t}\n \tstatusAt(at: number) {\n+\t\tif (this.historical)\n+\t\t\treturn this.historical(Math.max(0, Math.min(at, this.project.logLength)), (p) => ({\n+\t\t\t\tat: Math.min(at, this.project.logLength),\n+\t\t\t\t...(p.initialized ? p.status() : { version: -1, agents: [] }),\n+\t\t\t}));\n \t\tconst p = this.at(at);\n \t\tconst answer = {\n \t\t\tat: Math.min(at, this.project.logLength),\n@@ -647,6 +696,11 @@\n \t\treturn answer;\n \t}\n \twhereAt(at: number) {\n+\t\tif (this.historical)\n+\t\t\treturn this.historical(Math.max(0, Math.min(at, this.project.logLength)), (p) => ({\n+\t\t\t\tat: Math.min(at, this.project.logLength),\n+\t\t\t\t...(p.initialized ? where(p) : { version: -1, files: {} }),\n+\t\t\t}));\n \t\tconst p = this.at(at);\n \t\tconst answer = {\n \t\t\tat: Math.min(at, this.project.logLength),"},{"path":"server/src/history-host.ts","added":247,"removed":0,"diff":"--- /dev/null\n+++ b/server/src/history-host.ts\n@@ -0,0 +1,247 @@\n+import { MemoryStore, Project } from \"../../worker/project/project.ts\";\n+import { withDecodedFrames } from \"./decoded-frames.ts\";\n+import type { SqliteLog, SqliteStorage } from \"./engine-project.ts\";\n+import { SqliteHistoryState } from \"./history-state.ts\";\n+import type { WriterProjectionSession } from \"./writer-host.ts\";\n+import { SqliteWriterState, type WriterRoot, writerFrameChunksDigest } from \"./writer-host.ts\";\n+\n+type Cursor = { root: WriterRoot; next: number; digest: string };\n+const same = (a: WriterRoot, b: WriterRoot) =>\n+\ta.format === b.format &&\n+\ta.generation === b.generation &&\n+\ta.logLength === b.logLength &&\n+\ta.sharedVersion === b.sharedVersion &&\n+\ta.digest === b.digest;\n+\n+/** Derived historical state, bound to the host's exact canonical root. */\n+export class SqliteHistoryHost {\n+\treadonly #storage: SqliteStorage;\n+\treadonly #namespace: string;\n+\treadonly #meta: SqliteWriterState;\n+\tconstructor(storage: SqliteStorage, namespace: string) {\n+\t\tif (!namespace || namespace.length > 80) throw Error(\"invalid historical host namespace\");\n+\t\tthis.#storage = storage;\n+\t\tthis.#namespace = namespace;\n+\t\tthis.#meta = new SqliteWriterState(storage, `${namespace}:control`);\n+\t}\n+\t#validate(root: WriterRoot, currentRoot: () => WriterRoot, authority: () => void) {\n+\t\tconst result: unknown = authority();\n+\t\tif (result && (typeof result === \"object\" || typeof result === \"function\") && \"then\" in result)\n+\t\t\tthrow Error(\"historical authority must be synchronous\");\n+\t\tif (!same(root, currentRoot())) throw Error(\"historical canonical root changed\");\n+\t}\n+\t#beginReset() {\n+\t\tthis.#meta.remove(\"history\", \"cursor\");\n+\t\tthis.#meta.remove(\"history\", \"verification\");\n+\t\tthis.#meta.write(\"history\", \"reset\", true);\n+\t\treturn { ready: false, next: 0 };\n+\t}\n+\t#resetPage() {\n+\t\tconst sql = this.#storage.sql;\n+\t\tconst clauses: [string, string, (string | number)[]][] = [\n+\t\t\t[\"writer_state\", \"namespace = ?\", [this.#namespace]],\n+\t\t\t[\n+\t\t\t\t\"writer_state\",\n+\t\t\t\t\"namespace >= ? AND namespace < ?\",\n+\t\t\t\t[`${this.#namespace}:history:`, `${this.#namespace}:history;`],\n+\t\t\t],\n+\t\t\t[\"writer_history_keys\", \"namespace = ?\", [this.#namespace]],\n+\t\t\t[\"writer_history_heads\", \"namespace = ?\", [this.#namespace]],\n+\t\t];\n+\t\tfor (const [table, condition, bindings] of clauses) {\n+\t\t\tconst rows = sql.exec(`SELECT rowid AS id FROM ${table} WHERE ${condition} LIMIT 256`, ...bindings).toArray() as {\n+\t\t\t\tid: number;\n+\t\t\t}[];\n+\t\t\tif (!rows.length) continue;\n+\t\t\tsql.exec(`DELETE FROM ${table} WHERE rowid IN (${rows.map(() => \"?\").join(\",\")})`, ...rows.map((row) => row.id));\n+\t\t\treturn { ready: false, next: 0 };\n+\t\t}\n+\t\tthis.#meta.remove(\"history\", \"reset\");\n+\t\treturn { ready: false, next: 0 };\n+\t}\n+\n+\tprepare(log: SqliteLog, root: WriterRoot, currentRoot: () => WriterRoot, authority: () => void) {\n+\t\treturn this.#storage.transactionSync(() => {\n+\t\t\tthis.#validate(root, currentRoot, authority);\n+\t\t\tSqliteHistoryState.initialize(this.#storage);\n+\t\t\tif (this.#meta.read(\"history\", \"reset\") === true) {\n+\t\t\t\tconst result = this.#resetPage();\n+\t\t\t\tthis.#validate(root, currentRoot, authority);\n+\t\t\t\treturn result;\n+\t\t\t}\n+\t\t\tlet cursor = this.#meta.read(\"history\", \"cursor\") as Cursor | undefined;\n+\t\t\tif (cursor && !same(cursor.root, root)) {\n+\t\t\t\tif (cursor.next > root.logLength) return this.#beginReset();\n+\t\t\t\tconst saved = this.#meta.read(\"history\", \"verification\") as Cursor | undefined;\n+\t\t\t\tconst verification = saved && same(saved.root, root) ? saved : { root, next: 0, digest: \"\" };\n+\t\t\t\tconst budget = log.adoptionPageBytes(verification.next);\n+\t\t\t\tlet bytes = 0,\n+\t\t\t\t\tcount = 0;\n+\t\t\t\twhile (verification.next < cursor.next && count < 32) {\n+\t\t\t\t\tconst size = log.frameBytes(verification.next);\n+\t\t\t\t\tif (bytes && size > budget - bytes) break;\n+\t\t\t\t\tverification.digest = writerFrameChunksDigest(\n+\t\t\t\t\t\tverification.digest,\n+\t\t\t\t\t\tverification.next,\n+\t\t\t\t\t\tlog.frameChunks(verification.next),\n+\t\t\t\t\t);\n+\t\t\t\t\tverification.next++;\n+\t\t\t\t\tbytes += size;\n+\t\t\t\t\tcount++;\n+\t\t\t\t}\n+\t\t\t\tthis.#validate(root, currentRoot, authority);\n+\t\t\t\tif (verification.next < cursor.next) {\n+\t\t\t\t\tthis.#meta.write(\"history\", \"verification\", verification);\n+\t\t\t\t\treturn { ready: false, next: cursor.next };\n+\t\t\t\t}\n+\t\t\t\tif (verification.digest !== cursor.digest) return this.#beginReset();\n+\t\t\t\tcursor = { ...cursor, root };\n+\t\t\t\tthis.#meta.write(\"history\", \"cursor\", cursor);\n+\t\t\t\tthis.#meta.remove(\"history\", \"verification\");\n+\t\t\t}\n+\t\t\tif (cursor?.next === root.logLength) return { ready: true, next: cursor.next };\n+\t\t\tconst from = cursor?.next ?? 0;\n+\t\t\tconst state = new SqliteHistoryState(this.#storage, this.#namespace, from);\n+\t\t\tlet digest = cursor?.digest ?? \"\";\n+\t\t\tconst budget = log.adoptionPageBytes(from);\n+\t\t\tconst decoded = withDecodedFrames(\n+\t\t\t\tthis.#storage,\n+\t\t\t\t`${this.#namespace}:decoded`,\n+\t\t\t\tlog,\n+\t\t\t\t{ from, to: root.logLength, maxEntries: 32, maxBytes: budget, digest },\n+\t\t\t\t(frames) => {\n+\t\t\t\t\tconst page =\n+\t\t\t\t\t\tfrom > 0\n+\t\t\t\t\t\t\t? (() => {\n+\t\t\t\t\t\t\t\t\tconst extended = Project.extendHistoricalPage(state, {\n+\t\t\t\t\t\t\t\t\t\tfrom,\n+\t\t\t\t\t\t\t\t\t\tframes,\n+\t\t\t\t\t\t\t\t\t\tmaxEntries: 32,\n+\t\t\t\t\t\t\t\t\t\tmaxBytes: budget,\n+\t\t\t\t\t\t\t\t\t\tdecodedFrames: true,\n+\t\t\t\t\t\t\t\t\t\tbeginRevision: (revision) => state.beginRevision(revision),\n+\t\t\t\t\t\t\t\t\t\tvalidateAuthority: () => this.#validate(root, currentRoot, authority),\n+\t\t\t\t\t\t\t\t\t});\n+\t\t\t\t\t\t\t\t\treturn { ...extended, ready: extended.next === root.logLength };\n+\t\t\t\t\t\t\t\t})()\n+\t\t\t\t\t\t\t: Project.adoptWriterPage(state, {\n+\t\t\t\t\t\t\t\t\tsource: root,\n+\t\t\t\t\t\t\t\t\tfrom,\n+\t\t\t\t\t\t\t\t\tframes,\n+\t\t\t\t\t\t\t\t\tmaxEntries: 32,\n+\t\t\t\t\t\t\t\t\tmaxBytes: budget,\n+\t\t\t\t\t\t\t\t\tdecodedFrames: true,\n+\t\t\t\t\t\t\t\t\tcurrentSource: () => currentRoot(),\n+\t\t\t\t\t\t\t\t\tbeginRevision: (revision) => state.beginRevision(revision),\n+\t\t\t\t\t\t\t\t});\n+\t\t\t\t\treturn page;\n+\t\t\t\t},\n+\t\t\t);\n+\t\t\tconst page = decoded.result;\n+\t\t\tdigest = decoded.digest;\n+\t\t\tif (page.ready && digest !== root.digest) throw Error(\"historical canonical digest mismatch\");\n+\t\t\tthis.#validate(root, currentRoot, authority);\n+\t\t\tstate.seal();\n+\t\t\tthis.#meta.write(\"history\", \"cursor\", { root, next: page.next, digest } satisfies Cursor);\n+\t\t\treturn { ready: page.ready, next: page.next };\n+\t\t});\n+\t}\n+\t/** Called inside the canonical writer transaction, before its receipt commits. */\n+\tadvance(\n+\t\tlog: SqliteLog,\n+\t\tprevious: WriterRoot,\n+\t\tcommitted: WriterRoot,\n+\t\tcurrentRoot: () => WriterRoot,\n+\t\tauthority: () => void,\n+\t): void {\n+\t\tthis.#storage.transactionSync(() => {\n+\t\t\tconst validate = () => this.#validate(committed, currentRoot, authority);\n+\t\t\tvalidate();\n+\t\t\tconst cursor = this.#meta.read(\"history\", \"cursor\") as Cursor | undefined;\n+\t\t\tif (\n+\t\t\t\t!cursor ||\n+\t\t\t\t!same(cursor.root, previous) ||\n+\t\t\t\tcursor.next !== previous.logLength ||\n+\t\t\t\tcursor.digest !== previous.digest\n+\t\t\t)\n+\t\t\t\tthrow Error(\"historical committed prefix is stale\");\n+\t\t\tif (committed.logLength < previous.logLength || committed.generation < previous.generation)\n+\t\t\t\tthrow Error(\"historical root cannot move backwards\");\n+\t\t\tlet from = previous.logLength,\n+\t\t\t\tdigest = previous.digest;\n+\t\t\twhile (from < committed.logLength) {\n+\t\t\t\tconst budget = log.adoptionPageBytes(from);\n+\t\t\t\tconst state = new SqliteHistoryState(this.#storage, this.#namespace, from);\n+\t\t\t\tconst decoded = withDecodedFrames(\n+\t\t\t\t\tthis.#storage,\n+\t\t\t\t\t`${this.#namespace}:decoded`,\n+\t\t\t\t\tlog,\n+\t\t\t\t\t{ from, to: committed.logLength, maxEntries: 32, maxBytes: budget, digest },\n+\t\t\t\t\t(frames) => {\n+\t\t\t\t\t\tconst page = Project.extendHistoricalPage(state, {\n+\t\t\t\t\t\t\tfrom,\n+\t\t\t\t\t\t\tframes,\n+\t\t\t\t\t\t\tmaxEntries: 32,\n+\t\t\t\t\t\t\tmaxBytes: budget,\n+\t\t\t\t\t\t\tdecodedFrames: true,\n+\t\t\t\t\t\t\tbeginRevision: (revision) => state.beginRevision(revision),\n+\t\t\t\t\t\t\tvalidateAuthority: validate,\n+\t\t\t\t\t\t});\n+\t\t\t\t\t\treturn page;\n+\t\t\t\t\t},\n+\t\t\t\t);\n+\t\t\t\tconst page = decoded.result;\n+\t\t\t\tdigest = decoded.digest;\n+\t\t\t\tstate.seal();\n+\t\t\t\tfrom = page.next;\n+\t\t\t}\n+\t\t\tif (digest !== committed.digest) throw Error(\"historical canonical tail digest mismatch\");\n+\t\t\tvalidate();\n+\t\t\tthis.#meta.write(\"history\", \"cursor\", { root: committed, next: from, digest } satisfies Cursor);\n+\t\t});\n+\t}\n+\tread<T>(\n+\t\troot: WriterRoot,\n+\t\tcurrentRoot: () => WriterRoot,\n+\t\tauthority: () => void,\n+\t\tat: number,\n+\t\toperation: (project: Project) => T,\n+\t\tviewProvider?: WriterProjectionSession[\"historicalReadViewProvider\"],\n+\t): T {\n+\t\treturn this.#storage.transactionSync(() => {\n+\t\t\tlet active = true;\n+\t\t\tconst assertScope = () => {\n+\t\t\t\tif (!active) throw Error(\"historical scope ended\");\n+\t\t\t};\n+\t\t\tconst validate = () => {\n+\t\t\t\tassertScope();\n+\t\t\t\tthis.#validate(root, currentRoot, authority);\n+\t\t\t};\n+\t\t\ttry {\n+\t\t\t\tvalidate();\n+\t\t\t\tconst cursor = this.#meta.read(\"history\", \"cursor\") as Cursor | undefined;\n+\t\t\t\tif (!cursor || !same(cursor.root, root) || cursor.next !== root.logLength || cursor.digest !== root.digest)\n+\t\t\t\t\tthrow Error(\"historical state is not ready for canonical root\");\n+\t\t\t\tif (!Number.isSafeInteger(at) || at < 0 || at > root.logLength)\n+\t\t\t\t\tthrow Error(\"historical position outside authority\");\n+\t\t\t\tconst state = new SqliteHistoryState(this.#storage, this.#namespace, root.logLength);\n+\t\t\t\tconst historical = state.at(at, assertScope);\n+\t\t\t\tconst project =\n+\t\t\t\t\tat === 0\n+\t\t\t\t\t\t? new Project(new MemoryStore())\n+\t\t\t\t\t\t: Project.openHistorical(\n+\t\t\t\t\t\t\t\thistorical,\n+\t\t\t\t\t\t\t\tat,\n+\t\t\t\t\t\t\t\tnew SqliteWriterState(this.#storage, `${this.#namespace}:scratch`),\n+\t\t\t\t\t\t\t\tassertScope,\n+\t\t\t\t\t\t\t\tviewProvider?.(historical),\n+\t\t\t\t\t\t\t);\n+\t\t\t\tconst result = structuredClone(operation(project));\n+\t\t\t\tvalidate();\n+\t\t\t\treturn result;\n+\t\t\t} finally {\n+\t\t\t\tactive = false;\n+\t\t\t}\n+\t\t});\n+\t}\n+}"},{"path":"server/src/history-state.ts","added":180,"removed":0,"diff":"--- /dev/null\n+++ b/server/src/history-state.ts\n@@ -0,0 +1,180 @@\n+import type { GraphStateStorage } from \"../../src/engine/state-source.ts\";\n+import type { SqliteStorage } from \"./engine-project.ts\";\n+import { SqliteWriterState } from \"./writer-host.ts\";\n+\n+/** Derived history for a freshly adopted writer namespace. The host supplies\n+ * canonical log positions and commits this state with the canonical transaction. */\n+export class SqliteHistoryState implements GraphStateStorage {\n+\treadonly #storage: SqliteStorage;\n+\treadonly #namespace: string;\n+\treadonly #current: SqliteWriterState;\n+\t#revision: number;\n+\t#sealedThrough = -1;\n+\tstatic initialize(storage: SqliteStorage): void {\n+\t\tSqliteWriterState.initialize(storage);\n+\t\tstorage.sql.exec(\n+\t\t\t\"CREATE TABLE IF NOT EXISTS writer_history_keys (namespace TEXT NOT NULL, collection TEXT NOT NULL, key TEXT NOT NULL, revision INTEGER NOT NULL, deleted INTEGER NOT NULL, PRIMARY KEY(namespace, collection, key, revision))\",\n+\t\t);\n+\t\tstorage.sql.exec(\n+\t\t\t\"CREATE TABLE IF NOT EXISTS writer_history_heads (namespace TEXT PRIMARY KEY, sealed INTEGER NOT NULL)\",\n+\t\t);\n+\t}\n+\tconstructor(storage: SqliteStorage, namespace: string, revision = 0) {\n+\t\tif (!namespace || namespace.length > 80) throw Error(\"invalid history namespace\");\n+\t\tif (!Number.isSafeInteger(revision) || revision < 0) throw Error(\"invalid history revision\");\n+\t\tthis.#storage = storage;\n+\t\tthis.#namespace = namespace;\n+\t\tthis.#current = new SqliteWriterState(storage, namespace);\n+\t\tthis.#revision = revision;\n+\t}\n+\tbeginRevision(revision: number): void {\n+\t\tif (!Number.isSafeInteger(revision) || revision < this.#revision)\n+\t\t\tthrow Error(\"history revision must not go backwards\");\n+\t\tif (revision > this.#revision) this.seal();\n+\t\tthis.#revision = revision;\n+\t}\n+\t#sealed(): number {\n+\t\treturn (\n+\t\t\t(\n+\t\t\t\tthis.#storage.sql\n+\t\t\t\t\t.exec(\"SELECT sealed FROM writer_history_heads WHERE namespace = ?\", this.#namespace)\n+\t\t\t\t\t.toArray()[0] as { sealed: number } | undefined\n+\t\t\t)?.sealed ?? -1\n+\t\t);\n+\t}\n+\tseal(): void {\n+\t\tthis.#storage.sql.exec(\n+\t\t\t\"INSERT INTO writer_history_heads VALUES (?, ?) ON CONFLICT(namespace) DO UPDATE SET sealed = MAX(sealed, excluded.sealed)\",\n+\t\t\tthis.#namespace,\n+\t\t\tthis.#revision,\n+\t\t);\n+\t\tthis.#sealedThrough = this.#revision;\n+\t}\n+\t#savedNamespace(revision: number): string {\n+\t\treturn `${this.#namespace}:history:${revision}`;\n+\t}\n+\tread(collection: string, key: string): unknown {\n+\t\treturn this.#current.read(collection, key);\n+\t}\n+\tentries(collection: string): Iterable<readonly [string, unknown]> {\n+\t\treturn this.#current.entries(collection);\n+\t}\n+\twrite(collection: string, key: string, value: unknown): void {\n+\t\tif (this.#revision <= Math.max(this.#sealedThrough, this.#sealed())) throw Error(\"historical revision is sealed\");\n+\t\tthis.transaction(() => {\n+\t\t\tthis.#current.write(collection, key, value);\n+\t\t\tconst saved = this.#savedNamespace(this.#revision);\n+\t\t\tthis.#storage.sql.exec(\n+\t\t\t\t\"DELETE FROM writer_state WHERE namespace = ? AND collection = ? AND key = ?\",\n+\t\t\t\tsaved,\n+\t\t\t\tcollection,\n+\t\t\t\tkey,\n+\t\t\t);\n+\t\t\tthis.#storage.sql.exec(\n+\t\t\t\t\"INSERT INTO writer_state SELECT ?, collection, key, part, value FROM writer_state WHERE namespace = ? AND collection = ? AND key = ?\",\n+\t\t\t\tsaved,\n+\t\t\t\tthis.#namespace,\n+\t\t\t\tcollection,\n+\t\t\t\tkey,\n+\t\t\t);\n+\t\t\tthis.#storage.sql.exec(\n+\t\t\t\t\"INSERT OR REPLACE INTO writer_history_keys VALUES (?, ?, ?, ?, 0)\",\n+\t\t\t\tthis.#namespace,\n+\t\t\t\tcollection,\n+\t\t\t\tkey,\n+\t\t\t\tthis.#revision,\n+\t\t\t);\n+\t\t});\n+\t}\n+\tremove(collection: string, key: string): void {\n+\t\tif (this.#revision <= Math.max(this.#sealedThrough, this.#sealed())) throw Error(\"historical revision is sealed\");\n+\t\tthis.transaction(() => {\n+\t\t\tthis.#current.remove(collection, key);\n+\t\t\tnew SqliteWriterState(this.#storage, this.#savedNamespace(this.#revision)).remove(collection, key);\n+\t\t\tthis.#storage.sql.exec(\n+\t\t\t\t\"INSERT OR REPLACE INTO writer_history_keys VALUES (?, ?, ?, ?, 1)\",\n+\t\t\t\tthis.#namespace,\n+\t\t\t\tcollection,\n+\t\t\t\tkey,\n+\t\t\t\tthis.#revision,\n+\t\t\t);\n+\t\t});\n+\t}\n+\ttransaction<T>(body: () => T): T {\n+\t\tconst revision = this.#revision;\n+\t\tconst sealed = this.#sealedThrough;\n+\t\ttry {\n+\t\t\treturn this.#storage.transactionSync(body);\n+\t\t} catch (error) {\n+\t\t\tthis.#revision = revision;\n+\t\t\tthis.#sealedThrough = sealed;\n+\t\t\tthrow error;\n+\t\t}\n+\t}\n+\t/** Read-only historical values, with bounded key pages and value decoding. */\n+\tat(revision: number, assertAuthority: () => void = () => {}): GraphStateStorage {\n+\t\tassertAuthority();\n+\t\tif (!Number.isSafeInteger(revision) || revision < 0 || revision > this.#revision)\n+\t\t\tthrow Error(\"history position outside authority\");\n+\t\tif (revision > this.#sealed()) throw Error(\"historical revision is not sealed\");\n+\t\tconst storage = this.#storage,\n+\t\t\tnamespace = this.#namespace;\n+\t\tconst read = (collection: string, key: string): unknown => {\n+\t\t\tassertAuthority();\n+\t\t\tconst row = storage.sql\n+\t\t\t\t.exec(\n+\t\t\t\t\t\"SELECT revision, deleted FROM writer_history_keys WHERE namespace = ? AND collection = ? AND key = ? AND revision <= ? ORDER BY revision DESC LIMIT 1\",\n+\t\t\t\t\tnamespace,\n+\t\t\t\t\tcollection,\n+\t\t\t\t\tkey,\n+\t\t\t\t\trevision,\n+\t\t\t\t)\n+\t\t\t\t.toArray()[0] as { revision: number; deleted: number } | undefined;\n+\t\t\tif (!row || row.deleted) return undefined;\n+\t\t\treturn new SqliteWriterState(storage, this.#savedNamespace(row.revision)).read(collection, key);\n+\t\t};\n+\t\tconst refuse = (): never => {\n+\t\t\tthrow Error(\"historical state is read-only\");\n+\t\t};\n+\t\treturn {\n+\t\t\tread,\n+\t\t\t*entries(collection) {\n+\t\t\t\tlet after: string | undefined;\n+\t\t\t\tfor (;;) {\n+\t\t\t\t\tassertAuthority();\n+\t\t\t\t\tconst rows = storage.sql\n+\t\t\t\t\t\t.exec(\n+\t\t\t\t\t\t\t`SELECT key FROM writer_history_keys WHERE namespace = ? AND collection = ? AND revision <= ? ${after === undefined ? \"\" : \"AND key > ?\"} GROUP BY key ORDER BY key LIMIT 64`,\n+\t\t\t\t\t\t\tnamespace,\n+\t\t\t\t\t\t\tcollection,\n+\t\t\t\t\t\t\trevision,\n+\t\t\t\t\t\t\t...(after === undefined ? [] : [after]),\n+\t\t\t\t\t\t)\n+\t\t\t\t\t\t.toArray() as { key: string }[];\n+\t\t\t\t\tif (!rows.length) return;\n+\t\t\t\t\tfor (const row of rows) {\n+\t\t\t\t\t\tconst value = read(collection, row.key);\n+\t\t\t\t\t\t// Stored undefined is a value; deletion is determined by the ledger.\n+\t\t\t\t\t\tconst latest = storage.sql\n+\t\t\t\t\t\t\t.exec(\n+\t\t\t\t\t\t\t\t\"SELECT deleted FROM writer_history_keys WHERE namespace = ? AND collection = ? AND key = ? AND revision <= ? ORDER BY revision DESC LIMIT 1\",\n+\t\t\t\t\t\t\t\tnamespace,\n+\t\t\t\t\t\t\t\tcollection,\n+\t\t\t\t\t\t\t\trow.key,\n+\t\t\t\t\t\t\t\trevision,\n+\t\t\t\t\t\t\t)\n+\t\t\t\t\t\t\t.toArray()[0] as { deleted: number };\n+\t\t\t\t\t\tif (!latest.deleted) yield [row.key, value] as const;\n+\t\t\t\t\t}\n+\t\t\t\t\tafter = rows.at(-1)!.key;\n+\t\t\t\t}\n+\t\t\t},\n+\t\t\twrite: refuse,\n+\t\t\tremove: refuse,\n+\t\t\ttransaction: (body) => {\n+\t\t\t\tassertAuthority();\n+\t\t\t\treturn storage.transactionSync(body);\n+\t\t\t},\n+\t\t};\n+\t}\n+}"},{"path":"server/src/json-chunk-cursor.ts","added":68,"removed":0,"diff":"--- /dev/null\n+++ b/server/src/json-chunk-cursor.ts\n@@ -0,0 +1,68 @@\n+/** Incremental UTF-16 cursor over canonical log chunks. */\n+export class JsonChunkCursor {\n+\treadonly #input: Iterator<string>;\n+\t#chunk = \"\";\n+\t#offset = 0;\n+\tconstructor(chunks: Iterable<string>) {\n+\t\tthis.#input = chunks[Symbol.iterator]();\n+\t}\n+\tpeek(): string | undefined {\n+\t\twhile (this.#offset === this.#chunk.length) {\n+\t\t\tconst next = this.#input.next();\n+\t\t\tif (next.done) return undefined;\n+\t\t\tif (typeof next.value !== \"string\" || next.value.length > 600000) throw Error(\"invalid JSON input chunk\");\n+\t\t\tthis.#chunk = next.value;\n+\t\t\tthis.#offset = 0;\n+\t\t}\n+\t\treturn this.#chunk[this.#offset];\n+\t}\n+\ttake(): string {\n+\t\tconst char = this.peek();\n+\t\tif (char === undefined) throw Error(\"truncated JSON input\");\n+\t\tthis.#offset++;\n+\t\treturn char;\n+\t}\n+\t/** Consume one quoted JSON string, yielding bounded decoded text. */\n+\t*stringChunks(): IterableIterator<string> {\n+\t\tif (this.take() !== '\"') throw Error(\"expected JSON string\");\n+\t\tlet buffer = \"\";\n+\t\tfor (;;) {\n+\t\t\tlet char = this.take();\n+\t\t\tif (char === '\"') {\n+\t\t\t\tif (buffer) yield buffer;\n+\t\t\t\treturn;\n+\t\t\t}\n+\t\t\tif (char.charCodeAt(0) < 32) throw Error(\"unescaped JSON control character\");\n+\t\t\tif (char === \"\\\\\") {\n+\t\t\t\tconst escape = this.take();\n+\t\t\t\tconst simple: Record<string, string> = {\n+\t\t\t\t\t'\"': '\"',\n+\t\t\t\t\t\"\\\\\": \"\\\\\",\n+\t\t\t\t\t\"/\": \"/\",\n+\t\t\t\t\tb: \"\\b\",\n+\t\t\t\t\tf: \"\\f\",\n+\t\t\t\t\tn: \"\\n\",\n+\t\t\t\t\tr: \"\\r\",\n+\t\t\t\t\tt: \"\\t\",\n+\t\t\t\t};\n+\t\t\t\tif (escape === \"u\") {\n+\t\t\t\t\tlet hex = \"\";\n+\t\t\t\t\tfor (let i = 0; i < 4; i++) hex += this.take();\n+\t\t\t\t\tif (!/^[0-9a-fA-F]{4}$/.test(hex)) throw Error(\"invalid JSON Unicode escape\");\n+\t\t\t\t\tchar = String.fromCharCode(Number.parseInt(hex, 16));\n+\t\t\t\t} else {\n+\t\t\t\t\tif (!Object.hasOwn(simple, escape)) throw Error(\"invalid JSON escape\");\n+\t\t\t\t\tchar = simple[escape]!;\n+\t\t\t\t}\n+\t\t\t}\n+\t\t\tbuffer += char;\n+\t\t\tif (buffer.length === 16384) {\n+\t\t\t\tyield buffer;\n+\t\t\t\tbuffer = \"\";\n+\t\t\t}\n+\t\t}\n+\t}\n+\tclose(): void {\n+\t\tthis.#input.return?.();\n+\t}\n+}"},{"path":"server/src/json-events.ts","added":74,"removed":0,"diff":"--- /dev/null\n+++ b/server/src/json-events.ts\n@@ -0,0 +1,74 @@\n+import { JsonChunkCursor } from \"./json-chunk-cursor.ts\";\n+\n+export type JsonEvent =\n+\t| { kind: \"object\" | \"array\" | \"end\" | \"string\" | \"string-end\" }\n+\t| { kind: \"key\" | \"text\"; value: string }\n+\t| { kind: \"value\"; value: number | boolean | null };\n+\n+/** Structural JSON decoding. Retains nesting and one bounded string fragment, not a decoded tree. */\n+export function* jsonEvents(chunks: Iterable<string>): IterableIterator<JsonEvent> {\n+\tconst cursor = new JsonChunkCursor(chunks);\n+\tconst whitespace = () => {\n+\t\twhile (cursor.peek() !== undefined && /[ \\t\\n\\r]/.test(cursor.peek()!)) cursor.take();\n+\t};\n+\tfunction* value(depth: number): IterableIterator<JsonEvent> {\n+\t\tif (depth > 128) throw Error(\"JSON nesting exceeds bound\");\n+\t\twhitespace();\n+\t\tconst first = cursor.peek();\n+\t\tif (first === '\"') {\n+\t\t\tyield { kind: \"string\" };\n+\t\t\tfor (const text of cursor.stringChunks()) yield { kind: \"text\", value: text };\n+\t\t\tyield { kind: \"string-end\" };\n+\t\t\treturn;\n+\t\t}\n+\t\tif (first === \"{\" || first === \"[\") {\n+\t\t\tconst object = cursor.take() === \"{\";\n+\t\t\tconst close = object ? \"}\" : \"]\";\n+\t\t\tyield { kind: object ? \"object\" : \"array\" };\n+\t\t\twhitespace();\n+\t\t\tif (cursor.peek() === close) {\n+\t\t\t\tcursor.take();\n+\t\t\t\tyield { kind: \"end\" };\n+\t\t\t\treturn;\n+\t\t\t}\n+\t\t\tfor (;;) {\n+\t\t\t\tif (object) {\n+\t\t\t\t\twhitespace();\n+\t\t\t\t\tlet key = \"\";\n+\t\t\t\t\tfor (const text of cursor.stringChunks()) {\n+\t\t\t\t\t\tkey += text;\n+\t\t\t\t\t\tif (key.length > 4096) throw Error(\"JSON key exceeds bound\");\n+\t\t\t\t\t}\n+\t\t\t\t\tyield { kind: \"key\", value: key };\n+\t\t\t\t\twhitespace();\n+\t\t\t\t\tif (cursor.take() !== \":\") throw Error(\"expected JSON colon\");\n+\t\t\t\t}\n+\t\t\t\tyield* value(depth + 1);\n+\t\t\t\twhitespace();\n+\t\t\t\tconst separator = cursor.take();\n+\t\t\t\tif (separator === close) break;\n+\t\t\t\tif (separator !== \",\") throw Error(\"expected JSON separator\");\n+\t\t\t}\n+\t\t\tyield { kind: \"end\" };\n+\t\t\treturn;\n+\t\t}\n+\t\tlet token = \"\";\n+\t\twhile (cursor.peek() !== undefined && !/[ \\t\\n\\r,\\]}]/.test(cursor.peek()!)) {\n+\t\t\ttoken += cursor.take();\n+\t\t\tif (token.length > 256) throw Error(\"JSON scalar exceeds bound\");\n+\t\t}\n+\t\tif (token === \"true\" || token === \"false\" || token === \"null\") {\n+\t\t\tyield { kind: \"value\", value: token === \"null\" ? null : token === \"true\" };\n+\t\t} else {\n+\t\t\tif (!/^-?(?:0|[1-9][0-9]*)(?:\\.[0-9]+)?(?:[eE][+-]?[0-9]+)?$/.test(token)) throw Error(\"invalid JSON scalar\");\n+\t\t\tyield { kind: \"value\", value: Number(token) };\n+\t\t}\n+\t}\n+\ttry {\n+\t\tyield* value(0);\n+\t\twhitespace();\n+\t\tif (cursor.peek() !== undefined) throw Error(\"trailing JSON input\");\n+\t} finally {\n+\t\tcursor.close();\n+\t}\n+}"},{"path":"server/src/project-object.ts","added":70,"removed":13,"diff":"--- a/server/src/project-object.ts\n+++ b/server/src/project-object.ts\n@@ -4,8 +4,10 @@\n // R2 copies, edge cache, probes or disk-first writer.\n \n import { DurableObject } from \"cloudflare:workers\";\n-import { type Answer, answer, type Readers } from \"../../worker/project/http.ts\";\n+import { createHash } from \"node:crypto\";\n+import { type Answer, answer, type Readers, readerAnswer } from \"../../worker/project/http.ts\";\n import type { ProjectCalls, ProjectHistory } from \"../../worker/project/project-api.ts\";\n+import { ProjectError } from \"../../worker/project/project-error.ts\";\n import { BLOB_MAX, BlobStore } from \"./blobs.ts\";\n import { DiskFirstRuntime } from \"./disk-first-runtime.ts\";\n import { EngineProject, SqliteLog } from \"./engine-project.ts\";\n@@ -163,6 +165,7 @@\n \t\tbody: unknown,\n \t\thow: string | undefined,\n \t\trevision: number,\n+\t\trequest?: { id: string; principal: string },\n \t): Promise<Answer> {\n \t\tconst runtime = this.diskRuntime()!;\n \t\tconst validate = () => {\n@@ -170,7 +173,11 @@\n \t\t\t\tthrow Object.assign(Error(\"project authorization changed during call setup\"), { code: \"authority-changed\" });\n \t\t};\n \t\tconst progress = await this.prepareDisk(validate);\n-\t\tconst known = new Set((await this.ctx.storage.get<string[]>(\"readers\")) ?? []);\n+\t\tconst legacyReaders = (await this.ctx.storage.get<string[]>(\"readers\")) ?? [];\n+\t\tconst storedReaders = progress?.ready\n+\t\t\t? (new SqliteWriterState(this.ctx.storage, \"server-disk-v1\").read(\"runtime\", \"readers\") as string[] | undefined)\n+\t\t\t: undefined;\n+\t\tconst known = new Set(storedReaders ?? legacyReaders);\n \t\tvalidate();\n \t\tlet readersChanged = false;\n \t\tconst readers: Readers = {\n@@ -187,25 +194,44 @@\n \t\t\treturn { status: 404, body: { error: \"no such project; run init first\" } };\n \t\tif (!progress?.ready && !(progress?.phase === \"empty\" && op === \"init\"))\n \t\t\treturn { status: 503, body: { error: \"project indexes are being prepared\", retryAfter: 1, progress } };\n+\t\tif (agent && op !== \"reader\") {\n+\t\t\tconst refused = readerAnswer({ status: () => undefined }, op, agent, body, readers);\n+\t\t\tif (refused) return refused;\n+\t\t}\n \t\tconst before = new SqliteLog(this.ctx.storage).seq();\n \t\tconst action = (calls: EngineProject) => {\n \t\t\tconst result = answer(calls, op, agent, body, readers, how);\n \t\t\tif (result.status >= 500) throw Error(`project operation failed: ${JSON.stringify(result.body)}`);\n+\t\t\tif (readersChanged)\n+\t\t\t\tnew SqliteWriterState(this.ctx.storage, \"server-disk-v1\").write(\"runtime\", \"readers\", readers.list());\n \t\t\treturn result;\n \t\t};\n \n+\t\tconst receipt = request\n+\t\t\t? {\n+\t\t\t\t\tid: `http:${createHash(\"sha256\").update(request.principal).digest(\"hex\")}:${request.id}`,\n+\t\t\t\t\tidentity: {\n+\t\t\t\t\t\tproject: name,\n+\t\t\t\t\t\tprincipal: request.principal,\n+\t\t\t\t\t\tagent: agent ?? null,\n+\t\t\t\t\t\toperation: op,\n+\t\t\t\t\t\tbody: body ?? null,\n+\t\t\t\t\t\thow: how ?? null,\n+\t\t\t\t\t},\n+\t\t\t\t}\n+\t\t\t: undefined;\n \t\tconst result =\n \t\t\tprogress.phase === \"empty\"\n-\t\t\t\t? runtime.initialize(action, validate)\n+\t\t\t\t? runtime.initialize(action, validate, receipt)\n \t\t\t\t: READ_OPS.has(op) || op.startsWith(\"change/\")\n \t\t\t\t\t? runtime.read(action, validate)\n-\t\t\t\t\t: runtime.write(action, validate);\n+\t\t\t\t\t: runtime.write(action, validate, receipt);\n+\n \t\tif (readersChanged) {\n \t\t\tthis.authorityRevision++;\n-\t\t\tawait this.ctx.storage.put(\"readers\", readers.list());\n \t\t}\n \t\tconst log = new SqliteLog(this.ctx.storage);\n-\t\tif (log.seq() !== before) {\n+\t\tif (log.seq() !== before || (request && !READ_OPS.has(op))) {\n \t\t\tthis.wake();\n \t\t\tawait this.ctx.storage.put(\"name\", name);\n \t\t\tawait this.soon(Date.now() + 100);\n@@ -345,20 +371,38 @@\n \t\tinFeed = false,\n \t\thow?: string,\n \t\tkey?: KeyForCall,\n+\t\trequestId?: string,\n \t): Promise<Answer> {\n \t\tconst revision = this.authorityRevision;\n+\t\tlet principal = \"shared-token\";\n+\t\tif (\n+\t\t\trequestId !== undefined &&\n+\t\t\t!/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i.test(requestId)\n+\t\t)\n+\t\t\treturn { status: 400, body: { error: \"Idempotency-Key must be a UUID\" } };\n \t\tif (key) {\n \t\t\tconst decided = await this.checkAgentKey(key.presented, agent, key.address);\n \t\t\tif (!decided.ok) return { status: decided.status, body: { error: decided.error } };\n \t\t\tconst allowed = keyAllows(decided.role, { write: key.write, agent, route: key.route });\n \t\t\tif (!allowed.ok) return { status: allowed.status, body: { error: allowed.error } };\n \t\t\thow = decided.as;\n+\t\t\tprincipal = `key:${decided.id}`;\n \t\t}\n \t\tif (op === \"feed\" && !inFeed) return this.feed(name, body);\n \t\tif (this.diskRuntime()) {\n \t\t\ttry {\n-\t\t\t\treturn await this.diskCall(name, op, agent, body, how, revision);\n+\t\t\t\treturn await this.diskCall(\n+\t\t\t\t\tname,\n+\t\t\t\t\top,\n+\t\t\t\t\tagent,\n+\t\t\t\t\tbody,\n+\t\t\t\t\thow,\n+\t\t\t\t\trevision,\n+\t\t\t\t\trequestId ? { id: requestId, principal } : undefined,\n+\t\t\t\t);\n \t\t\t} catch (error) {\n+\t\t\t\tif ((error as { code?: string })?.code === \"request-reused\")\n+\t\t\t\t\treturn { status: 409, body: { error: \"Idempotency-Key was reused for a different request\" } };\n \t\t\t\tif ((error as { code?: string })?.code === \"authority-changed\")\n \t\t\t\t\treturn { status: 409, body: { error: \"project authorization changed; retry the request\", retryable: true } };\n \t\t\t\tthrow error;\n@@ -499,14 +543,27 @@\n \t\t\tif (found) await this.ctx.storage.put(\"git:head\", found.head);\n \t\t\treturn null;\n \t\t}\n+\t\t// Unexpected failures leave the cursor unacknowledged for retry. Engine\n+\t\t// refusals are recorded and acknowledged so a later fixing commit can advance.\n+\t\tconst ingest = (p: EngineProject) =>\n+\t\t\tp.ingest({ author: found.author, base: found.base, commits: found.commits }, Date.now());\n+\t\tconst runtime = this.diskRuntime();\n \t\tlet result: unknown;\n \t\ttry {\n-\t\t\tresult = this.useProject(\n-\t\t\t\t(p) => p.ingest({ author: found.author, base: found.base, commits: found.commits }, Date.now()),\n-\t\t\t\ttrue,\n-\t\t\t);\n-\t\t} catch (e) {\n-\t\t\tresult = { error: e instanceof Error ? e.message : String(e) };\n+\t\t\tresult = runtime\n+\t\t\t\t? runtime.write(ingest, () => {}, {\n+\t\t\t\t\t\tid: `git:${found.head}`,\n+\t\t\t\t\t\tidentity: {\n+\t\t\t\t\t\t\tproject: name,\n+\t\t\t\t\t\t\thead: found.head,\n+\t\t\t\t\t\t\tbase: found.base,\n+\t\t\t\t\t\t\tcommits: found.commits.map((commit) => commit.sha),\n+\t\t\t\t\t\t},\n+\t\t\t\t\t})\n+\t\t\t\t: this.useProject(ingest, true);\n+\t\t} catch (error) {\n+\t\t\tif (!(error instanceof ProjectError)) throw error;\n+\t\t\tresult = { error: error.message };\n \t\t}\n \t\tconst taken = {\n \t\t\tat: new Date().toISOString(),"},{"path":"server/src/projection-store.ts","added":85,"removed":31,"diff":"--- a/server/src/projection-store.ts\n+++ b/server/src/projection-store.ts\n@@ -10,7 +10,7 @@\n } from \"../../src/engine/experimental/projection-root.ts\";\n import { ProjectionSnapshots } from \"../../src/engine/experimental/projection-snapshots.ts\";\n import { Graph } from \"../../src/engine/graph.ts\";\n-import { CachedStateStorage } from \"../../src/engine/state-source.ts\";\n+import { CachedStateStorage, type GraphStateStorage } from \"../../src/engine/state-source.ts\";\n import { canonicalJson } from \"../../worker/project/operation-protocol.ts\";\n import { projectedReader } from \"../../worker/project/projection-provider.ts\";\n import { Membership, type Published } from \"../../worker/project/spaces.ts\";\n@@ -326,7 +326,8 @@\n \t\tconst token = {};\n \t\tconst overlays: ProjectionOverlayStorage[] = [];\n \t\tconst scopes: ProjectionReadScope[] = [];\n-\t\tconst versions = new Membership(state).shared.versions;\n+\t\tconst membership = new Membership(state);\n+\t\tconst versions = membership.shared.versions;\n \t\tconst current = (): WriterRoot => {\n \t\t\tif (!live) throw Error(\"closed projection writer\");\n \t\t\tif (log.seq() === observed.logLength && log.generation() !== observed.generation)\n@@ -339,45 +340,98 @@\n \t\t\t\t});\n \t\t\treturn observed;\n \t\t};\n-\t\treturn {\n-\t\t\treadViewProvider: (graph) => {\n+\t\tconst provider =\n+\t\t\t(membershipState: GraphStateStorage): WriterProjectionSession[\"readViewProvider\"] =>\n+\t\t\t(graph) => {\n+\t\t\t\tconst membership = new Membership(membershipState);\n+\t\t\t\tconst versions = membership.shared.versions;\n \t\t\t\tconst scope = new ProjectionReadScope(graph, () => (live ? token : undefined));\n \t\t\t\tscopes.push(scope);\n+\t\t\t\tconst readers = new Map<string, ReturnType<typeof projectedReader>>();\n+\t\t\t\tlet identity = \"\";\n+\t\t\t\tconst reuse = (key: string, build: () => ReturnType<typeof projectedReader>) => {\n+\t\t\t\t\tconst source = current();\n+\t\t\t\t\tconst next = JSON.stringify([\n+\t\t\t\t\t\tgraph.size,\n+\t\t\t\t\t\tsource.generation,\n+\t\t\t\t\t\tsource.logLength,\n+\t\t\t\t\t\tsource.digest,\n+\t\t\t\t\t\tversions.length,\n+\t\t\t\t\t]);\n+\t\t\t\t\tif (next !== identity) {\n+\t\t\t\t\t\treaders.clear();\n+\t\t\t\t\t\tidentity = next;\n+\t\t\t\t\t}\n+\t\t\t\t\tconst cacheable = key.length <= 8192 && /^(?:v|a) @/.test(key);\n+\t\t\t\t\tconst cached = cacheable ? readers.get(key) : undefined;\n+\t\t\t\t\tif (cached) {\n+\t\t\t\t\t\tscope.guard(graph)();\n+\t\t\t\t\t\treturn cached;\n+\t\t\t\t\t}\n+\t\t\t\t\tconst reader = build();\n+\t\t\t\t\tif (cacheable) {\n+\t\t\t\t\t\tif (readers.size >= 32) readers.delete(readers.keys().next().value!);\n+\t\t\t\t\t\treaders.set(key, reader);\n+\t\t\t\t\t}\n+\t\t\t\t\treturn reader;\n+\t\t\t\t};\n \t\t\t\treturn {\n \t\t\t\t\tkeyed: (key) =>\n-\t\t\t\t\t\tprojectedReader(\n-\t\t\t\t\t\t\t{\n-\t\t\t\t\t\t\t\tgraph,\n-\t\t\t\t\t\t\t\tcontext: this.#context,\n-\t\t\t\t\t\t\t\tsourceGeneration: this.#generation,\n-\t\t\t\t\t\t\t\tsourceLength: () => current().logLength,\n-\t\t\t\t\t\t\t\tprefixDigest: (length) =>\n-\t\t\t\t\t\t\t\t\tlength === current().logLength\n-\t\t\t\t\t\t\t\t\t\t? current().digest\n-\t\t\t\t\t\t\t\t\t\t: (state.read(`${this.#meta}:prefixes`, String(length)) as string | undefined),\n-\t\t\t\t\t\t\t\tversion: () => versions.length - 1,\n-\t\t\t\t\t\t\t\tcommitted: () => head,\n-\t\t\t\t\t\t\t\tat: (version) => state.read(`${this.#meta}:versions`, String(version)) as ProjectionHandle | undefined,\n-\t\t\t\t\t\t\t\tdelta: (version) => versions[version],\n-\t\t\t\t\t\t\t\tguard: () => scope.guard(graph),\n-\t\t\t\t\t\t\t\tallocate: () => {\n-\t\t\t\t\t\t\t\t\tconst overlay = new ProjectionOverlayStorage(\n-\t\t\t\t\t\t\t\t\t\tstate,\n-\t\t\t\t\t\t\t\t\t\t`${this.#context.namespace}:${this.#nextOverlay++}`,\n-\t\t\t\t\t\t\t\t\t\t(collection) => state.clearProjectionOverlay(collection),\n-\t\t\t\t\t\t\t\t\t);\n-\t\t\t\t\t\t\t\t\toverlays.push(overlay);\n-\t\t\t\t\t\t\t\t\treturn new CachedStateStorage(overlay, overlays.length <= 32 ? 8192 : 0, 32);\n+\t\t\t\t\t\treuse(key, () =>\n+\t\t\t\t\t\t\tprojectedReader(\n+\t\t\t\t\t\t\t\t{\n+\t\t\t\t\t\t\t\t\tgraph,\n+\t\t\t\t\t\t\t\t\tcontext: this.#context,\n+\t\t\t\t\t\t\t\t\tsourceGeneration: this.#generation,\n+\t\t\t\t\t\t\t\t\tsourceLength: () => current().logLength,\n+\t\t\t\t\t\t\t\t\tprefixDigest: (length) =>\n+\t\t\t\t\t\t\t\t\t\tlength === current().logLength\n+\t\t\t\t\t\t\t\t\t\t\t? current().digest\n+\t\t\t\t\t\t\t\t\t\t\t: (state.read(`${this.#meta}:prefixes`, String(length)) as string | undefined),\n+\t\t\t\t\t\t\t\t\tversion: () => versions.length - 1,\n+\t\t\t\t\t\t\t\t\tcommitted: () => head,\n+\t\t\t\t\t\t\t\t\tat: (version) =>\n+\t\t\t\t\t\t\t\t\t\tstate.read(`${this.#meta}:versions`, String(version)) as ProjectionHandle | undefined,\n+\t\t\t\t\t\t\t\t\tdelta: (version) => versions[version],\n+\t\t\t\t\t\t\t\t\tnamedVersion: (name, version) => {\n+\t\t\t\t\t\t\t\t\t\tconst space = membership.spaces.get(name);\n+\t\t\t\t\t\t\t\t\t\tconst selected = space?.versions[version];\n+\t\t\t\t\t\t\t\t\t\tif (!space || selected?.sharedBase === undefined) return undefined;\n+\t\t\t\t\t\t\t\t\t\treturn {\n+\t\t\t\t\t\t\t\t\t\t\tsharedBase: selected.sharedBase,\n+\t\t\t\t\t\t\t\t\t\t\tatoms: (function* () {\n+\t\t\t\t\t\t\t\t\t\t\t\tfor (let at = 0; at <= version; at++) {\n+\t\t\t\t\t\t\t\t\t\t\t\t\tconst delta = space.versions[at]!;\n+\t\t\t\t\t\t\t\t\t\t\t\t\tif (delta.dropped?.length) throw Error(\"unexpected named draft removal\");\n+\t\t\t\t\t\t\t\t\t\t\t\t\tyield* delta.atoms;\n+\t\t\t\t\t\t\t\t\t\t\t\t}\n+\t\t\t\t\t\t\t\t\t\t\t})(),\n+\t\t\t\t\t\t\t\t\t\t};\n+\t\t\t\t\t\t\t\t\t},\n+\t\t\t\t\t\t\t\t\tguard: () => scope.guard(graph),\n+\t\t\t\t\t\t\t\t\tallocate: () => {\n+\t\t\t\t\t\t\t\t\t\tconst overlay = new ProjectionOverlayStorage(\n+\t\t\t\t\t\t\t\t\t\t\tstate,\n+\t\t\t\t\t\t\t\t\t\t\t`${this.#context.namespace}:${this.#nextOverlay++}`,\n+\t\t\t\t\t\t\t\t\t\t\t(collection) => state.clearProjectionOverlay(collection),\n+\t\t\t\t\t\t\t\t\t\t);\n+\t\t\t\t\t\t\t\t\t\toverlays.push(overlay);\n+\t\t\t\t\t\t\t\t\t\treturn new CachedStateStorage(overlay, overlays.length <= 32 ? 65_536 : 0, 256);\n+\t\t\t\t\t\t\t\t\t},\n \t\t\t\t\t\t\t\t},\n-\t\t\t\t\t\t\t},\n-\t\t\t\t\t\t\tkey,\n+\t\t\t\t\t\t\t\tkey,\n+\t\t\t\t\t\t\t),\n \t\t\t\t\t\t),\n \t\t\t\t};\n-\t\t\t},\n+\t\t\t};\n+\t\treturn {\n+\t\t\treadViewProvider: provider(state),\n+\t\t\thistoricalReadViewProvider: provider,\n \t\t\tcommit: (project, committed) => {\n \t\t\t\tif (canonicalJson(current()) !== canonicalJson(committed)) throw Error(\"projection commit source mismatch\");\n+\t\t\t\tconst commitState = new CachedStateStorage(state, 65_536, 256);\n \t\t\t\tconst adapter = new ExperimentalMarkerProjection(\n-\t\t\t\t\tstate,\n+\t\t\t\t\tcommitState,\n \t\t\t\t\tproject.graph,\n \t\t\t\t\tthis.#context.defaultFile,\n \t\t\t\t\tthis.#context.namespace,"},{"path":"server/src/router.ts","added":10,"removed":1,"diff":"--- a/server/src/router.ts\n+++ b/server/src/router.ts\n@@ -257,7 +257,16 @@\n \t\tbody = { ...rest, ...(/^[\\w.+-]{1,20}\\/[\\w.+-]{1,40}$/.test(client) ? { client } : {}) };\n \t}\n \ttry {\n-\t\tconst a = (await obj.call(project, (op ?? top)!, agent, body, false, how, keyForCall)) as unknown as Answer;\n+\t\tconst a = (await obj.call(\n+\t\t\tproject,\n+\t\t\t(op ?? top)!,\n+\t\t\tagent,\n+\t\t\tbody,\n+\t\t\tfalse,\n+\t\t\thow,\n+\t\t\tkeyForCall,\n+\t\t\trequest.headers.get(\"Idempotency-Key\") ?? undefined,\n+\t\t)) as unknown as Answer;\n \t\treturn json(a.status, a.body);\n \t} catch (e) {\n \t\tconst error = `the project object failed: ${e instanceof Error ? e.message : String(e)}`;"},{"path":"server/src/stored-json-view.ts","added":56,"removed":0,"diff":"--- /dev/null\n+++ b/server/src/stored-json-view.ts\n@@ -0,0 +1,56 @@\n+import type { StoredJson } from \"./stored-json.ts\";\n+\n+/** Read-only JSON view. Containers stay on disk; a requested string is materialized explicitly. */\n+export function storedJsonView(node: StoredJson): unknown {\n+\tconst kind = node.kind;\n+\tif (kind === \"value\") return node.scalar();\n+\tif (kind === \"string\") return [...node.textChunks()].join(\"\");\n+\tconst array = kind === \"array\";\n+\tconst target = array ? [] : Object.create(null);\n+\tconst index = (key: PropertyKey): number | undefined => {\n+\t\tif (typeof key !== \"string\" || !/^(0|[1-9][0-9]*)$/.test(key)) return undefined;\n+\t\tconst value = Number(key);\n+\t\treturn Number.isSafeInteger(value) ? value : undefined;\n+\t};\n+\tconst child = (key: PropertyKey) => {\n+\t\tif (typeof key !== \"string\") return undefined;\n+\t\tif (!array) return node.child(key);\n+\t\tconst position = index(key);\n+\t\treturn position === undefined ? undefined : node.child(position);\n+\t};\n+\treturn new Proxy(target, {\n+\t\tget(target, key, receiver) {\n+\t\t\tif (array && key === \"length\") return node.length;\n+\t\t\tconst value = child(key);\n+\t\t\tif (value) return storedJsonView(value);\n+\t\t\treturn array ? Reflect.get(target, key, receiver) : undefined;\n+\t\t},\n+\t\thas(target, key) {\n+\t\t\treturn !!child(key) || (array && Reflect.has(target, key));\n+\t\t},\n+\t\townKeys() {\n+\t\t\treturn array\n+\t\t\t\t? [...Array.from({ length: node.length }, (_, i) => String(i)), \"length\"]\n+\t\t\t\t: [...node.properties()].map(([key]) => key);\n+\t\t},\n+\t\tgetOwnPropertyDescriptor(target, key) {\n+\t\t\tif (array && key === \"length\") return { ...Reflect.getOwnPropertyDescriptor(target, key)!, value: node.length };\n+\t\t\tconst value = child(key);\n+\t\t\treturn value\n+\t\t\t\t? { configurable: true, enumerable: true, writable: false, value: storedJsonView(value) }\n+\t\t\t\t: undefined;\n+\t\t},\n+\t\tset() {\n+\t\t\tthrow Error(\"stored JSON view is read-only\");\n+\t\t},\n+\t\tdefineProperty() {\n+\t\t\tthrow Error(\"stored JSON view is read-only\");\n+\t\t},\n+\t\tdeleteProperty() {\n+\t\t\tthrow Error(\"stored JSON view is read-only\");\n+\t\t},\n+\t\tpreventExtensions() {\n+\t\t\tthrow Error(\"stored JSON view is read-only\");\n+\t\t},\n+\t});\n+}"},{"path":"server/src/stored-json.ts","added":150,"removed":0,"diff":"--- /dev/null\n+++ b/server/src/stored-json.ts\n@@ -0,0 +1,150 @@\n+import type { GraphStateStorage } from \"../../src/engine/state-source.ts\";\n+import { StoredText } from \"../../src/engine/stored-text.ts\";\n+import { type JsonEvent, jsonEvents } from \"./json-events.ts\";\n+\n+/** Temporary decoded JSON on disk. A root is published only after complete parsing. */\n+export function storeJson(storage: GraphStateStorage, namespace: string, chunks: Iterable<string>): number {\n+\treturn storage.transaction(() => {\n+\t\tif (storage.read(namespace, \"root\") !== undefined) throw Error(\"decoded JSON already exists\");\n+\t\tconst events = jsonEvents(chunks);\n+\t\tlet nextId = 0;\n+\t\tconst take = (): JsonEvent => {\n+\t\t\tconst event = events.next();\n+\t\t\tif (event.done) throw Error(\"truncated JSON events\");\n+\t\t\treturn event.value;\n+\t\t};\n+\t\tconst text = new StoredText(storage, `${namespace}:text`);\n+\t\tconst value = (event = take()): number => {\n+\t\t\tconst id = nextId++;\n+\t\t\tif (!Number.isSafeInteger(nextId)) throw Error(\"decoded JSON identity overflow\");\n+\t\t\tif (event.kind === \"value\")\n+\t\t\t\tstorage.write(namespace, String(id), {\n+\t\t\t\t\tkind: \"value\",\n+\t\t\t\t\tvalue: typeof event.value === \"number\" ? String(event.value) : event.value,\n+\t\t\t\t\tnumber: typeof event.value === \"number\",\n+\t\t\t\t\tnegativeZero: Object.is(event.value, -0),\n+\t\t\t\t});\n+\t\t\telse if (event.kind === \"string\") {\n+\t\t\t\ttext.writeChunks(\n+\t\t\t\t\tString(id),\n+\t\t\t\t\t(function* () {\n+\t\t\t\t\t\tfor (;;) {\n+\t\t\t\t\t\t\tconst part = take();\n+\t\t\t\t\t\t\tif (part.kind === \"string-end\") return;\n+\t\t\t\t\t\t\tif (part.kind !== \"text\") throw Error(\"invalid JSON string events\");\n+\t\t\t\t\t\t\tyield part.value;\n+\t\t\t\t\t\t}\n+\t\t\t\t\t})(),\n+\t\t\t\t);\n+\t\t\t\tstorage.write(namespace, String(id), { kind: \"string\" });\n+\t\t\t} else if (event.kind === \"array\" || event.kind === \"object\") {\n+\t\t\t\tlet count = 0;\n+\t\t\t\tfor (;;) {\n+\t\t\t\t\tconst child = take();\n+\t\t\t\t\tif (child.kind === \"end\") break;\n+\t\t\t\t\tif (event.kind === \"object\" && child.kind !== \"key\") throw Error(\"invalid JSON object events\");\n+\t\t\t\t\tconst key = child.kind === \"key\" ? child.value : String(count);\n+\t\t\t\t\tconst childId = value(event.kind === \"object\" ? take() : child);\n+\t\t\t\t\tconst edge = JSON.stringify([id, key]);\n+\t\t\t\t\tif (event.kind === \"object\" && storage.read(`${namespace}:edges`, edge) === undefined) {\n+\t\t\t\t\t\tstorage.write(`${namespace}:keys`, JSON.stringify([id, count]), key);\n+\t\t\t\t\t\tcount++;\n+\t\t\t\t\t}\n+\t\t\t\t\tstorage.write(`${namespace}:edges`, edge, childId);\n+\t\t\t\t\tif (event.kind === \"array\") count++;\n+\t\t\t\t}\n+\t\t\t\tstorage.write(namespace, String(id), { kind: event.kind, count });\n+\t\t\t} else throw Error(\"invalid JSON value event\");\n+\t\t\treturn id;\n+\t\t};\n+\t\ttry {\n+\t\t\tconst root = value();\n+\t\t\tif (!events.next().done) throw Error(\"trailing JSON events\");\n+\t\t\tstorage.write(namespace, \"root\", { format: 1, id: root, nodes: nextId });\n+\t\t\treturn root;\n+\t\t} finally {\n+\t\t\tevents.return?.();\n+\t\t}\n+\t});\n+}\n+\n+/** A disk-backed JSON node. Child lookup does not decode siblings or string payloads. */\n+export class StoredJson {\n+\treadonly storage: GraphStateStorage;\n+\treadonly namespace: string;\n+\treadonly id: number;\n+\treadonly nodes: number;\n+\tconstructor(storage: GraphStateStorage, namespace: string, id?: number) {\n+\t\tthis.storage = storage;\n+\t\tthis.namespace = namespace;\n+\t\tconst root = storage.read(namespace, \"root\") as { format: number; id: number; nodes: number } | undefined;\n+\t\tif (root?.format !== 1 || !Number.isSafeInteger(root.nodes) || root.nodes < 1 || root.id !== 0)\n+\t\t\tthrow Error(\"invalid stored JSON root\");\n+\t\tthis.nodes = root.nodes;\n+\t\tthis.id = id ?? root.id;\n+\t\tif (!Number.isSafeInteger(this.id) || this.id < 0 || this.id >= this.nodes)\n+\t\t\tthrow Error(\"invalid stored JSON identity\");\n+\t}\n+\tprivate node(): { kind: string; count?: number; value?: unknown; number?: boolean; negativeZero?: boolean } {\n+\t\tconst node = this.storage.read(this.namespace, String(this.id)) as\n+\t\t\t| { kind: string; count?: number; value?: unknown; number?: boolean; negativeZero?: boolean }\n+\t\t\t| undefined;\n+\t\tif (!node || ![\"array\", \"object\", \"string\", \"value\"].includes(node.kind)) throw Error(\"invalid stored JSON node\");\n+\t\treturn node;\n+\t}\n+\tget kind(): string {\n+\t\treturn this.node().kind;\n+\t}\n+\tget length(): number {\n+\t\tconst node = this.node();\n+\t\tif (node.kind !== \"array\" || !Number.isSafeInteger(node.count) || node.count! < 0)\n+\t\t\tthrow Error(\"invalid stored JSON array\");\n+\t\treturn node.count!;\n+\t}\n+\tchild(key: string | number): StoredJson | undefined {\n+\t\tconst node = this.node();\n+\t\tif (node.kind !== \"object\" && node.kind !== \"array\") throw Error(\"stored JSON node is not a container\");\n+\t\tif (\n+\t\t\tnode.kind === \"array\" &&\n+\t\t\t(typeof key !== \"number\" || !Number.isSafeInteger(key) || key < 0 || key >= this.length)\n+\t\t)\n+\t\t\treturn undefined;\n+\t\tconst id = this.storage.read(`${this.namespace}:edges`, JSON.stringify([this.id, String(key)]));\n+\t\tif (id === undefined) {\n+\t\t\tif (node.kind === \"array\") throw Error(\"missing stored JSON array element\");\n+\t\t\treturn undefined;\n+\t\t}\n+\t\tif (typeof id !== \"number\") throw Error(\"invalid stored JSON edge\");\n+\t\treturn new StoredJson(this.storage, this.namespace, id);\n+\t}\n+\t*elements(): IterableIterator<StoredJson> {\n+\t\tconst length = this.length;\n+\t\tfor (let index = 0; index < length; index++) yield this.child(index)!;\n+\t}\n+\t*properties(): IterableIterator<[string, StoredJson]> {\n+\t\tconst node = this.node();\n+\t\tif (node.kind !== \"object\" || !Number.isSafeInteger(node.count) || node.count! < 0)\n+\t\t\tthrow Error(\"invalid stored JSON object\");\n+\t\tfor (let index = 0; index < node.count!; index++) {\n+\t\t\tconst key = this.storage.read(`${this.namespace}:keys`, JSON.stringify([this.id, index]));\n+\t\t\tif (typeof key !== \"string\") throw Error(\"missing stored JSON object key\");\n+\t\t\tconst child = this.child(key);\n+\t\t\tif (!child) throw Error(\"missing stored JSON object member\");\n+\t\t\tyield [key, child];\n+\t\t}\n+\t}\n+\t*textChunks(): IterableIterator<string> {\n+\t\tif (this.kind !== \"string\") throw Error(\"stored JSON node is not text\");\n+\t\tyield* new StoredText(this.storage, `${this.namespace}:text`).chunks(String(this.id));\n+\t}\n+\tscalar(): number | boolean | null {\n+\t\tconst node = this.node();\n+\t\tif (node.kind !== \"value\") throw Error(\"stored JSON node is not a scalar\");\n+\t\tif (node.number) {\n+\t\t\tif (typeof node.value !== \"string\" || Number.isNaN(Number(node.value))) throw Error(\"invalid stored JSON number\");\n+\t\t\treturn node.negativeZero ? -0 : Number(node.value);\n+\t\t}\n+\t\tif (node.value === null || typeof node.value === \"boolean\" || typeof node.value === \"number\") return node.value;\n+\t\tthrow Error(\"invalid stored JSON scalar\");\n+\t}\n+}"},{"path":"server/src/writer-host.ts","added":76,"removed":31,"diff":"--- a/server/src/writer-host.ts\n+++ b/server/src/writer-host.ts\n@@ -5,6 +5,7 @@\n import type { GraphStateStorage } from \"../../src/engine/state-source.ts\";\n import { Project, type WriterSource } from \"../../worker/project/project.ts\";\n import type { ProjectOptions } from \"../../worker/project/project-types.ts\";\n+import { withDecodedFrames } from \"./decoded-frames.ts\";\n import {\n \tEngineProject,\n \tlogParts,\n@@ -12,6 +13,7 @@\n \tSqliteLog,\n \ttype SqliteStorage,\n } from \"./engine-project.ts\";\n+import type { SqliteHistoryHost } from \"./history-host.ts\";\n \n export class SqliteWriterState implements GraphStateStorage {\n \treadonly #storage: SqliteStorage;\n@@ -145,25 +147,39 @@\n \n /** Domain-separated SHA-256 chain over exact canonical UTF-8 frames and their positions. */\n export function writerFrameDigest(previous: string, seq: number, json: string): string {\n-\treturn createHash(\"sha256\")\n+\treturn writerFrameChunksDigest(previous, seq, [json]);\n+}\n+\n+/** Same canonical digest without retaining the complete frame. */\n+export function writerFrameChunksDigest(previous: string, seq: number, chunks: Iterable<string>): string {\n+\tconst hash = createHash(\"sha256\")\n \t\t.update(\"abso-writer-log-v1\\n\")\n \t\t.update(JSON.stringify([previous, seq]))\n-\t\t.update(\"\\n\")\n-\t\t.update(json, \"utf8\")\n-\t\t.digest(\"hex\");\n+\t\t.update(\"\\n\");\n+\tlet carry = \"\";\n+\tfor (const chunk of chunks) {\n+\t\tconst text = carry + chunk;\n+\t\tconst last = text.charCodeAt(text.length - 1);\n+\t\tconst split = last >= 0xd800 && last <= 0xdbff;\n+\t\tcarry = split ? text.slice(-1) : \"\";\n+\t\thash.update(split ? text.slice(0, -1) : text, \"utf8\");\n+\t}\n+\tif (carry) hash.update(carry, \"utf8\");\n+\treturn hash.digest(\"hex\");\n }\n \n export function advanceWriterRoot(log: SqliteLog, previous: WriterRoot, source: WriterSource): WriterRoot {\n \tlet digest = previous.digest;\n \tif (source.logLength < previous.logLength) throw new Error(\"writer root cannot move backwards\");\n \tfor (let seq = previous.logLength; seq < source.logLength; seq++)\n-\t\tdigest = writerFrameDigest(digest, seq, log.boundedFrame(seq, 8_000_000));\n+\t\tdigest = writerFrameChunksDigest(digest, seq, log.frameChunks(seq));\n \treturn { format: 1, ...source, digest };\n }\n \n /** Inactive host for explicit adoption and synchronous fenced writer operations. */\n export interface WriterProjectionSession {\n \treadonly readViewProvider: NonNullable<ProjectOptions[\"readViewProvider\"]>;\n+\thistoricalReadViewProvider?(state: GraphStateStorage): NonNullable<ProjectOptions[\"readViewProvider\"]>;\n \tcommit(project: Project, root: WriterRoot): void;\n \t/** Cleanup is inside the canonical transaction. Any failure aborts roots and receipt too. */\n \tclose(): void;\n@@ -176,21 +192,25 @@\n \n export class SqliteWriterHost {\n \treadonly #storage: SqliteStorage;\n+\treadonly #namespace: string;\n \treadonly #state: SqliteWriterState;\n \treadonly #log: SqliteLog;\n \treadonly #projection?: WriterProjectionHost;\n \treadonly #indexProjectionAtoms: boolean;\n+\treadonly #history?: SqliteHistoryHost;\n \tconstructor(\n \t\tstorage: SqliteStorage,\n \t\tnamespace: string,\n \t\tprojection?: WriterProjectionHost,\n-\t\toptions: { indexProjectionAtoms?: boolean } = {},\n+\t\toptions: { indexProjectionAtoms?: boolean; history?: SqliteHistoryHost } = {},\n \t) {\n \t\tthis.#storage = storage;\n+\t\tthis.#namespace = namespace;\n \t\tthis.#state = new SqliteWriterState(storage, namespace);\n \t\tthis.#log = new SqliteLog(storage);\n \t\tthis.#projection = projection;\n \t\tthis.#indexProjectionAtoms = options.indexProjectionAtoms ?? false;\n+\t\tthis.#history = options.history;\n \t}\n \t#indexOptions(adopting = false) {\n \t\tconst mode = this.#state.read(\"host\", \"projection-atom-index-mode\");\n@@ -246,7 +266,6 @@\n \t\t\t\tinput.maxEntries > 256 ||\n \t\t\t\t!Number.isSafeInteger(input.maxBytes) ||\n \t\t\t\tinput.maxBytes < 1 ||\n-\t\t\t\tinput.maxBytes > 8_000_000 ||\n \t\t\t\t!(input.digest === \"\" || /^[a-f0-9]{64}$/.test(input.digest))\n \t\t\t)\n \t\t\t\tthrow new Error(\"invalid bounded adoption request\");\n@@ -288,30 +307,29 @@\n \t\t\t)\n \t\t\t\tthrow new Error(\"writer adoption root cursor is stale\");\n \t\t\tlet digest = previous?.digest ?? \"\";\n-\t\t\tconst frames = function* () {\n-\t\t\t\tlet bytes = 0;\n-\t\t\t\tfor (let seq = from; seq < source.logLength && seq < from + limits.maxEntries; seq++) {\n-\t\t\t\t\t// Each frame is bounded before reading; the core also checks the\n-\t\t\t\t\t// cumulative byte count before applying a frame.\n-\t\t\t\t\tconst json = log.boundedFrame(seq, limits.maxBytes);\n-\t\t\t\t\tconst next = new TextEncoder().encode(json).byteLength;\n-\t\t\t\t\tif (bytes + next > limits.maxBytes && bytes > 0) return;\n-\t\t\t\t\tbytes += next;\n-\t\t\t\t\tdigest = writerFrameDigest(digest, seq, json);\n-\t\t\t\t\tyield { seq, json };\n-\t\t\t\t}\n-\t\t\t};\n-\t\t\tconst result = Project.adoptWriterPage(\n-\t\t\t\tthis.#state,\n-\t\t\t\t{\n-\t\t\t\t\tsource,\n-\t\t\t\t\tfrom,\n-\t\t\t\t\tframes: frames(),\n-\t\t\t\t\t...limits,\n-\t\t\t\t\tcurrentSource: () => this.source(),\n+\t\t\tconst decoded = withDecodedFrames(\n+\t\t\t\tthis.#storage,\n+\t\t\t\t`${this.#namespace}:decoded`,\n+\t\t\t\tlog,\n+\t\t\t\t{ from, to: source.logLength, ...limits, digest },\n+\t\t\t\t(frames) => {\n+\t\t\t\t\tconst result = Project.adoptWriterPage(\n+\t\t\t\t\t\tthis.#state,\n+\t\t\t\t\t\t{\n+\t\t\t\t\t\t\tsource,\n+\t\t\t\t\t\t\tfrom,\n+\t\t\t\t\t\t\tframes,\n+\t\t\t\t\t\t\t...limits,\n+\t\t\t\t\t\t\tdecodedFrames: true,\n+\t\t\t\t\t\t\tcurrentSource: () => this.source(),\n+\t\t\t\t\t\t},\n+\t\t\t\t\t\tindexOptions,\n+\t\t\t\t\t);\n+\t\t\t\t\treturn result;\n \t\t\t\t},\n-\t\t\t\tindexOptions,\n \t\t\t);\n+\t\t\tconst result = decoded.result;\n+\t\t\tdigest = decoded.digest;\n \t\t\tSqliteWriterHost.#sync(validateAuthority());\n \t\t\tthis.#state.write(\"host\", \"adoption-root\", { source, next: result.next, digest });\n \t\t\tif (result.ready) {\n@@ -351,7 +369,25 @@\n \t\t\t\t\treadViewProvider: projection?.readViewProvider,\n \t\t\t\t\tentryAt: (index) => this.#log.since(index, 1)[0]!,\n \t\t\t\t});\n-\t\t\t\tconst result = input.operation(new EngineProject(project, (from, limit) => this.#log.since(from, limit)));\n+\t\t\t\tconst root = this.root();\n+\t\t\t\tconst result = input.operation(\n+\t\t\t\t\tnew EngineProject(\n+\t\t\t\t\t\tproject,\n+\t\t\t\t\t\t(from, limit) => this.#log.since(from, limit),\n+\t\t\t\t\t\tundefined,\n+\t\t\t\t\t\tthis.#history\n+\t\t\t\t\t\t\t? (at, operation) =>\n+\t\t\t\t\t\t\t\t\tthis.#history!.read(\n+\t\t\t\t\t\t\t\t\t\troot,\n+\t\t\t\t\t\t\t\t\t\t() => this.root(),\n+\t\t\t\t\t\t\t\t\t\tinput.validateAuthority,\n+\t\t\t\t\t\t\t\t\t\tat,\n+\t\t\t\t\t\t\t\t\t\toperation,\n+\t\t\t\t\t\t\t\t\t\tprojection?.historicalReadViewProvider,\n+\t\t\t\t\t\t\t\t\t)\n+\t\t\t\t\t\t\t: undefined,\n+\t\t\t\t\t),\n+\t\t\t\t);\n \t\t\t\tSqliteWriterHost.#sync(result);\n \t\t\t\tSqliteWriterHost.#sync(input.validateAuthority());\n \t\t\t\tif (!SqliteWriterHost.#same(source, this.source())) throw new Error(\"reader source changed\");\n@@ -374,7 +410,15 @@\n \t\treturn this.run({\n \t\t\t...input,\n \t\t\toperation: (project) => {\n-\t\t\t\tconst calls = new EngineProject(project, (from, limit) => this.#log.since(from, limit), this.#log);\n+\t\t\t\tconst root = this.root();\n+\t\t\t\tconst calls = new EngineProject(\n+\t\t\t\t\tproject,\n+\t\t\t\t\t(from, limit) => this.#log.since(from, limit),\n+\t\t\t\t\tthis.#log,\n+\t\t\t\t\tthis.#history\n+\t\t\t\t\t\t? (at, operation) => this.#history!.read(root, () => this.root(), input.validateAuthority, at, operation)\n+\t\t\t\t\t\t: undefined,\n+\t\t\t\t);\n \t\t\t\tcalls.setCheckerReady(input.checkerReady);\n \t\t\t\treturn input.operation(calls);\n \t\t\t},\n@@ -413,6 +457,7 @@\n \t\t\t\t\tconst committedRoot = advanceWriterRoot(this.#log, root, committed);\n \t\t\t\t\tthis.#state.write(\"host\", \"canonical-root\", committedRoot);\n \t\t\t\t\tSqliteWriterHost.#sync(projection?.commit(project, committedRoot));\n+\t\t\t\t\tthis.#history?.advance(this.#log, root, committedRoot, () => this.root(), input.validateAuthority);\n \t\t\t\t\tSqliteWriterHost.#sync(input.commitReceipt(result, committed));\n \t\t\t\t\treturn result;\n \t\t\t\t} finally {"},{"path":"server/test/atom-list-history.test.ts","added":65,"removed":0,"diff":"--- /dev/null\n+++ b/server/test/atom-list-history.test.ts\n@@ -0,0 +1,65 @@\n+import assert from \"node:assert/strict\";\n+import { test } from \"node:test\";\n+import { Graph } from \"../../src/engine/graph.ts\";\n+import { answer } from \"../../worker/project/http.ts\";\n+import { Project } from \"../../worker/project/project.ts\";\n+import { DiskFirstRuntime } from \"../src/disk-first-runtime.ts\";\n+import { SqliteLog } from \"../src/engine-project.ts\";\n+import { SqliteHistoryState } from \"../src/history-state.ts\";\n+import { memoryStorage } from \"./helpers.ts\";\n+\n+test(\"large atom lists preserve historical reads after later writes\", (t) => {\n+\tconst storage = memoryStorage();\n+\tt.after(() => storage.db.close());\n+\tconst runtime = () => new DiskFirstRuntime(storage, \"list-history\", \"list-history\");\n+\tconst old = Array.from({ length: 300 }, (_, i) => `old line ${i}`).join(\"\\n\") + \"\\n\";\n+\tconst current = Array.from({ length: 300 }, (_, i) => `new line ${i}`).join(\"\\n\") + \"\\n\";\n+\truntime().initialize(\n+\t\t(calls) => answer(calls, \"init\", undefined, { files: { \"a.txt\": old } }),\n+\t\t() => {},\n+\t);\n+\twhile (!runtime().preparePage(() => {}).ready) {}\n+\tconst before = runtime().read(\n+\t\t(calls) => calls.fileAt(\"a.txt\", 0, null),\n+\t\t() => {},\n+\t);\n+\tassert.equal(\n+\t\truntime().write(\n+\t\t\t(calls) => answer(calls, \"record\", \"alice\", { files: { \"a.txt\": current } }),\n+\t\t\t() => {},\n+\t\t).status,\n+\t\t200,\n+\t);\n+\tassert.equal(\n+\t\truntime().write(\n+\t\t\t(calls) => answer(calls, \"publish\", \"alice\", { message: \"Replace all lines\" }),\n+\t\t\t() => {},\n+\t\t).status,\n+\t\t200,\n+\t);\n+\tt.mock.method(Project, \"load\", () => {\n+\t\tthrow Error(\"full history replay forbidden\");\n+\t});\n+\tassert.deepEqual(\n+\t\truntime().read(\n+\t\t\t(calls) => calls.fileAt(\"a.txt\", 0, null),\n+\t\t\t() => {},\n+\t\t),\n+\t\tbefore,\n+\t);\n+\tassert.equal(\n+\t\truntime().read(\n+\t\t\t(calls) => calls.shared().files[\"a.txt\"],\n+\t\t\t() => {},\n+\t\t),\n+\t\tcurrent,\n+\t);\n+\tassert.ok(\n+\t\t(storage.db.prepare(\"SELECT COUNT(*) AS n FROM writer_state WHERE collection LIKE 'atom-list:%'\").get()!\n+\t\t\t.n as number) > 0,\n+\t);\n+\tconst history = new SqliteHistoryState(storage, \"list-history:history\", new SqliteLog(storage).seq());\n+\tconst graph = new Graph({ storage: history.at(1, () => {}) });\n+\tassert.equal(graph.lineText(\"a0.0\"), \"old line 0\");\n+\tassert.equal(graph.atom(\"a0\").inserts[0]!.lines[0], \"old line 0\");\n+});"},{"path":"server/test/decoded-adoption-bounds.test.ts","added":31,"removed":0,"diff":"--- /dev/null\n+++ b/server/test/decoded-adoption-bounds.test.ts\n@@ -0,0 +1,31 @@\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 } from \"../../worker/project/project.ts\";\n+\n+test(\"large adoption budgets require decoded frames and refuse JSON without mutation\", (t) => {\n+\tconst storage = new SqlState();\n+\tt.after(() => storage.db.close());\n+\tconst log = new MemoryStore();\n+\tnew Project(log).init({ \"a.txt\": \"small\\n\" }, 0);\n+\tconst source = { generation: 1, logLength: 1, sharedVersion: 0 };\n+\tconst frames = [{ seq: 0, json: JSON.stringify(log.entries[0]) }];\n+\tconst before = storage.db.prepare(\"SELECT * FROM state ORDER BY collection,key\").all();\n+\tconst input = { source, from: 0, frames, maxEntries: 1, maxBytes: 8100000, currentSource: () => source };\n+\tassert.throws(() => Project.adoptWriterPage(storage, input), /invalid writer adoption bounds/);\n+\tassert.throws(() => Project.adoptWriterPage(storage, { ...input, decodedFrames: true }), /requires decoded frames/);\n+\tassert.deepEqual(storage.db.prepare(\"SELECT * FROM state ORDER BY collection,key\").all(), before);\n+\tassert.throws(\n+\t\t() =>\n+\t\t\tProject.extendHistoricalPage(storage, {\n+\t\t\t\tfrom: 1,\n+\t\t\t\tframes,\n+\t\t\t\tmaxEntries: 1,\n+\t\t\t\tmaxBytes: 8100000,\n+\t\t\t\tbeginRevision() {},\n+\t\t\t\tvalidateAuthority() {},\n+\t\t\t}),\n+\t\t/invalid historical extension bounds/,\n+\t);\n+\tassert.deepEqual(storage.db.prepare(\"SELECT * FROM state ORDER BY collection,key\").all(), before);\n+});"},{"path":"server/test/decoded-entry-adoption.test.ts","added":62,"removed":0,"diff":"--- /dev/null\n+++ b/server/test/decoded-entry-adoption.test.ts\n@@ -0,0 +1,62 @@\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 } from \"../../worker/project/project.ts\";\n+import type { Entry } from \"../../worker/project/project-types.ts\";\n+import { StoredJson, storeJson } from \"../src/stored-json.ts\";\n+import { storedJsonView } from \"../src/stored-json-view.ts\";\n+\n+test(\"Project adopts disk-backed decoded entries with replay parity and source fencing\", (t) => {\n+\tconst storage = new SqlState();\n+\tt.after(() => storage.db.close());\n+\tconst log = new MemoryStore();\n+\tconst oracle = new Project(log);\n+\toracle.init({ \"a.txt\": \"old\\n\" }, 0);\n+\toracle.record(\"alice\", { \"a.txt\": \"new\\n\" }, 1);\n+\toracle.publish(\"alice\", \"edit\", 2);\n+\tconst source = { generation: 1, logLength: log.entries.length, sharedVersion: oracle.version };\n+\tconst frames = log.entries.map((entry, seq) => {\n+\t\tconst json = JSON.stringify(entry);\n+\t\tconst namespace = `decoded:${seq}`;\n+\t\tstoreJson(\n+\t\t\tstorage,\n+\t\t\tnamespace,\n+\t\t\t(function* () {\n+\t\t\t\tfor (let i = 0; i < json.length; i += 11) yield json.slice(i, i + 11);\n+\t\t\t})(),\n+\t\t);\n+\t\treturn { seq, bytes: Buffer.byteLength(json), entry: storedJsonView(new StoredJson(storage, namespace)) as Entry };\n+\t});\n+\tconst before = storage.db.prepare(\"SELECT * FROM state ORDER BY collection,key\").all();\n+\tlet checks = 0;\n+\tassert.throws(\n+\t\t() =>\n+\t\t\tProject.adoptWriterPage(storage, {\n+\t\t\t\tsource,\n+\t\t\t\tfrom: 0,\n+\t\t\t\tframes,\n+\t\t\t\tmaxEntries: 32,\n+\t\t\t\tmaxBytes: 100000,\n+\t\t\t\tcurrentSource: () => (++checks === 1 ? source : { ...source, generation: 2 }),\n+\t\t\t}),\n+\t\t/source changed during/,\n+\t);\n+\tassert.deepEqual(storage.db.prepare(\"SELECT * FROM state ORDER BY collection,key\").all(), before);\n+\tt.mock.method(Project, \"load\", () => {\n+\t\tthrow Error(\"full history load forbidden\");\n+\t});\n+\tassert.equal(\n+\t\tProject.adoptWriterPage(storage, {\n+\t\t\tsource,\n+\t\t\tfrom: 0,\n+\t\t\tframes,\n+\t\t\tmaxEntries: 32,\n+\t\t\tmaxBytes: 100000,\n+\t\t\tcurrentSource: () => source,\n+\t\t}).ready,\n+\t\ttrue,\n+\t);\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+});"},{"path":"server/test/decoded-frames.test.ts","added":36,"removed":0,"diff":"--- /dev/null\n+++ b/server/test/decoded-frames.test.ts\n@@ -0,0 +1,36 @@\n+import assert from \"node:assert/strict\";\n+import { test } from \"node:test\";\n+import { withDecodedFrames } from \"../src/decoded-frames.ts\";\n+import { logParts, SqliteLog } from \"../src/engine-project.ts\";\n+import { SqliteWriterState, writerFrameDigest } from \"../src/writer-host.ts\";\n+import { memoryStorage } from \"./helpers.ts\";\n+\n+test(\"decoded frame pages retain views through consumption and remove scratch on all exits\", (t) => {\n+\tconst storage = memoryStorage();\n+\tt.after(() => storage.db.close());\n+\tconst log = new SqliteLog(storage);\n+\tconst json = JSON.stringify({ type: \"join\", agent: \"alice\", version: 0 });\n+\tfor (const [part, text] of logParts(json).entries())\n+\t\tstorage.sql.exec(\"INSERT INTO log(seq,part,text) VALUES(?,?,?)\", 0, part, text);\n+\tSqliteWriterState.initialize(storage);\n+\tconst before = storage.db.prepare(\"SELECT * FROM writer_state\").all();\n+\tconst input = { from: 0, to: 1, maxEntries: 1, maxBytes: 1000, digest: \"\" };\n+\tconst result = withDecodedFrames(storage, \"decoded-page\", log, input, (frames) => {\n+\t\tconst frame = [...frames][0]!;\n+\t\tassert.ok(\"entry\" in frame);\n+\t\tassert.equal(frame.entry.type, \"join\");\n+\t\treturn frame.entry.type;\n+\t});\n+\tassert.equal(result.result, \"join\");\n+\tassert.equal(result.digest, writerFrameDigest(\"\", 0, json));\n+\tassert.deepEqual(storage.db.prepare(\"SELECT * FROM writer_state\").all(), before);\n+\tassert.throws(\n+\t\t() =>\n+\t\t\twithDecodedFrames(storage, \"decoded-page\", log, input, (frames) => {\n+\t\t\t\t[...frames];\n+\t\t\t\tthrow Error(\"consumer failure\");\n+\t\t\t}),\n+\t\t/consumer failure/,\n+\t);\n+\tassert.deepEqual(storage.db.prepare(\"SELECT * FROM writer_state\").all(), before);\n+});"},{"path":"server/test/disk-first-runtime.test.ts","added":358,"removed":2,"diff":"--- a/server/test/disk-first-runtime.test.ts\n+++ b/server/test/disk-first-runtime.test.ts\n@@ -4,11 +4,96 @@\n import { join } from \"node:path\";\n import { test } from \"node:test\";\n import { answer } from \"../../worker/project/http.ts\";\n-import { Project } from \"../../worker/project/project.ts\";\n+import { MemoryStore, Project } from \"../../worker/project/project.ts\";\n+import { where } from \"../../worker/project/where.ts\";\n import { DiskFirstRuntime } from \"../src/disk-first-runtime.ts\";\n-import { SqliteLog } from \"../src/engine-project.ts\";\n+import { type EngineProject, SqliteLog } from \"../src/engine-project.ts\";\n+import { SqliteProjectionStore } from \"../src/projection-store.ts\";\n+import { SqliteWriterHost, SqliteWriterState } from \"../src/writer-host.ts\";\n import { memoryStorage } from \"./helpers.ts\";\n \n+test(\"runtime defers a large later frame and adopts it on its own page\", (t) => {\n+\tconst storage = memoryStorage();\n+\tt.after(() => storage.db.close());\n+\tconst memory = new MemoryStore();\n+\tconst project = new Project(memory);\n+\tproject.init({ \"a.txt\": \"small\\n\" }, 0);\n+\tproject.record(\"alice\", { \"a.txt\": `${\"x\".repeat(1_100_000)}\\n` }, 1);\n+\tproject.publish(\"alice\", \"Large entry\", 2);\n+\tconst log = new SqliteLog(storage);\n+\tlog.append(memory.entries);\n+\tconst large = memory.entries.findIndex((entry) => Buffer.byteLength(JSON.stringify(entry)) > 1_048_576);\n+\tassert.ok(large > 0);\n+\tconst before = storage.db.prepare(\"SELECT * FROM log ORDER BY seq,part\").all();\n+\tt.mock.method(Project, \"load\", () => {\n+\t\tthrow Error(\"full-history replay forbidden\");\n+\t});\n+\tconst runtime = () => new DiskFirstRuntime(storage, \"large-later\", \"large-later\");\n+\tconst first = runtime().preparePage(() => {});\n+\tassert.equal(first.phase, \"writer\");\n+\tassert.equal(first.next, large);\n+\tlet pages = 0;\n+\twhile (!runtime().preparePage(() => {}).ready) assert.ok(++pages < 100);\n+\tassert.equal(\n+\t\truntime().read(\n+\t\t\t(calls) => calls.statusAt(log.seq()).version,\n+\t\t\t() => {},\n+\t\t),\n+\t\t1,\n+\t);\n+\tassert.equal(\n+\t\truntime().read(\n+\t\t\t(calls) => calls.shared().files[\"a.txt\"]?.length,\n+\t\t\t() => {},\n+\t\t),\n+\t\t1_100_001,\n+\t);\n+\tassert.deepEqual(storage.db.prepare(\"SELECT * FROM log ORDER BY seq,part\").all(), before);\n+});\n+\n+test(\"historical runtime preserves named draft bases and intermediate states after landing\", (t) => {\n+\tconst storage = memoryStorage();\n+\tt.after(() => storage.db.close());\n+\tconst memory = new MemoryStore();\n+\tconst project = new Project(memory);\n+\tproject.init({ \"a.txt\": \"one\\ntwo\\n\", \"b.txt\": \"other\\n\" }, 0);\n+\tproject.switchTo(\"alice\", \"rewrite\", 1);\n+\tproject.record(\"alice\", { \"a.txt\": \"ONE\\ntwo\\n\" }, 2);\n+\tproject.publish(\"alice\", \"First draft version\", 3);\n+\tproject.switchTo(\"bob\", \"rewrite\", 4);\n+\tproject.record(\"bob\", { \"b.txt\": \"OTHER\\n\" }, 5);\n+\tproject.publish(\"bob\", \"Second draft version\", 6);\n+\tassert.equal(project.land(\"bob\", \"Land rewrite\", 7).ok, true);\n+\tconst expected = memory.entries.map((_, i) => {\n+\t\tconst prefix = Project.load(memory.entries.slice(0, i + 1), new MemoryStore());\n+\t\treturn { status: prefix.status(), where: where(prefix) };\n+\t});\n+\tnew SqliteLog(storage).append(memory.entries);\n+\tt.mock.method(Project, \"load\", () => {\n+\t\tthrow Error(\"full-history replay forbidden\");\n+\t});\n+\tconst runtime = () => new DiskFirstRuntime(storage, \"named-history\", \"named-history\");\n+\twhile (!runtime().preparePage(() => {}).ready) {}\n+\tfor (let at = 1; at <= expected.length; at++) {\n+\t\tassert.deepEqual(\n+\t\t\truntime().read(\n+\t\t\t\t(calls) => calls.statusAt(at),\n+\t\t\t\t() => {},\n+\t\t\t),\n+\t\t\t{ at, ...expected[at - 1]!.status },\n+\t\t\t`status at ${at}`,\n+\t\t);\n+\t\tassert.deepEqual(\n+\t\t\truntime().read(\n+\t\t\t\t(calls) => calls.whereAt(at),\n+\t\t\t\t() => {},\n+\t\t\t),\n+\t\t\t{ at, ...expected[at - 1]!.where },\n+\t\t\t`where at ${at}`,\n+\t\t);\n+\t}\n+});\n+\n test(\"runtime resumes from disk and detaches reads, with exact authorized retries\", (t) => {\n \tconst directory = mkdtempSync(join(tmpdir(), \"abso-runtime-\"));\n \tconst filename = join(directory, \"state.sqlite\");\n@@ -42,12 +127,29 @@\n \t\tstorage = memoryStorage(filename);\n \t}\n \tassert.ok(pages > 0);\n+\tconst initialLength = new SqliteLog(storage).seq();\n+\tconst initialStatus = runtime().read((calls) => calls.statusAt(initialLength), validate);\n+\tconst initialWhere = runtime().read((calls) => calls.whereAt(initialLength), validate);\n+\t// Reproduce the published runtime's ready state before historical indexing existed.\n+\tnew SqliteWriterState(storage, \"disk-v1\").remove(\"runtime\", \"history-ready\");\n+\tstorage.db.exec(\n+\t\t\"DELETE FROM writer_state WHERE namespace LIKE 'disk-v1:history%'; DROP TABLE writer_history_keys; DROP TABLE writer_history_heads;\",\n+\t);\n+\tassert.throws(() => runtime().read((calls) => calls.status(), validate), /not complete/);\n+\tassert.throws(() => runtime().write(() => undefined, validate), /not complete/);\n+\twhile (!runtime().preparePage(validate).ready) {}\n+\tassert.deepEqual(\n+\t\truntime().read((calls) => calls.statusAt(initialLength), validate),\n+\t\tinitialStatus,\n+\t);\n \tconst req = { id: \"record-1\", identity: { agent: \"alice\", operation: \"record\", files: { \"a.txt\": \"changed\\n\" } } };\n \tconst operation = (calls: Parameters<Parameters<DiskFirstRuntime[\"write\"]>[0]>[0]) =>\n \t\tanswer(calls, \"record\", \"alice\", { files: req.identity.files });\n \tconst first = runtime().write(operation, validate, req);\n \tassert.equal(first.status, 200);\n \tconst length = new SqliteLog(storage).seq();\n+\tconst draftStatus = runtime().read((calls) => calls.statusAt(length), validate);\n+\tconst draftWhere = runtime().read((calls) => calls.whereAt(length), validate);\n \tstorage.db.close();\n \tstorage = memoryStorage(filename);\n \tassert.deepEqual(\n@@ -83,7 +185,32 @@\n \tstorage.db.close();\n \tstorage = memoryStorage(filename);\n \tassert.equal(runtime().preparePage(validate).ready, true);\n+\tassert.deepEqual(\n+\t\truntime().read((calls) => calls.statusAt(initialLength), validate),\n+\t\tinitialStatus,\n+\t);\n+\tassert.deepEqual(\n+\t\truntime().read((calls) => calls.whereAt(initialLength), validate),\n+\t\tinitialWhere,\n+\t);\n+\tconst end = new SqliteLog(storage).seq();\n+\tassert.deepEqual(\n+\t\truntime().read((calls) => calls.statusAt(length), validate),\n+\t\tdraftStatus,\n+\t);\n+\tassert.deepEqual(\n+\t\truntime().read((calls) => calls.whereAt(length), validate),\n+\t\tdraftWhere,\n+\t);\n \tassert.equal(\n+\t\truntime().read((calls) => calls.statusAt(end).version, validate),\n+\t\t1,\n+\t);\n+\tassert.equal(\n+\t\truntime().read((calls) => calls.whereAt(end).version, validate),\n+\t\t1,\n+\t);\n+\tassert.equal(\n \t\truntime().read((calls) => calls.shared().files[\"a.txt\"], validate),\n \t\t\"changed\\n\",\n \t);\n@@ -129,4 +256,233 @@\n \t\t/authority changed/,\n \t);\n \tassert.deepEqual(rows(), adopted);\n+\tconst originalWrite = SqliteWriterState.prototype.write;\n+\tconst failure = t.mock.method(\n+\t\tSqliteWriterState.prototype,\n+\t\t\"write\",\n+\t\tfunction (this: SqliteWriterState, collection: string, key: string, value: unknown) {\n+\t\t\tif (collection === \"runtime:receipts\") throw Error(\"receipt persistence failed\");\n+\t\t\treturn originalWrite.call(this, collection, key, value);\n+\t\t},\n+\t);\n+\tassert.throws(\n+\t\t() =>\n+\t\t\truntime.write(\n+\t\t\t\t(calls) => answer(calls, \"record\", \"alice\", { files: { \"a.txt\": \"two\\n\" } }),\n+\t\t\t\t() => {},\n+\t\t\t\t{ id: \"receipt-failed\", identity: \"record\" },\n+\t\t\t),\n+\t\t/receipt persistence failed/,\n+\t);\n+\tassert.deepEqual(rows(), adopted, \"receipt failure must roll back canonical state, history and its cursor\");\n+\tfailure.mock.restore();\n });\n+\n+test(\"runtime recovers after a writer without historical support commits\", (t) => {\n+\tconst storage = memoryStorage();\n+\tt.after(() => storage.db.close());\n+\tconst namespace = \"old-writer\";\n+\tconst runtime = () => new DiskFirstRuntime(storage, \"recovery\", namespace);\n+\truntime().initialize(\n+\t\t(calls) => answer(calls, \"init\", undefined, { files: { \"a.txt\": \"one\\n\" } }),\n+\t\t() => {},\n+\t);\n+\twhile (!runtime().preparePage(() => {}).ready) {}\n+\tconst historical = runtime().read(\n+\t\t(calls) => calls.statusAt(1),\n+\t\t() => {},\n+\t);\n+\tconst projection = new SqliteProjectionStore(\n+\t\t{\n+\t\t\tdatabase: \"recovery\",\n+\t\t\tnamespace: `${namespace}:views`,\n+\t\t\tregistry: `${namespace}:roots`,\n+\t\t\tdefaultFile: \"__abso_projection_default__\",\n+\t\t},\n+\t\t1,\n+\t\t{ indexedAtoms: true },\n+\t);\n+\tconst oldWriter = () => new SqliteWriterHost(storage, namespace, projection, { indexProjectionAtoms: true });\n+\tfor (const [op, body] of [\n+\t\t[\"record\", { files: { \"a.txt\": \"two\\n\" } }],\n+\t\t[\"publish\", { message: \"Old writer\" }],\n+\t] as const) {\n+\t\tassert.equal(\n+\t\t\toldWriter().runCalls({\n+\t\t\t\texpected: oldWriter().source(),\n+\t\t\t\tvalidateAuthority: () => {},\n+\t\t\t\tcheckerReady: false,\n+\t\t\t\tcommitReceipt: () => {},\n+\t\t\t\toperation: (calls) => answer(calls, op, \"alice\", body),\n+\t\t\t}).status,\n+\t\t\t200,\n+\t\t);\n+\t}\n+\tt.mock.method(Project, \"load\", () => {\n+\t\tthrow Error(\"full-history load forbidden\");\n+\t});\n+\tlet ready = false;\n+\tfor (let page = 0; page < 100 && !ready; page++) ready = runtime().preparePage(() => {}).ready;\n+\tassert.equal(ready, true);\n+\tassert.deepEqual(\n+\t\truntime().read(\n+\t\t\t(calls) => calls.statusAt(1),\n+\t\t\t() => {},\n+\t\t),\n+\t\thistorical,\n+\t);\n+\tassert.equal(\n+\t\truntime().read(\n+\t\t\t(calls) => calls.shared().files[\"a.txt\"],\n+\t\t\t() => {},\n+\t\t),\n+\t\t\"two\\n\",\n+\t);\n+\tassert.equal(\n+\t\truntime().write(\n+\t\t\t(calls) => answer(calls, \"record\", \"alice\", { files: { \"a.txt\": \"three\\n\" } }),\n+\t\t\t() => {},\n+\t\t).status,\n+\t\t200,\n+\t);\n+});\n+\n+test(\"a large retry response must not roll back an otherwise successful write\", (t) => {\n+\tconst storage = memoryStorage();\n+\tt.after(() => storage.db.close());\n+\tconst runtime = () => new DiskFirstRuntime(storage, \"large-receipt\", \"large-receipt\");\n+\truntime().initialize(\n+\t\t(calls) => answer(calls, \"init\", undefined, { files: { \"a.txt\": \"one\\n\" } }),\n+\t\t() => {},\n+\t);\n+\twhile (!runtime().preparePage(() => {}).ready) {}\n+\tconst large = \"x\".repeat(8_100_000);\n+\tconst request = { id: \"large-response\", identity: { agent: \"alice\", operation: \"large-fixture\" } };\n+\tconst result = runtime().write(\n+\t\t(calls) => {\n+\t\t\tconst recorded = answer(calls, \"record\", \"alice\", { files: { \"a.txt\": \"two\\n\" } });\n+\t\t\tassert.equal(recorded.status, 200);\n+\t\t\treturn { status: 200, body: large };\n+\t\t},\n+\t\t() => {},\n+\t\trequest,\n+\t);\n+\tassert.equal(result.body.length, large.length);\n+\tconst before = storage.db.prepare(\"SELECT * FROM log ORDER BY seq,part\").all();\n+\tconst replay = runtime().write(\n+\t\t() => {\n+\t\t\tthrow Error(\"receipt replay must not execute twice\");\n+\t\t},\n+\t\t() => {},\n+\t\trequest,\n+\t) as typeof result;\n+\tassert.deepEqual(replay, result);\n+\tassert.deepEqual(storage.db.prepare(\"SELECT * FROM log ORDER BY seq,part\").all(), before);\n+});\n+\n+test(\"chunked receipts roll back failures and reject damaged replay\", (t) => {\n+\tconst storage = memoryStorage();\n+\tt.after(() => storage.db.close());\n+\tconst runtime = () => new DiskFirstRuntime(storage, \"receipt-failure\", \"receipt-failure\");\n+\truntime().initialize(\n+\t\t(calls) => answer(calls, \"init\", undefined, { files: { \"a.txt\": \"one\\n\" } }),\n+\t\t() => {},\n+\t);\n+\twhile (!runtime().preparePage(() => {}).ready) {}\n+\tconst rows = () => ({\n+\t\tlog: storage.db.prepare(\"SELECT * FROM log ORDER BY seq,part\").all(),\n+\t\tstate: storage.db.prepare(\"SELECT * FROM writer_state ORDER BY namespace,collection,key,part\").all(),\n+\t\thistory: storage.db.prepare(\"SELECT * FROM writer_history_keys ORDER BY namespace,collection,key,revision\").all(),\n+\t\theads: storage.db.prepare(\"SELECT * FROM writer_history_heads ORDER BY namespace\").all(),\n+\t});\n+\tconst before = rows();\n+\tconst original = SqliteWriterState.prototype.write;\n+\tconst failure = t.mock.method(\n+\t\tSqliteWriterState.prototype,\n+\t\t\"write\",\n+\t\tfunction (this: SqliteWriterState, collection: string, key: string, value: unknown) {\n+\t\t\toriginal.call(this, collection, key, value);\n+\t\t\tif (collection === \"runtime:receipt:chunk-failure\" && key === \"1\") throw Error(\"injected receipt chunk failure\");\n+\t\t},\n+\t);\n+\tconst request = { id: \"chunk-failure\", identity: { operation: \"fixture\" } };\n+\tconst operation = (calls: EngineProject) => {\n+\t\tassert.equal(answer(calls, \"record\", \"alice\", { files: { \"a.txt\": \"two\\n\" } }).status, 200);\n+\t\treturn { body: \"x\".repeat(140000) };\n+\t};\n+\tassert.throws(() => runtime().write(operation, () => {}, request), /injected receipt chunk failure/);\n+\tassert.deepEqual(rows(), before);\n+\tfailure.mock.restore();\n+\tconst result = runtime().write(operation, () => {}, request);\n+\tconst committed = rows();\n+\tassert.deepEqual(\n+\t\truntime().write(\n+\t\t\t() => {\n+\t\t\t\tthrow Error(\"must not execute\");\n+\t\t\t},\n+\t\t\t() => {},\n+\t\t\trequest,\n+\t\t),\n+\t\tresult,\n+\t);\n+\tassert.deepEqual(rows(), committed);\n+\tconst state = new SqliteWriterState(storage, \"receipt-failure\");\n+\tconst chunk = state.read(\"runtime:receipt:chunk-failure\", \"1\") as string;\n+\tstate.write(\"runtime:receipt:chunk-failure\", \"1\", \"y\" + chunk.slice(1));\n+\tassert.throws(\n+\t\t() =>\n+\t\t\truntime().write(\n+\t\t\t\t() => {\n+\t\t\t\t\tthrow Error(\"must not execute\");\n+\t\t\t\t},\n+\t\t\t\t() => {},\n+\t\t\t\trequest,\n+\t\t\t),\n+\t\t/digest mismatch/,\n+\t);\n+\tstate.remove(\"runtime:receipt:chunk-failure\", \"1\");\n+\tassert.throws(\n+\t\t() =>\n+\t\t\truntime().write(\n+\t\t\t\t() => {\n+\t\t\t\t\tthrow Error(\"must not execute\");\n+\t\t\t\t},\n+\t\t\t\t() => {},\n+\t\t\t\trequest,\n+\t\t\t),\n+\t\t/incomplete receipt/,\n+\t);\n+\tassert.deepEqual(rows().log, committed.log);\n+});\n+\n+test(\"runtime format upgrade is authorized, atomic, and rejects unknown formats\", (t) => {\n+\tconst storage = memoryStorage();\n+\tt.after(() => storage.db.close());\n+\tconst runtime = () => new DiskFirstRuntime(storage, \"format-test\", \"format-test\");\n+\truntime().initialize(\n+\t\t(calls) => answer(calls, \"init\", undefined, { files: { \"a.txt\": \"one\\n\" } }),\n+\t\t() => {},\n+\t);\n+\twhile (!runtime().preparePage(() => {}).ready) {}\n+\tconst state = new SqliteWriterState(storage, \"format-test\");\n+\tassert.equal(state.read(\"runtime\", \"format\"), 5);\n+\tstate.write(\"runtime\", \"format\", 3);\n+\tconst before = storage.db.prepare(\"SELECT * FROM writer_state ORDER BY namespace,collection,key,part\").all();\n+\tlet validations = 0;\n+\tassert.throws(\n+\t\t() =>\n+\t\t\truntime().preparePage(() => {\n+\t\t\t\tif (++validations === 2) throw Error(\"revoked during upgrade\");\n+\t\t\t}),\n+\t\t/revoked/,\n+\t);\n+\tassert.deepEqual(\n+\t\tstorage.db.prepare(\"SELECT * FROM writer_state ORDER BY namespace,collection,key,part\").all(),\n+\t\tbefore,\n+\t);\n+\tassert.equal(runtime().preparePage(() => {}).ready, true);\n+\tassert.equal(state.read(\"runtime\", \"format\"), 5);\n+\tstate.write(\"runtime\", \"format\", 999);\n+\tassert.throws(() => runtime().preparePage(() => {}), /unsupported disk-first runtime format/);\n+\tassert.equal(state.read(\"runtime\", \"format\"), 999);\n+});"},{"path":"server/test/frame-chunks.test.ts","added":35,"removed":0,"diff":"--- /dev/null\n+++ b/server/test/frame-chunks.test.ts\n@@ -0,0 +1,35 @@\n+import assert from \"node:assert/strict\";\n+import { createHash } from \"node:crypto\";\n+import { test } from \"node:test\";\n+import { logParts, SqliteLog } from \"../src/engine-project.ts\";\n+import { writerFrameChunksDigest, writerFrameDigest } from \"../src/writer-host.ts\";\n+import { memoryStorage } from \"./helpers.ts\";\n+\n+test(\"canonical chunks stream oversized frames and reject missing parts\", (t) => {\n+\tconst storage = memoryStorage();\n+\tt.after(() => storage.db.close());\n+\tconst log = new SqliteLog(storage);\n+\tconst json = JSON.stringify({ value: \"x\".repeat(8_100_000) });\n+\tfor (const [part, text] of logParts(json).entries())\n+\t\tstorage.sql.exec(\"INSERT INTO log (seq,part,text) VALUES (?, ?, ?)\", 0, part, text);\n+\tassert.equal(writerFrameChunksDigest(\"\", 0, log.frameChunks(0)), writerFrameDigest(\"\", 0, json));\n+\tstorage.sql.exec(\"DELETE FROM log WHERE seq = 0 AND part = 1\");\n+\tassert.throws(() => {\n+\t\tfor (const _ of log.frameChunks(0)) {\n+\t\t}\n+\t}, /incomplete/);\n+\tassert.throws(() => log.frameChunks(1).next(), /missing/);\n+});\n+test(\"chunked writer digests preserve Unicode across every split\", () => {\n+\tconst text = '{\"value\":\"a\\u{1f600}b\\u{1d11e}c\"}'.replace(/\\\\u\\{([0-9a-f]+)\\}/g, (_, hex) =>\n+\t\tString.fromCodePoint(Number.parseInt(hex, 16)),\n+\t);\n+\tconst reference = createHash(\"sha256\")\n+\t\t.update(\"abso-writer-log-v1\\n\")\n+\t\t.update(JSON.stringify([\"prior\", 7]))\n+\t\t.update(\"\\n\")\n+\t\t.update(text, \"utf8\")\n+\t\t.digest(\"hex\");\n+\tfor (let at = 0; at <= text.length; at++)\n+\t\tassert.equal(writerFrameChunksDigest(\"prior\", 7, [text.slice(0, at), \"\", text.slice(at)]), reference);\n+});"},{"path":"server/test/history-host.test.ts","added":180,"removed":0,"diff":"--- /dev/null\n+++ b/server/test/history-host.test.ts\n@@ -0,0 +1,180 @@\n+import assert from \"node:assert/strict\";\n+import { test } from \"node:test\";\n+import { MemoryStore, Project } from \"../../worker/project/project.ts\";\n+import { SqliteLog } from \"../src/engine-project.ts\";\n+import { SqliteHistoryHost } from \"../src/history-host.ts\";\n+import { advanceWriterRoot, SqliteWriterHost, SqliteWriterState } from \"../src/writer-host.ts\";\n+import { memoryStorage } from \"./helpers.ts\";\n+\n+test(\"historical host binds paged snapshots to the verified canonical root\", (t) => {\n+\tconst storage = memoryStorage();\n+\tt.after(() => storage.db.close());\n+\tconst memory = new MemoryStore();\n+\tconst project = new Project(memory);\n+\tproject.init({ \"a.txt\": \"one\\n\" }, 0);\n+\tfor (let i = 1; i <= 18; i++) {\n+\t\tproject.record(\"alice\", { \"a.txt\": `${i}\\n` }, i * 2);\n+\t\tproject.publish(\"alice\", `Change ${i}`, i * 2 + 1);\n+\t}\n+\tconst expected = memory.entries.map((_, index) =>\n+\t\tProject.load(memory.entries.slice(0, index + 1), new MemoryStore()).status(),\n+\t);\n+\tconst log = new SqliteLog(storage);\n+\tlog.append(memory.entries);\n+\tSqliteWriterState.initialize(storage);\n+\tconst writer = new SqliteWriterHost(storage, \"writer\");\n+\tlet from = 0;\n+\tfor (;;) {\n+\t\tconst page = writer.adoptPage(from, { maxEntries: 32, maxBytes: 1_048_576 }, () => {});\n+\t\tfrom = page.next;\n+\t\tif (page.ready) break;\n+\t}\n+\tconst root = writer.root();\n+\tt.mock.method(Project, \"load\", () => {\n+\t\tthrow Error(\"full-history replay forbidden\");\n+\t});\n+\tconst history = () => new SqliteHistoryHost(storage, \"history\");\n+\tlet pages = 0;\n+\twhile (\n+\t\t!history().prepare(\n+\t\t\tlog,\n+\t\t\troot,\n+\t\t\t() => writer.root(),\n+\t\t\t() => {},\n+\t\t).ready\n+\t) {\n+\t\tpages++;\n+\t\tassert.throws(\n+\t\t\t() =>\n+\t\t\t\thistory().read(\n+\t\t\t\t\troot,\n+\t\t\t\t\t() => writer.root(),\n+\t\t\t\t\t() => {},\n+\t\t\t\t\t1,\n+\t\t\t\t\t(p) => p.status(),\n+\t\t\t\t),\n+\t\t\t/not ready/,\n+\t\t);\n+\t}\n+\tassert.ok(pages > 0);\n+\tlet authorized = true;\n+\tassert.throws(\n+\t\t() =>\n+\t\t\thistory().read(\n+\t\t\t\troot,\n+\t\t\t\t() => root,\n+\t\t\t\t() => {\n+\t\t\t\t\tif (!authorized) throw Error(\"authority expired during read\");\n+\t\t\t\t},\n+\t\t\t\t1,\n+\t\t\t\t(p) => {\n+\t\t\t\t\tconst result = p.status();\n+\t\t\t\t\tauthorized = false;\n+\t\t\t\t\treturn result;\n+\t\t\t\t},\n+\t\t\t),\n+\t\t/authority expired during read/,\n+\t);\n+\tlet observedRoot = root;\n+\tassert.throws(\n+\t\t() =>\n+\t\t\thistory().read(\n+\t\t\t\troot,\n+\t\t\t\t() => observedRoot,\n+\t\t\t\t() => {},\n+\t\t\t\t1,\n+\t\t\t\t(p) => {\n+\t\t\t\t\tconst result = p.status();\n+\t\t\t\t\tobservedRoot = { ...root, generation: root.generation + 1 };\n+\t\t\t\t\treturn result;\n+\t\t\t\t},\n+\t\t\t),\n+\t\t/root changed/,\n+\t);\n+\tfor (let at = 1; at <= root.logLength; at++) {\n+\t\tassert.deepEqual(\n+\t\t\thistory().read(\n+\t\t\t\troot,\n+\t\t\t\t() => writer.root(),\n+\t\t\t\t() => {},\n+\t\t\t\tat,\n+\t\t\t\t(p) => p.status(),\n+\t\t\t),\n+\t\t\texpected[at - 1],\n+\t\t);\n+\t}\n+\tassert.throws(\n+\t\t() =>\n+\t\t\thistory().read(\n+\t\t\t\troot,\n+\t\t\t\t() => ({ ...root, generation: root.generation + 1 }),\n+\t\t\t\t() => {},\n+\t\t\t\t1,\n+\t\t\t\t(p) => p.status(),\n+\t\t\t),\n+\t\t/root changed/,\n+\t);\n+\tassert.throws(\n+\t\t() =>\n+\t\t\thistory().read(\n+\t\t\t\troot,\n+\t\t\t\t() => root,\n+\t\t\t\t() => {\n+\t\t\t\t\tthrow Error(\"revoked\");\n+\t\t\t\t},\n+\t\t\t\t1,\n+\t\t\t\t(p) => p.status(),\n+\t\t\t),\n+\t\t/revoked/,\n+\t);\n+\tconst rows = () => ({\n+\t\tvalues: storage.db.prepare(\"SELECT * FROM writer_state ORDER BY namespace,collection,key,part\").all(),\n+\t\thistory: storage.db.prepare(\"SELECT * FROM writer_history_keys ORDER BY namespace,collection,key,revision\").all(),\n+\t\theads: storage.db.prepare(\"SELECT * FROM writer_history_heads ORDER BY namespace\").all(),\n+\t});\n+\tconst before = rows();\n+\tproject.record(\"alice\", { \"a.txt\": \"tail\\n\" }, 100);\n+\tproject.publish(\"alice\", \"Tail\", 101);\n+\tlog.append(memory.entries.slice(root.logLength));\n+\tconst committed = advanceWriterRoot(log, root, writer.source());\n+\tconst wrong = { ...committed, digest: \"0\".repeat(64) };\n+\tassert.throws(\n+\t\t() =>\n+\t\t\thistory().advance(\n+\t\t\t\tlog,\n+\t\t\t\troot,\n+\t\t\t\twrong,\n+\t\t\t\t() => wrong,\n+\t\t\t\t() => {},\n+\t\t\t),\n+\t\t/tail digest mismatch/,\n+\t);\n+\tassert.deepEqual(rows(), before);\n+\thistory().advance(\n+\t\tlog,\n+\t\troot,\n+\t\tcommitted,\n+\t\t() => committed,\n+\t\t() => {},\n+\t);\n+\tassert.deepEqual(\n+\t\thistory().read(\n+\t\t\tcommitted,\n+\t\t\t() => committed,\n+\t\t\t() => {},\n+\t\t\tcommitted.logLength,\n+\t\t\t(p) => p.status(),\n+\t\t),\n+\t\tproject.status(),\n+\t);\n+\tassert.deepEqual(\n+\t\thistory().read(\n+\t\t\tcommitted,\n+\t\t\t() => committed,\n+\t\t\t() => {},\n+\t\t\troot.logLength,\n+\t\t\t(p) => p.status(),\n+\t\t),\n+\t\texpected.at(-1),\n+\t);\n+});"},{"path":"server/test/history-recovery.test.ts","added":189,"removed":0,"diff":"--- /dev/null\n+++ b/server/test/history-recovery.test.ts\n@@ -0,0 +1,189 @@\n+import assert from \"node:assert/strict\";\n+import { test } from \"node:test\";\n+import { MemoryStore, Project } from \"../../worker/project/project.ts\";\n+import { SqliteLog } from \"../src/engine-project.ts\";\n+import { SqliteHistoryHost } from \"../src/history-host.ts\";\n+import { advanceWriterRoot, SqliteWriterHost, SqliteWriterState } from \"../src/writer-host.ts\";\n+import { memoryStorage } from \"./helpers.ts\";\n+\n+test(\"historical preparation recovers after a writer without history appends\", (t) => {\n+\tconst storage = memoryStorage();\n+\tt.after(() => storage.db.close());\n+\tconst memory = new MemoryStore();\n+\tconst project = new Project(memory);\n+\tproject.init({ \"a.txt\": \"one\\n\" }, 0);\n+\tfor (let i = 1; i <= 20; i++) {\n+\t\tproject.record(\"alice\", { \"a.txt\": `before ${i}\\n` }, i * 2);\n+\t\tproject.publish(\"alice\", `Before ${i}`, i * 2 + 1);\n+\t}\n+\tconst log = new SqliteLog(storage);\n+\tlog.append(memory.entries);\n+\tSqliteWriterState.initialize(storage);\n+\tconst writer = new SqliteWriterHost(storage, \"writer\");\n+\tlet from = 0;\n+\tfor (;;) {\n+\t\tconst page = writer.adoptPage(from, { maxEntries: 32, maxBytes: 1048576 }, () => {});\n+\t\tfrom = page.next;\n+\t\tif (page.ready) break;\n+\t}\n+\tconst previous = writer.root();\n+\tconst history = () => new SqliteHistoryHost(storage, \"history\");\n+\twhile (\n+\t\t!history().prepare(\n+\t\t\tlog,\n+\t\t\tprevious,\n+\t\t\t() => previous,\n+\t\t\t() => {},\n+\t\t).ready\n+\t) {}\n+\tconst oldStatus = project.status();\n+\tproject.record(\"alice\", { \"a.txt\": \"two\\n\" }, 1);\n+\tproject.publish(\"alice\", \"Second\", 2);\n+\tlog.append(memory.entries.slice(previous.logLength));\n+\tconst current = advanceWriterRoot(log, previous, writer.source());\n+\t// The previous runtime commits canonical history but does not advance historical indexes.\n+\tassert.equal(\n+\t\thistory().prepare(\n+\t\t\tlog,\n+\t\t\tcurrent,\n+\t\t\t() => current,\n+\t\t\t() => {},\n+\t\t).ready,\n+\t\tfalse,\n+\t);\n+\tlet ready = false;\n+\tfor (let page = 0; page < 20 && !ready; page++) {\n+\t\tready = history().prepare(\n+\t\t\tlog,\n+\t\t\tcurrent,\n+\t\t\t() => current,\n+\t\t\t() => {},\n+\t\t).ready;\n+\t}\n+\tassert.equal(ready, true);\n+\tassert.deepEqual(\n+\t\thistory().read(\n+\t\t\tcurrent,\n+\t\t\t() => current,\n+\t\t\t() => {},\n+\t\t\tprevious.logLength,\n+\t\t\t(p) => p.status(),\n+\t\t),\n+\t\toldStatus,\n+\t);\n+\tassert.deepEqual(\n+\t\thistory().read(\n+\t\t\tcurrent,\n+\t\t\t() => current,\n+\t\t\t() => {},\n+\t\t\tcurrent.logLength,\n+\t\t\t(p) => p.status(),\n+\t\t),\n+\t\tproject.status(),\n+\t);\n+});\n+\n+for (const shortened of [false, true]) {\n+\ttest(`historical recovery rebuilds ${shortened ? \"shortened\" : \"replaced\"} canonical history`, (t) => {\n+\t\tconst storage = memoryStorage();\n+\t\tt.after(() => storage.db.close());\n+\t\tconst memory = new MemoryStore();\n+\t\tconst project = new Project(memory);\n+\t\tproject.init({ \"old.txt\": \"old\\n\" }, 0);\n+\t\tproject.record(\"alice\", { \"old.txt\": \"changed\\n\" }, 1);\n+\t\tproject.publish(\"alice\", \"Old\", 2);\n+\t\tconst log = new SqliteLog(storage);\n+\t\tlog.append(memory.entries);\n+\t\tSqliteWriterState.initialize(storage);\n+\t\tconst empty = { format: 1 as const, generation: 0, logLength: 0, sharedVersion: 0, digest: \"\" };\n+\t\tconst oldRoot = advanceWriterRoot(log, empty, {\n+\t\t\tgeneration: log.generation(),\n+\t\t\tlogLength: log.seq(),\n+\t\t\tsharedVersion: project.version,\n+\t\t});\n+\t\tconst history = () => new SqliteHistoryHost(storage, \"history\");\n+\t\twhile (\n+\t\t\t!history().prepare(\n+\t\t\t\tlog,\n+\t\t\t\toldRoot,\n+\t\t\t\t() => oldRoot,\n+\t\t\t\t() => {},\n+\t\t\t).ready\n+\t\t) {}\n+\t\tconst replacement = new MemoryStore();\n+\t\tconst current = new Project(replacement);\n+\t\tcurrent.init({ \"new.txt\": \"new\\n\" }, 0);\n+\t\tif (!shortened) {\n+\t\t\tcurrent.record(\"bob\", { \"new.txt\": \"different\\n\" }, 1);\n+\t\t\tcurrent.publish(\"bob\", \"New\", 2);\n+\t\t}\n+\t\tlog.clear();\n+\t\tlog.append(replacement.entries);\n+\t\tconst root = advanceWriterRoot(log, empty, {\n+\t\t\tgeneration: log.generation(),\n+\t\t\tlogLength: log.seq(),\n+\t\t\tsharedVersion: current.version,\n+\t\t});\n+\t\tconst canonical = JSON.stringify(log.since(0, 100));\n+\t\tassert.equal(\n+\t\t\thistory().prepare(\n+\t\t\t\tlog,\n+\t\t\t\troot,\n+\t\t\t\t() => root,\n+\t\t\t\t() => {},\n+\t\t\t).ready,\n+\t\t\tfalse,\n+\t\t);\n+\t\tassert.throws(\n+\t\t\t() =>\n+\t\t\t\thistory().read(\n+\t\t\t\t\troot,\n+\t\t\t\t\t() => root,\n+\t\t\t\t\t() => {},\n+\t\t\t\t\t1,\n+\t\t\t\t\t(p) => p.status(),\n+\t\t\t\t),\n+\t\t\t/not ready/,\n+\t\t);\n+\t\tconst rows = () => ({\n+\t\t\tstate: storage.db.prepare(\"SELECT * FROM writer_state ORDER BY namespace,collection,key,part\").all(),\n+\t\t\tkeys: storage.db.prepare(\"SELECT * FROM writer_history_keys ORDER BY namespace,collection,key,revision\").all(),\n+\t\t\theads: storage.db.prepare(\"SELECT * FROM writer_history_heads ORDER BY namespace\").all(),\n+\t\t});\n+\t\tconst beforeCleanup = rows();\n+\t\tlet validations = 0;\n+\t\tassert.throws(\n+\t\t\t() =>\n+\t\t\t\thistory().prepare(\n+\t\t\t\t\tlog,\n+\t\t\t\t\troot,\n+\t\t\t\t\t() => root,\n+\t\t\t\t\t() => {\n+\t\t\t\t\t\tif (++validations === 2) throw Error(\"authority revoked during cleanup\");\n+\t\t\t\t\t},\n+\t\t\t\t),\n+\t\t\t/authority revoked/,\n+\t\t);\n+\t\tassert.deepEqual(rows(), beforeCleanup);\n+\t\tlet ready = false;\n+\t\tfor (let page = 0; page < 100 && !ready; page++)\n+\t\t\tready = history().prepare(\n+\t\t\t\tlog,\n+\t\t\t\troot,\n+\t\t\t\t() => root,\n+\t\t\t\t() => {},\n+\t\t\t).ready;\n+\t\tassert.equal(ready, true);\n+\t\tassert.deepEqual(\n+\t\t\thistory().read(\n+\t\t\t\troot,\n+\t\t\t\t() => root,\n+\t\t\t\t() => {},\n+\t\t\t\troot.logLength,\n+\t\t\t\t(p) => p.status(),\n+\t\t\t),\n+\t\t\tcurrent.status(),\n+\t\t);\n+\t\tassert.equal(JSON.stringify(log.since(0, 100)), canonical);\n+\t});\n+}"},{"path":"server/test/history-state.test.ts","added":254,"removed":0,"diff":"--- /dev/null\n+++ b/server/test/history-state.test.ts\n@@ -0,0 +1,254 @@\n+import assert from \"node:assert/strict\";\n+import { test } from \"node:test\";\n+import { MemoryStore, Project } from \"../../worker/project/project.ts\";\n+import { where } from \"../../worker/project/where.ts\";\n+import { EngineProject } from \"../src/engine-project.ts\";\n+import { SqliteHistoryState } from \"../src/history-state.ts\";\n+import { SqliteWriterState } from \"../src/writer-host.ts\";\n+import { memoryStorage } from \"./helpers.ts\";\n+\n+test(\"bounded adoption checkpoints reopen every historical Project prefix without replay\", (t) => {\n+\tconst storage = memoryStorage();\n+\tt.after(() => storage.db.close());\n+\tSqliteHistoryState.initialize(storage);\n+\tconst log = new MemoryStore();\n+\tconst project = new Project(log);\n+\tproject.init({ \"a.txt\": \"one\\ntwo\\n\" }, 0);\n+\tproject.record(\"alice\", { \"a.txt\": \"ONE\\ntwo\\n\" }, 1);\n+\tproject.publish(\"alice\", \"First\", 2);\n+\tproject.move(\"alice\", \"a.txt\", \"b.txt\", 3);\n+\tproject.publish(\"alice\", \"Move\", 4);\n+\tconst expected = log.entries.map((_, i) => {\n+\t\tconst prefix = Project.load(log.entries.slice(0, i + 1), new MemoryStore());\n+\t\treturn { status: prefix.status(), where: where(prefix) };\n+\t});\n+\tt.mock.method(Project, \"load\", () => {\n+\t\tthrow Error(\"full-history replay forbidden\");\n+\t});\n+\tconst source = { generation: 1, logLength: log.entries.length, sharedVersion: project.version };\n+\tlet from = 0;\n+\twhile (from < log.entries.length) {\n+\t\tconst state = new SqliteHistoryState(storage, \"project-history\", from);\n+\t\tconst frames = log.entries\n+\t\t\t.slice(from, from + 2)\n+\t\t\t.map((entry, i) => ({ seq: from + i, json: JSON.stringify(entry) }));\n+\t\tconst page = Project.adoptWriterPage(state, {\n+\t\t\tsource,\n+\t\t\tfrom,\n+\t\t\tframes,\n+\t\t\tmaxEntries: 2,\n+\t\t\tmaxBytes: 16384,\n+\t\t\tcurrentSource: () => source,\n+\t\t\tbeginRevision: (revision) => state.beginRevision(revision),\n+\t\t});\n+\t\tfrom = page.next;\n+\t}\n+\tconst state = new SqliteHistoryState(storage, \"project-history\", from);\n+\tstate.seal();\n+\tlet active = true;\n+\tconst calls = new EngineProject(project, undefined, undefined, (at, operation) => {\n+\t\tconst validate = () => {\n+\t\t\tif (!active) throw Error(\"historical scope expired\");\n+\t\t};\n+\t\tvalidate();\n+\t\treturn operation(\n+\t\t\tat === 0\n+\t\t\t\t? new Project(new MemoryStore())\n+\t\t\t\t: Project.openHistorical(state.at(at, validate), at, new SqliteWriterState(storage, \"history-scratch\")),\n+\t\t);\n+\t});\n+\tassert.deepEqual(calls.statusAt(0), { at: 0, version: -1, agents: [] });\n+\tassert.deepEqual(calls.whereAt(0), { at: 0, version: -1, files: {} });\n+\tfor (let at = 1; at <= from; at++) {\n+\t\tconst historical = Project.openHistorical(state.at(at), at, new SqliteWriterState(storage, \"history-scratch\"));\n+\t\tassert.deepEqual(historical.status(), expected[at - 1]!.status, `status at ${at}`);\n+\t\tassert.deepEqual(where(historical), expected[at - 1]!.where, `where at ${at}`);\n+\t\tassert.deepEqual(calls.statusAt(at), { at, ...expected[at - 1]!.status });\n+\t\tassert.deepEqual(calls.whereAt(at), { at, ...expected[at - 1]!.where });\n+\t}\n+\tassert.deepEqual(calls.statusAt(from + 10), { at: from, ...expected[from - 1]!.status });\n+\tactive = false;\n+\tassert.throws(() => calls.statusAt(1), /scope expired/);\n+\tassert.throws(() => calls.whereAt(1), /scope expired/);\n+\tassert.equal(\n+\t\tstorage.db.prepare(\"SELECT COUNT(*) AS n FROM writer_state WHERE namespace = 'history-scratch'\").get()!.n,\n+\t\t0,\n+\t);\n+});\n+\n+test(\"historical state preserves old values, deletions and undefined across reopen\", (t) => {\n+\tconst storage = memoryStorage();\n+\tt.after(() => storage.db.close());\n+\tSqliteHistoryState.initialize(storage);\n+\tlet state = new SqliteHistoryState(storage, \"history\");\n+\tstate.beginRevision(1);\n+\tstate.write(\"values\", \"\", \"empty key\");\n+\tfor (let i = 0; i < 150; i++) state.write(\"values\", `key-${i.toString().padStart(3, \"0\")}`, { value: i });\n+\tstate.write(\"values\", \"undefined\", undefined);\n+\tstate.beginRevision(2);\n+\tstate.write(\"values\", \"key-000\", { value: \"changed\" });\n+\tstate.remove(\"values\", \"key-001\");\n+\tstate.remove(\"values\", \"undefined\");\n+\tstate.seal();\n+\tstate = new SqliteHistoryState(storage, \"history\", 2);\n+\tassert.deepEqual(state.at(1).read(\"values\", \"key-000\"), { value: 0 });\n+\tassert.deepEqual(state.at(2).read(\"values\", \"key-000\"), { value: \"changed\" });\n+\tconst old = new Map(state.at(1).entries(\"values\"));\n+\tconst current = new Map(state.at(2).entries(\"values\"));\n+\tassert.equal(old.size, 152);\n+\tassert.equal(current.size, 150);\n+\tassert.equal(old.has(\"undefined\"), true);\n+\tassert.equal(current.has(\"undefined\"), false);\n+\tassert.equal(current.has(\"key-001\"), false);\n+\tassert.equal(current.get(\"\"), \"empty key\");\n+\tassert.throws(() => state.at(3), /outside authority/);\n+\tassert.throws(() => state.at(1).write(\"values\", \"bad\", 1), /read-only/);\n+\tassert.throws(() => state.write(\"values\", \"bad\", 1), /sealed/);\n+\tconst reopened = new SqliteHistoryState(storage, \"history\", 2);\n+\tassert.throws(() => reopened.write(\"values\", \"key-000\", \"overwrite\"), /sealed/);\n+\treopened.beginRevision(3);\n+\treopened.write(\"values\", \"key-000\", \"new revision\");\n+\treopened.seal();\n+\tassert.deepEqual(reopened.at(2).read(\"values\", \"key-000\"), { value: \"changed\" });\n+});\n+\n+test(\"new canonical tails extend historical snapshots atomically without replaying old entries\", (t) => {\n+\tconst storage = memoryStorage();\n+\tt.after(() => storage.db.close());\n+\tSqliteHistoryState.initialize(storage);\n+\tconst log = new MemoryStore();\n+\tconst live = new Project(log);\n+\tlive.init({ \"a.txt\": \"one\\ntwo\\n\" }, 0);\n+\tconst initialLength = log.entries.length;\n+\tconst initial = live.status();\n+\tconst state = new SqliteHistoryState(storage, \"tail\");\n+\tconst source = { generation: 1, logLength: initialLength, sharedVersion: live.version };\n+\tProject.adoptWriterPage(state, {\n+\t\tsource,\n+\t\tfrom: 0,\n+\t\tmaxEntries: 256,\n+\t\tmaxBytes: 16384,\n+\t\tframes: log.entries.map((entry, seq) => ({ seq, json: JSON.stringify(entry) })),\n+\t\tcurrentSource: () => source,\n+\t\tbeginRevision: (revision) => state.beginRevision(revision),\n+\t});\n+\tstate.seal();\n+\tlive.record(\"alice\", { \"a.txt\": \"ONE\\ntwo\\n\" }, 1);\n+\tlive.publish(\"alice\", \"First\", 2);\n+\tconst expected = log.entries.map((_, i) => {\n+\t\tconst p = Project.load(log.entries.slice(0, i + 1), new MemoryStore());\n+\t\treturn { status: p.status(), where: where(p) };\n+\t});\n+\tt.mock.method(Project, \"load\", () => {\n+\t\tthrow Error(\"full-history replay forbidden\");\n+\t});\n+\tconst rows = () => ({\n+\t\tvalues: storage.db.prepare(\"SELECT * FROM writer_state ORDER BY namespace,collection,key,part\").all(),\n+\t\thistory: storage.db.prepare(\"SELECT * FROM writer_history_keys ORDER BY namespace,collection,key,revision\").all(),\n+\t\theads: storage.db.prepare(\"SELECT * FROM writer_history_heads ORDER BY namespace\").all(),\n+\t});\n+\tconst before = rows();\n+\tconst frames = log.entries\n+\t\t.slice(initialLength)\n+\t\t.map((entry, i) => ({ seq: initialLength + i, json: JSON.stringify(entry) }));\n+\tlet validations = 0;\n+\tassert.throws(\n+\t\t() =>\n+\t\t\tProject.extendHistoricalPage(state, {\n+\t\t\t\tfrom: initialLength,\n+\t\t\t\tframes,\n+\t\t\t\tmaxEntries: 256,\n+\t\t\t\tmaxBytes: 16384,\n+\t\t\t\tbeginRevision: (revision) => state.beginRevision(revision),\n+\t\t\t\tvalidateAuthority: () => {\n+\t\t\t\t\tif (++validations === 2) throw Error(\"canonical tail changed\");\n+\t\t\t\t},\n+\t\t\t}),\n+\t\t/canonical tail changed/,\n+\t);\n+\tassert.deepEqual(rows(), before);\n+\tlet from = initialLength;\n+\twhile (from < log.entries.length) {\n+\t\tconst reopened = new SqliteHistoryState(storage, \"tail\", from);\n+\t\tconst page = Project.extendHistoricalPage(reopened, {\n+\t\t\tfrom,\n+\t\t\tframes: frames.filter((frame) => frame.seq >= from).slice(0, 2),\n+\t\t\tmaxEntries: 2,\n+\t\t\tmaxBytes: 16384,\n+\t\t\tbeginRevision: (revision) => reopened.beginRevision(revision),\n+\t\t\tvalidateAuthority: () => {},\n+\t\t});\n+\t\treopened.seal();\n+\t\tfrom = page.next;\n+\t}\n+\tconst reopened = new SqliteHistoryState(storage, \"tail\", from);\n+\tconst scratch = new SqliteWriterState(storage, \"tail-scratch\");\n+\tassert.deepEqual(Project.openHistorical(reopened.at(initialLength), initialLength, scratch).status(), initial);\n+\tfor (let at = initialLength + 1; at <= from; at++) {\n+\t\tconst historical = Project.openHistorical(reopened.at(at), at, scratch);\n+\t\tassert.deepEqual(historical.status(), expected[at - 1]!.status);\n+\t\tassert.deepEqual(where(historical), expected[at - 1]!.where);\n+\t}\n+});\n+\n+test(\"current state and its history roll back together\", (t) => {\n+\tconst storage = memoryStorage();\n+\tt.after(() => storage.db.close());\n+\tSqliteHistoryState.initialize(storage);\n+\tconst state = new SqliteHistoryState(storage, \"rollback\");\n+\tstate.beginRevision(1);\n+\tstate.write(\"values\", \"a\", { before: true });\n+\tstate.seal();\n+\tconst rows = () => ({\n+\t\tvalues: storage.db.prepare(\"SELECT * FROM writer_state ORDER BY namespace,collection,key,part\").all(),\n+\t\thistory: storage.db.prepare(\"SELECT * FROM writer_history_keys ORDER BY namespace,collection,key,revision\").all(),\n+\t\theads: storage.db.prepare(\"SELECT * FROM writer_history_heads ORDER BY namespace\").all(),\n+\t});\n+\tconst before = rows();\n+\tassert.throws(\n+\t\t() =>\n+\t\t\tstate.transaction(() => {\n+\t\t\t\tstate.beginRevision(2);\n+\t\t\t\tstate.write(\"values\", \"a\", { after: true });\n+\t\t\t\tstate.remove(\"values\", \"a\");\n+\t\t\t\tstate.seal();\n+\t\t\t\tthrow Error(\"injected failure\");\n+\t\t\t}),\n+\t\t/injected failure/,\n+\t);\n+\tassert.deepEqual(rows(), before);\n+\tassert.throws(() => state.at(2), /outside authority/);\n+\tassert.deepEqual(state.read(\"values\", \"a\"), { before: true });\n+});\n+\n+test(\"historical readers recheck canonical authority after creation and between yielded keys\", (t) => {\n+\tconst storage = memoryStorage();\n+\tt.after(() => storage.db.close());\n+\tSqliteHistoryState.initialize(storage);\n+\tconst state = new SqliteHistoryState(storage, \"authority\");\n+\tstate.beginRevision(1);\n+\tstate.write(\"values\", \"a\", 1);\n+\tstate.write(\"values\", \"b\", 2);\n+\tstate.seal();\n+\tlet valid = true;\n+\tconst guard = () => {\n+\t\tif (!valid) throw Error(\"canonical authority expired\");\n+\t};\n+\tconst historical = state.at(1, guard);\n+\tconst iterator = historical.entries(\"values\")[Symbol.iterator]();\n+\tassert.deepEqual(iterator.next().value, [\"a\", 1]);\n+\tvalid = false;\n+\tassert.throws(() => iterator.next(), /authority expired/);\n+\tassert.throws(() => historical.read(\"values\", \"a\"), /authority expired/);\n+\tassert.throws(() => historical.entries(\"values\")[Symbol.iterator]().next(), /authority expired/);\n+\tlet called = false;\n+\tassert.throws(\n+\t\t() =>\n+\t\t\thistorical.transaction(() => {\n+\t\t\t\tcalled = true;\n+\t\t\t}),\n+\t\t/authority expired/,\n+\t);\n+\tassert.equal(called, false);\n+\tassert.throws(() => state.at(1, guard), /authority expired/);\n+});"},{"path":"server/test/json-chunk-cursor.test.ts","added":43,"removed":0,"diff":"--- /dev/null\n+++ b/server/test/json-chunk-cursor.test.ts\n@@ -0,0 +1,43 @@\n+import assert from \"node:assert/strict\";\n+import { test } from \"node:test\";\n+import { JsonChunkCursor } from \"../src/json-chunk-cursor.ts\";\n+\n+test(\"JSON strings decode exactly across every input boundary\", () => {\n+\tconst values = [\"\", \"plain\", 'quotes\" and slash\\\\', \"\\n\\r\\t\\b\\f\", \"\\uD83D\\uDE00\", \"\\uD800\", \"\\uDC00\"];\n+\tconst encoded = values.map((value) => JSON.stringify(value));\n+\tencoded.push('\"\\\\uD83D\\\\uDE00\\\\u0000\\\\/\"');\n+\tfor (const json of encoded)\n+\t\tfor (let split = 0; split <= json.length; split++) {\n+\t\t\tconst cursor = new JsonChunkCursor([json.slice(0, split), \"\", json.slice(split), \",\"]);\n+\t\t\tassert.equal([...cursor.stringChunks()].join(\"\"), JSON.parse(json));\n+\t\t\tassert.equal(cursor.take(), \",\");\n+\t\t\tassert.equal(cursor.peek(), undefined);\n+\t\t}\n+\tfor (const invalid of ['\"unterminated', '\"\\\\x\"', '\"\\\\u12xz\"', '\"\\\\u123', '\"raw\\ncontrol\"']) {\n+\t\tconst cursor = new JsonChunkCursor(invalid.split(\"\"));\n+\t\tassert.throws(() => [...cursor.stringChunks()], /JSON/);\n+\t}\n+});\n+\n+test(\"long JSON strings decode in fixed-size output chunks\", () => {\n+\tlet closed = false;\n+\tconst cursor = new JsonChunkCursor(\n+\t\t(function* () {\n+\t\t\ttry {\n+\t\t\t\tyield '\"';\n+\t\t\t\tfor (let i = 0; i < 500; i++) yield \"x\".repeat(16384);\n+\t\t\t\tyield '\"';\n+\t\t\t} finally {\n+\t\t\t\tclosed = true;\n+\t\t\t}\n+\t\t})(),\n+\t);\n+\tlet count = 0;\n+\tfor (const chunk of cursor.stringChunks()) {\n+\t\tassert.ok(chunk.length <= 16384);\n+\t\tcount += chunk.length;\n+\t}\n+\tassert.equal(count, 8192000);\n+\tcursor.close();\n+\tassert.equal(closed, true);\n+});"},{"path":"server/test/json-events.test.ts","added":148,"removed":0,"diff":"--- /dev/null\n+++ b/server/test/json-events.test.ts\n@@ -0,0 +1,148 @@\n+import assert from \"node:assert/strict\";\n+import { test } from \"node:test\";\n+import { jsonEvents } from \"../src/json-events.ts\";\n+\n+test(\"structural JSON decoding is invariant at every chunk boundary\", () => {\n+\tconst documents = [\n+\t\t'{\"type\":\"init\",\"atom\":{\"lines\":[\"a\\\\n\",\"\\\\uD83D\\\\uDE00\"],\"seq\":0}}',\n+\t\t\"[true,false,null,-0,1.2e-3,{},[]]\",\n+\t\t'\"plain\"',\n+\t];\n+\tfor (const document of documents) {\n+\t\tconst expected = [...jsonEvents([document])];\n+\t\tfor (let split = 0; split <= document.length; split++)\n+\t\t\tassert.deepEqual([...jsonEvents([document.slice(0, split), document.slice(split)])], expected);\n+\t}\n+\tfor (const invalid of [\n+\t\t'{\"a\":1,}',\n+\t\t\"[1,]\",\n+\t\t'{\"a\" 1}',\n+\t\t\"[01]\",\n+\t\t\"[+1]\",\n+\t\t\"[.1]\",\n+\t\t\"[1e]\",\n+\t\t\"[undefined]\",\n+\t\t\"true false\",\n+\t\t\"[\",\n+\t\t\"{\",\n+\t])\n+\t\tassert.throws(() => [...jsonEvents([invalid])], /JSON/);\n+\tassert.throws(() => [...jsonEvents([\"[\".repeat(130) + \"0\" + \"]\".repeat(130)])], /nesting/);\n+});\n+\n+test(\"structural JSON decoding streams large arrays and closes early input\", () => {\n+\tlet closed = false;\n+\tconst source = function* () {\n+\t\ttry {\n+\t\t\tyield \"[\";\n+\t\t\tfor (let i = 0; i < 100000; i++) yield `${i ? \",\" : \"\"}${i}`;\n+\t\t\tyield \"]\";\n+\t\t} finally {\n+\t\t\tclosed = true;\n+\t\t}\n+\t};\n+\tlet count = 0;\n+\tfor (const event of jsonEvents(source()))\n+\t\tif (event.kind === \"value\") {\n+\t\t\tassert.equal(event.value, count);\n+\t\t\tcount++;\n+\t\t}\n+\tassert.equal(count, 100000);\n+\tassert.equal(closed, true);\n+\tclosed = false;\n+\tfor (const event of jsonEvents(source())) {\n+\t\tassert.equal(event.kind, \"array\");\n+\t\tbreak;\n+\t}\n+\tassert.equal(closed, true);\n+});\n+\n+function materialize(document: string): unknown {\n+\tconst events = jsonEvents(document.split(\"\"));\n+\tconst next = () => {\n+\t\tconst event = events.next();\n+\t\tif (event.done) throw Error(\"missing event\");\n+\t\treturn event.value;\n+\t};\n+\tconst value = (event = next()): unknown => {\n+\t\tif (event.kind === \"value\") return event.value;\n+\t\tif (event.kind === \"string\") {\n+\t\t\tlet text = \"\";\n+\t\t\tfor (;;) {\n+\t\t\t\tconst fragment = next();\n+\t\t\t\tif (fragment.kind === \"string-end\") return text;\n+\t\t\t\tif (fragment.kind !== \"text\") throw Error(\"bad string event\");\n+\t\t\t\ttext += fragment.value;\n+\t\t\t}\n+\t\t}\n+\t\tif (event.kind === \"array\") {\n+\t\t\tconst result: unknown[] = [];\n+\t\t\tfor (;;) {\n+\t\t\t\tconst child = next();\n+\t\t\t\tif (child.kind === \"end\") return result;\n+\t\t\t\tresult.push(value(child));\n+\t\t\t}\n+\t\t}\n+\t\tif (event.kind === \"object\") {\n+\t\t\tconst result: Record<string, unknown> = {};\n+\t\t\tfor (;;) {\n+\t\t\t\tconst key = next();\n+\t\t\t\tif (key.kind === \"end\") return result;\n+\t\t\t\tif (key.kind !== \"key\") throw Error(\"bad key event\");\n+\t\t\t\tObject.defineProperty(result, key.value, {\n+\t\t\t\t\tvalue: value(),\n+\t\t\t\t\tenumerable: true,\n+\t\t\t\t\twritable: true,\n+\t\t\t\t\tconfigurable: true,\n+\t\t\t\t});\n+\t\t\t}\n+\t\t}\n+\t\tthrow Error(\"unexpected event\");\n+\t};\n+\tconst result = value();\n+\tassert.equal(events.next().done, true);\n+\treturn result;\n+}\n+\n+test(\"streamed JSON agrees with JSON.parse on generated and adversarial documents\", () => {\n+\tlet seed = 731;\n+\tconst random = () => (seed = (Math.imul(seed, 1664525) + 1013904223) >>> 0);\n+\tconst generate = (depth: number): unknown => {\n+\t\tconst choice = random() % (depth ? 6 : 4);\n+\t\tif (choice === 0) return null;\n+\t\tif (choice === 1) return random() % 2 === 0;\n+\t\tif (choice === 2) return (random() - 0x80000000) / 17;\n+\t\tif (choice === 3) return `quotes\"\\\\\\n${String.fromCharCode(random() % 65536)}\\uD83D\\uDE00`;\n+\t\tif (choice === 4) return Array.from({ length: random() % 5 }, () => generate(depth - 1));\n+\t\treturn Object.fromEntries(Array.from({ length: random() % 5 }, (_, i) => [`key${i}`, generate(depth - 1)]));\n+\t};\n+\tfor (let i = 0; i < 200; i++) {\n+\t\tconst document = JSON.stringify(generate(4));\n+\t\tassert.deepEqual(materialize(document), JSON.parse(document));\n+\t}\n+\tfor (const document of [\n+\t\t'{\"__proto__\":{\"polluted\":true},\"constructor\":0,\"a\":1,\"a\":2}',\n+\t\t\"[-0,1e999,-1e999,1e-999]\",\n+\t\t'{\"\\\\u0061\":\"\\\\uD800\\\\uDC00\"}',\n+\t])\n+\t\tassert.deepEqual(materialize(document), JSON.parse(document));\n+});\n+\n+import { MemoryStore, Project } from \"../../worker/project/project.ts\";\n+\n+test(\"streamed JSON preserves real canonical project entries\", () => {\n+\tconst memory = new MemoryStore();\n+\tconst project = new Project(memory);\n+\tproject.init({ \"a.txt\": \"one\\ntwo\\n\" }, 0);\n+\tproject.record(\"alice\", { \"a.txt\": \"ONE\\ntwo\\n\" }, 1);\n+\tproject.publish(\"alice\", \"Publish\", 2);\n+\tproject.switchTo(\"alice\", \"draft\", 3);\n+\tproject.record(\"alice\", { \"a.txt\": \"ONE\\nTWO\\n\" }, 4);\n+\tproject.publish(\"alice\", \"Draft publish\", 5);\n+\tproject.land(\"alice\", \"Land\", 6);\n+\tfor (const entry of memory.entries) {\n+\t\tconst document = JSON.stringify(entry);\n+\t\tassert.deepEqual(materialize(document), JSON.parse(document));\n+\t}\n+\tassert.ok(memory.entries.length > 5);\n+});"},{"path":"server/test/long-text-history.test.ts","added":61,"removed":0,"diff":"--- /dev/null\n+++ b/server/test/long-text-history.test.ts\n@@ -0,0 +1,61 @@\n+import assert from \"node:assert/strict\";\n+import { test } from \"node:test\";\n+import { Graph } from \"../../src/engine/graph.ts\";\n+import { answer } from \"../../worker/project/http.ts\";\n+import { Project } from \"../../worker/project/project.ts\";\n+import { DiskFirstRuntime } from \"../src/disk-first-runtime.ts\";\n+import { SqliteLog } from \"../src/engine-project.ts\";\n+import { SqliteHistoryState } from \"../src/history-state.ts\";\n+import { memoryStorage } from \"./helpers.ts\";\n+\n+test(\"long text remains exact in current and historical storage after later writes\", (t) => {\n+\tconst storage = memoryStorage();\n+\tt.after(() => storage.db.close());\n+\tconst runtime = () => new DiskFirstRuntime(storage, \"long-history\", \"long-history\");\n+\tconst old = `${\"old\".repeat(20000)}\\uD83D\\uDE00\\n`;\n+\tconst current = `${\"new\".repeat(20000)}\\uD834\\uDD1E\\n`;\n+\truntime().initialize(\n+\t\t(calls) => answer(calls, \"init\", undefined, { files: { \"a.txt\": old } }),\n+\t\t() => {},\n+\t);\n+\twhile (!runtime().preparePage(() => {}).ready) {}\n+\tconst before = runtime().read(\n+\t\t(calls) => calls.fileAt(\"a.txt\", 0, null),\n+\t\t() => {},\n+\t);\n+\tassert.equal(\n+\t\truntime().write(\n+\t\t\t(calls) => answer(calls, \"record\", \"alice\", { files: { \"a.txt\": current } }),\n+\t\t\t() => {},\n+\t\t).status,\n+\t\t200,\n+\t);\n+\tassert.equal(\n+\t\truntime().write(\n+\t\t\t(calls) => answer(calls, \"publish\", \"alice\", { message: \"Replace long line\" }),\n+\t\t\t() => {},\n+\t\t).status,\n+\t\t200,\n+\t);\n+\tt.mock.method(Project, \"load\", () => {\n+\t\tthrow Error(\"full history replay forbidden\");\n+\t});\n+\tassert.deepEqual(\n+\t\truntime().read(\n+\t\t\t(calls) => calls.fileAt(\"a.txt\", 0, null),\n+\t\t\t() => {},\n+\t\t),\n+\t\tbefore,\n+\t);\n+\tassert.equal(\n+\t\truntime().read(\n+\t\t\t(calls) => calls.shared().files[\"a.txt\"],\n+\t\t\t() => {},\n+\t\t),\n+\t\tcurrent,\n+\t);\n+\tconst history = new SqliteHistoryState(storage, \"long-history:history\", new SqliteLog(storage).seq());\n+\tconst graph = new Graph({ storage: history.at(1, () => {}) });\n+\tassert.equal(graph.lineText(\"a0.0\"), old.slice(0, -1));\n+\tassert.equal(graph.atom(\"a0\").inserts[0]!.lines[0], old.slice(0, -1));\n+});"},{"path":"server/test/project-object-disk-first.test.ts","added":285,"removed":4,"diff":"--- a/server/test/project-object-disk-first.test.ts\n+++ b/server/test/project-object-disk-first.test.ts\n@@ -1,8 +1,10 @@\n import assert from \"node:assert/strict\";\n import { registerHooks } from \"node:module\";\n import { test } from \"node:test\";\n+import git from \"isomorphic-git\";\n import { Project } from \"../../worker/project/project.ts\";\n import { EngineProject } from \"../src/engine-project.ts\";\n+import { MemoryFS } from \"../src/memory-fs.ts\";\n import { memoryStorage } from \"./helpers.ts\";\n \n const hooks = registerHooks({\n@@ -45,6 +47,8 @@\n \tconst values = new Map<string, unknown>();\n \tlet alarm: number | null = null;\n \tlet onReaders: (() => Promise<void>) | undefined;\n+\tlet failGitAcknowledgement = false;\n+\tlet failNamePersistence = false;\n \tconst context = {\n \t\tid: { toString: () => \"project-1\" },\n \t\tstorage: {\n@@ -58,6 +62,14 @@\n \t\t\t\treturn values.get(key);\n \t\t\t},\n \t\t\tput: async (key: string | Record<string, unknown>, value?: unknown) => {\n+\t\t\t\tif (key === \"name\" && failNamePersistence) {\n+\t\t\t\t\tfailNamePersistence = false;\n+\t\t\t\t\tthrow Error(\"injected name persistence failure\");\n+\t\t\t\t}\n+\t\t\t\tif (failGitAcknowledgement && typeof key === \"object\" && \"git:head\" in key) {\n+\t\t\t\t\tfailGitAcknowledgement = false;\n+\t\t\t\t\tthrow Error(\"injected Git cursor persistence failure\");\n+\t\t\t\t}\n \t\t\t\tif (typeof key === \"string\") values.set(key, value);\n \t\t\t\telse for (const [name, v] of Object.entries(key)) values.set(name, v);\n \t\t\t},\n@@ -76,9 +88,9 @@\n \tt.mock.method(Project, \"load\", () => {\n \t\tthrow Error(\"full history replay forbidden\");\n \t});\n-\tconst call = async (op: string, agent: string | undefined, body: unknown) => {\n+\tconst call = async (op: string, agent: string | undefined, body: unknown, requestId?: string) => {\n \t\tfor (let page = 0; page < 100; page++) {\n-\t\t\tconst result = await object().call(\"project\", op, agent, body);\n+\t\t\tconst result = await object().call(\"project\", op, agent, body, false, undefined, undefined, requestId);\n \t\t\tif (result.status !== 503) {\n \t\t\t\tassert.notEqual(result.status, 500, JSON.stringify({ op, result }));\n \t\t\t\treturn result;\n@@ -88,12 +100,114 @@\n \t\t}\n \t\tthrow Error(\"adoption did not finish\");\n \t};\n-\tassert.equal((await call(\"init\", undefined, { files: { \"a.txt\": \"one\\ntwo\\n\" } })).status, 200);\n+\tconst initId = \"00000000-0000-4000-8000-000000000008\";\n+\tconst initBody = { files: { \"a.txt\": \"one\\ntwo\\n\" } };\n+\tfailNamePersistence = true;\n+\tawait assert.rejects(\n+\t\t() => object().call(\"project\", \"init\", undefined, initBody, false, undefined, undefined, initId),\n+\t\t/name persistence failure/,\n+\t);\n+\tconst initializedLog = storage.db.prepare(\"SELECT * FROM log ORDER BY seq,part\").all();\n+\tassert.equal((await call(\"init\", undefined, initBody, initId)).status, 200);\n+\tassert.deepEqual(storage.db.prepare(\"SELECT * FROM log ORDER BY seq,part\").all(), initializedLog);\n \tassert.equal((await call(\"sync\", \"alice\", {})).status, 200);\n-\tassert.equal((await call(\"record\", \"alice\", { files: { \"a.txt\": \"changed\\n\" } })).status, 200);\n+\tconst requestId = \"00000000-0000-4000-8000-000000000007\";\n+\tconst recordBody = { files: { \"a.txt\": \"changed\\n\" } };\n+\tfailNamePersistence = true;\n+\tawait assert.rejects(\n+\t\t() => object().call(\"project\", \"record\", \"alice\", recordBody, false, undefined, undefined, requestId),\n+\t\t/name persistence failure/,\n+\t);\n+\tconst recordedLog = storage.db.prepare(\"SELECT * FROM log ORDER BY seq,part\").all();\n+\tassert.equal(\n+\t\t(await object().call(\"project\", \"record\", \"alice\", recordBody, false, undefined, undefined, requestId)).status,\n+\t\t200,\n+\t);\n+\tassert.deepEqual(storage.db.prepare(\"SELECT * FROM log ORDER BY seq,part\").all(), recordedLog);\n+\tassert.equal(\n+\t\t(\n+\t\t\tawait object().call(\n+\t\t\t\t\"project\",\n+\t\t\t\t\"record\",\n+\t\t\t\t\"alice\",\n+\t\t\t\t{ files: { \"a.txt\": \"different\\n\" } },\n+\t\t\t\tfalse,\n+\t\t\t\tundefined,\n+\t\t\t\tundefined,\n+\t\t\t\trequestId,\n+\t\t\t)\n+\t\t).status,\n+\t\t409,\n+\t);\n \tconst published = await call(\"publish\", \"alice\", { message: \"Disk first\" });\n \tassert.equal(published.status, 200);\n \tassert.equal((published.body as { ok: boolean }).ok, true);\n+\tconst issued = await object().issueAgentKey(\"alice\", \"test-address\", null, \"writer\");\n+\tassert.ok(\"key\" in issued);\n+\tconst keyCall = { presented: issued.key, address: \"test-address\", write: true, route: \"record\" };\n+\tconst crossPrincipal = await object().call(\n+\t\t\"project\",\n+\t\t\"record\",\n+\t\t\"alice\",\n+\t\trecordBody,\n+\t\tfalse,\n+\t\tundefined,\n+\t\tkeyCall,\n+\t\trequestId,\n+\t);\n+\tassert.equal(crossPrincipal.status, 200, \"each checked principal owns its own request ID namespace\");\n+\tconst principalReceipts = storage.db\n+\t\t.prepare(\"SELECT DISTINCT key FROM writer_state WHERE collection = 'runtime:receipts' AND key LIKE ?\")\n+\t\t.all(`http:%:${requestId}`);\n+\tassert.equal(principalReceipts.length, 2);\n+\tconst beforeSharedReplay = storage.db.prepare(\"SELECT * FROM log ORDER BY seq,part\").all();\n+\tassert.equal((await call(\"record\", \"alice\", recordBody, requestId)).status, 200);\n+\tassert.deepEqual(storage.db.prepare(\"SELECT * FROM log ORDER BY seq,part\").all(), beforeSharedReplay);\n+\tconst keyRequestId = \"00000000-0000-4000-8000-000000000010\";\n+\tassert.equal(\n+\t\t(await object().call(\"project\", \"record\", \"alice\", recordBody, false, undefined, keyCall, keyRequestId)).status,\n+\t\t200,\n+\t);\n+\tawait object().revokeAgentKey(issued.id, \"test-address\");\n+\tconst beforeRevokedRetry = storage.db.prepare(\"SELECT * FROM log ORDER BY seq,part\").all();\n+\tconst revokedRetry = await object().call(\n+\t\t\"project\",\n+\t\t\"record\",\n+\t\t\"alice\",\n+\t\trecordBody,\n+\t\tfalse,\n+\t\tundefined,\n+\t\tkeyCall,\n+\t\tkeyRequestId,\n+\t);\n+\tassert.equal(revokedRetry.status, 403);\n+\tassert.deepEqual(storage.db.prepare(\"SELECT * FROM log ORDER BY seq,part\").all(), beforeRevokedRetry);\n+\tconst readerId = \"00000000-0000-4000-8000-000000000009\";\n+\tfailNamePersistence = true;\n+\tawait assert.rejects(\n+\t\t() => object().call(\"project\", \"reader\", \"alice\", { reader: true }, false, undefined, undefined, readerId),\n+\t\t/name persistence failure/,\n+\t);\n+\tconst nowRefused = await object().call(\n+\t\t\"project\",\n+\t\t\"record\",\n+\t\t\"alice\",\n+\t\trecordBody,\n+\t\tfalse,\n+\t\tundefined,\n+\t\tundefined,\n+\t\trequestId,\n+\t);\n+\tassert.equal(\n+\t\t(nowRefused.body as { ok: boolean }).ok,\n+\t\tfalse,\n+\t\t\"current reader authority overrides an earlier successful receipt\",\n+\t);\n+\tassert.equal(\n+\t\t(await object().call(\"project\", \"reader\", \"alice\", { reader: true }, false, undefined, undefined, readerId)).status,\n+\t\t200,\n+\t);\n+\tassert.equal((await call(\"reader\", \"alice\", { reader: false })).status, 200);\n \tconst file = await call(\"file\", undefined, { path: \"a.txt\", version: \"1\" });\n \tassert.equal(file.status, 200);\n \tassert.match(JSON.stringify(file.body), /changed/);\n@@ -165,4 +279,171 @@\n \t\t/injected after record/,\n \t);\n \tassert.deepEqual(rows(), stable);\n+\t// Exercise the real alarm and commit builder; only remote transport is mocked.\n+\tt.mock.method(git, \"listServerRefs\", async () => []);\n+\tt.mock.method(git, \"clone\", async () => {\n+\t\tthrow Error(\"empty test repository\");\n+\t});\n+\tlet pushed = 0;\n+\tlet remoteFiles: MemoryFS | undefined;\n+\tt.mock.method(git, \"push\", async (options: Parameters<typeof git.push>[0]) => {\n+\t\tconst oid = await git.resolveRef({ fs: options.fs, dir: options.dir, ref: \"main\" });\n+\t\tconst commit = await git.readCommit({ fs: options.fs, dir: options.dir, oid });\n+\t\tassert.match(commit.commit.message, /abso-version: 2/);\n+\t\tconst blob = await git.readBlob({ fs: options.fs, dir: options.dir, oid, filepath: \"a.txt\" });\n+\t\tassert.equal(new TextDecoder().decode(blob.blob), \"Alice's change\\n\");\n+\t\tpushed++;\n+\t\tremoteFiles = options.fs as MemoryFS;\n+\t\treturn { ok: true };\n+\t});\n+\tconst artifacts = {\n+\t\tget: async () => ({\n+\t\t\tinfo: async () => ({ remote: \"https://artifacts.invalid/test\" }),\n+\t\t\tcreateToken: async () => ({ plaintext: \"invented-test-token\" }),\n+\t\t\t[Symbol.dispose]() {},\n+\t\t}),\n+\t};\n+\tconst bound = () => new ProjectObject(context as never, { ABSO_DISK_FIRST: \"on\", ARTIFACTS: artifacts } as never);\n+\tawait bound().alarm();\n+\tassert.equal(pushed, 1);\n+\tassert.equal((await bound().out()).pushed?.version, 2);\n+\tassert.deepEqual(rows(), stable, \"pushing shared does not mutate canonical project state\");\n+\tawait bound().alarm();\n+\tassert.equal(pushed, 1, \"a cold alarm does not push the same version again\");\n+\tassert.ok(remoteFiles);\n+\tconst remote = remoteFiles;\n+\tconst parent = await git.resolveRef({ fs: remote, dir: \"/repo\", ref: \"main\" });\n+\tconst blob = await git.writeBlob({ fs: remote, dir: \"/repo\", blob: new TextEncoder().encode(\"From Git\\n\") });\n+\tconst tree = await git.writeTree({\n+\t\tfs: remote,\n+\t\tdir: \"/repo\",\n+\t\ttree: [{ mode: \"100644\", path: \"a.txt\", oid: blob, type: \"blob\" }],\n+\t});\n+\tconst incoming = await git.commit({\n+\t\tfs: remote,\n+\t\tdir: \"/repo\",\n+\t\ttree,\n+\t\tparent: [parent],\n+\t\tmessage: \"Plain Git edit\",\n+\t\tauthor: { name: \"Git writer\", email: \"test@example.invalid\" },\n+\t});\n+\tawait git.writeRef({ fs: remote, dir: \"/repo\", ref: \"main\", value: incoming, force: true });\n+\tt.mock.method(git, \"listServerRefs\", async () => [{ ref: \"refs/heads/main\", oid: incoming }]);\n+\tt.mock.method(git, \"clone\", async (options: Parameters<typeof git.clone>[0]) => {\n+\t\t(options.fs as MemoryFS).entries = structuredClone(remote.entries);\n+\t});\n+\tconst beforeIntake = rows();\n+\tconst originalIngest = EngineProject.prototype.ingest;\n+\tconst failedIngest = t.mock.method(\n+\t\tEngineProject.prototype,\n+\t\t\"ingest\",\n+\t\tfunction (this: EngineProject, ...args: Parameters<EngineProject[\"ingest\"]>) {\n+\t\t\toriginalIngest.apply(this, args);\n+\t\t\tthrow Error(\"injected after Git intake\");\n+\t\t},\n+\t);\n+\tawait assert.rejects(() => bound().gitSync(), /injected after Git intake/);\n+\tassert.deepEqual(rows(), beforeIntake);\n+\tassert.equal((await bound().out()).git.head, parent, \"failed intake must not acknowledge the remote head\");\n+\tfailedIngest.mock.restore();\n+\tfailGitAcknowledgement = true;\n+\tawait assert.rejects(() => bound().gitSync(), /Git cursor persistence failure/);\n+\tconst committedIntake = rows();\n+\tassert.equal((await bound().out()).version, 3);\n+\tassert.equal((await bound().out()).git.head, parent);\n+\tconst intake = await bound().gitSync();\n+\tassert.deepEqual(rows(), committedIntake, \"retry after cursor failure returns the atomic intake receipt\");\n+\tassert.ok(intake);\n+\tassert.equal(intake?.head, incoming);\n+\tassert.equal(intake?.commits, 1);\n+\tassert.equal((intake.answer as { landed: boolean }).landed, true, JSON.stringify(intake));\n+\tconst imported = await call(\"file\", undefined, { path: \"a.txt\", version: \"3\" });\n+\tassert.equal(imported.status, 200);\n+\tassert.match(JSON.stringify(imported.body), /From Git/);\n+\tconst afterIntake = rows();\n+\tassert.equal(await bound().gitSync(), null);\n+\tassert.deepEqual(rows(), afterIntake, \"cold intake does not apply the same commit twice\");\n });\n+\n+for (const disk of [false, true]) {\n+\ttest(`Git refusal permits a later fixing commit with disk mode ${disk}`, async (t) => {\n+\t\tconst storage = memoryStorage();\n+\t\tt.after(() => storage.db.close());\n+\t\tconst values = new Map<string, unknown>();\n+\t\tconst context = {\n+\t\t\tid: { toString: () => \"refusal\" },\n+\t\t\tstorage: {\n+\t\t\t\t...storage,\n+\t\t\t\tget: async (key: string) => values.get(key),\n+\t\t\t\tput: async (key: string | Record<string, unknown>, value?: unknown) => {\n+\t\t\t\t\tif (typeof key === \"string\") values.set(key, value);\n+\t\t\t\t\telse for (const [k, v] of Object.entries(key)) values.set(k, v);\n+\t\t\t\t},\n+\t\t\t\tgetAlarm: async () => null,\n+\t\t\t\tsetAlarm: async () => {},\n+\t\t\t},\n+\t\t};\n+\t\tconst artifacts = {\n+\t\t\tget: async () => ({\n+\t\t\t\tinfo: async () => ({ remote: \"https://artifacts.invalid/refusal\" }),\n+\t\t\t\tcreateToken: async () => ({ plaintext: \"invented-test-token\" }),\n+\t\t\t\t[Symbol.dispose]() {},\n+\t\t\t}),\n+\t\t};\n+\t\tconst object = () =>\n+\t\t\tnew ProjectObject(context as never, { ABSO_DISK_FIRST: disk ? \"on\" : \"off\", ARTIFACTS: artifacts } as never);\n+\t\tconst call = async (op: string, body: unknown) => {\n+\t\t\tfor (let page = 0; page < 100; page++) {\n+\t\t\t\tconst result = await object().call(\"refusal\", op, undefined, body);\n+\t\t\t\tif (result.status !== 503) return result;\n+\t\t\t}\n+\t\t\tthrow Error(\"preparation did not finish\");\n+\t\t};\n+\t\tassert.equal((await call(\"init\", { files: { \"a.txt\": \"original\\n\" } })).status, 200);\n+\t\tassert.equal((await call(\"status\", {})).status, 200);\n+\t\tconst remote = new MemoryFS();\n+\t\tawait git.init({ fs: remote, dir: \"/repo\", defaultBranch: \"main\" });\n+\t\tconst commit = async (files: Record<string, string>, message: string, parent: string[]) => {\n+\t\t\tconst entries = [];\n+\t\t\tfor (const [path, text] of Object.entries(files))\n+\t\t\t\tentries.push({\n+\t\t\t\t\tmode: \"100644\",\n+\t\t\t\t\tpath,\n+\t\t\t\t\ttype: \"blob\" as const,\n+\t\t\t\t\toid: await git.writeBlob({ fs: remote, dir: \"/repo\", blob: new TextEncoder().encode(text) }),\n+\t\t\t\t});\n+\t\t\tconst tree = await git.writeTree({ fs: remote, dir: \"/repo\", tree: entries });\n+\t\t\tconst oid = await git.commit({\n+\t\t\t\tfs: remote,\n+\t\t\t\tdir: \"/repo\",\n+\t\t\t\ttree,\n+\t\t\t\tparent,\n+\t\t\t\tmessage,\n+\t\t\t\tauthor: { name: \"Git writer\", email: \"test@example.invalid\" },\n+\t\t\t});\n+\t\t\tawait git.writeRef({ fs: remote, dir: \"/repo\", ref: \"main\", value: oid, force: true });\n+\t\t\treturn oid;\n+\t\t};\n+\t\tconst base = await commit({ \"a.txt\": \"original\\n\" }, \"Initial\\n\\nabso-version: 0\", []);\n+\t\tvalues.set(\"git:head\", base);\n+\t\tlet head = await commit({ \"A.TXT\": \"clash\\n\", \"a.txt\": \"original\\n\" }, \"Refused\", [base]);\n+\t\tt.mock.method(git, \"listServerRefs\", async () => [{ ref: \"refs/heads/main\", oid: head }]);\n+\t\tt.mock.method(git, \"clone\", async (options: Parameters<typeof git.clone>[0]) => {\n+\t\t\t(options.fs as MemoryFS).entries = structuredClone(remote.entries);\n+\t\t});\n+\t\tconst refused = await object().gitSync();\n+\t\tassert.ok(refused);\n+\t\tassert.match(JSON.stringify(refused.answer), /one file|clash/i);\n+\t\tassert.equal(values.get(\"git:head\"), head);\n+\t\tassert.equal(await object().gitSync(), null);\n+\t\thead = await commit({ \"a.txt\": \"fixed\\n\" }, \"Fixed\", [head]);\n+\t\tconst fixed = await object().gitSync();\n+\t\tassert.ok(fixed);\n+\t\tassert.equal((fixed.answer as { landed: boolean }).landed, true, JSON.stringify(fixed));\n+\t\tassert.equal(values.get(\"git:head\"), head);\n+\t\tassert.match(\n+\t\t\tJSON.stringify((await call(\"file\", { path: \"a.txt\", version: String((await object().out()).version) })).body),\n+\t\t\t/fixed/,\n+\t\t);\n+\t});\n+}"},{"path":"server/test/router.test.ts","added":17,"removed":0,"diff":"--- a/server/test/router.test.ts\n+++ b/server/test/router.test.ts\n@@ -45,6 +45,23 @@\n };\n \n describe(\"routes\", () => {\n+\tit(\"forwards request identity separately from untrusted JSON body\", async () => {\n+\t\tconst { env, calls } = fakeEnv();\n+\t\tconst id = \"00000000-0000-4000-8000-000000000007\";\n+\t\tconst response = await handle(\n+\t\t\trequest(\"/p/game/a/alice/record\", {\n+\t\t\t\tmethod: \"POST\",\n+\t\t\t\theaders: { \"content-type\": \"application/json\", \"Idempotency-Key\": id },\n+\t\t\t\tbody: JSON.stringify({ files: {}, principal: \"forged\" }),\n+\t\t\t}),\n+\t\t\tenv,\n+\t\t\tctx,\n+\t\t\tnoIssues as never,\n+\t\t);\n+\t\tassert.equal(response.status, 200);\n+\t\tassert.equal(calls[0]!.args[7], id);\n+\t\tassert.equal(calls[0]!.args[6], undefined);\n+\t});\n \tit(\"matches the project's top routes and an agent's ops\", () => {\n \t\tassert.deepEqual(PROJECT_ROUTE.exec(\"/p/game/status\")?.slice(1, 3), [\"game\", \"status\"]);\n \t\tassert.deepEqual(PROJECT_ROUTE.exec(\"/p/game/a/alice/publish\")?.slice(1), ["},{"path":"server/test/stored-json-view.test.ts","added":35,"removed":0,"diff":"--- /dev/null\n+++ b/server/test/stored-json-view.test.ts\n@@ -0,0 +1,35 @@\n+import assert from \"node:assert/strict\";\n+import { test } from \"node:test\";\n+import { StoredJson, storeJson } from \"../src/stored-json.ts\";\n+import { storedJsonView } from \"../src/stored-json-view.ts\";\n+import { SqliteWriterState } from \"../src/writer-host.ts\";\n+import { memoryStorage } from \"./helpers.ts\";\n+\n+test(\"stored JSON views expose array operations without decoding unrelated payloads\", (t) => {\n+\tconst database = memoryStorage();\n+\tt.after(() => database.db.close());\n+\tSqliteWriterState.initialize(database);\n+\tconst state = new SqliteWriterState(database, \"view\");\n+\tconst input = { type: \"draft\", atom: { deps: [\"a0\", \"a1\"], message: \"x\".repeat(50000) } };\n+\tstoreJson(state, \"entry\", [JSON.stringify(input)]);\n+\tconst read = state.read.bind(state);\n+\tlet chunks = 0;\n+\tstate.read = (collection, key) => {\n+\t\tif (collection.endsWith(\":text:chunks\")) chunks++;\n+\t\treturn read(collection, key);\n+\t};\n+\tconst value = storedJsonView(new StoredJson(state, \"entry\")) as typeof input;\n+\tassert.equal(chunks, 0);\n+\tassert.equal(value.atom.deps.length, 2);\n+\tassert.equal(chunks, 0);\n+\tassert.deepEqual(\n+\t\tvalue.atom.deps.map((x) => x),\n+\t\t[\"a0\", \"a1\"],\n+\t);\n+\tassert.equal(chunks, 2);\n+\tassert.equal(\"message\" in value.atom, true);\n+\tassert.throws(() => {\n+\t\tvalue.atom.deps[0] = \"changed\";\n+\t}, /read-only/);\n+\tassert.deepEqual(JSON.parse(JSON.stringify(value)), input);\n+});"},{"path":"server/test/stored-json.test.ts","added":94,"removed":0,"diff":"--- /dev/null\n+++ b/server/test/stored-json.test.ts\n@@ -0,0 +1,94 @@\n+import assert from \"node:assert/strict\";\n+import { test } from \"node:test\";\n+import { StoredText } from \"../../src/engine/stored-text.ts\";\n+import { StoredJson, storeJson } from \"../src/stored-json.ts\";\n+import { SqliteWriterState } from \"../src/writer-host.ts\";\n+import { memoryStorage } from \"./helpers.ts\";\n+\n+test(\"large JSON text streams into bounded SQLite values\", (t) => {\n+\tconst database = memoryStorage();\n+\tt.after(() => database.db.close());\n+\tSqliteWriterState.initialize(database);\n+\tconst state = new SqliteWriterState(database, \"decoded\");\n+\tconst root = storeJson(\n+\t\tstate,\n+\t\t\"entry\",\n+\t\t(function* () {\n+\t\t\tyield '{\"line\":\"';\n+\t\t\tfor (let i = 0; i < 500; i++) yield \"x\".repeat(16384);\n+\t\t\tyield '\",\"sequence\":0}';\n+\t\t})(),\n+\t);\n+\tassert.deepEqual(state.read(\"entry\", String(root)), { kind: \"object\", count: 2 });\n+\tconst line = state.read(\"entry:edges\", JSON.stringify([root, \"line\"])) as number;\n+\tlet length = 0;\n+\tfor (const chunk of new StoredText(state, \"entry:text\").chunks(String(line))) length += chunk.length;\n+\tassert.equal(length, 8192000);\n+\tassert.ok((database.db.prepare(\"SELECT MAX(length(value)) AS n FROM writer_state\").get()!.n as number) < 100000);\n+\tconst before = database.db.prepare(\"SELECT * FROM writer_state ORDER BY namespace,collection,key,part\").all();\n+\tassert.throws(() => storeJson(state, \"failed\", ['{\"line\":\"', \"x\".repeat(50000), '\",oops}']), /JSON/);\n+\tassert.deepEqual(\n+\t\tdatabase.db.prepare(\"SELECT * FROM writer_state ORDER BY namespace,collection,key,part\").all(),\n+\t\tbefore,\n+\t);\n+\tassert.equal(state.read(\"failed\", \"root\"), undefined);\n+});\n+\n+test(\"disk JSON reads selected children without reading unrelated text\", (t) => {\n+\tconst database = memoryStorage();\n+\tt.after(() => database.db.close());\n+\tSqliteWriterState.initialize(database);\n+\tconst state = new SqliteWriterState(database, \"decoded\");\n+\tstoreJson(state, \"entry\", [\n+\t\t'{\"ignored\":\"',\n+\t\t\"x\".repeat(50000),\n+\t\t'\",\"items\":[true,null,42],\"duplicate\":1,\"duplicate\":2}',\n+\t]);\n+\tconst originalRead = state.read.bind(state);\n+\tstate.read = (collection, key) => {\n+\t\tassert.ok(!collection.includes(\":text\"), \"metadata lookup read text payload\");\n+\t\treturn originalRead(collection, key);\n+\t};\n+\tconst root = new StoredJson(state, \"entry\");\n+\tassert.equal(root.kind, \"object\");\n+\tassert.equal(root.child(\"missing\"), undefined);\n+\tassert.equal(root.child(\"duplicate\")!.scalar(), 2);\n+\tassert.deepEqual(\n+\t\t[...root.child(\"items\")!.elements()].map((node) => node.scalar()),\n+\t\t[true, null, 42],\n+\t);\n+\tassert.equal(root.child(\"items\")!.child(3), undefined);\n+\tstate.write(\"entry:edges\", JSON.stringify([root.child(\"items\")!.id, \"1\"]), 999999);\n+\tassert.throws(() => root.child(\"items\")!.child(1), /identity/);\n+});\n+\n+test(\"disk JSON preserves JSON numeric overflow and negative zero\", (t) => {\n+\tconst database = memoryStorage();\n+\tt.after(() => database.db.close());\n+\tSqliteWriterState.initialize(database);\n+\tconst state = new SqliteWriterState(database, \"decoded\");\n+\tstoreJson(state, \"numbers\", [\"[1e400,-1e400,-0,1.25]\"]);\n+\tassert.deepEqual(\n+\t\t[...new StoredJson(state, \"numbers\").elements()].map((node) => node.scalar()),\n+\t\tJSON.parse(\"[1e400,-1e400,-0,1.25]\"),\n+\t);\n+});\n+\n+test(\"disk JSON object traversal preserves unique keys and last duplicate values\", (t) => {\n+\tconst database = memoryStorage();\n+\tt.after(() => database.db.close());\n+\tSqliteWriterState.initialize(database);\n+\tconst state = new SqliteWriterState(database, \"decoded\");\n+\tstoreJson(state, \"object\", ['{\"__proto__\":1,\"a\":2,\"__proto__\":3,\"constructor\":4}']);\n+\tconst object = new StoredJson(state, \"object\");\n+\tassert.deepEqual(\n+\t\t[...object.properties()].map(([key, node]) => [key, node.scalar()]),\n+\t\t[\n+\t\t\t[\"__proto__\", 3],\n+\t\t\t[\"a\", 2],\n+\t\t\t[\"constructor\", 4],\n+\t\t],\n+\t);\n+\tstate.remove(\"object:keys\", JSON.stringify([object.id, 1]));\n+\tassert.throws(() => [...object.properties()], /missing stored JSON object key/);\n+});"},{"path":"server/test/streamed-history-host.test.ts","added":71,"removed":0,"diff":"--- /dev/null\n+++ b/server/test/streamed-history-host.test.ts\n@@ -0,0 +1,71 @@\n+import assert from \"node:assert/strict\";\n+import { test } from \"node:test\";\n+import { MemoryStore, Project } from \"../../worker/project/project.ts\";\n+import { SqliteLog } from \"../src/engine-project.ts\";\n+import { SqliteHistoryHost } from \"../src/history-host.ts\";\n+import { advanceWriterRoot, SqliteWriterHost, SqliteWriterState } from \"../src/writer-host.ts\";\n+import { memoryStorage } from \"./helpers.ts\";\n+\n+test(\"history preparation and advancement never reconstruct a canonical frame string\", (t) => {\n+\tconst storage = memoryStorage();\n+\tt.after(() => storage.db.close());\n+\tconst memory = new MemoryStore();\n+\tconst oracle = new Project(memory);\n+\toracle.init({ \"a.txt\": \"before\\n\" }, 0);\n+\tconst log = new SqliteLog(storage);\n+\tlog.append(memory.entries);\n+\tSqliteWriterState.initialize(storage);\n+\tconst writer = new SqliteWriterHost(storage, \"writer\");\n+\twriter.adoptPage(0, { maxEntries: 32, maxBytes: 100000 }, () => {});\n+\tconst root = writer.root();\n+\tt.mock.method(log, \"boundedFrame\", () => {\n+\t\tthrow Error(\"whole canonical frame forbidden\");\n+\t});\n+\tt.mock.method(Project, \"load\", () => {\n+\t\tthrow Error(\"whole history forbidden\");\n+\t});\n+\tconst history = new SqliteHistoryHost(storage, \"streamed-history\");\n+\twhile (\n+\t\t!history.prepare(\n+\t\t\tlog,\n+\t\t\troot,\n+\t\t\t() => root,\n+\t\t\t() => {},\n+\t\t).ready\n+\t) {}\n+\toracle.record(\"alice\", { \"a.txt\": \"after\\n\" }, 1);\n+\toracle.publish(\"alice\", \"change\", 2);\n+\tlog.append(memory.entries.slice(root.logLength));\n+\tconst committed = advanceWriterRoot(log, root, writer.source());\n+\thistory.advance(\n+\t\tlog,\n+\t\troot,\n+\t\tcommitted,\n+\t\t() => committed,\n+\t\t() => {},\n+\t);\n+\tassert.deepEqual(\n+\t\thistory.read(\n+\t\t\tcommitted,\n+\t\t\t() => committed,\n+\t\t\t() => {},\n+\t\t\tcommitted.logLength,\n+\t\t\t(p) => p.files(),\n+\t\t),\n+\t\toracle.files(),\n+\t);\n+\tassert.equal(\n+\t\thistory.read(\n+\t\t\tcommitted,\n+\t\t\t() => committed,\n+\t\t\t() => {},\n+\t\t\t1,\n+\t\t\t(p) => p.files(),\n+\t\t)[\"a.txt\"],\n+\t\t\"before\\n\",\n+\t);\n+\tassert.equal(\n+\t\tstorage.db.prepare(\"SELECT COUNT(*) AS n FROM writer_state WHERE namespace='streamed-history:decoded'\").get()!.n,\n+\t\t0,\n+\t);\n+});"},{"path":"server/test/streamed-large-frame.test.ts","added":34,"removed":0,"diff":"--- /dev/null\n+++ b/server/test/streamed-large-frame.test.ts\n@@ -0,0 +1,34 @@\n+import assert from \"node:assert/strict\";\n+import { test } from \"node:test\";\n+import { MemoryStore, Project } from \"../../worker/project/project.ts\";\n+import { SqliteLog } from \"../src/engine-project.ts\";\n+import { SqliteWriterHost, SqliteWriterState } from \"../src/writer-host.ts\";\n+import { memoryStorage } from \"./helpers.ts\";\n+\n+test(\"streamed writer adoption accepts a canonical frame above the full-decoder ceiling\", (t) => {\n+\tconst storage = memoryStorage();\n+\tt.after(() => storage.db.close());\n+\tconst memory = new MemoryStore();\n+\tnew Project(memory).init({ \"large.txt\": \"x\".repeat(8100000) }, 0);\n+\tconst log = new SqliteLog(storage);\n+\tlog.append(memory.entries);\n+\tSqliteWriterState.initialize(storage);\n+\tconst host = new SqliteWriterHost(storage, \"large-stream\");\n+\tconst expected = host.source();\n+\tt.mock.method(SqliteLog.prototype, \"boundedFrame\", () => {\n+\t\tthrow Error(\"whole frame forbidden\");\n+\t});\n+\tt.mock.method(Project, \"load\", () => {\n+\t\tthrow Error(\"whole history forbidden\");\n+\t});\n+\tconst maxBytes = log.adoptionPageBytes(0);\n+\tassert.ok(maxBytes > 8000000);\n+\tconst page = host.adoptVerifiedPage({ expected, from: 0, digest: \"\", maxEntries: 1, maxBytes }, () => {});\n+\tassert.equal(page.ready, true);\n+\tassert.equal(host.root().logLength, 1);\n+\tassert.ok(JSON.stringify(new SqliteWriterState(storage, \"large-stream\").read(\"atoms\", \"0\")).length < 4096);\n+\tassert.equal(\n+\t\tstorage.db.prepare(\"SELECT COUNT(*) AS n FROM writer_state WHERE namespace='large-stream:decoded'\").get()!.n,\n+\t\t0,\n+\t);\n+});"},{"path":"server/test/streamed-large-history.test.ts","added":72,"removed":0,"diff":"--- /dev/null\n+++ b/server/test/streamed-large-history.test.ts\n@@ -0,0 +1,72 @@\n+import assert from \"node:assert/strict\";\n+import { test } from \"node:test\";\n+import { MemoryStore, Project } from \"../../worker/project/project.ts\";\n+import { SqliteLog } from \"../src/engine-project.ts\";\n+import { SqliteHistoryHost } from \"../src/history-host.ts\";\n+import { advanceWriterRoot, SqliteWriterHost, SqliteWriterState } from \"../src/writer-host.ts\";\n+import { memoryStorage } from \"./helpers.ts\";\n+\n+test(\"history prepares an oversized entry and preserves it after later publication\", (t) => {\n+\tconst storage = memoryStorage();\n+\tt.after(() => storage.db.close());\n+\tconst memory = new MemoryStore();\n+\tconst oracle = new Project(memory);\n+\toracle.init({ \"a.txt\": \"x\".repeat(8100000) }, 0);\n+\tconst initialText = oracle.files()[\"a.txt\"];\n+\tconst log = new SqliteLog(storage);\n+\tlog.append(memory.entries);\n+\tSqliteWriterState.initialize(storage);\n+\tconst writer = new SqliteWriterHost(storage, \"writer\");\n+\twriter.adoptPage(0, { maxEntries: 32, maxBytes: log.adoptionPageBytes(0) }, () => {});\n+\tconst root = writer.root();\n+\tt.mock.method(log, \"boundedFrame\", () => {\n+\t\tthrow Error(\"whole canonical frame forbidden\");\n+\t});\n+\tt.mock.method(Project, \"load\", () => {\n+\t\tthrow Error(\"whole history forbidden\");\n+\t});\n+\tconst history = new SqliteHistoryHost(storage, \"streamed-history\");\n+\twhile (\n+\t\t!history.prepare(\n+\t\t\tlog,\n+\t\t\troot,\n+\t\t\t() => root,\n+\t\t\t() => {},\n+\t\t).ready\n+\t) {}\n+\toracle.record(\"alice\", { \"b.txt\": \"after\\n\" }, 1);\n+\toracle.publish(\"alice\", \"change\", 2);\n+\tlog.append(memory.entries.slice(root.logLength));\n+\tconst committed = advanceWriterRoot(log, root, writer.source());\n+\thistory.advance(\n+\t\tlog,\n+\t\troot,\n+\t\tcommitted,\n+\t\t() => committed,\n+\t\t() => {},\n+\t);\n+\tassert.deepEqual(\n+\t\thistory.read(\n+\t\t\tcommitted,\n+\t\t\t() => committed,\n+\t\t\t() => {},\n+\t\t\tcommitted.logLength,\n+\t\t\t(p) => p.files(),\n+\t\t),\n+\t\toracle.files(),\n+\t);\n+\tassert.equal(\n+\t\thistory.read(\n+\t\t\tcommitted,\n+\t\t\t() => committed,\n+\t\t\t() => {},\n+\t\t\t1,\n+\t\t\t(p) => p.files(),\n+\t\t)[\"a.txt\"],\n+\t\tinitialText,\n+\t);\n+\tassert.equal(\n+\t\tstorage.db.prepare(\"SELECT COUNT(*) AS n FROM writer_state WHERE namespace='streamed-history:decoded'\").get()!.n,\n+\t\t0,\n+\t);\n+});"},{"path":"server/test/streamed-writer-adoption.test.ts","added":48,"removed":0,"diff":"--- /dev/null\n+++ b/server/test/streamed-writer-adoption.test.ts\n@@ -0,0 +1,48 @@\n+import assert from \"node:assert/strict\";\n+import { test } from \"node:test\";\n+import { MemoryStore, Project } from \"../../worker/project/project.ts\";\n+import { SqliteLog } from \"../src/engine-project.ts\";\n+import { SqliteWriterHost, SqliteWriterState } from \"../src/writer-host.ts\";\n+import { memoryStorage } from \"./helpers.ts\";\n+\n+test(\"writer adoption streams canonical frames and preserves exact page retries\", (t) => {\n+\tconst storage = memoryStorage();\n+\tt.after(() => storage.db.close());\n+\tconst memory = new MemoryStore();\n+\tconst oracle = new Project(memory);\n+\toracle.init({ \"a.txt\": \"one\\n\" }, 0);\n+\toracle.record(\"alice\", { \"a.txt\": \"two\\n\" }, 1);\n+\toracle.publish(\"alice\", \"change\", 2);\n+\tnew SqliteLog(storage).append(memory.entries);\n+\tSqliteWriterState.initialize(storage);\n+\tconst host = () => new SqliteWriterHost(storage, \"streamed-writer\");\n+\tconst expected = host().source();\n+\tconst canonical = storage.db.prepare(\"SELECT * FROM log ORDER BY seq,part\").all();\n+\tt.mock.method(SqliteLog.prototype, \"boundedFrame\", () => {\n+\t\tthrow Error(\"whole frame reconstruction forbidden\");\n+\t});\n+\tt.mock.method(Project, \"load\", () => {\n+\t\tthrow Error(\"full history forbidden\");\n+\t});\n+\tlet from = 0,\n+\t\tdigest = \"\";\n+\twhile (from < expected.logLength) {\n+\t\tconst input = { expected, from, digest, maxEntries: 2, maxBytes: 100000 };\n+\t\tconst page = host().adoptVerifiedPage(input, () => {});\n+\t\tassert.deepEqual(\n+\t\t\thost().adoptVerifiedPage(input, () => {}),\n+\t\t\tpage,\n+\t\t);\n+\t\tfrom = page.next;\n+\t\tdigest = page.digest;\n+\t}\n+\tassert.deepEqual(\n+\t\thost().readCalls({ expected, validateAuthority: () => {}, operation: (calls) => calls.shared().files }),\n+\t\toracle.files(),\n+\t);\n+\tassert.deepEqual(storage.db.prepare(\"SELECT * FROM log ORDER BY seq,part\").all(), canonical);\n+\tassert.equal(\n+\t\tstorage.db.prepare(\"SELECT COUNT(*) AS n FROM writer_state WHERE namespace='streamed-writer:decoded'\").get()!.n,\n+\t\t0,\n+\t);\n+});"},{"path":"server/test/writer-host.test.ts","added":34,"removed":0,"diff":"--- a/server/test/writer-host.test.ts\n+++ b/server/test/writer-host.test.ts\n@@ -72,6 +72,37 @@\n \t\t}).ready\n \t)\n \t\tassert.ok(++pages < 1000);\n+\t// Repeated anonymous views share one reader only inside their verified session.\n+\tconst session = projection.open({ state, log: new SqliteLog(storage), root: host().root() });\n+\tconst views = session.readViewProvider(oracle.graph);\n+\tconst first = views.keyed!(\"v @0\");\n+\tassert.equal(views.keyed!(\"v @0\"), first);\n+\tassert.deepEqual(first.files(), { \"a.txt\": \"one\\ntwo\\n\" });\n+\tconst seq = oracle.graph.size;\n+\toracle.graph.add({\n+\t\tid: `a${seq}`,\n+\t\tseq,\n+\t\tauthor: \"fixture\",\n+\t\tmessage: \"Advance graph\",\n+\t\ttime: 5,\n+\t\tinserts: [],\n+\t\tdeletes: [],\n+\t\twrites: [],\n+\t\treads: [],\n+\t\tholds: [],\n+\t\tneeds: [],\n+\t\tresolves: [],\n+\t\treasons: [],\n+\t\tdeps: [\"a0\"],\n+\t});\n+\tassert.throws(() => first.files(), /stale/);\n+\tconst refreshed = views.keyed!(\"v @0\");\n+\tassert.notEqual(refreshed, first);\n+\tassert.deepEqual(refreshed.files(), { \"a.txt\": \"one\\ntwo\\n\" });\n+\tsession.close();\n+\tassert.throws(() => refreshed.files(), /expired|closed/);\n+\tassert.throws(() => first.files(), /expired|closed/);\n+\tassert.throws(() => views.keyed!(\"v @0\"), /expired|closed/);\n \tconst writer = () => new SqliteWriterHost(storage, namespace, projection, { indexProjectionAtoms: true });\n \tconst run = (operation: \"record\" | \"publish\", body: unknown, failReceipt = false) =>\n \t\twriter().runCalls({\n@@ -92,6 +123,9 @@\n \tassert.throws(() => run(\"record\", { files: { \"b.txt\": \"failed\\n\" } }, true), /receipt failure/);\n \tassert.deepEqual(rows(), before);\n \tassert.equal(run(\"record\", { files: { \"b.txt\": \"finished\\n\" } }).status, 200);\n+\tconst beforePublish = rows();\n+\tassert.throws(() => run(\"publish\", { message: \"Disk first\" }, true), /receipt failure/);\n+\tassert.deepEqual(rows(), beforePublish);\n \tconst published = run(\"publish\", { message: \"Disk first\" });\n \tassert.equal(published.status, 200);\n \tassert.equal((published.body as { ok: boolean }).ok, true);"},{"path":"src/engine/experimental/projection-atom-index.ts","added":2,"removed":1,"diff":"--- a/src/engine/experimental/projection-atom-index.ts\n+++ b/src/engine/experimental/projection-atom-index.ts\n@@ -61,7 +61,8 @@\n \t\t)\n \t\t\tthrow Error(\"invalid projection atom attribute\");\n \t}\n-\treturn structuredClone(value);\n+\t// Every validated record field is scalar; detach proxy-backed records without cloning a container graph.\n+\treturn value && typeof value === \"object\" ? { ...value } : value;\n }\n \n /** Derived index only. The caller supplies an already validated canonical atom and"},{"path":"src/engine/experimental/projection-locator.ts","added":40,"removed":30,"diff":"--- a/src/engine/experimental/projection-locator.ts\n+++ b/src/engine/experimental/projection-locator.ts\n@@ -63,42 +63,52 @@\n \t\tthis.#storage.write(this.#collection, \"next\", next + 1);\n \t\treturn next;\n \t}\n-\t/** Persist only pages reachable from the final root of a bounded update batch. */\n+\t/** Update each touched branch once, retaining at most 256 decoded values. */\n \tsetMany(root: Page, values: ReadonlyArray<readonly [number, T]>): Page {\n \t\tpage(root);\n \t\tif (values.length > 256) throw Error(\"locator batch limit\");\n \t\treturn this.#storage.transaction(() => {\n-\t\t\tconst staged = new Map<string, unknown>();\n-\t\t\tconst storage: GraphStateStorage = {\n-\t\t\t\tread: (collection, key) =>\n-\t\t\t\t\tcollection === this.#collection && staged.has(key) ? staged.get(key) : this.#storage.read(collection, key),\n-\t\t\t\twrite: (collection, key, value) => {\n-\t\t\t\t\tif (collection !== this.#collection) throw Error(\"unexpected batch collection\");\n-\t\t\t\t\tstaged.set(key, value);\n-\t\t\t\t},\n-\t\t\t\tremove: () => {\n-\t\t\t\t\tthrow Error(\"unexpected batch removal\");\n-\t\t\t\t},\n-\t\t\t\tentries: () => {\n-\t\t\t\t\tthrow Error(\"unexpected batch scan\");\n-\t\t\t\t},\n-\t\t\t\ttransaction: (body) => body(),\n+\t\t\tif (!values.length) return root;\n+\t\t\tlet next = this.#storage.read(this.#collection, \"next\") ?? 0;\n+\t\t\tif (!safe(next)) throw Error(\"invalid locator allocation\");\n+\t\t\tconst write = (node: Node): number => {\n+\t\t\t\tif (!safe(next) || !Number.isSafeInteger(next + 1)) throw Error(\"invalid locator allocation\");\n+\t\t\t\tif (this.#storage.read(this.#collection, String(next)) !== undefined)\n+\t\t\t\t\tthrow Error(\"locator allocation collision\");\n+\t\t\t\tconst id = next++;\n+\t\t\t\tthis.#storage.write(this.#collection, String(id), node);\n+\t\t\t\treturn id;\n \t\t\t};\n-\t\t\t// The namespace is encoded into the collection at construction.\n-\t\t\tconst namespace = JSON.parse(this.#collection.slice(\"experimental-locator:\".length)) as string;\n-\t\t\tconst index = new ProjectionLocator<T>(storage, namespace, this.#decode);\n-\t\t\tlet result = root;\n-\t\t\tfor (const [id, value] of values) result = index.set(result, id, value);\n-\t\t\tconst retained = new Set<number>();\n-\t\t\tconst visit = (id: Page): void => {\n-\t\t\t\tif (id === null || retained.has(id) || !staged.has(String(id))) return;\n-\t\t\t\tretained.add(id);\n-\t\t\t\tconst node = staged.get(String(id)) as Node;\n-\t\t\t\tif (node.kind === \"branch\") for (const child of Object.values(node.children)) visit(child);\n+\t\t\tconst checked = new Map<string, T>();\n+\t\t\tfor (const [id, value] of values) checked.set(keyOf(id), structuredClone(this.#decode(structuredClone(value))));\n+\t\t\tconst updates = [...checked].sort(([a], [b]) => a.localeCompare(b));\n+\t\t\tconst visit = (current: Page, edits: [string, T][], parent?: string, digit?: string, depth = 0): Page => {\n+\t\t\t\tif (!edits.length) return current;\n+\t\t\t\tif (depth > 8) throw Error(\"invalid locator depth\");\n+\t\t\t\tconst node = current === null ? undefined : this.#read(current, parent, digit);\n+\t\t\t\tlet prefix = node?.prefix ?? edits[0]![0];\n+\t\t\t\tfor (const [key] of edits) {\n+\t\t\t\t\tlet common = 0;\n+\t\t\t\t\twhile (common < prefix.length && prefix[common] === key[common]) common++;\n+\t\t\t\t\tprefix = prefix.slice(0, common);\n+\t\t\t\t}\n+\t\t\t\tif (prefix.length === 8) return write({ format: 1, kind: \"leaf\", prefix, value: edits[edits.length - 1]![1] });\n+\t\t\t\tconst children: Record<string, number> =\n+\t\t\t\t\tnode?.kind === \"branch\" && node.prefix === prefix ? { ...node.children } : {};\n+\t\t\t\tif (node && node.prefix !== prefix) children[node.prefix[prefix.length]!] = current!;\n+\t\t\t\tconst groups = new Map<string, [string, T][]>();\n+\t\t\t\tfor (const edit of edits) {\n+\t\t\t\t\tconst edge = edit[0][prefix.length]!;\n+\t\t\t\t\tconst group = groups.get(edge) ?? [];\n+\t\t\t\t\tgroup.push(edit);\n+\t\t\t\t\tgroups.set(edge, group);\n+\t\t\t\t}\n+\t\t\t\tfor (const [edge, group] of groups)\n+\t\t\t\t\tchildren[edge] = visit(children[edge] ?? null, group, prefix, edge, depth + 1)!;\n+\t\t\t\treturn write({ format: 1, kind: \"branch\", prefix, children });\n \t\t\t};\n-\t\t\tvisit(result);\n-\t\t\tfor (const id of retained) this.#storage.write(this.#collection, String(id), staged.get(String(id)));\n-\t\t\tif (staged.has(\"next\")) this.#storage.write(this.#collection, \"next\", staged.get(\"next\"));\n+\t\t\tconst result = visit(root, updates);\n+\t\t\tthis.#storage.write(this.#collection, \"next\", next);\n \t\t\treturn result;\n \t\t});\n \t}"},{"path":"src/engine/experimental/projection-marker.ts","added":13,"removed":10,"diff":"--- a/src/engine/experimental/projection-marker.ts\n+++ b/src/engine/experimental/projection-marker.ts\n@@ -118,16 +118,21 @@\n \t\t\tif (!this.members.get(previous.membership, this.graph.atom(id).seq)?.present) throw Error(\"missing dependency\");\n \t\treturn this.storage.transaction(() => {\n \t\t\tconst state = { ...previous };\n-\t\t\tconst sequence = this.sequence;\n \t\t\tthis.ensureFile(state, this.path);\n \t\t\tfor (const run of atom.inserts) this.ensureFile(state, run.file);\n \t\t\tlet k = 0;\n \t\t\tfor (const run of atom.inserts) for (const _ of run.lines) this.insertLine(state, `${atom.id}.${k++}`);\n+\t\t\tlet visibility: Array<{ kind: \"visibility\"; id: number; delta: number }> = [];\n \t\t\tfor (const line of atom.deletes) {\n \t\t\t\tconst marker = this.markers.get(state.locator, this.graph.lineN(line) + 1);\n \t\t\t\tif (!marker) throw Error(\"missing deleted marker\");\n-\t\t\t\tstate.sequence = sequence.update(state.sequence, { kind: \"visibility\", id: marker.enter, delta: 1 });\n+\t\t\t\tvisibility.push({ kind: \"visibility\", id: marker.enter, delta: 1 });\n+\t\t\t\tif (visibility.length === 16) {\n+\t\t\t\t\tstate.sequence = this.sequence.updateMany(state.sequence, visibility);\n+\t\t\t\t\tvisibility = [];\n+\t\t\t\t}\n \t\t\t}\n+\t\t\tif (visibility.length) state.sequence = this.sequence.updateMany(state.sequence, visibility);\n \t\t\tfor (const id of atom.deps) {\n \t\t\t\tconst seq = this.graph.atom(id).seq,\n \t\t\t\t\tmember = required(this.members.get(state.membership, seq));\n@@ -143,12 +148,6 @@\n \tinsertLine(state: MarkerState, line: string): void {\n \t\tthis.assertContext(state);\n \t\tconst sequence = this.sequence;\n-\t\tconst insert = (rank: number, text: string, hidden = false): number => {\n-\t\t\tconst id = state.sequence.next;\n-\t\t\tstate.sequence = sequence.update(state.sequence, { kind: \"insert\", rank, text });\n-\t\t\tif (hidden) state.sequence = sequence.update(state.sequence, { kind: \"visibility\", id, delta: 1 });\n-\t\t\treturn id;\n-\t\t};\n \t\tconst n = this.graph.lineN(line),\n \t\t\tparent = this.graph.parentCodeOf(n);\n \t\tif (n + 1 >= 0x80000000) throw Error(\"prototype line identity limit\");\n@@ -175,8 +174,12 @@\n \t\t\tpreceding === undefined ? parentMarker.enter : required(this.markers.get(state.locator, preceding + 1)).exit;\n \t\tstate.children = this.childRoots.set(state.children, parentKey, { root: index.insert(root, key, n) });\n \t\tconst at = sequence.rank(state.sequence, anchor) + 1;\n-\t\tconst enter = insert(at, line),\n-\t\t\texit = insert(at + 1, `${line}:end`, true);\n+\t\tconst enter = state.sequence.next,\n+\t\t\texit = enter + 1;\n+\t\tstate.sequence = sequence.updateMany(state.sequence, [\n+\t\t\t{ kind: \"insert\", rank: at, text: line },\n+\t\t\t{ kind: \"insert\", rank: at + 1, text: `${line}:end`, hidden: true },\n+\t\t]);\n \t\tstate.locator = this.markers.set(state.locator, n + 1, { kind: \"line\", enter, exit, parentKey, key });\n \t}\n \tremoveDeleter(previous: MarkerState, atom: Atom): MarkerState {"},{"path":"src/engine/experimental/projection-priority.ts","added":106,"removed":71,"diff":"--- a/src/engine/experimental/projection-priority.ts\n+++ b/src/engine/experimental/projection-priority.ts\n@@ -1,26 +1,15 @@\n import type { GraphStateStorage } from \"../state-source.ts\";\n \n type Page = number | null;\n-interface Leaf {\n-\tformat: 1;\n-\tkind: \"leaf\";\n-\tdepth: 57;\n-\tvalue: unknown;\n-}\n-interface Branch {\n-\tformat: 1;\n-\tkind: \"branch\";\n-\tdepth: number;\n-\tchildren: Record<string, number>;\n-}\n-type Node = Leaf | Branch;\n-const safe = (value: unknown): value is number => Number.isSafeInteger(value) && Number(value) >= 0;\n-const object = (value: unknown): value is Record<string, unknown> =>\n-\tvalue !== null && typeof value === \"object\" && !Array.isArray(value);\n+type Node =\n+\t| { format: 2; kind: \"leaf\"; prefix: string; value: unknown }\n+\t| { format: 2; kind: \"branch\"; prefix: string; children: Record<string, number> };\n+const safe = (v: unknown): v is number => Number.isSafeInteger(v) && Number(v) >= 0;\n+const object = (v: unknown): v is Record<string, unknown> => v !== null && typeof v === \"object\" && !Array.isArray(v);\n function check(root: Page, key: string): void {\n \tif ((root !== null && !safe(root)) || !/^[0-9a-f]{57}$/.test(key)) throw Error(\"invalid priority lookup\");\n }\n-/** Internal immutable priority experiment. At most 57 levels and 16 children. */\n+/** Immutable compressed priority paths. Reads legacy depth pages; writes format 2. */\n export class ProjectionPriority<T> {\n \treadonly #storage: GraphStateStorage;\n \treadonly #collection: string;\n@@ -31,85 +20,131 @@\n \t\tthis.#collection = `experimental-priority:${JSON.stringify(namespace)}`;\n \t\tthis.#decode = decode;\n \t}\n-\t#read(id: number, depth: number): Node {\n-\t\tif (!safe(id) || !safe(depth) || depth > 57) throw Error(\"invalid priority reference\");\n+\t#read(id: number, expected: string): Node {\n+\t\tif (!safe(id) || expected.length > 57) throw Error(\"invalid priority reference\");\n \t\tconst row = this.#storage.read(this.#collection, String(id));\n-\t\tif (!object(row) || row.format !== 1 || row.depth !== depth || Object.keys(row).length !== 4)\n-\t\t\tthrow Error(\"invalid priority node\");\n-\t\tif (depth === 57) {\n-\t\t\tif (row.kind !== \"leaf\" || !(\"value\" in row)) throw Error(\"invalid priority leaf\");\n-\t\t\treturn row as unknown as Leaf;\n+\t\tif (!object(row) || Object.keys(row).length !== 4) throw Error(\"invalid priority node\");\n+\t\tconst legacy = row.format === 1;\n+\t\tconst prefix = legacy ? expected : row.prefix;\n+\t\tif (\n+\t\t\t(legacy ? row.depth !== expected.length : row.format !== 2) ||\n+\t\t\ttypeof prefix !== \"string\" ||\n+\t\t\t!/^[0-9a-f]{0,57}$/.test(prefix) ||\n+\t\t\t!prefix.startsWith(expected)\n+\t\t)\n+\t\t\tthrow Error(\"invalid priority prefix\");\n+\t\tif (row.kind === \"leaf\") {\n+\t\t\tif (prefix.length !== 57 || !(\"value\" in row)) throw Error(\"invalid priority leaf\");\n+\t\t\treturn { format: 2, kind: \"leaf\", prefix, value: row.value };\n \t\t}\n-\t\tif (row.kind !== \"branch\" || !object(row.children)) throw Error(\"invalid priority branch\");\n+\t\tif (row.kind !== \"branch\" || prefix.length >= 57 || !object(row.children)) throw Error(\"invalid priority branch\");\n \t\tconst entries = Object.entries(row.children);\n-\t\tif (!entries.length || entries.length > 16) throw Error(\"invalid priority fanout\");\n+\t\tif (entries.length < (legacy ? 1 : 2) || entries.length > 16) throw Error(\"invalid priority fanout\");\n \t\tfor (const [digit, child] of entries)\n \t\t\tif (!/^[0-9a-f]$/.test(digit) || !safe(child) || child === id) throw Error(\"invalid priority child\");\n-\t\treturn row as unknown as Branch;\n+\t\treturn { format: 2, kind: \"branch\", prefix, children: row.children as Record<string, number> };\n \t}\n-\t#write(node: Node): number {\n-\t\tconst next = this.#storage.read(this.#collection, \"next\") ?? 0;\n-\t\tif (!safe(next) || !Number.isSafeInteger(next + 1)) throw Error(\"invalid priority allocation\");\n-\t\tif (this.#storage.read(this.#collection, String(next)) !== undefined) throw Error(\"priority allocation collision\");\n-\t\tthis.#storage.write(this.#collection, String(next), node);\n-\t\tthis.#storage.write(this.#collection, \"next\", next + 1);\n-\t\treturn next;\n+\t#allocate<R>(body: (write: (node: Node) => number) => R): R {\n+\t\treturn this.#storage.transaction(() => {\n+\t\t\tlet next = this.#storage.read(this.#collection, \"next\") ?? 0;\n+\t\t\tif (!safe(next)) throw Error(\"invalid priority allocation\");\n+\t\t\tconst initial = next;\n+\t\t\tconst result = body((node) => {\n+\t\t\t\t// Collapse legacy singleton paths before storing a compressed page.\n+\t\t\t\twhile (node.kind === \"branch\" && Object.keys(node.children).length === 1) {\n+\t\t\t\t\tconst [digit, child] = Object.entries(node.children)[0]!;\n+\t\t\t\t\tnode = this.#read(child, node.prefix + digit);\n+\t\t\t\t}\n+\t\t\t\tif (!safe(next) || !Number.isSafeInteger(next + 1)) throw Error(\"invalid priority allocation\");\n+\t\t\t\tif (this.#storage.read(this.#collection, String(next)) !== undefined)\n+\t\t\t\t\tthrow Error(\"priority allocation collision\");\n+\t\t\t\tconst id = next++;\n+\t\t\t\tthis.#storage.write(this.#collection, String(id), node);\n+\t\t\t\treturn id;\n+\t\t\t});\n+\t\t\tif (next !== initial) this.#storage.write(this.#collection, \"next\", next);\n+\t\t\treturn result;\n+\t\t});\n \t}\n+\n \tinsert(root: Page, key: string, value: T): number {\n \t\tcheck(root, key);\n \t\tconst checked = structuredClone(this.#decode(structuredClone(value)));\n-\t\treturn this.#storage.transaction(() => {\n-\t\t\tconst visit = (id: Page, depth: number): number => {\n-\t\t\t\tconst node = id === null ? undefined : this.#read(id, depth);\n-\t\t\t\tif (depth === 57) return this.#write({ format: 1, kind: \"leaf\", depth: 57, value: checked });\n-\t\t\t\tif (node?.kind === \"leaf\") throw Error(\"invalid priority depth\");\n-\t\t\t\tconst children = node?.children ?? {},\n-\t\t\t\t\tdigit = key[depth]!;\n-\t\t\t\tconst child = visit(children[digit] ?? null, depth + 1);\n-\t\t\t\treturn this.#write({ format: 1, kind: \"branch\", depth, children: { ...children, [digit]: child } });\n+\t\treturn this.#allocate((write) => {\n+\t\t\tconst leaf = () => write({ format: 2, kind: \"leaf\", prefix: key, value: checked });\n+\t\t\tconst visit = (id: Page, expected: string): number => {\n+\t\t\t\tif (id === null) return leaf();\n+\t\t\t\tconst node = this.#read(id, expected);\n+\t\t\t\tlet common = 0;\n+\t\t\t\twhile (common < node.prefix.length && node.prefix[common] === key[common]) common++;\n+\t\t\t\tif (common < node.prefix.length) {\n+\t\t\t\t\t// Legacy pages need their inferred prefix persisted when moved below a new branch.\n+\t\t\t\t\tconst old = write(node),\n+\t\t\t\t\t\tadded = leaf();\n+\t\t\t\t\treturn write({\n+\t\t\t\t\t\tformat: 2,\n+\t\t\t\t\t\tkind: \"branch\",\n+\t\t\t\t\t\tprefix: key.slice(0, common),\n+\t\t\t\t\t\tchildren: { [node.prefix[common]!]: old, [key[common]!]: added },\n+\t\t\t\t\t});\n+\t\t\t\t}\n+\t\t\t\tif (node.kind === \"leaf\") return leaf();\n+\t\t\t\tconst digit = key[node.prefix.length]!;\n+\t\t\t\tconst child = visit(node.children[digit] ?? null, node.prefix + digit);\n+\t\t\t\treturn write({ ...node, children: { ...node.children, [digit]: child } });\n \t\t\t};\n-\t\t\treturn visit(root, 0);\n+\t\t\treturn visit(root, \"\");\n \t\t});\n \t}\n \tremove(root: Page, key: string): Page {\n \t\tcheck(root, key);\n-\t\treturn this.#storage.transaction(() => {\n-\t\t\tconst visit = (id: Page, depth: number): Page => {\n+\t\treturn this.#allocate((write) => {\n+\t\t\tconst visit = (id: Page, expected: string): Page => {\n \t\t\t\tif (id === null) throw Error(\"missing priority key\");\n-\t\t\t\tconst node = this.#read(id, depth);\n+\t\t\t\tconst node = this.#read(id, expected);\n+\t\t\t\tif (!key.startsWith(node.prefix)) throw Error(\"missing priority key\");\n \t\t\t\tif (node.kind === \"leaf\") return null;\n-\t\t\t\tconst digit = key[depth]!,\n-\t\t\t\t\tchild = visit(node.children[digit] ?? null, depth + 1),\n+\t\t\t\tconst digit = key[node.prefix.length]!,\n+\t\t\t\t\tchild = visit(node.children[digit] ?? null, node.prefix + digit),\n \t\t\t\t\tchildren = { ...node.children };\n \t\t\t\tif (child === null) delete children[digit];\n \t\t\t\telse children[digit] = child;\n-\t\t\t\treturn Object.keys(children).length ? this.#write({ ...node, children }) : null;\n+\t\t\t\tconst entries = Object.entries(children);\n+\t\t\t\tif (!entries.length) return null;\n+\t\t\t\tif (entries.length === 1) {\n+\t\t\t\t\tconst [d, c] = entries[0]!;\n+\t\t\t\t\treturn write(this.#read(c, node.prefix + d));\n+\t\t\t\t}\n+\t\t\t\treturn write({ ...node, children });\n \t\t\t};\n-\t\t\treturn visit(root, 0);\n+\t\t\treturn visit(root, \"\");\n \t\t});\n \t}\n \tbefore(root: Page, key: string): T | undefined {\n \t\tcheck(root, key);\n-\t\tlet current = root;\n-\t\tlet candidate: { id: number; depth: number } | undefined;\n-\t\tfor (let depth = 0; current !== null && depth < 57; depth++) {\n-\t\t\tconst node = this.#read(current, depth);\n-\t\t\tif (node.kind !== \"branch\") throw Error(\"invalid priority depth\");\n-\t\t\tconst digit = key[depth]!,\n-\t\t\t\tlower = Object.keys(node.children)\n-\t\t\t\t\t.filter((item) => item < digit)\n-\t\t\t\t\t.sort()\n-\t\t\t\t\t.at(-1);\n-\t\t\tif (lower !== undefined) candidate = { id: node.children[lower]!, depth: depth + 1 };\n-\t\t\tcurrent = node.children[digit] ?? null;\n-\t\t}\n-\t\tif (!candidate) return undefined;\n-\t\tlet { id, depth } = candidate;\n-\t\tfor (; depth <= 57; depth++) {\n-\t\t\tconst node = this.#read(id, depth);\n+\t\tconst maximum = (id: number, expected: string): T => {\n+\t\t\tconst node = this.#read(id, expected);\n \t\t\tif (node.kind === \"leaf\") return this.#decode(structuredClone(node.value));\n-\t\t\tid = node.children[Object.keys(node.children).sort().at(-1)!]!;\n-\t\t}\n-\t\tthrow Error(\"invalid priority depth\");\n+\t\t\tconst digit = Object.keys(node.children).sort().at(-1)!;\n+\t\t\treturn maximum(node.children[digit]!, node.prefix + digit);\n+\t\t};\n+\t\tconst visit = (id: Page, expected: string): T | undefined => {\n+\t\t\tif (id === null) return undefined;\n+\t\t\tconst node = this.#read(id, expected);\n+\t\t\tif (!key.startsWith(node.prefix)) return node.prefix < key ? maximum(id, expected) : undefined;\n+\t\t\tif (node.kind === \"leaf\") return undefined;\n+\t\t\tconst digit = key[node.prefix.length]!;\n+\t\t\tconst same = node.children[digit];\n+\t\t\tif (same !== undefined) {\n+\t\t\t\tconst found = visit(same, node.prefix + digit);\n+\t\t\t\tif (found !== undefined) return found;\n+\t\t\t}\n+\t\t\tconst lower = Object.keys(node.children)\n+\t\t\t\t.filter((d) => d < digit)\n+\t\t\t\t.sort()\n+\t\t\t\t.at(-1);\n+\t\t\treturn lower === undefined ? undefined : maximum(node.children[lower]!, node.prefix + lower);\n+\t\t};\n+\t\treturn visit(root, \"\");\n \t}\n }"},{"path":"src/engine/experimental/projection-sequence.ts","added":112,"removed":104,"diff":"--- a/src/engine/experimental/projection-sequence.ts\n+++ b/src/engine/experimental/projection-sequence.ts\n@@ -20,7 +20,7 @@\n \treadonly next: number;\n }\n export type SequenceOperation =\n-\t| { kind: \"insert\"; rank: number; text: string }\n+\t| { kind: \"insert\"; rank: number; text: string; hidden?: boolean }\n \t| { kind: \"visibility\"; id: number; delta: number }\n \t| { kind: \"move\"; from: number; length: number; to: number };\n const safe = (value: unknown): value is number => Number.isSafeInteger(value) && Number(value) >= 0;\n@@ -132,6 +132,11 @@\n \t\treturn file;\n \t}\n \tupdate(state: SequenceState, operation: SequenceOperation): SequenceState {\n+\t\treturn this.updateMany(state, [operation]);\n+\t}\n+\t/** A small bounded group shares changed AVL nodes and one locator flush. */\n+\tupdateMany(state: SequenceState, operations: readonly SequenceOperation[]): SequenceState {\n+\t\tif (operations.length < 1 || operations.length > 16) throw Error(\"invalid sequence operation batch\");\n \t\tthis.#state(state);\n \t\treturn this.storage.transaction(() => {\n \t\t\tlet map = state.map;\n@@ -192,114 +197,117 @@\n \t\t\t};\n \t\t\tlet root = state.root,\n \t\t\t\tnext = state.next;\n-\t\t\tif (operation.kind === \"insert\") {\n-\t\t\t\tconst { rank, text } = operation;\n-\t\t\t\tif (!Number.isInteger(rank) || rank < 0 || rank > count(root) || next >= 2 ** 32) throw Error(\"invalid insert\");\n-\t\t\t\tconst added = next++;\n-\t\t\t\tconst insert = (id: Page, at: number, p: Page): number => {\n-\t\t\t\t\tif (id === null)\n-\t\t\t\t\t\treturn put({\n-\t\t\t\t\t\t\tid: added,\n-\t\t\t\t\t\t\tparent: p,\n-\t\t\t\t\t\t\tleft: null,\n-\t\t\t\t\t\t\tright: null,\n-\t\t\t\t\t\t\ttext,\n-\t\t\t\t\t\t\tdeletions: 0,\n-\t\t\t\t\t\t\theight: 1,\n-\t\t\t\t\t\t\tcount: 1,\n-\t\t\t\t\t\t\tvisible: 1,\n-\t\t\t\t\t\t\tfileStarts: text.startsWith(\"root:\") ? 1 : 0,\n-\t\t\t\t\t\t});\n-\t\t\t\t\tconst node = get(id),\n-\t\t\t\t\t\tleftCount = count(node.left);\n-\t\t\t\t\tif (at <= leftCount) save({ ...node, left: insert(node.left, at, id) });\n-\t\t\t\t\telse save({ ...node, right: insert(node.right, at - leftCount - 1, id) });\n-\t\t\t\t\treturn balance(id);\n-\t\t\t\t};\n-\t\t\t\troot = insert(root, rank, null);\n-\t\t\t\tparent(root, null);\n-\t\t\t} else if (operation.kind === \"move\") {\n-\t\t\t\tconst { from, length, to } = operation;\n-\t\t\t\tconst total = count(root);\n-\t\t\t\tif (\n-\t\t\t\t\t![from, length, to].every(Number.isSafeInteger) ||\n-\t\t\t\t\tfrom < 0 ||\n-\t\t\t\t\tlength < 0 ||\n-\t\t\t\t\tfrom + length > total ||\n-\t\t\t\t\tto < 0 ||\n-\t\t\t\t\tto > total - length\n-\t\t\t\t)\n-\t\t\t\t\tthrow Error(\"invalid move range\");\n-\t\t\t\t// Join two AVL trees around one existing stable marker.\n-\t\t\t\tconst join = (left: Page, pivot: number, right: Page): number => {\n-\t\t\t\t\tif (height(left) > height(right) + 1) {\n-\t\t\t\t\t\tconst node = get(left!);\n-\t\t\t\t\t\tsave({ ...node, right: join(node.right, pivot, right) });\n-\t\t\t\t\t\tconst result = balance(left!);\n-\t\t\t\t\t\tparent(result, null);\n-\t\t\t\t\t\treturn result;\n-\t\t\t\t\t}\n-\t\t\t\t\tif (height(right) > height(left) + 1) {\n-\t\t\t\t\t\tconst node = get(right!);\n-\t\t\t\t\t\tsave({ ...node, left: join(left, pivot, node.left) });\n-\t\t\t\t\t\tconst result = balance(right!);\n-\t\t\t\t\t\tparent(result, null);\n-\t\t\t\t\t\treturn result;\n-\t\t\t\t\t}\n-\t\t\t\t\treturn save({ ...get(pivot), left, right, parent: null });\n-\t\t\t\t};\n-\t\t\t\tconst split = (id: Page, at: number): [Page, Page] => {\n-\t\t\t\t\tif (id === null) return [null, null];\n-\t\t\t\t\tconst node = get(id),\n-\t\t\t\t\t\tsize = count(node.left);\n-\t\t\t\t\tif (at <= size) {\n-\t\t\t\t\t\tconst [left, middle] = split(node.left, at);\n-\t\t\t\t\t\tconst right = join(middle, id, node.right);\n+\t\t\tfor (const operation of operations) {\n+\t\t\t\tif (operation.kind === \"insert\") {\n+\t\t\t\t\tconst { rank, text } = operation;\n+\t\t\t\t\tif (!Number.isInteger(rank) || rank < 0 || rank > count(root) || next >= 2 ** 32)\n+\t\t\t\t\t\tthrow Error(\"invalid insert\");\n+\t\t\t\t\tconst added = next++;\n+\t\t\t\t\tconst insert = (id: Page, at: number, p: Page): number => {\n+\t\t\t\t\t\tif (id === null)\n+\t\t\t\t\t\t\treturn put({\n+\t\t\t\t\t\t\t\tid: added,\n+\t\t\t\t\t\t\t\tparent: p,\n+\t\t\t\t\t\t\t\tleft: null,\n+\t\t\t\t\t\t\t\tright: null,\n+\t\t\t\t\t\t\t\ttext,\n+\t\t\t\t\t\t\t\tdeletions: operation.hidden ? 1 : 0,\n+\t\t\t\t\t\t\t\theight: 1,\n+\t\t\t\t\t\t\t\tcount: 1,\n+\t\t\t\t\t\t\t\tvisible: operation.hidden ? 0 : 1,\n+\t\t\t\t\t\t\t\tfileStarts: text.startsWith(\"root:\") ? 1 : 0,\n+\t\t\t\t\t\t\t});\n+\t\t\t\t\t\tconst node = get(id),\n+\t\t\t\t\t\t\tleftCount = count(node.left);\n+\t\t\t\t\t\tif (at <= leftCount) save({ ...node, left: insert(node.left, at, id) });\n+\t\t\t\t\t\telse save({ ...node, right: insert(node.right, at - leftCount - 1, id) });\n+\t\t\t\t\t\treturn balance(id);\n+\t\t\t\t\t};\n+\t\t\t\t\troot = insert(root, rank, null);\n+\t\t\t\t\tparent(root, null);\n+\t\t\t\t} else if (operation.kind === \"move\") {\n+\t\t\t\t\tconst { from, length, to } = operation;\n+\t\t\t\t\tconst total = count(root);\n+\t\t\t\t\tif (\n+\t\t\t\t\t\t![from, length, to].every(Number.isSafeInteger) ||\n+\t\t\t\t\t\tfrom < 0 ||\n+\t\t\t\t\t\tlength < 0 ||\n+\t\t\t\t\t\tfrom + length > total ||\n+\t\t\t\t\t\tto < 0 ||\n+\t\t\t\t\t\tto > total - length\n+\t\t\t\t\t)\n+\t\t\t\t\t\tthrow Error(\"invalid move range\");\n+\t\t\t\t\t// Join two AVL trees around one existing stable marker.\n+\t\t\t\t\tconst join = (left: Page, pivot: number, right: Page): number => {\n+\t\t\t\t\t\tif (height(left) > height(right) + 1) {\n+\t\t\t\t\t\t\tconst node = get(left!);\n+\t\t\t\t\t\t\tsave({ ...node, right: join(node.right, pivot, right) });\n+\t\t\t\t\t\t\tconst result = balance(left!);\n+\t\t\t\t\t\t\tparent(result, null);\n+\t\t\t\t\t\t\treturn result;\n+\t\t\t\t\t\t}\n+\t\t\t\t\t\tif (height(right) > height(left) + 1) {\n+\t\t\t\t\t\t\tconst node = get(right!);\n+\t\t\t\t\t\t\tsave({ ...node, left: join(left, pivot, node.left) });\n+\t\t\t\t\t\t\tconst result = balance(right!);\n+\t\t\t\t\t\t\tparent(result, null);\n+\t\t\t\t\t\t\treturn result;\n+\t\t\t\t\t\t}\n+\t\t\t\t\t\treturn save({ ...get(pivot), left, right, parent: null });\n+\t\t\t\t\t};\n+\t\t\t\t\tconst split = (id: Page, at: number): [Page, Page] => {\n+\t\t\t\t\t\tif (id === null) return [null, null];\n+\t\t\t\t\t\tconst node = get(id),\n+\t\t\t\t\t\t\tsize = count(node.left);\n+\t\t\t\t\t\tif (at <= size) {\n+\t\t\t\t\t\t\tconst [left, middle] = split(node.left, at);\n+\t\t\t\t\t\t\tconst right = join(middle, id, node.right);\n+\t\t\t\t\t\t\tparent(left, null);\n+\t\t\t\t\t\t\tparent(right, null);\n+\t\t\t\t\t\t\treturn [left, right];\n+\t\t\t\t\t\t}\n+\t\t\t\t\t\tconst [middle, right] = split(node.right, at - size - 1);\n+\t\t\t\t\t\tconst left = join(node.left, id, middle);\n \t\t\t\t\t\tparent(left, null);\n \t\t\t\t\t\tparent(right, null);\n \t\t\t\t\t\treturn [left, right];\n+\t\t\t\t\t};\n+\t\t\t\t\tconst merge = (left: Page, right: Page): Page => {\n+\t\t\t\t\t\tif (left === null) {\n+\t\t\t\t\t\t\tparent(right, null);\n+\t\t\t\t\t\t\treturn right;\n+\t\t\t\t\t\t}\n+\t\t\t\t\t\tif (right === null) {\n+\t\t\t\t\t\t\tparent(left, null);\n+\t\t\t\t\t\t\treturn left;\n+\t\t\t\t\t\t}\n+\t\t\t\t\t\tconst [pivot, rest] = split(right, 1);\n+\t\t\t\t\t\treturn join(left, pivot!, rest);\n+\t\t\t\t\t};\n+\t\t\t\t\tif (length && from !== to) {\n+\t\t\t\t\t\tconst [left, tail] = split(root, from);\n+\t\t\t\t\t\tconst [moved, right] = split(tail, length);\n+\t\t\t\t\t\tconst remaining = merge(left, right);\n+\t\t\t\t\t\tconst [before, after] = split(remaining, to);\n+\t\t\t\t\t\troot = merge(merge(before, moved), after);\n+\t\t\t\t\t\tparent(root, null);\n \t\t\t\t\t}\n-\t\t\t\t\tconst [middle, right] = split(node.right, at - size - 1);\n-\t\t\t\t\tconst left = join(node.left, id, middle);\n-\t\t\t\t\tparent(left, null);\n-\t\t\t\t\tparent(right, null);\n-\t\t\t\t\treturn [left, right];\n-\t\t\t\t};\n-\t\t\t\tconst merge = (left: Page, right: Page): Page => {\n-\t\t\t\t\tif (left === null) {\n-\t\t\t\t\t\tparent(right, null);\n-\t\t\t\t\t\treturn right;\n+\t\t\t\t} else if (operation.kind === \"visibility\") {\n+\t\t\t\t\tlet node = get(operation.id);\n+\t\t\t\t\tif (\n+\t\t\t\t\t\t!node ||\n+\t\t\t\t\t\t!Number.isInteger(operation.delta) ||\n+\t\t\t\t\t\tMath.abs(operation.delta) !== 1 ||\n+\t\t\t\t\t\tnode.deletions + operation.delta < 0\n+\t\t\t\t\t)\n+\t\t\t\t\t\tthrow Error(\"invalid visibility\");\n+\t\t\t\t\tsave({ ...node, deletions: node.deletions + operation.delta });\n+\t\t\t\t\twhile (node.parent !== null) {\n+\t\t\t\t\t\tnode = get(node.parent);\n+\t\t\t\t\t\tsave(node);\n \t\t\t\t\t}\n-\t\t\t\t\tif (right === null) {\n-\t\t\t\t\t\tparent(left, null);\n-\t\t\t\t\t\treturn left;\n-\t\t\t\t\t}\n-\t\t\t\t\tconst [pivot, rest] = split(right, 1);\n-\t\t\t\t\treturn join(left, pivot!, rest);\n-\t\t\t\t};\n-\t\t\t\tif (length && from !== to) {\n-\t\t\t\t\tconst [left, tail] = split(root, from);\n-\t\t\t\t\tconst [moved, right] = split(tail, length);\n-\t\t\t\t\tconst remaining = merge(left, right);\n-\t\t\t\t\tconst [before, after] = split(remaining, to);\n-\t\t\t\t\troot = merge(merge(before, moved), after);\n-\t\t\t\t\tparent(root, null);\n-\t\t\t\t}\n-\t\t\t} else if (operation.kind === \"visibility\") {\n-\t\t\t\tlet node = get(operation.id);\n-\t\t\t\tif (\n-\t\t\t\t\t!node ||\n-\t\t\t\t\t!Number.isInteger(operation.delta) ||\n-\t\t\t\t\tMath.abs(operation.delta) !== 1 ||\n-\t\t\t\t\tnode.deletions + operation.delta < 0\n-\t\t\t\t)\n-\t\t\t\t\tthrow Error(\"invalid visibility\");\n-\t\t\t\tsave({ ...node, deletions: node.deletions + operation.delta });\n-\t\t\t\twhile (node.parent !== null) {\n-\t\t\t\t\tnode = get(node.parent);\n-\t\t\t\t\tsave(node);\n-\t\t\t\t}\n-\t\t\t} else throw Error(\"unknown operation\");\n+\t\t\t\t} else throw Error(\"unknown operation\");\n+\t\t\t}\n \t\t\t// Keep locator staging bounded even if a valid split/merge changes more\n \t\t\t// than one batch. The enclosing transaction commits all batches together.\n \t\t\tlet batch: Array<readonly [number, SequenceNode]> = [];"},{"path":"src/engine/graph.ts","added":310,"removed":70,"diff":"--- a/src/engine/graph.ts\n+++ b/src/engine/graph.ts\n@@ -20,12 +20,14 @@\n import { withProjectionScratch } from \"./projection-scratch.ts\";\n import {\n \ttype GraphStateStorage,\n+\treadonlyStoredArray,\n \ttype StateMap,\n \tstoredArray,\n \tstoredLists,\n \tstoredMap,\n \tstoredNumbers,\n } from \"./state-source.ts\";\n+import { StoredText } from \"./stored-text.ts\";\n import {\n \tATTR_NAMES,\n \ttype Atom,\n@@ -306,12 +308,169 @@\n \t\tif (options.storage) {\n \t\t\tconst storage = options.storage;\n \t\t\tconst numbers = (name: string): NumberIndex => storedNumbers(storage, name);\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\tconst atomText = new StoredText(storage, \"atom-text:long\");\n+\t\t\ttype TextReference = { text: string };\n+\t\t\tconst listFields = [\n+\t\t\t\t\"deletes\",\n+\t\t\t\t\"writes\",\n+\t\t\t\t\"reads\",\n+\t\t\t\t\"holds\",\n+\t\t\t\t\"needs\",\n+\t\t\t\t\"resolves\",\n+\t\t\t\t\"deps\",\n+\t\t\t\t\"reasons\",\n+\t\t\t\t\"attrs\",\n+\t\t\t\t\"moves\",\n+\t\t\t] as const;\n+\t\t\ttype EncodedAtom = {\n+\t\t\t\tinsertionFormat?: 1;\n+\t\t\t\tinsertionRuns?: string;\n+\t\t\t\ttextFormat?: 1;\n+\t\t\t\tlistFormat?: 1;\n+\t\t\t\tlistCount?: number;\n+\t\t\t\tlists?: Partial<Record<(typeof listFields)[number], string>>;\n+\t\t\t\tatom: Atom;\n+\t\t\t};\n+\t\t\tthis.#atoms = storedArray<Atom>(\n+\t\t\t\tstorage,\n+\t\t\t\t\"atoms\",\n+\t\t\t\t(value) => {\n+\t\t\t\t\tconst encoded = value as unknown as Partial<EncodedAtom>;\n+\t\t\t\t\tif (encoded.textFormat !== undefined && encoded.textFormat !== 1)\n+\t\t\t\t\t\tthrow Error(\"invalid stored atom text format\");\n+\t\t\t\t\tif (encoded.listFormat !== undefined && encoded.listFormat !== 1)\n+\t\t\t\t\t\tthrow Error(\"invalid stored atom list format\");\n+\t\t\t\t\tif (encoded.listFormat === 1) {\n+\t\t\t\t\t\tif (\n+\t\t\t\t\t\t\t!encoded.lists ||\n+\t\t\t\t\t\t\ttypeof encoded.lists !== \"object\" ||\n+\t\t\t\t\t\t\tArray.isArray(encoded.lists) ||\n+\t\t\t\t\t\t\t!Number.isSafeInteger(encoded.listCount) ||\n+\t\t\t\t\t\t\tencoded.listCount! < 1 ||\n+\t\t\t\t\t\t\tObject.keys(encoded.lists).length !== encoded.listCount ||\n+\t\t\t\t\t\t\tObject.keys(encoded.lists).some((field) => !listFields.includes(field as (typeof listFields)[number]))\n+\t\t\t\t\t\t)\n+\t\t\t\t\t\t\tthrow Error(\"invalid stored atom list references\");\n+\t\t\t\t\t}\n+\t\t\t\t\tif (encoded.insertionFormat !== undefined && encoded.insertionFormat !== 1)\n+\t\t\t\t\t\tthrow Error(\"invalid stored insertion format\");\n+\t\t\t\t\tconst atom =\n+\t\t\t\t\t\tencoded.textFormat === 1 || encoded.listFormat === 1 || encoded.insertionFormat === 1\n+\t\t\t\t\t\t\t? encoded.atom!\n+\t\t\t\t\t\t\t: value;\n+\t\t\t\t\tconst text =\n+\t\t\t\t\t\tencoded.textFormat === 1\n+\t\t\t\t\t\t\t? (start: number, length: number): readonly string[] => {\n+\t\t\t\t\t\t\t\t\tconst result: string[] = [];\n+\t\t\t\t\t\t\t\t\tlet index = 0;\n+\t\t\t\t\t\t\t\t\tfor (const run of atom.inserts)\n+\t\t\t\t\t\t\t\t\t\tfor (const raw of run.lines) {\n+\t\t\t\t\t\t\t\t\t\t\tif (index >= start && index < start + length) {\n+\t\t\t\t\t\t\t\t\t\t\t\tconst reference = raw as unknown as TextReference;\n+\t\t\t\t\t\t\t\t\t\t\t\tif (typeof raw === \"string\") result.push(raw);\n+\t\t\t\t\t\t\t\t\t\t\t\telse if (reference && typeof reference.text === \"string\")\n+\t\t\t\t\t\t\t\t\t\t\t\t\tresult.push(atomText.read(reference.text));\n+\t\t\t\t\t\t\t\t\t\t\t\telse throw Error(\"invalid stored atom text reference\");\n+\t\t\t\t\t\t\t\t\t\t\t}\n+\t\t\t\t\t\t\t\t\t\t\tif (++index >= start + length) return result;\n+\t\t\t\t\t\t\t\t\t\t}\n+\t\t\t\t\t\t\t\t\tthrow Error(\"stored atom text range missing\");\n+\t\t\t\t\t\t\t\t}\n+\t\t\t\t\t\t\t: undefined;\n+\t\t\t\t\tconst frozen = freezeAtom(\n+\t\t\t\t\t\tatom,\n+\t\t\t\t\t\t(id) => id,\n+\t\t\t\t\t\t(author) => author,\n+\t\t\t\t\t\ttext,\n+\t\t\t\t\t);\n+\t\t\t\t\tif (encoded.listFormat !== 1 && encoded.insertionFormat !== 1) return frozen;\n+\t\t\t\t\tconst result = { ...frozen };\n+\t\t\t\t\tif (encoded.insertionFormat === 1) {\n+\t\t\t\t\t\tconst collection = `atom-inserts:${atom.seq}`;\n+\t\t\t\t\t\tif (encoded.insertionRuns !== collection) throw Error(\"invalid stored insertion reference\");\n+\t\t\t\t\t\tconst inserts = readonlyStoredArray<InsertRun>(storage, collection, (raw, index) => {\n+\t\t\t\t\t\t\tconst run = raw as { file: string; parent: InsertRun[\"parent\"]; lines: string };\n+\t\t\t\t\t\t\tconst lines = `${collection}:lines:${index}`;\n+\t\t\t\t\t\t\tif (run.lines !== lines || typeof run.file !== \"string\" || typeof run.parent !== \"string\")\n+\t\t\t\t\t\t\t\tthrow Error(\"invalid stored insertion run\");\n+\t\t\t\t\t\t\treturn Object.freeze({\n+\t\t\t\t\t\t\t\tfile: run.file,\n+\t\t\t\t\t\t\t\tparent: run.parent,\n+\t\t\t\t\t\t\t\tlines: readonlyStoredArray<string>(storage, lines, (rawLine) => {\n+\t\t\t\t\t\t\t\t\tif (typeof rawLine === \"string\") return rawLine;\n+\t\t\t\t\t\t\t\t\tconst ref = rawLine as TextReference;\n+\t\t\t\t\t\t\t\t\tif (!ref || typeof ref.text !== \"string\") throw Error(\"invalid stored insertion text\");\n+\t\t\t\t\t\t\t\t\treturn atomText.read(ref.text);\n+\t\t\t\t\t\t\t\t}),\n+\t\t\t\t\t\t\t});\n+\t\t\t\t\t\t});\n+\t\t\t\t\t\tObject.defineProperty(result, \"inserts\", { value: inserts, enumerable: true });\n+\t\t\t\t\t}\n+\t\t\t\t\tfor (const field of listFields) {\n+\t\t\t\t\t\tconst collection = encoded.lists?.[field];\n+\t\t\t\t\t\tif (collection === undefined) continue;\n+\t\t\t\t\t\tif (typeof collection !== \"string\" || collection !== `atom-list:${atom.seq}:${field}`)\n+\t\t\t\t\t\t\tthrow Error(\"invalid stored atom list reference\");\n+\t\t\t\t\t\tObject.defineProperty(result, field, { value: readonlyStoredArray(storage, collection), enumerable: true });\n+\t\t\t\t\t}\n+\t\t\t\t\treturn Object.freeze(result);\n+\t\t\t\t},\n+\t\t\t\t(input, key) => {\n+\t\t\t\t\tconst atom = { ...input };\n+\t\t\t\t\tconst lists: Partial<Record<(typeof listFields)[number], string>> = {};\n+\t\t\t\t\tfor (const field of listFields) {\n+\t\t\t\t\t\tconst values = input[field];\n+\t\t\t\t\t\tif (!values || values.length <= 256) continue;\n+\t\t\t\t\t\tconst collection = `atom-list:${input.seq}:${field}`;\n+\t\t\t\t\t\tconst saved = storedArray<unknown>(storage, collection);\n+\t\t\t\t\t\tfor (const value of values) saved.push(value);\n+\t\t\t\t\t\tlists[field] = collection;\n+\t\t\t\t\t\tObject.defineProperty(atom, field, { value: [], enumerable: true });\n+\t\t\t\t\t}\n+\t\t\t\t\tconst listCount = Object.keys(lists).length;\n+\t\t\t\t\tconst hasLists = listCount > 0;\n+\t\t\t\t\tif (atom.inserts.length > 256 || atom.inserts.some((run) => run.lines.length > 256)) {\n+\t\t\t\t\t\tconst collection = `atom-inserts:${input.seq}`;\n+\t\t\t\t\t\tconst runs = storedArray<unknown>(storage, collection);\n+\t\t\t\t\t\tlet runIndex = 0;\n+\t\t\t\t\t\tlet lineIndex = 0;\n+\t\t\t\t\t\tfor (const run of atom.inserts) {\n+\t\t\t\t\t\t\tconst lineCollection = `${collection}:lines:${runIndex++}`;\n+\t\t\t\t\t\t\tconst lines = storedArray<unknown>(storage, lineCollection);\n+\t\t\t\t\t\t\tfor (const line of run.lines) {\n+\t\t\t\t\t\t\t\tconst text = JSON.stringify([key, lineIndex++]);\n+\t\t\t\t\t\t\t\tif (line.length > StoredText.chunkCharacters) {\n+\t\t\t\t\t\t\t\t\tatomText.write(text, line);\n+\t\t\t\t\t\t\t\t\tlines.push({ text });\n+\t\t\t\t\t\t\t\t} else lines.push(line);\n+\t\t\t\t\t\t\t}\n+\t\t\t\t\t\t\truns.push({ file: run.file, parent: run.parent, lines: lineCollection });\n+\t\t\t\t\t\t}\n+\t\t\t\t\t\treturn {\n+\t\t\t\t\t\t\tinsertionFormat: 1,\n+\t\t\t\t\t\t\tinsertionRuns: collection,\n+\t\t\t\t\t\t\t...(hasLists ? { listFormat: 1, listCount, lists } : {}),\n+\t\t\t\t\t\t\tatom: { ...atom, inserts: [] },\n+\t\t\t\t\t\t};\n+\t\t\t\t\t}\n+\t\t\t\t\tif (!atom.inserts.some((run) => run.lines.some((line) => line.length > StoredText.chunkCharacters)))\n+\t\t\t\t\t\treturn hasLists ? { listFormat: 1, listCount, lists, atom } : atom;\n+\t\t\t\t\tlet index = 0;\n+\t\t\t\t\tconst inserts = atom.inserts.map((run) => ({\n+\t\t\t\t\t\t...run,\n+\t\t\t\t\t\tlines: run.lines.map((line) => {\n+\t\t\t\t\t\t\tconst text = JSON.stringify([key, index++]);\n+\t\t\t\t\t\t\tif (line.length <= StoredText.chunkCharacters) return line;\n+\t\t\t\t\t\t\tatomText.write(text, line);\n+\t\t\t\t\t\t\treturn { text };\n+\t\t\t\t\t\t}),\n+\t\t\t\t\t}));\n+\t\t\t\t\treturn {\n+\t\t\t\t\t\ttextFormat: 1,\n+\t\t\t\t\t\t...(hasLists ? { listFormat: 1, listCount, lists } : {}),\n+\t\t\t\t\t\tatom: { ...atom, inserts },\n+\t\t\t\t\t};\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@@ -324,7 +483,26 @@\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\tconst longText = atomText;\n+\t\t\tthis.#lineText = storedArray<string>(\n+\t\t\t\tstorage,\n+\t\t\t\t\"line-text\",\n+\t\t\t\t(value) => {\n+\t\t\t\t\tif (typeof value === \"string\") return value;\n+\t\t\t\t\tconst reference = value as unknown as { format: number; text: string };\n+\t\t\t\t\tif (reference?.format !== 1 || typeof reference.text !== \"string\") throw Error(\"invalid long line reference\");\n+\t\t\t\t\treturn longText.read(reference.text);\n+\t\t\t\t},\n+\t\t\t\t(value, key) => {\n+\t\t\t\t\tif (value.length <= StoredText.chunkCharacters) return value;\n+\t\t\t\t\tconst number = Number(key);\n+\t\t\t\t\tconst seq = this.#lineAtom.at(number);\n+\t\t\t\t\tconst text = JSON.stringify([String(seq), number - this.#lineBase[seq]!]);\n+\t\t\t\t\tconst header = storage.read(\"atom-text:long\", text) as { characters?: number } | undefined;\n+\t\t\t\t\tif (header?.characters !== value.length) throw Error(\"long line atom text is missing\");\n+\t\t\t\t\treturn { format: 1, text };\n+\t\t\t\t},\n+\t\t\t);\n \t\t\tthis.#pathIndex = storedMap(storage, \"path-index\");\n \t\t\tthis.#moreDeleterPages = storedLists<number>(storage, \"more-deleters\", (key) =>\n \t\t\t\tJSON.stringify([\"number\", Number(key)]),\n@@ -565,6 +743,15 @@\n \n \t/** The lines an atom deletes, from the graph's own packed copy (#46): never a read of the log. */\n \tdeletedLines(id: AtomId): readonly LineId[] {\n+\t\tconst seq = this.#seq(id);\n+\t\tconst count = this.#storage?.read(\"atom-delete-counts\", String(seq));\n+\t\tif (count !== undefined) {\n+\t\t\tconst out: LineId[] = [];\n+\t\t\tfor (const n of storedLists<number>(this.#storage!, \"atom-deletes\").values(String(seq)))\n+\t\t\t\tout.push(this.#lineName(n));\n+\t\t\tif (out.length !== count) throw Error(\"incomplete atom deletion index\");\n+\t\t\treturn out;\n+\t\t}\n \t\tconst ns = this.#atomDeletes[this.#seq(id)];\n \t\tif (!ns) return EMPTY;\n \t\tconst out: LineId[] = new Array(ns.length);\n@@ -574,7 +761,13 @@\n \n \t/** How many lines an atom deletes, without reading its lists. */\n \tdeleteCount(id: AtomId): number {\n-\t\treturn this.#atomDeletes[this.#seq(id)]?.length ?? 0;\n+\t\tconst seq = this.#seq(id);\n+\t\tconst count = this.#storage?.read(\"atom-delete-counts\", String(seq));\n+\t\tif (count !== undefined) {\n+\t\t\tif (!Number.isSafeInteger(count) || (count as number) < 0) throw Error(\"invalid atom deletion count\");\n+\t\t\treturn count as number;\n+\t\t}\n+\t\treturn this.#atomDeletes[seq]?.length ?? 0;\n \t}\n \n \ttextOf(n: number): string {\n@@ -957,10 +1150,6 @@\n \t#reaches(from: Iterable<AtomId>, target: AtomId): boolean {\n \t\tconst floor = this.#lamport[this.#seq(target)]!;\n \t\tif (this.#storage) {\n-\t\t\t// Roots belong to the current atom's dependency list, not its history.\n-\t\t\tconst roots = [...from];\n-\t\t\tif (roots.includes(target)) return true;\n-\t\t\tif (roots.every((id) => this.#lamport[this.#seq(id)]! <= floor)) return false;\n \t\t\treturn this.withProjectionScratch((scratch) => {\n \t\t\t\tlet length = 0;\n \t\t\t\tconst push = (id: AtomId): void => {\n@@ -968,7 +1157,10 @@\n \t\t\t\t\tscratch.write(\"seen\", id, true);\n \t\t\t\t\tscratch.write(\"stack\", String(length++), id);\n \t\t\t\t};\n-\t\t\t\tfor (const id of roots) push(id);\n+\t\t\t\tfor (const id of from) {\n+\t\t\t\t\tif (id === target) return true;\n+\t\t\t\t\tif (this.#lamport[this.#seq(id)]! > floor) push(id);\n+\t\t\t\t}\n \t\t\t\twhile (length > 0) {\n \t\t\t\t\tconst key = String(--length);\n \t\t\t\t\tconst current = scratch.read(\"stack\", key) as AtomId;\n@@ -1011,12 +1203,11 @@\n \t\telse this.#add(atom);\n \t}\n \n-\t#add(atom: Atom): void {\n-\t\tif (this.#storage && this.#storage.read(\"ordered-children\", \"format\") !== 2) {\n-\t\t\tif (this.#atoms.length !== 0) throw new Error(\"ordered children require fresh adoption\");\n-\t\t\tthis.#storage.write(\"ordered-children\", \"format\", 2);\n-\t\t}\n-\n+\t#validateAcceptedAtom(atom: Atom, scratch?: GraphStateStorage): void {\n+\t\tconst membership = <T extends string>(name: string): { has(key: T): boolean; add(key: T): unknown } => {\n+\t\t\tif (!scratch) return new Set<T>();\n+\t\t\treturn { has: (key) => scratch.read(name, key) === true, add: (key) => scratch.write(name, key, true) };\n+\t\t};\n \t\tvalidateShape(atom);\n \t\tconst seq = this.#atoms.length;\n \t\tconst bad = (why: string): never => {\n@@ -1024,24 +1215,32 @@\n \t\t};\n \t\tif (atom.seq !== seq || atom.id !== atomId(seq)) bad(`expected id ${atomId(seq)} with seq ${seq}`);\n \n-\t\tconst deps = new Set<AtomId>();\n+\t\tconst deps = membership<AtomId>(\"deps\");\n \t\tfor (const d of atom.deps) {\n \t\t\tif (!this.has(d)) bad(`dependency ${d} is not in the graph`);\n \t\t\tif (deps.has(d)) bad(`dependency ${d} listed twice`);\n \t\t\tdeps.add(d);\n \t\t}\n-\t\tfor (const d of [...atom.needs, ...atom.resolves]) {\n-\t\t\tif (!deps.has(d)) bad(`${d} is in needs/resolves but not in deps`);\n-\t\t}\n+\t\tfor (const list of [atom.needs, atom.resolves])\n+\t\t\tfor (const d of list) {\n+\t\t\t\tif (!deps.has(d)) bad(`${d} is in needs/resolves but not in deps`);\n+\t\t\t}\n \t\tfor (const r of atom.reasons) if (!this.has(r.to)) bad(`reason points at unknown atom ${r.to}`);\n \n \t\t// Everything it touches must come from its closure. Derived deps name the\n \t\t// writers directly, so this is usually one lookup per writer.\n-\t\tconst below = new Map<AtomId, boolean>();\n+\t\tconst memoryBelow = scratch ? undefined : new Map<AtomId, boolean>();\n+\t\tconst below = {\n+\t\t\tget: (key: AtomId) => (scratch ? (scratch.read(\"below\", key) as boolean | undefined) : memoryBelow!.get(key)),\n+\t\t\tset: (key: AtomId, value: boolean) => {\n+\t\t\t\tif (scratch) scratch.write(\"below\", key, value);\n+\t\t\t\telse memoryBelow!.set(key, value);\n+\t\t\t},\n+\t\t};\n \t\tconst inClosure = (writer: AtomId): boolean => {\n \t\t\tlet hit = below.get(writer);\n \t\t\tif (hit === undefined) {\n-\t\t\t\thit = deps.has(writer) || this.#reaches(deps, writer);\n+\t\t\t\thit = deps.has(writer) || this.#reaches(atom.deps, writer);\n \t\t\t\tbelow.set(writer, hit);\n \t\t\t}\n \t\t\treturn hit;\n@@ -1060,45 +1259,65 @@\n \t\t\t\tcheckLine(run.parent, \"an insert\");\n \t\t\t}\n \t\t}\n-\t\tconst moved = new Set<LineId>();\n+\t\tconst writes = membership<Key>(\"writes\");\n+\t\tfor (const key of atom.writes) writes.add(key);\n+\t\tconst moved = membership<LineId>(\"moved\");\n \t\tfor (const m of atom.moves ?? []) {\n \t\t\tcheckLine(m.line, \"a move\");\n \t\t\tif (!isStartNode(m.parent)) checkLine(m.parent, \"a move\");\n \t\t\tif (m.line === m.parent) bad(`moves ${m.line} after itself`);\n \t\t\tif (moved.has(m.line)) bad(`moves ${m.line} twice`);\n \t\t\tmoved.add(m.line);\n-\t\t\tif (!atom.writes.includes(posKey(m.line)) || !atom.writes.includes(gapKey(m.parent))) {\n+\t\t\tif (!writes.has(posKey(m.line)) || !writes.has(gapKey(m.parent))) {\n \t\t\t\tbad(`moves ${m.line} without writing ${posKey(m.line)} and ${gapKey(m.parent)}`);\n \t\t\t}\n \t\t}\n-\t\tconst deleted = new Set<LineId>();\n+\t\tconst deleted = membership<LineId>(\"deleted\");\n \t\tfor (const line of atom.deletes) {\n \t\t\tcheckLine(line, \"a delete\");\n \t\t\tif (deleted.has(line)) bad(`deletes ${line} twice`);\n \t\t\tdeleted.add(line);\n \t\t}\n-\t\tconst writes = new Set(atom.writes);\n-\t\tfor (const line of deleted) if (!writes.has(lineKey(line))) bad(`deletes ${line} without writing ${lineKey(line)}`);\n-\t\tfor (const key of [...atom.writes, ...atom.reads, ...atom.holds]) {\n-\t\t\tconst parsed = parseKey(key);\n-\t\t\tif (parsed.kind === \"line\") checkLine(parsed.node, `key ${key}`);\n-\t\t\telse if ((parsed.kind === \"gap\" || parsed.kind === \"pos\") && !isStartNode(parsed.node))\n-\t\t\t\tcheckLine(parsed.node, `key ${key}`);\n+\t\tfor (const line of atom.deletes)\n+\t\t\tif (!writes.has(lineKey(line))) bad(`deletes ${line} without writing ${lineKey(line)}`);\n+\t\tfor (const list of [atom.writes, atom.reads, atom.holds])\n+\t\t\tfor (const key of list) {\n+\t\t\t\tconst parsed = parseKey(key);\n+\t\t\t\tif (parsed.kind === \"line\") checkLine(parsed.node, `key ${key}`);\n+\t\t\t\telse if ((parsed.kind === \"gap\" || parsed.kind === \"pos\") && !isStartNode(parsed.node))\n+\t\t\t\t\tcheckLine(parsed.node, `key ${key}`);\n+\t\t\t}\n+\t}\n+\n+\t#add(atom: Atom): void {\n+\t\tif (this.#storage && this.#storage.read(\"ordered-children\", \"format\") !== 2) {\n+\t\t\tif (this.#atoms.length !== 0) throw new Error(\"ordered children require fresh adoption\");\n+\t\t\tthis.#storage.write(\"ordered-children\", \"format\", 2);\n \t\t}\n \n+\t\tif (this.#storage) this.withProjectionScratch((scratch) => this.#validateAcceptedAtom(atom, scratch));\n+\t\telse this.#validateAcceptedAtom(atom);\n+\t\tconst seq = this.#atoms.length;\n+\t\tconst deps = atom.deps;\n+\t\tconst deleted = this.#storage ? undefined : new Set(atom.deletes);\n+\t\tconst writes = this.#storage ? atom.writes : new Set(atom.writes);\n+\n \t\t// Accept.\n-\t\tconst frozen = freezeAtom(\n-\t\t\tatom,\n-\t\t\t(id) => this.idOfSeq(seqOf(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-\t\t\t},\n-\t\t\tthis.#texts ? this.#reader(seq) : undefined,\n-\t\t\tthis.#lists ? this.#listReader(seq) : undefined,\n-\t\t);\n+\t\t// Persistent storage copies the accepted atom; a second frozen copy only duplicates its lists.\n+\t\tconst frozen = this.#storage\n+\t\t\t? atom\n+\t\t\t: freezeAtom(\n+\t\t\t\t\tatom,\n+\t\t\t\t\t(id) => this.idOfSeq(seqOf(id)),\n+\t\t\t\t\t(author) => {\n+\t\t\t\t\t\tif (this.#storage) return author;\n+\t\t\t\t\t\tlet a = this.#authors.get(author);\n+\t\t\t\t\t\tif (a === undefined) this.#authors.set(author, (a = author));\n+\t\t\t\t\t\treturn a;\n+\t\t\t\t\t},\n+\t\t\t\t\tthis.#texts ? this.#reader(seq) : undefined,\n+\t\t\t\t\tthis.#lists ? this.#listReader(seq) : undefined,\n+\t\t\t\t);\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@@ -1106,9 +1325,28 @@\n \n \t\t// The run starts' parents and the deleted lines, as codes, before this atom's own lines exist.\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 ? (this.#storage ? deletedN : Int32Array.from(deletedN)) : undefined);\n+\t\tconst deletes = (line: LineId | NodeId): boolean => {\n+\t\t\tif (isStartNode(line)) return false;\n+\t\t\tif (deleted) return deleted.has(line);\n+\t\t\tconst n = this.#lineN(line);\n+\t\t\treturn this.#deleter.at(n) === seq || this.#moreDeleterPages!.last(String(n)) === seq;\n+\t\t};\n+\t\tconst deletedN = this.#storage ? undefined : atom.deletes.map((line) => this.#lineN(line));\n+\t\tthis.#atomDeletes.push(deletedN?.length ? Int32Array.from(deletedN) : undefined);\n+\t\tif (this.#storage) {\n+\t\t\tconst pages = storedLists<number>(this.#storage, \"atom-deletes\");\n+\t\t\tfor (const line of atom.deletes) pages.append(String(seq), this.#lineN(line));\n+\t\t\tthis.#storage.write(\"atom-delete-counts\", String(seq), atom.deletes.length);\n+\t\t}\n+\t\tconst deletedNumbers = function* (graph: Graph) {\n+\t\t\tif (deletedN) yield* deletedN;\n+\t\t\telse for (const line of atom.deletes) yield graph.#lineN(line);\n+\t\t};\n+\t\tfor (const n of deletedNumbers(this)) {\n+\t\t\tif (this.#deleter.at(n) < 0) this.#deleter.set(n, seq);\n+\t\t\telse if (this.#moreDeleterPages) this.#moreDeleterPages.append(String(n), seq);\n+\t\t\telse pushIndex(this.#moreDeleters, n, seq);\n+\t\t}\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@@ -1119,7 +1357,7 @@\n \t\t\t\tnew OrderedIndex(this.#storage, \"ordered-children\", String(parent)).insert(\n \t\t\t\t\torderedChildKey({\n \t\t\t\t\t\tn: first,\n-\t\t\t\t\t\treplaces: deletes?.has(run.parent) ? 1 : 0,\n+\t\t\t\t\t\treplaces: deletes(run.parent) ? 1 : 0,\n \t\t\t\t\t\tlamport: lam,\n \t\t\t\t\t\tseq,\n \t\t\t\t\t\tk: first - this.#lineBase[seq]!,\n@@ -1137,7 +1375,7 @@\n \t\t\t\tthis.#lineParent.push(parent);\n \t\t\t\tthis.#lineText?.push(run.lines[i]!);\n \t\t\t\tthis.#deleter.push(-1);\n-\t\t\t\tthis.#replacing.push(i === 0 && deletes?.has(run.parent) ? 1 : 0);\n+\t\t\t\tthis.#replacing.push(i === 0 && deletes(run.parent) ? 1 : 0);\n \t\t\t\tparent = n;\n \t\t\t}\n \t\t}\n@@ -1152,37 +1390,39 @@\n \t\t\telse pushIndex(this.#relocatedToCode, parentCode, info);\n \t\t});\n \t\tif (frozen.moves) this.#movers.push(frozen.id);\n-\t\tfor (const n of deletedN) {\n-\t\t\tif (this.#deleter.at(n) < 0) this.#deleter.set(n, seq);\n-\t\t\telse if (this.#moreDeleterPages) this.#moreDeleterPages.append(String(n), seq);\n-\t\t\telse pushIndex(this.#moreDeleters, n, seq);\n-\t\t}\n-\t\tfor (const key of new Set(atom.writes)) {\n+\t\tfor (const key of writes) {\n \t\t\tconst code = this.#code(key);\n-\t\t\tif (this.#writersPages) this.#writersPages.append(JSON.stringify([typeof code, code]), frozen.id);\n-\t\t\telse pushOne(this.#writers, code, frozen.id);\n+\t\t\tif (this.#writersPages) {\n+\t\t\t\tconst key = JSON.stringify([typeof code, code]);\n+\t\t\t\tif (this.#writersPages.last(key) !== frozen.id) this.#writersPages.append(key, frozen.id);\n+\t\t\t} else pushOne(this.#writers, code, frozen.id);\n \t\t}\n-\t\tfor (const key of new Set(atom.reads)) {\n+\t\tfor (const key of this.#storage ? atom.reads : new Set(atom.reads)) {\n \t\t\tconst code = this.#code(key);\n-\t\t\tif (this.#readersPages) this.#readersPages.append(JSON.stringify([typeof code, code]), frozen.id);\n-\t\t\telse pushOne(this.#readers, code, frozen.id);\n+\t\t\tif (this.#readersPages) {\n+\t\t\t\tconst key = JSON.stringify([typeof code, code]);\n+\t\t\t\tif (this.#readersPages.last(key) !== frozen.id) this.#readersPages.append(key, frozen.id);\n+\t\t\t} else pushOne(this.#readers, code, frozen.id);\n \t\t}\n-\t\tfor (const key of new Set(atom.holds)) {\n+\t\tfor (const key of this.#storage ? atom.holds : new Set(atom.holds)) {\n \t\t\tconst code = this.#code(key);\n-\t\t\tif (this.#holdersPages) this.#holdersPages.append(JSON.stringify([typeof code, code]), frozen.id);\n-\t\t\telse pushOne(this.#holders, code, frozen.id);\n+\t\t\tif (this.#holdersPages) {\n+\t\t\t\tconst key = JSON.stringify([typeof code, code]);\n+\t\t\t\tif (this.#holdersPages.last(key) !== frozen.id) this.#holdersPages.append(key, frozen.id);\n+\t\t\t} else pushOne(this.#holders, code, frozen.id);\n \t\t}\n \t\tfor (const d of deps) {\n \t\t\tif (this.#dependentsPages) this.#dependentsPages.append(d, frozen.id);\n \t\t\telse pushOne(this.#dependents, d, frozen.id);\n \t\t}\n-\t\tfor (const r of new Set(frozen.resolves)) {\n-\t\t\tif (this.#resolversPages) this.#resolversPages.append(r, frozen.id);\n-\t\t\telse pushOne(this.#resolvers, r, frozen.id);\n+\t\tfor (const r of this.#storage ? frozen.resolves : new Set(frozen.resolves)) {\n+\t\t\tif (this.#resolversPages) {\n+\t\t\t\tif (this.#resolversPages.last(r) !== frozen.id) this.#resolversPages.append(r, frozen.id);\n+\t\t\t} else pushOne(this.#resolvers, r, frozen.id);\n \t\t}\n \t\tconst files = new Set<string>();\n \t\tfor (const run of atom.inserts) files.add(run.file);\n-\t\tfor (const n of deletedN) files.add(this.#paths[this.#lineFile.at(n)]!);\n+\t\tfor (const n of deletedNumbers(this)) files.add(this.#paths[this.#lineFile.at(n)]!);\n \t\tfor (const a of frozen.attrs ?? []) files.add(a.file);\n \t\tfor (const m of frozen.moves ?? []) {\n \t\t\tfiles.add(this.lineFile(m.line)!);"},{"path":"src/engine/state-source.ts","added":75,"removed":2,"diff":"--- a/src/engine/state-source.ts\n+++ b/src/engine/state-source.ts\n@@ -282,7 +282,12 @@\n }\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+export function storedArray<T>(\n+\tstorage: GraphStateStorage,\n+\tname: string,\n+\tdecode?: (value: T) => T,\n+\tencode?: (value: T, key: string) => unknown,\n+): T[] {\n \tconst length = () => (storage.read(`${name}:meta`, \"length\") as number | undefined) ?? 0;\n \tconst read = (key: string) => {\n \t\tconst value = storage.read(name, key) as T;\n@@ -303,7 +308,7 @@\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\tstorage.write(name, key, encode ? encode(value, key) : value);\n \t\t\tif (index === size) storage.write(`${name}:meta`, \"length\", size + 1);\n \t\t\treturn true;\n \t\t},\n@@ -371,6 +376,14 @@\n \t\t\t\tyield* values;\n \t\t\t}\n \t\t},\n+\t\tlast(key: string): V | undefined {\n+\t\t\tconst count = length(key);\n+\t\t\tif (count === 0) return undefined;\n+\t\t\tconst values = page(key, Math.floor((count - 1) / pageSize));\n+\t\t\tconst expected = ((count - 1) % pageSize) + 1;\n+\t\t\tif (values.length !== expected) throw new Error(`incomplete writer list page in ${name}`);\n+\t\t\treturn values[expected - 1];\n+\t\t},\n \t\tappend(key: string, value: V): void {\n \t\t\tconst count = length(key);\n \t\t\tconst offset = count % pageSize;\n@@ -532,3 +545,63 @@\n \t\tfor (const key of this.values()) callback.call(thisArg, key, key, this);\n \t}\n }\n+\n+/** Read-only array access to individually stored values, without copying the list. */\n+export function readonlyStoredArray<T>(\n+\tstorage: GraphStateStorage,\n+\tname: string,\n+\tdecode?: (value: unknown, index: number) => T,\n+): readonly T[] {\n+\tconst length = () => {\n+\t\tconst count = storage.read(`${name}:meta`, \"length\");\n+\t\tif (!Number.isSafeInteger(count) || (count as number) < 0) throw Error(\"invalid stored list length\");\n+\t\treturn count as number;\n+\t};\n+\tlength();\n+\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)) {\n+\t\t\t\tif (Number(key) >= length()) return undefined;\n+\t\t\t\tconst raw = storage.read(name, key);\n+\t\t\t\tconst value = raw === undefined ? undefined : decode ? decode(raw, Number(key)) : (raw as T);\n+\t\t\t\tif (value === undefined) throw Error(\"missing stored list element\");\n+\t\t\t\treturn value && typeof value === \"object\" ? Object.freeze(value) : value;\n+\t\t\t}\n+\t\t\treturn Reflect.get(target, key, receiver);\n+\t\t},\n+\t\thas(target, key) {\n+\t\t\treturn indexKey(key) ? Number(key) < length() : Reflect.has(target, key);\n+\t\t},\n+\t\townKeys() {\n+\t\t\treturn [...Array.from({ length: length() }, (_, index) => String(index)), \"length\"];\n+\t\t},\n+\t\tgetOwnPropertyDescriptor(target, key) {\n+\t\t\tif (key === \"length\") return { ...Reflect.getOwnPropertyDescriptor(target, key)!, value: length() };\n+\t\t\tif (indexKey(key) && Number(key) < length()) {\n+\t\t\t\tconst raw = storage.read(name, key);\n+\t\t\t\tconst value = raw === undefined ? undefined : decode ? decode(raw, Number(key)) : (raw as T);\n+\t\t\t\tif (value === undefined) throw Error(\"missing stored list element\");\n+\t\t\t\treturn {\n+\t\t\t\t\tconfigurable: true,\n+\t\t\t\t\tenumerable: true,\n+\t\t\t\t\twritable: false,\n+\t\t\t\t\tvalue: value && typeof value === \"object\" ? Object.freeze(value) : value,\n+\t\t\t\t};\n+\t\t\t}\n+\t\t\treturn Reflect.getOwnPropertyDescriptor(target, key);\n+\t\t},\n+\t\tpreventExtensions() {\n+\t\t\tthrow Error(\"stored list is read-only\");\n+\t\t},\n+\t\tset() {\n+\t\t\tthrow Error(\"stored list is read-only\");\n+\t\t},\n+\t\tdeleteProperty() {\n+\t\t\tthrow Error(\"stored list is read-only\");\n+\t\t},\n+\t\tdefineProperty() {\n+\t\t\tthrow Error(\"stored list is read-only\");\n+\t\t},\n+\t});\n+}"},{"path":"src/engine/stored-text.ts","added":70,"removed":0,"diff":"--- /dev/null\n+++ b/src/engine/stored-text.ts\n@@ -0,0 +1,70 @@\n+import type { GraphStateStorage } from \"./state-source.ts\";\n+\n+/** Exact UTF-16 text storage with bounded values; callers choose streaming or full reads. */\n+export class StoredText {\n+\tstatic readonly chunkCharacters = 16384;\n+\treadonly storage: GraphStateStorage;\n+\treadonly collection: string;\n+\tconstructor(storage: GraphStateStorage, collection: string) {\n+\t\tthis.storage = storage;\n+\t\tthis.collection = collection;\n+\t}\n+\twrite(key: string, text: string): void {\n+\t\tthis.writeChunks(\n+\t\t\tkey,\n+\t\t\t(function* () {\n+\t\t\t\tfor (let offset = 0; offset < text.length; offset += StoredText.chunkCharacters)\n+\t\t\t\t\tyield text.slice(offset, offset + StoredText.chunkCharacters);\n+\t\t\t})(),\n+\t\t);\n+\t}\n+\t/** Input pieces and the retained buffer are bounded independently of total text length. */\n+\twriteChunks(key: string, chunks: Iterable<string>): void {\n+\t\tthis.storage.transaction(() => {\n+\t\t\tif (this.storage.read(this.collection, key) !== undefined) throw Error(\"stored text already exists\");\n+\t\t\tlet pending = \"\",\n+\t\t\t\tcharacters = 0,\n+\t\t\t\tparts = 0;\n+\t\t\tconst persist = (chunk: string) =>\n+\t\t\t\tthis.storage.write(`${this.collection}:chunks`, JSON.stringify([key, parts++]), chunk);\n+\t\t\tfor (const chunk of chunks) {\n+\t\t\t\tif (typeof chunk !== \"string\" || chunk.length > StoredText.chunkCharacters)\n+\t\t\t\t\tthrow Error(\"stored text input chunk exceeds bound\");\n+\t\t\t\tcharacters += chunk.length;\n+\t\t\t\tif (!Number.isSafeInteger(characters)) throw Error(\"stored text length overflow\");\n+\t\t\t\tpending += chunk;\n+\t\t\t\tif (pending.length >= StoredText.chunkCharacters) {\n+\t\t\t\t\tpersist(pending.slice(0, StoredText.chunkCharacters));\n+\t\t\t\t\tpending = pending.slice(StoredText.chunkCharacters);\n+\t\t\t\t}\n+\t\t\t}\n+\t\t\tif (pending) persist(pending);\n+\t\t\tthis.storage.write(this.collection, key, { format: 1, characters, parts });\n+\t\t});\n+\t}\n+\n+\t*chunks(key: string): IterableIterator<string> {\n+\t\tconst header = this.storage.read(this.collection, key) as\n+\t\t\t| { format: number; characters: number; parts: number }\n+\t\t\t| undefined;\n+\t\tif (\n+\t\t\theader?.format !== 1 ||\n+\t\t\t!Number.isSafeInteger(header.characters) ||\n+\t\t\theader.characters < 0 ||\n+\t\t\theader.parts !== Math.ceil(header.characters / StoredText.chunkCharacters)\n+\t\t)\n+\t\t\tthrow Error(\"invalid stored text header\");\n+\t\tfor (let part = 0; part < header.parts; part++) {\n+\t\t\tconst chunk = this.storage.read(`${this.collection}:chunks`, JSON.stringify([key, part]));\n+\t\t\tif (\n+\t\t\t\ttypeof chunk !== \"string\" ||\n+\t\t\t\tchunk.length !== Math.min(StoredText.chunkCharacters, header.characters - part * StoredText.chunkCharacters)\n+\t\t\t)\n+\t\t\t\tthrow Error(\"incomplete stored text\");\n+\t\t\tyield chunk;\n+\t\t}\n+\t}\n+\tread(key: string): string {\n+\t\treturn [...this.chunks(key)].join(\"\");\n+\t}\n+}"},{"path":"src/engine/test/graph-atom-list-integrity.test.ts","added":40,"removed":0,"diff":"--- /dev/null\n+++ b/src/engine/test/graph-atom-list-integrity.test.ts\n@@ -0,0 +1,40 @@\n+import assert from \"node:assert/strict\";\n+import { test } from \"node:test\";\n+import { buildBase, Graph } from \"../index.ts\";\n+import { lineKey } from \"../keys.ts\";\n+import type { Atom } from \"../types.ts\";\n+import { SqlState } from \"./storage-helper.ts\";\n+\n+test(\"stored atom list metadata refuses missing or substituted references\", () => {\n+\tconst storage = new SqlState();\n+\ttry {\n+\t\tconst graph = new Graph({ storage });\n+\t\tgraph.add(buildBase({ \"a.txt\": \"base\" }, { author: \"fixture\", message: \"base\", time: 0 }));\n+\t\tconst keys = Array.from({ length: 513 }, () => lineKey(\"a0.0\"));\n+\t\tconst atom: Atom = {\n+\t\t\tid: \"a1\",\n+\t\t\tseq: 1,\n+\t\t\tauthor: \"fixture\",\n+\t\t\tmessage: \"lists\",\n+\t\t\ttime: 1,\n+\t\t\tinserts: [],\n+\t\t\tdeletes: [],\n+\t\t\twrites: keys,\n+\t\t\treads: keys,\n+\t\t\tholds: keys,\n+\t\t\tneeds: [],\n+\t\t\tresolves: [],\n+\t\t\treasons: [],\n+\t\t\tdeps: [\"a0\"],\n+\t\t};\n+\t\tgraph.add(atom);\n+\n+\t\tconst stored = storage.read(\"atoms\", \"1\") as Record<string, unknown>;\n+\t\tfor (const lists of [undefined, {}, { writes: \"atom-list:1:reads\" }]) {\n+\t\t\tstorage.write(\"atoms\", \"1\", { ...stored, lists });\n+\t\t\tassert.throws(() => new Graph({ storage }).atom(\"a1\"), /stored atom list/);\n+\t\t}\n+\t} finally {\n+\t\tstorage.db.close();\n+\t}\n+});"},{"path":"src/engine/test/graph-atom-list-rollback.test.ts","added":45,"removed":0,"diff":"--- /dev/null\n+++ b/src/engine/test/graph-atom-list-rollback.test.ts\n@@ -0,0 +1,45 @@\n+import assert from \"node:assert/strict\";\n+import { test } from \"node:test\";\n+import { buildBase, Graph } from \"../index.ts\";\n+import { lineKey } from \"../keys.ts\";\n+import type { Atom } from \"../types.ts\";\n+import { SqlState } from \"./storage-helper.ts\";\n+\n+test(\"partial atom-list persistence rolls back and retries on the same graph\", () => {\n+\tconst storage = new SqlState();\n+\ttry {\n+\t\tconst graph = new Graph({ storage });\n+\t\tgraph.add(buildBase({ \"a.txt\": \"base\" }, { author: \"fixture\", message: \"base\", time: 0 }));\n+\t\tconst keys = Array.from({ length: 257 }, () => lineKey(\"a0.0\"));\n+\t\tconst atom: Atom = {\n+\t\t\tid: \"a1\",\n+\t\t\tseq: 1,\n+\t\t\tauthor: \"fixture\",\n+\t\t\tmessage: \"lists\",\n+\t\t\ttime: 1,\n+\t\t\tinserts: [],\n+\t\t\tdeletes: [],\n+\t\t\twrites: keys,\n+\t\t\treads: [],\n+\t\t\tholds: [],\n+\t\t\tneeds: [],\n+\t\t\tresolves: [],\n+\t\t\treasons: [],\n+\t\t\tdeps: [\"a0\"],\n+\t\t};\n+\t\tconst before = storage.db.prepare(\"SELECT * FROM state ORDER BY collection,key\").all();\n+\t\tconst write = storage.write.bind(storage);\n+\t\tstorage.write = (collection, key, value) => {\n+\t\t\twrite(collection, key, value);\n+\t\t\tif (collection === \"atom-list:1:writes\" && key === \"128\") throw Error(\"injected list persistence failure\");\n+\t\t};\n+\t\tassert.throws(() => graph.add(atom), /injected list persistence failure/);\n+\t\tassert.deepEqual(storage.db.prepare(\"SELECT * FROM state ORDER BY collection,key\").all(), before);\n+\t\tassert.equal(graph.size, 1);\n+\t\tstorage.write = write;\n+\t\tgraph.add(atom);\n+\t\tassert.deepEqual([...new Graph({ storage }).atom(\"a1\").writes], keys);\n+\t} finally {\n+\t\tstorage.db.close();\n+\t}\n+});"},{"path":"src/engine/test/graph-atom-lists.test.ts","added":51,"removed":0,"diff":"--- /dev/null\n+++ b/src/engine/test/graph-atom-lists.test.ts\n@@ -0,0 +1,51 @@\n+import assert from \"node:assert/strict\";\n+import { test } from \"node:test\";\n+import { buildBase, Graph } from \"../index.ts\";\n+import { lineKey } from \"../keys.ts\";\n+import type { Atom } from \"../types.ts\";\n+import { SqlState } from \"./storage-helper.ts\";\n+\n+test(\"large persisted atom lists stay out of metadata and read incrementally\", () => {\n+\tconst storage = new SqlState();\n+\ttry {\n+\t\tconst graph = new Graph({ storage });\n+\t\tgraph.add(buildBase({ \"a.txt\": \"base\" }, { author: \"fixture\", message: \"base\", time: 0 }));\n+\t\tconst keys = Array.from({ length: 513 }, () => lineKey(\"a0.0\"));\n+\t\tconst atom: Atom = {\n+\t\t\tid: \"a1\",\n+\t\t\tseq: 1,\n+\t\t\tauthor: \"fixture\",\n+\t\t\tmessage: \"lists\",\n+\t\t\ttime: 1,\n+\t\t\tinserts: [],\n+\t\t\tdeletes: [],\n+\t\t\twrites: keys,\n+\t\t\treads: keys,\n+\t\t\tholds: keys,\n+\t\t\tneeds: [],\n+\t\t\tresolves: [],\n+\t\t\treasons: [],\n+\t\t\tdeps: [\"a0\"],\n+\t\t};\n+\t\tgraph.add(atom);\n+\t\tassert.ok(JSON.stringify(storage.read(\"atoms\", \"1\")).length < 2048);\n+\t\tlet items = 0;\n+\t\tconst read = storage.read.bind(storage);\n+\t\tstorage.read = (collection, key) => {\n+\t\t\tif (collection.startsWith(\"atom-list:\") && !collection.endsWith(\":meta\")) items++;\n+\t\t\treturn read(collection, key);\n+\t\t};\n+\t\tconst saved = new Graph({ storage }).atom(\"a1\");\n+\t\tassert.equal(items, 0);\n+\t\tassert.equal(saved.writes.length, 513);\n+\t\tassert.equal(items, 0);\n+\t\tassert.equal(saved.writes[512], keys[512]);\n+\t\tassert.equal(items, 1);\n+\t\tassert.throws(() => {\n+\t\t\t(saved.writes as string[])[0] = \"changed\";\n+\t\t}, /read-only/);\n+\t\tassert.deepEqual([...saved.writes], keys);\n+\t} finally {\n+\t\tstorage.db.close();\n+\t}\n+});"},{"path":"src/engine/test/graph-deletion-pages.test.ts","added":49,"removed":0,"diff":"--- /dev/null\n+++ b/src/engine/test/graph-deletion-pages.test.ts\n@@ -0,0 +1,49 @@\n+import assert from \"node:assert/strict\";\n+import { test } from \"node:test\";\n+import { buildBase, Graph } from \"../index.ts\";\n+import { lineKey } from \"../keys.ts\";\n+import type { Atom, LineId } from \"../types.ts\";\n+import { SqlState } from \"./storage-helper.ts\";\n+\n+test(\"persistent delete counts do not load the atom's deleted-line payload\", () => {\n+\tconst storage = new SqlState();\n+\ttry {\n+\t\tconst graph = new Graph({ storage });\n+\t\tgraph.add(\n+\t\t\tbuildBase(\n+\t\t\t\t{ \"a.txt\": Array.from({ length: 300 }, (_, i) => `line ${i}`).join(\"\\n\") },\n+\t\t\t\t{ author: \"fixture\", message: \"base\", time: 0 },\n+\t\t\t),\n+\t\t);\n+\t\tconst deletes = Array.from({ length: 300 }, (_, i) => `a0.${i}` as LineId);\n+\t\tconst atom: Atom = {\n+\t\t\tid: \"a1\",\n+\t\t\tseq: 1,\n+\t\t\tauthor: \"fixture\",\n+\t\t\tmessage: \"delete\",\n+\t\t\ttime: 1,\n+\t\t\tinserts: [],\n+\t\t\tdeletes,\n+\t\t\twrites: deletes.map(lineKey),\n+\t\t\treads: [],\n+\t\t\tholds: [],\n+\t\t\tneeds: [],\n+\t\t\tresolves: [],\n+\t\t\treasons: [],\n+\t\t\tdeps: [\"a0\"],\n+\t\t};\n+\t\tgraph.add(atom);\n+\t\tconst reopened = new Graph({ storage });\n+\t\tconst read = storage.read.bind(storage);\n+\t\tstorage.read = (collection, key) => {\n+\t\t\tassert.notEqual(collection, \"atom-deletes\", \"count decoded the full deletion list\");\n+\t\t\tassert.notEqual(collection, \"atom-deletes:pages\", \"count read deletion payload pages\");\n+\t\t\treturn read(collection, key);\n+\t\t};\n+\t\tassert.equal(reopened.deleteCount(\"a1\"), 300);\n+\t\tstorage.read = read;\n+\t\tassert.deepEqual(reopened.deletedLines(\"a1\"), deletes);\n+\t} finally {\n+\t\tstorage.db.close();\n+\t}\n+});"},{"path":"src/engine/test/graph-deletion-rollback.test.ts","added":54,"removed":0,"diff":"--- /dev/null\n+++ b/src/engine/test/graph-deletion-rollback.test.ts\n@@ -0,0 +1,54 @@\n+import assert from \"node:assert/strict\";\n+import { test } from \"node:test\";\n+import { buildBase, Graph } from \"../index.ts\";\n+import { lineKey } from \"../keys.ts\";\n+import type { Atom, LineId } from \"../types.ts\";\n+import { SqlState } from \"./storage-helper.ts\";\n+\n+test(\"deletion page failure rolls back acceptance and missing pages fail after reopen\", () => {\n+\tconst storage = new SqlState();\n+\ttry {\n+\t\tconst graph = new Graph({ storage });\n+\t\tgraph.add(\n+\t\t\tbuildBase(\n+\t\t\t\t{ \"a.txt\": Array.from({ length: 300 }, (_, i) => `line ${i}`).join(\"\\n\") },\n+\t\t\t\t{ author: \"fixture\", message: \"base\", time: 0 },\n+\t\t\t),\n+\t\t);\n+\t\tconst deletes = Array.from({ length: 300 }, (_, i) => `a0.${i}` as LineId);\n+\t\tconst atom: Atom = {\n+\t\t\tid: \"a1\",\n+\t\t\tseq: 1,\n+\t\t\tauthor: \"fixture\",\n+\t\t\tmessage: \"delete\",\n+\t\t\ttime: 1,\n+\t\t\tinserts: [],\n+\t\t\tdeletes,\n+\t\t\twrites: deletes.map(lineKey),\n+\t\t\treads: [],\n+\t\t\tholds: [],\n+\t\t\tneeds: [],\n+\t\t\tresolves: [],\n+\t\t\treasons: [],\n+\t\t\tdeps: [\"a0\"],\n+\t\t};\n+\t\tconst before = storage.db.prepare(\"SELECT * FROM state ORDER BY collection,key\").all();\n+\t\tconst write = storage.write.bind(storage);\n+\t\tstorage.write = (collection, key, value) => {\n+\t\t\twrite(collection, key, value);\n+\t\t\tif (collection === \"atom-deletes:pages\" && key === JSON.stringify([\"1\", 1]))\n+\t\t\t\tthrow Error(\"injected deletion page failure\");\n+\t\t};\n+\t\tassert.throws(() => graph.add(atom), /injected deletion page failure/);\n+\t\tassert.deepEqual(storage.db.prepare(\"SELECT * FROM state ORDER BY collection,key\").all(), before);\n+\t\tassert.equal(graph.size, 1);\n+\t\tstorage.write = write;\n+\t\tgraph.add(atom);\n+\t\tassert.equal(new Graph({ storage }).deleteCount(\"a1\"), 300);\n+\t\tassert.deepEqual(new Graph({ storage }).deletedLines(\"a1\"), deletes);\n+\t\tstorage.remove(\"atom-deletes:pages\", JSON.stringify([\"1\", 1]));\n+\t\tassert.throws(() => new Graph({ storage }).deletedLines(\"a1\"), /missing or invalid writer list page/);\n+\t} finally {\n+\t\tstorage.db.close();\n+\t}\n+});"},{"path":"src/engine/test/graph-index-dedup.test.ts","added":64,"removed":0,"diff":"--- /dev/null\n+++ b/src/engine/test/graph-index-dedup.test.ts\n@@ -0,0 +1,64 @@\n+import assert from \"node:assert/strict\";\n+import { test } from \"node:test\";\n+import { buildBase, Graph } from \"../index.ts\";\n+import { lineKey } from \"../keys.ts\";\n+import { storedLists } from \"../state-source.ts\";\n+import type { Atom } from \"../types.ts\";\n+import { SqlState } from \"./storage-helper.ts\";\n+\n+test(\"persistent key indexes deduplicate repeated keys without per-atom key sets\", () => {\n+\tconst storage = new SqlState();\n+\ttry {\n+\t\tconst graph = new Graph({ storage });\n+\t\tgraph.add(buildBase({ \"a.txt\": \"base\" }, { author: \"fixture\", message: \"base\", time: 0 }));\n+\t\tconst keys = Array.from({ length: 513 }, () => lineKey(\"a0.0\"));\n+\t\tconst atom: Atom = {\n+\t\t\tid: \"a1\",\n+\t\t\tseq: 1,\n+\t\t\tauthor: \"fixture\",\n+\t\t\tmessage: \"keys\",\n+\t\t\ttime: 1,\n+\t\t\tinserts: [],\n+\t\t\tdeletes: [],\n+\t\t\twrites: keys,\n+\t\t\treads: keys,\n+\t\t\tholds: keys,\n+\t\t\tneeds: [],\n+\t\t\tresolves: [\"a0\", \"a0\"],\n+\t\t\treasons: [],\n+\t\t\tdeps: [\"a0\"],\n+\t\t};\n+\t\tgraph.add(atom);\n+\t\tfor (const collection of [\"writers\", \"readers\", \"holders\", \"resolvers\"]) {\n+\t\t\tconst index = storedLists<string>(storage, collection, (key) => key);\n+\t\t\tlet matches = 0;\n+\t\t\tfor (const key of index.keys()) {\n+\t\t\t\tconst values = [...index.values(key)];\n+\t\t\t\tconst count = values.filter((value) => value === \"a1\").length;\n+\t\t\t\tassert.ok(count <= 1);\n+\t\t\t\tmatches += count;\n+\t\t\t}\n+\t\t\tassert.equal(matches, 1, collection);\n+\t\t}\n+\t} finally {\n+\t\tstorage.db.close();\n+\t}\n+});\n+\n+test(\"last list entry reads only its final page and rejects truncated pages\", () => {\n+\tconst storage = new SqlState();\n+\ttry {\n+\t\tconst list = storedLists<number>(storage, \"items\");\n+\t\tfor (let i = 0; i < 513; i++) list.append(\"key\", i);\n+\t\tconst read = storage.read.bind(storage);\n+\t\tstorage.read = (collection, key) => {\n+\t\t\tif (collection === \"items:pages\") assert.equal(key, JSON.stringify([\"key\", 2]));\n+\t\t\treturn read(collection, key);\n+\t\t};\n+\t\tassert.equal(list.last(\"key\"), 512);\n+\t\tstorage.write(\"items:pages\", JSON.stringify([\"key\", 2]), [512, 513]);\n+\t\tassert.throws(() => list.last(\"key\"), /incomplete writer list page/);\n+\t} finally {\n+\t\tstorage.db.close();\n+\t}\n+});"},{"path":"src/engine/test/graph-insertion-integrity.test.ts","added":18,"removed":0,"diff":"--- /dev/null\n+++ b/src/engine/test/graph-insertion-integrity.test.ts\n@@ -0,0 +1,18 @@\n+import assert from \"node:assert/strict\";\n+import { test } from \"node:test\";\n+import { buildBase, Graph } from \"../index.ts\";\n+import { SqlState } from \"./storage-helper.ts\";\n+\n+test(\"stored insertion reads reject missing lines and substituted run references\", (t) => {\n+\tconst storage = new SqlState();\n+\tt.after(() => storage.db.close());\n+\tconst lines = Array.from({ length: 257 }, (_, i) => (i === 128 ? \"x\".repeat(40000) : `line ${i}`));\n+\tconst atom = buildBase({ \"a.txt\": lines.join(\"\\n\") }, { author: \"fixture\", message: \"base\", time: 0 });\n+\tnew Graph({ storage }).add(atom);\n+\tassert.equal(new Graph({ storage }).atom(\"a0\").inserts[0]!.lines[128], lines[128]);\n+\tstorage.remove(\"atom-inserts:0:lines:0\", \"12\");\n+\tassert.throws(() => new Graph({ storage }).atom(\"a0\").inserts[0]!.lines[12], /missing stored list element/);\n+\tconst run = storage.read(\"atom-inserts:0\", \"0\") as Record<string, unknown>;\n+\tstorage.write(\"atom-inserts:0\", \"0\", { ...run, lines: \"unrelated\" });\n+\tassert.throws(() => new Graph({ storage }).atom(\"a0\").inserts[0], /invalid stored insertion run/);\n+});"},{"path":"src/engine/test/graph-insertion-runs.test.ts","added":24,"removed":0,"diff":"--- /dev/null\n+++ b/src/engine/test/graph-insertion-runs.test.ts\n@@ -0,0 +1,24 @@\n+import assert from \"node:assert/strict\";\n+import { test } from \"node:test\";\n+import { buildBase, Graph } from \"../index.ts\";\n+import { SqlState } from \"./storage-helper.ts\";\n+\n+test(\"many insertion runs reopen without fetching every run\", (t) => {\n+\tconst storage = new SqlState();\n+\tt.after(() => storage.db.close());\n+\tconst files = Object.fromEntries(Array.from({ length: 257 }, (_, i) => [`file-${i}.txt`, `value ${i}`]));\n+\tconst atom = buildBase(files, { author: \"fixture\", message: \"many files\", time: 0 });\n+\tnew Graph({ storage }).add(atom);\n+\tassert.ok(JSON.stringify(storage.read(\"atoms\", \"0\")).length < 2048);\n+\tconst read = storage.read.bind(storage);\n+\tlet runs = 0;\n+\tstorage.read = (collection, key) => {\n+\t\tif (collection === \"atom-inserts:0\") runs++;\n+\t\treturn read(collection, key);\n+\t};\n+\tconst saved = new Graph({ storage }).atom(\"a0\");\n+\tassert.equal(saved.inserts.length, atom.inserts.length);\n+\tassert.equal(runs, 0);\n+\tassert.deepEqual([...saved.inserts[256]!.lines], atom.inserts[256]!.lines);\n+\tassert.equal(runs, 1);\n+});"},{"path":"src/engine/test/graph-insertion-storage.test.ts","added":52,"removed":0,"diff":"--- /dev/null\n+++ b/src/engine/test/graph-insertion-storage.test.ts\n@@ -0,0 +1,52 @@\n+import assert from \"node:assert/strict\";\n+import { test } from \"node:test\";\n+import { buildBase, Graph } from \"../index.ts\";\n+import { SqlState } from \"./storage-helper.ts\";\n+\n+test(\"persisted insertion lines stay out of atom metadata\", (t) => {\n+\tconst storage = new SqlState();\n+\tt.after(() => storage.db.close());\n+\tconst text = Array.from({ length: 513 }, (_, i) => `line ${i}\\n`).join(\"\");\n+\tconst graph = new Graph({ storage });\n+\tconst atom = buildBase({ \"a.txt\": text }, { author: \"fixture\", message: \"base\", time: 0 });\n+\tconst oracle = new Graph();\n+\toracle.add(atom);\n+\tgraph.add(atom);\n+\tconst bytes = Buffer.byteLength(JSON.stringify(storage.read(\"atoms\", \"0\")));\n+\tassert.ok(bytes < 2048, `atom metadata retained ${bytes} bytes for 513 insertion lines`);\n+\tassert.deepEqual([...new Graph({ storage }).atom(\"a0\").inserts[0]!.lines], oracle.atom(\"a0\").inserts[0]!.lines);\n+\tconst read = storage.read.bind(storage);\n+\tlet lineReads = 0;\n+\tstorage.read = (collection, key) => {\n+\t\tif (collection === \"atom-inserts:0:lines:0\") lineReads++;\n+\t\treturn read(collection, key);\n+\t};\n+\tconst saved = new Graph({ storage }).atom(\"a0\");\n+\tassert.equal(lineReads, 0);\n+\tassert.equal(saved.inserts[0]!.lines.length, 513);\n+\tassert.equal(lineReads, 0);\n+\tassert.equal(saved.inserts[0]!.lines[512], oracle.atom(\"a0\").inserts[0]!.lines[512]);\n+\tassert.equal(lineReads, 1);\n+});\n+\n+test(\"partial insertion persistence rolls back and retries on the same graph\", (t) => {\n+\tconst storage = new SqlState();\n+\tt.after(() => storage.db.close());\n+\tconst graph = new Graph({ storage });\n+\tconst atom = buildBase(\n+\t\t{ \"a.txt\": Array.from({ length: 513 }, (_, i) => `line ${i}\\n`).join(\"\") },\n+\t\t{ author: \"fixture\", message: \"base\", time: 0 },\n+\t);\n+\tconst before = storage.db.prepare(\"SELECT * FROM state ORDER BY collection,key\").all();\n+\tconst write = storage.write.bind(storage);\n+\tstorage.write = (collection, key, value) => {\n+\t\twrite(collection, key, value);\n+\t\tif (collection === \"atom-inserts:0:lines:0\" && key === \"128\") throw Error(\"injected insertion failure\");\n+\t};\n+\tassert.throws(() => graph.add(atom), /injected insertion failure/);\n+\tassert.deepEqual(storage.db.prepare(\"SELECT * FROM state ORDER BY collection,key\").all(), before);\n+\tassert.equal(graph.size, 0);\n+\tstorage.write = write;\n+\tgraph.add(atom);\n+\tassert.deepEqual([...new Graph({ storage }).atom(\"a0\").inserts[0]!.lines], atom.inserts[0]!.lines);\n+});"},{"path":"src/engine/test/graph-long-text.test.ts","added":123,"removed":0,"diff":"--- /dev/null\n+++ b/src/engine/test/graph-long-text.test.ts\n@@ -0,0 +1,123 @@\n+import assert from \"node:assert/strict\";\n+import { test } from \"node:test\";\n+import { MemoryStore, Project } from \"../../../worker/project/project.ts\";\n+import { Graph } from \"../graph.ts\";\n+import { SqlState } from \"./storage-helper.ts\";\n+\n+test(\"persistent graph stores long lines in chunks and reopens exact text\", () => {\n+\tconst storage = new SqlState();\n+\ttry {\n+\t\tconst memory = new MemoryStore();\n+\t\tconst value = `${\"x\".repeat(100000)}\\uD83D\\uDE00`;\n+\t\tnew Project(memory).init({ \"a.txt\": value }, 0);\n+\t\tconst entry = memory.entries[0]!;\n+\t\tassert.equal(entry.type, \"init\");\n+\t\tif (entry.type !== \"init\") throw Error(\"expected init\");\n+\t\tnew Graph({ storage }).add(entry.atom);\n+\t\tassert.deepEqual(storage.read(\"line-text\", \"0\"), { format: 1, text: JSON.stringify([\"0\", 0]) });\n+\t\tassert.equal(new Graph({ storage }).lineText(\"a0.0\"), value);\n+\t\tassert.ok(\n+\t\t\t(storage.db.prepare(\"SELECT COUNT(*) AS n FROM state WHERE collection = 'atom-text:long:chunks'\").get()!\n+\t\t\t\t.n as number) > 1,\n+\t\t);\n+\t} finally {\n+\t\tstorage.db.close();\n+\t}\n+});\n+\n+import { SqliteWriterState } from \"../../../server/src/writer-host.ts\";\n+import { memoryStorage } from \"../../../server/test/helpers.ts\";\n+\n+test(\"persistent atom metadata accepts text beyond the generic state limit\", (t) => {\n+\tconst database = memoryStorage();\n+\tt.after(() => database.db.close());\n+\tSqliteWriterState.initialize(database);\n+\tconst storage = new SqliteWriterState(database, \"long-atom\");\n+\tconst memory = new MemoryStore();\n+\tconst value = \"x\".repeat(8100000);\n+\tnew Project(memory).init({ \"large.txt\": value }, 0);\n+\tconst entry = memory.entries[0]!;\n+\tif (entry.type !== \"init\") throw Error(\"expected init\");\n+\tnew Graph({ storage }).add(entry.atom);\n+\tassert.ok(JSON.stringify(storage.read(\"atoms\", \"0\")).length < 4096);\n+\tconst read = storage.read.bind(storage);\n+\tlet textReads = 0;\n+\tt.mock.method(storage, \"read\", (collection: string, key: string) => {\n+\t\tif (collection === \"atom-text:long:chunks\") textReads++;\n+\t\treturn read(collection, key);\n+\t});\n+\tconst graph = new Graph({ storage });\n+\tconst atom = graph.atom(\"a0\");\n+\tassert.equal(textReads, 0, \"reading atom metadata must not load long text\");\n+\tassert.equal(atom.inserts[0]!.lines[0], value);\n+\tassert.ok(textReads > 0);\n+\tassert.equal(graph.lineText(\"a0.0\"), value);\n+\tassert.equal(\n+\t\tdatabase.db\n+\t\t\t.prepare(\n+\t\t\t\t\"SELECT COUNT(*) AS n FROM writer_state WHERE namespace = 'long-atom' AND collection = 'atom-text:long:chunks' AND part = -1\",\n+\t\t\t)\n+\t\t\t.get()!.n,\n+\t\tMath.ceil(value.length / 16384),\n+\t);\n+\tassert.equal(\n+\t\tdatabase.db\n+\t\t\t.prepare(\n+\t\t\t\t\"SELECT COUNT(*) AS n FROM writer_state WHERE namespace = 'long-atom' AND collection = 'line-text:long:chunks'\",\n+\t\t\t)\n+\t\t\t.get()!.n,\n+\t\t0,\n+\t);\n+});\n+\n+test(\"long atom acceptance rolls back partial chunks and detects missing text\", (t) => {\n+\tconst storage = new SqlState();\n+\tt.after(() => storage.db.close());\n+\tconst memory = new MemoryStore();\n+\tconst value = \"z\".repeat(100000);\n+\tnew Project(memory).init({ \"a.txt\": value }, 0);\n+\tconst entry = memory.entries[0]!;\n+\tif (entry.type !== \"init\") throw Error(\"expected init\");\n+\tconst graph = new Graph({ storage });\n+\tconst rows = () => storage.db.prepare(\"SELECT * FROM state ORDER BY collection,key\").all();\n+\tconst before = rows();\n+\tconst write = storage.write.bind(storage);\n+\tlet chunks = 0;\n+\tconst failure = t.mock.method(storage, \"write\", (collection: string, key: string, value: unknown) => {\n+\t\twrite(collection, key, value);\n+\t\tif (collection === \"atom-text:long:chunks\" && ++chunks === 2) throw Error(\"injected partial atom text\");\n+\t});\n+\tassert.throws(() => graph.add(entry.atom), /partial atom text/);\n+\tassert.deepEqual(rows(), before);\n+\tassert.equal(graph.size, 0);\n+\tfailure.mock.restore();\n+\tgraph.add(entry.atom);\n+\tassert.equal(graph.lineText(\"a0.0\"), value);\n+\tconst textKey = JSON.stringify([\"0\", 0]);\n+\tstorage.remove(\"atom-text:long:chunks\", JSON.stringify([textKey, 1]));\n+\tconst reopened = new Graph({ storage });\n+\tassert.throws(() => reopened.lineText(\"a0.0\"), /incomplete stored text/);\n+\tassert.throws(() => reopened.atom(\"a0\").inserts[0]!.lines[0], /incomplete stored text/);\n+});\n+\n+test(\"persistent graph detaches accepted lists without freezing a second input copy\", () => {\n+\tconst storage = new SqlState();\n+\ttry {\n+\t\tconst memory = new MemoryStore();\n+\t\tnew Project(memory).init({ \"a.txt\": \"before\\nsecond\" }, 0);\n+\t\tconst entry = memory.entries[0]!;\n+\t\tif (entry.type !== \"init\") throw Error(\"expected init\");\n+\t\tconst atom = structuredClone(entry.atom);\n+\t\tconst expected = structuredClone(atom);\n+\t\tconst graph = new Graph({ storage });\n+\t\tgraph.add(atom);\n+\t\t(atom.inserts[0]!.lines as string[])[0] = \"changed\";\n+\t\t(atom.writes as string[]).length = 0;\n+\t\tfor (const loaded of [graph, new Graph({ storage })]) {\n+\t\t\tassert.deepEqual(JSON.parse(JSON.stringify(loaded.atom(\"a0\"))), expected);\n+\t\t\tassert.equal(loaded.lineText(\"a0.0\"), expected.inserts[0]!.lines[0]);\n+\t\t}\n+\t} finally {\n+\t\tstorage.db.close();\n+\t}\n+});"},{"path":"src/engine/test/graph-move-write-membership.test.ts","added":41,"removed":0,"diff":"--- /dev/null\n+++ b/src/engine/test/graph-move-write-membership.test.ts\n@@ -0,0 +1,41 @@\n+import assert from \"node:assert/strict\";\n+import { test } from \"node:test\";\n+import { buildBase, Graph } from \"../index.ts\";\n+import { gapKey, posKey } from \"../keys.ts\";\n+import type { Atom } from \"../types.ts\";\n+import { SqlState } from \"./storage-helper.ts\";\n+\n+test(\"move validation uses indexed write membership without rescanning the write list\", () => {\n+\tconst storage = new SqlState();\n+\ttry {\n+\t\tconst graph = new Graph({ storage });\n+\t\tgraph.add(buildBase({ \"a.txt\": \"one\\ntwo\" }, { author: \"fixture\", message: \"base\", time: 0 }));\n+\t\tconst writes = [posKey(\"a0.1\"), gapKey(\"a0.0\")];\n+\t\twrites.includes = () => {\n+\t\t\tthrow Error(\"whole write list scan forbidden\");\n+\t\t};\n+\t\tconst atom: Atom = {\n+\t\t\tid: \"a1\",\n+\t\t\tseq: 1,\n+\t\t\tauthor: \"fixture\",\n+\t\t\tmessage: \"move\",\n+\t\t\ttime: 1,\n+\t\t\tinserts: [],\n+\t\t\tdeletes: [],\n+\t\t\twrites,\n+\t\t\treads: [],\n+\t\t\tholds: [],\n+\t\t\tneeds: [],\n+\t\t\tresolves: [],\n+\t\t\treasons: [],\n+\t\t\tdeps: [\"a0\"],\n+\t\t\tmoves: [{ line: \"a0.1\", parent: \"a0.0\" }],\n+\t\t};\n+\t\tgraph.add(atom);\n+\t\tassert.equal(new Graph({ storage }).size, 2);\n+\t\tassert.throws(() => graph.add({ ...atom, id: \"a2\", seq: 2, writes: [posKey(\"a0.1\")] }), /without writing/);\n+\t\tassert.equal(graph.size, 2);\n+\t} finally {\n+\t\tstorage.db.close();\n+\t}\n+});"},{"path":"src/engine/test/graph-replacement-membership.test.ts","added":42,"removed":0,"diff":"--- /dev/null\n+++ b/src/engine/test/graph-replacement-membership.test.ts\n@@ -0,0 +1,42 @@\n+import assert from \"node:assert/strict\";\n+import { test } from \"node:test\";\n+import { buildBase, Graph } from \"../index.ts\";\n+import { lineKey } from \"../keys.ts\";\n+import type { Atom } from \"../types.ts\";\n+import { SqlState } from \"./storage-helper.ts\";\n+\n+test(\"replacement membership distinguishes first, repeated and previous deletions\", () => {\n+\tconst storage = new SqlState();\n+\ttry {\n+\t\tconst graph = new Graph({ storage });\n+\t\tconst oracle = new Graph();\n+\t\tconst base = buildBase({ \"a.txt\": \"base\" }, { author: \"fixture\", message: \"base\", time: 0 });\n+\t\tgraph.add(base);\n+\t\toracle.add(base);\n+\t\tfor (let seq = 1; seq <= 3; seq++) {\n+\t\t\tconst deleting = seq < 3;\n+\t\t\tconst atom: Atom = {\n+\t\t\t\tid: `a${seq}`,\n+\t\t\t\tseq,\n+\t\t\t\tauthor: \"fixture\",\n+\t\t\t\tmessage: \"replacement\",\n+\t\t\t\ttime: seq,\n+\t\t\t\tinserts: [{ file: \"a.txt\", parent: \"a0.0\", lines: [`new ${seq}`] }],\n+\t\t\t\tdeletes: deleting ? [\"a0.0\"] : [],\n+\t\t\t\twrites: deleting ? [lineKey(\"a0.0\")] : [],\n+\t\t\t\treads: [],\n+\t\t\t\tholds: [],\n+\t\t\t\tneeds: [],\n+\t\t\t\tresolves: [],\n+\t\t\t\treasons: [],\n+\t\t\t\tdeps: [`a${seq - 1}`],\n+\t\t\t};\n+\t\t\tgraph.add(atom);\n+\t\t\toracle.add(atom);\n+\t\t\tassert.equal(graph.replaces(`a${seq}.0`), deleting);\n+\t\t\tassert.equal(new Graph({ storage }).replaces(`a${seq}.0`), oracle.replaces(`a${seq}.0`));\n+\t\t}\n+\t} finally {\n+\t\tstorage.db.close();\n+\t}\n+});"},{"path":"src/engine/test/graph-validation-scratch.test.ts","added":47,"removed":0,"diff":"--- /dev/null\n+++ b/src/engine/test/graph-validation-scratch.test.ts\n@@ -0,0 +1,47 @@\n+import assert from \"node:assert/strict\";\n+import { test } from \"node:test\";\n+import { buildBase, Graph } from \"../index.ts\";\n+import type { Atom } from \"../types.ts\";\n+import { SqlState } from \"./storage-helper.ts\";\n+\n+test(\"persistent atom validation uses rollback scratch for memberships\", () => {\n+\tconst storage = new SqlState();\n+\ttry {\n+\t\tconst graph = new Graph({ storage });\n+\t\tgraph.add(buildBase({ \"a.txt\": \"base\" }, { author: \"fixture\", message: \"base\", time: 0 }));\n+\t\tconst atom: Atom = {\n+\t\t\tid: \"a1\",\n+\t\t\tseq: 1,\n+\t\t\tauthor: \"fixture\",\n+\t\t\tmessage: \"next\",\n+\t\t\ttime: 1,\n+\t\t\tinserts: [],\n+\t\t\tdeletes: [],\n+\t\t\twrites: [],\n+\t\t\treads: [],\n+\t\t\tholds: [],\n+\t\t\tneeds: [],\n+\t\t\tresolves: [],\n+\t\t\treasons: [],\n+\t\t\tdeps: [\"a0\"],\n+\t\t};\n+\t\tconst before = storage.db.prepare(\"SELECT * FROM state ORDER BY collection,key\").all();\n+\t\tassert.throws(() => graph.add({ ...atom, deps: [\"a0\", \"a0\"] }), /listed twice/);\n+\t\tassert.deepEqual(storage.db.prepare(\"SELECT * FROM state ORDER BY collection,key\").all(), before);\n+\t\tlet scratchWrites = 0;\n+\t\tconst write = storage.write.bind(storage);\n+\t\tstorage.write = (collection, key, value) => {\n+\t\t\tif (collection.startsWith(\"projection-scratch:\") && collection.endsWith(\":deps\")) scratchWrites++;\n+\t\t\twrite(collection, key, value);\n+\t\t};\n+\t\tgraph.add(atom);\n+\t\tassert.ok(scratchWrites > 0);\n+\t\tassert.equal(\n+\t\t\tstorage.db.prepare(\"SELECT COUNT(*) AS n FROM state WHERE collection LIKE 'projection-scratch:%'\").get()!.n,\n+\t\t\t0,\n+\t\t);\n+\t\tassert.equal(new Graph({ storage }).size, 2);\n+\t} finally {\n+\t\tstorage.db.close();\n+\t}\n+});"},{"path":"src/engine/test/projection-locator.test.ts","added":27,"removed":0,"diff":"--- a/src/engine/test/projection-locator.test.ts\n+++ b/src/engine/test/projection-locator.test.ts\n@@ -103,3 +103,30 @@\n \t\tdb.db.close();\n \t}\n });\n+\n+test(\"multi-key locator updates match sequential sparse edits and retain previous roots\", () => {\n+\tconst db = new SqlState();\n+\ttry {\n+\t\tconst batched = new ProjectionLocator(db, \"multi\", decode);\n+\t\tconst sequential = new ProjectionLocator(db, \"oracle\", decode);\n+\t\tlet left: number | null = null,\n+\t\t\tright: number | null = null;\n+\t\tlet seed = 12345;\n+\t\tconst random = () => (seed = (Math.imul(seed, 1664525) + 1013904223) >>> 0);\n+\t\tconst keys = [0, 0xffffffff, 1, 16, 255, 256, ...Array.from({ length: 60 }, random)];\n+\t\tfor (let round = 0; round < 8; round++) {\n+\t\t\tconst edits: [number, number][] = Array.from({ length: 64 }, (_, i) => [\n+\t\t\t\tkeys[random() % keys.length]!,\n+\t\t\t\tround * 100 + i,\n+\t\t\t]);\n+\t\t\tconst prior: number | null = left;\n+\t\t\tconst oldEntries: (readonly [number, number])[] = [...batched.entries(prior)];\n+\t\t\tleft = batched.setMany(left, edits);\n+\t\t\tfor (const [key, value] of edits) right = sequential.set(right, key, value);\n+\t\t\tassert.deepEqual([...batched.entries(left)], [...sequential.entries(right)]);\n+\t\t\tassert.deepEqual([...batched.entries(prior)], oldEntries);\n+\t\t}\n+\t} finally {\n+\t\tdb.db.close();\n+\t}\n+});"},{"path":"src/engine/test/projection-marker.test.ts","added":47,"removed":0,"diff":"--- a/src/engine/test/projection-marker.test.ts\n+++ b/src/engine/test/projection-marker.test.ts\n@@ -118,3 +118,50 @@\n \t\tstorage.db.close();\n \t}\n });\n+\n+test(\"visibility batches roll back earlier batches and retry with exact line parity\", (t) => {\n+\tconst db = new SqlState();\n+\tt.after(() => db.db.close());\n+\tconst text = Array.from({ length: 35 }, (_, n) => `line ${n}\\n`).join(\"\");\n+\tconst repo = Repo.init({ \"f.txt\": text });\n+\tconst graph = new Graph({ storage: new CachedStateStorage(db) });\n+\tgraph.add(repo.graph.atom(\"a0\"));\n+\tconst p = new MarkerProjection(db, graph, \"f.txt\", \"batch-failure\");\n+\tconst initial = p.apply(p.empty(), repo.graph.atom(\"a0\"));\n+\tconst originalLines = p.lines(initial, \"f.txt\");\n+\tconst atom = repo.edit({ edits: [{ file: \"f.txt\", old: text, new: \"\" }] });\n+\tgraph.add(atom);\n+\tconst rows = () => db.db.prepare(\"SELECT * FROM state ORDER BY collection,key\").all();\n+\tconst before = rows();\n+\tconst original = p.sequence.updateMany.bind(p.sequence);\n+\tconst sizes: number[] = [];\n+\tlet fail = true;\n+\tt.mock.method(\n+\t\tp.sequence,\n+\t\t\"updateMany\",\n+\t\t(state: Parameters<typeof original>[0], operations: Parameters<typeof original>[1]) => {\n+\t\t\tconst next = original(state, operations);\n+\t\t\tif (operations.every((op) => op.kind === \"visibility\")) {\n+\t\t\t\tsizes.push(operations.length);\n+\t\t\t\tif (fail && sizes.length === 2) throw Error(\"second visibility batch failure\");\n+\t\t\t}\n+\t\t\treturn next;\n+\t\t},\n+\t);\n+\tassert.throws(() => p.apply(initial, atom), /second visibility batch/);\n+\tassert.deepEqual(sizes, [16, 16]);\n+\tassert.deepEqual(rows(), before);\n+\tassert.deepEqual(p.lines(initial, \"f.txt\"), originalLines);\n+\tfail = false;\n+\tsizes.length = 0;\n+\tconst next = p.apply(initial, atom);\n+\tassert.deepEqual(sizes, [16, 16, 3]);\n+\tassert.deepEqual(\n+\t\tp.lines(next, \"f.txt\"),\n+\t\trepo\n+\t\t\t.view()\n+\t\t\t.lines(\"f.txt\")\n+\t\t\t.map((line) => line.id),\n+\t);\n+\tassert.deepEqual(p.lines(initial, \"f.txt\"), originalLines);\n+});"},{"path":"src/engine/test/projection-priority.test.ts","added":124,"removed":0,"diff":"--- a/src/engine/test/projection-priority.test.ts\n+++ b/src/engine/test/projection-priority.test.ts\n@@ -51,3 +51,127 @@\n \t\tstorage.db.close();\n \t}\n });\n+\n+test(\"priority allocation rolls back a failed final counter and retries without collisions\", (t) => {\n+\tconst storage = new SqlState();\n+\tt.after(() => storage.db.close());\n+\tconst index = new ProjectionPriority(storage, \"counter-retry\", decode);\n+\tconst key = \"1\".repeat(57);\n+\tconst root = index.insert(null, key, 1);\n+\tconst rows = () => storage.db.prepare(\"SELECT * FROM state ORDER BY collection,key\").all();\n+\tconst before = rows();\n+\tconst original = storage.write.bind(storage);\n+\tlet fail = true;\n+\tt.mock.method(storage, \"write\", (collection: string, key: string, value: unknown) => {\n+\t\toriginal(collection, key, value);\n+\t\tif (key === \"next\" && fail) throw Error(\"final allocation counter failure\");\n+\t});\n+\tassert.throws(() => index.insert(root, \"2\".repeat(57), 2), /final allocation counter/);\n+\tassert.deepEqual(rows(), before);\n+\tassert.equal(index.before(root, \"f\".repeat(57)), 1);\n+\tfail = false;\n+\tconst next = index.insert(root, \"2\".repeat(57), 2);\n+\tassert.equal(index.before(next, \"f\".repeat(57)), 2);\n+\tassert.equal(index.before(root, \"f\".repeat(57)), 1);\n+\tconst beforeRemove = rows();\n+\tfail = true;\n+\tassert.throws(() => index.remove(next, \"2\".repeat(57)), /final allocation counter/);\n+\tassert.deepEqual(rows(), beforeRemove);\n+\tfail = false;\n+\tconst removed = index.remove(next, \"2\".repeat(57));\n+\tassert.equal(index.before(removed, \"f\".repeat(57)), 1);\n+});\n+\n+test(\"compressed priority updates legacy depth paths without changing old roots\", (t) => {\n+\tconst storage = new SqlState();\n+\tt.after(() => storage.db.close());\n+\tconst collection = 'experimental-priority:\"legacy\"';\n+\tconst key = \"1\".repeat(57);\n+\tstorage.write(collection, \"57\", { format: 1, kind: \"leaf\", depth: 57, value: 1 });\n+\tfor (let depth = 56; depth >= 0; depth--)\n+\t\tstorage.write(collection, String(depth), {\n+\t\t\tformat: 1,\n+\t\t\tkind: \"branch\",\n+\t\t\tdepth,\n+\t\t\tchildren: { [key[depth]!]: depth + 1 },\n+\t\t});\n+\tstorage.write(collection, \"next\", 58);\n+\tconst index = new ProjectionPriority(storage, \"legacy\", decode);\n+\tassert.equal(index.before(0, \"f\".repeat(57)), 1);\n+\tconst mixed = index.insert(0, \"1\".repeat(56) + \"2\", 2);\n+\tassert.equal(index.before(mixed, \"f\".repeat(57)), 2);\n+\tassert.equal(index.before(mixed, \"1\".repeat(56) + \"2\"), 1);\n+\tassert.equal(index.before(0, \"f\".repeat(57)), 1);\n+\tconst removed = index.remove(mixed, key);\n+\tassert.equal(index.before(removed, \"f\".repeat(57)), 2);\n+\tassert.equal(index.remove(removed, \"1\".repeat(56) + \"2\"), null);\n+\tassert.equal(index.before(0, \"f\".repeat(57)), 1);\n+});\n+\n+test(\"compressed priority matches a sorted oracle across varied prefixes and removals\", (t) => {\n+\tconst storage = new SqlState();\n+\tt.after(() => storage.db.close());\n+\tconst index = new ProjectionPriority(storage, \"varied\", decode);\n+\tconst oracle = new Map<string, number>();\n+\tlet root: number | null = null;\n+\tlet seed = 731;\n+\tconst randomKey = () =>\n+\t\tArray.from({ length: 57 }, () => {\n+\t\t\tseed = (Math.imul(seed, 1664525) + 1013904223) >>> 0;\n+\t\t\treturn (seed >>> 28).toString(16);\n+\t\t}).join(\"\");\n+\tconst keys = [\n+\t\t\"0\".repeat(57),\n+\t\t\"f\".repeat(57),\n+\t\t...Array.from({ length: 128 }, randomKey),\n+\t\t...Array.from({ length: 32 }, (_, n) => \"a\".repeat(55) + n.toString(16).padStart(2, \"0\")),\n+\t];\n+\tconst verify = () => {\n+\t\tconst sorted = [...oracle.keys()].sort();\n+\t\tfor (const key of [...keys, randomKey()]) {\n+\t\t\tconst before = sorted.filter((candidate) => candidate < key).at(-1);\n+\t\t\tassert.equal(index.before(root, key), before === undefined ? undefined : oracle.get(before));\n+\t\t}\n+\t};\n+\tfor (const [n, key] of keys.entries()) {\n+\t\troot = index.insert(root, key, n);\n+\t\toracle.set(key, n);\n+\t\tif (n % 23 === 0) verify();\n+\t}\n+\tverify();\n+\tfor (const [n, key] of keys.entries()) {\n+\t\troot = index.remove(root, key);\n+\t\toracle.delete(key);\n+\t\tif (n % 19 === 0) verify();\n+\t}\n+\tassert.equal(root, null);\n+\tverify();\n+});\n+\n+test(\"compressed priority rejects malformed prefixes and cyclic child edges\", (t) => {\n+\tconst storage = new SqlState();\n+\tt.after(() => storage.db.close());\n+\tconst collection = 'experimental-priority:\"corrupt\"';\n+\tconst index = new ProjectionPriority(storage, \"corrupt\", decode);\n+\tconst first = index.insert(null, \"1\".repeat(57), 1);\n+\tconst root = index.insert(first, \"2\".repeat(57), 2);\n+\tconst saved = storage.read(collection, String(root));\n+\tfor (const node of [\n+\t\t{ format: 2, kind: \"branch\", prefix: \"\", children: { \"1\": root, \"2\": first } },\n+\t\t{ format: 2, kind: \"branch\", prefix: \"x\", children: { \"1\": first, \"2\": first } },\n+\t\t{ format: 2, kind: \"branch\", prefix: \"\", children: { \"1\": first } },\n+\t\t{ format: 2, kind: \"leaf\", prefix: \"1\", value: 1 },\n+\t\t{ format: 3, kind: \"leaf\", prefix: \"1\".repeat(57), value: 1 },\n+\t]) {\n+\t\tstorage.write(collection, String(root), node);\n+\t\tassert.throws(() => index.before(root, \"f\".repeat(57)), /invalid priority/);\n+\t}\n+\tstorage.write(collection, String(root), saved);\n+\tconst branch = saved as { children: Record<string, number> };\n+\tconst child = branch.children[\"2\"]!;\n+\tconst leaf = storage.read(collection, String(child));\n+\tstorage.write(collection, String(child), { format: 2, kind: \"leaf\", prefix: \"3\".repeat(57), value: 2 });\n+\tassert.throws(() => index.before(root, \"f\".repeat(57)), /invalid priority/);\n+\tstorage.write(collection, String(child), leaf);\n+\tassert.equal(index.before(root, \"f\".repeat(57)), 2);\n+});"},{"path":"src/engine/test/stored-list-array.test.ts","added":24,"removed":0,"diff":"--- /dev/null\n+++ b/src/engine/test/stored-list-array.test.ts\n@@ -0,0 +1,24 @@\n+import assert from \"node:assert/strict\";\n+import { test } from \"node:test\";\n+import { readonlyStoredArray, storedArray } from \"../state-source.ts\";\n+import { SqlState } from \"./storage-helper.ts\";\n+\n+test(\"readonly stored lists preserve array traversal and explicit enumeration\", () => {\n+\tconst storage = new SqlState();\n+\ttry {\n+\t\tstoredArray<number>(storage, \"numbers\").push(10, 20, 30);\n+\t\tconst values = readonlyStoredArray<number>(storage, \"numbers\");\n+\t\tassert.equal(Array.isArray(values), true);\n+\t\tassert.deepEqual(\n+\t\t\tvalues.map((value) => value + 1),\n+\t\t\t[11, 21, 31],\n+\t\t);\n+\t\tassert.deepEqual([...values], [10, 20, 30]);\n+\t\tassert.equal(JSON.stringify(values), \"[10,20,30]\");\n+\t\tassert.deepEqual(Object.keys(values), [\"0\", \"1\", \"2\"]);\n+\t\tassert.equal(Object.getOwnPropertyDescriptor(values, \"1\")?.value, 20);\n+\t\tassert.throws(() => Object.defineProperty(values, \"0\", { value: 99 }), /read-only/);\n+\t} finally {\n+\t\tstorage.db.close();\n+\t}\n+});"},{"path":"src/engine/test/stored-list-integrity.test.ts","added":21,"removed":0,"diff":"--- /dev/null\n+++ b/src/engine/test/stored-list-integrity.test.ts\n@@ -0,0 +1,21 @@\n+import assert from \"node:assert/strict\";\n+import { test } from \"node:test\";\n+import { readonlyStoredArray, storedArray } from \"../state-source.ts\";\n+import { SqlState } from \"./storage-helper.ts\";\n+\n+test(\"referenced stored lists reject missing metadata and missing elements\", () => {\n+\tconst storage = new SqlState();\n+\ttry {\n+\t\tassert.throws(() => readonlyStoredArray(storage, \"missing\"), /stored list/);\n+\t\tconst values = storedArray<number>(storage, \"values\");\n+\t\tvalues.push(1, 2, 3);\n+\t\tconst readonly = readonlyStoredArray<number>(storage, \"values\");\n+\t\tassert.equal(readonly.length, 3);\n+\t\tstorage.remove(\"values\", \"1\");\n+\t\tassert.throws(() => readonly[1], /stored list/);\n+\t\tstorage.remove(\"values:meta\", \"length\");\n+\t\tassert.throws(() => readonly.length, /stored list/);\n+\t} finally {\n+\t\tstorage.db.close();\n+\t}\n+});"},{"path":"src/engine/test/stored-text.test.ts","added":68,"removed":0,"diff":"--- /dev/null\n+++ b/src/engine/test/stored-text.test.ts\n@@ -0,0 +1,68 @@\n+import assert from \"node:assert/strict\";\n+import { test } from \"node:test\";\n+import { StoredText } from \"../stored-text.ts\";\n+import { SqlState } from \"./storage-helper.ts\";\n+\n+test(\"stored text preserves long lines and split surrogate pairs with bounded values\", () => {\n+\tconst state = new SqlState();\n+\ttry {\n+\t\tconst text = new StoredText(state, \"text\");\n+\t\tconst value = \"x\".repeat(StoredText.chunkCharacters - 1) + \"\\uD83D\\uDE00\" + \"y\".repeat(8100000);\n+\t\ttext.write(\"line\", value);\n+\t\tlet count = 0;\n+\t\tfor (const chunk of text.chunks(\"line\")) {\n+\t\t\tassert.ok(chunk.length <= StoredText.chunkCharacters);\n+\t\t\tcount += chunk.length;\n+\t\t}\n+\t\tassert.equal(count, value.length);\n+\t\tassert.equal(text.read(\"line\"), value);\n+\t\tassert.throws(() => text.write(\"line\", \"overwrite\"), /already exists/);\n+\t\ttext.write(\"empty\", \"\");\n+\t\tassert.equal(text.read(\"empty\"), \"\");\n+\t\tconst before = state.db.prepare(\"SELECT * FROM state ORDER BY collection,key\").all();\n+\t\tstate.failWrite = state.writes + 2;\n+\t\tassert.throws(() => text.write(\"failure\", value), /injected/);\n+\t\tassert.deepEqual(state.db.prepare(\"SELECT * FROM state ORDER BY collection,key\").all(), before);\n+\t\tstate.failWrite = Infinity;\n+\t\tstate.remove(\"text:chunks\", JSON.stringify([\"line\", 1]));\n+\t\tassert.throws(() => text.read(\"line\"), /incomplete/);\n+\t} finally {\n+\t\tstate.db.close();\n+\t}\n+});\n+\n+test(\"streamed text repacks small chunks and rolls back interrupted input\", () => {\n+\tconst state = new SqlState();\n+\ttry {\n+\t\tconst text = new StoredText(state, \"stream\");\n+\t\tconst value = `${\"a\".repeat(20000)}\\uD83D\\uDE00${\"b\".repeat(20000)}`;\n+\t\ttext.writeChunks(\n+\t\t\t\"unicode\",\n+\t\t\t(function* () {\n+\t\t\t\tfor (const unit of value.split(\"\")) yield unit;\n+\t\t\t})(),\n+\t\t);\n+\t\tassert.equal(text.read(\"unicode\"), value);\n+\t\tconst rows = () => state.db.prepare(\"SELECT * FROM state ORDER BY collection,key\").all();\n+\t\tconst before = rows();\n+\t\tassert.throws(\n+\t\t\t() =>\n+\t\t\t\ttext.writeChunks(\n+\t\t\t\t\t\"interrupted\",\n+\t\t\t\t\t(function* () {\n+\t\t\t\t\t\tyield \"x\".repeat(StoredText.chunkCharacters);\n+\t\t\t\t\t\tyield \"tail\";\n+\t\t\t\t\t\tthrow Error(\"input interrupted\");\n+\t\t\t\t\t})(),\n+\t\t\t\t),\n+\t\t\t/input interrupted/,\n+\t\t);\n+\t\tassert.deepEqual(rows(), before);\n+\t\tassert.throws(() => text.writeChunks(\"oversized\", [\"x\".repeat(StoredText.chunkCharacters + 1)]), /exceeds bound/);\n+\t\tassert.deepEqual(rows(), before);\n+\t\ttext.writeChunks(\"interrupted\", [\"retry\"]);\n+\t\tassert.equal(text.read(\"interrupted\"), \"retry\");\n+\t} finally {\n+\t\tstate.db.close();\n+\t}\n+});"},{"path":"worker/project/collisions.ts","added":35,"removed":17,"diff":"--- a/worker/project/collisions.ts\n+++ b/worker/project/collisions.ts\n@@ -68,26 +68,44 @@\n  * atom key, retaining no candidate set proportional to historical claims. */\n function* orderedClaimants(g: Graph, streams: IterableIterator<AtomId>[]): IterableIterator<AtomId> {\n \ttry {\n-\t\tconst heads = streams.map((stream) => stream.next());\n+\t\ttype Head = { id: AtomId; seq: number; stream: number };\n+\t\tconst heap: Head[] = [];\n+\t\tconst less = (a: Head, b: Head) => a.seq < b.seq || (a.seq === b.seq && a.stream < b.stream);\n+\t\tconst push = (head: Head) => {\n+\t\t\tlet at = heap.length;\n+\t\t\theap.push(head);\n+\t\t\twhile (at > 0) {\n+\t\t\t\tconst parent = (at - 1) >>> 1;\n+\t\t\t\tif (!less(head, heap[parent]!)) break;\n+\t\t\t\theap[at] = heap[parent]!;\n+\t\t\t\tat = parent;\n+\t\t\t}\n+\t\t\theap[at] = head;\n+\t\t};\n+\t\tconst advance = (stream: number) => {\n+\t\t\tconst next = streams[stream]!.next();\n+\t\t\tif (!next.done) push({ id: next.value, seq: g.atom(next.value).seq, stream });\n+\t\t};\n+\t\tfor (let stream = 0; stream < streams.length; stream++) advance(stream);\n \t\tlet previous = -1;\n-\t\tfor (;;) {\n-\t\t\tlet best = -1;\n-\t\t\tlet seq = Infinity;\n-\t\t\tfor (let i = 0; i < heads.length; i++) {\n-\t\t\t\tconst head = heads[i]!;\n-\t\t\t\tif (head.done) continue;\n-\t\t\t\tconst current = g.atom(head.value).seq;\n-\t\t\t\tif (current < seq) {\n-\t\t\t\t\tbest = i;\n-\t\t\t\t\tseq = current;\n+\t\twhile (heap.length) {\n+\t\t\tconst head = heap[0]!;\n+\t\t\tconst tail = heap.pop()!;\n+\t\t\tif (heap.length) {\n+\t\t\t\tlet at = 0;\n+\t\t\t\twhile (at * 2 + 1 < heap.length) {\n+\t\t\t\t\tlet child = at * 2 + 1;\n+\t\t\t\t\tif (child + 1 < heap.length && less(heap[child + 1]!, heap[child]!)) child++;\n+\t\t\t\t\tif (!less(heap[child]!, tail)) break;\n+\t\t\t\t\theap[at] = heap[child]!;\n+\t\t\t\t\tat = child;\n \t\t\t\t}\n+\t\t\t\theap[at] = tail;\n \t\t\t}\n-\t\t\tif (best < 0) return;\n-\t\t\tconst id = heads[best]!.value!;\n-\t\t\theads[best] = streams[best]!.next();\n-\t\t\tif (seq === previous) continue;\n-\t\t\tprevious = seq;\n-\t\t\tyield id;\n+\t\t\tadvance(head.stream);\n+\t\t\tif (head.seq === previous) continue;\n+\t\t\tprevious = head.seq;\n+\t\t\tyield head.id;\n \t\t}\n \t} finally {\n \t\tfor (const stream of streams) stream.return?.();"},{"path":"worker/project/land.ts","added":28,"removed":9,"diff":"--- a/worker/project/land.ts\n+++ b/worker/project/land.ts\n@@ -2,11 +2,12 @@\n // the host is Project. Ingest and pluck call landDraft, the inner step.\n \n import { type AtomId, buildAtom, type Graph, type ReadView } from \"../../src/engine/index.ts\";\n+import { differenceSet, StableOverlaySet, unionOverlay } from \"../../src/engine/state-source.ts\";\n import type { Pair } from \"./collisions.ts\";\n import type { DefinitionRule } from \"./definition-rule.ts\";\n import { ProjectError } from \"./project-error.ts\";\n import type { AgentState, Collision, Entry, LandAnswer } from \"./project-types.ts\";\n-import { SHARED, type Space, sharedBaseOf } from \"./spaces.ts\";\n+import { SHARED, SharedAdditions, type Space, sharedBaseOf } from \"./spaces.ts\";\n \n /** What landing a named draft needs from a project. */\n export interface LandHost {\n@@ -23,6 +24,7 @@\n \tsetOf(space: Space): ReadonlySet<AtomId>;\n \tat(space: Space, version: number): ReadonlySet<AtomId>;\n \tview(set: ReadonlySet<AtomId>): ReadView;\n+\tviewAt(space: Space, version: number, changes?: readonly AtomId[]): ReadView;\n \tsharedView(): ReadView;\n \tpairs(draft: readonly AtomId[], against: ReadonlySet<AtomId>, settled: ReadonlySet<AtomId>): Pair[];\n \tdescribe(pair: Pair, yoursView: ReadView, theirsView: ReadView, spaceName: string): Collision;\n@@ -70,21 +72,32 @@\n \tspace: Space,\n \tchanges: AtomId[],\n \tpick: boolean,\n-): { collisions: Collision[]; newer: Set<AtomId>; union: Set<AtomId> } {\n+): { collisions: Collision[]; newer: ReadonlySet<AtomId>; union: ReadonlySet<AtomId> } {\n \tconst shared = host.shared();\n \tconst base = host.at(shared, sharedBaseOf(space));\n-\tconst own = new Set(changes);\n-\tconst union = new Set([...shared.own, ...changes]);\n+\tconst own = new StableOverlaySet(changes);\n+\tconst current = host.at(shared, host.version());\n+\tconst union = unionOverlay(current, changes);\n \t// The draft's own changes (some already plucked into shared) are never newer work to it.\n-\tconst newer = new Set([...shared.own].filter((id) => !base.has(id) && !own.has(id) && !space.own.has(id)));\n+\tconst newer = differenceSet(\n+\t\tdifferenceSet(\n+\t\t\tshared.membershipVersion\n+\t\t\t\t? new SharedAdditions(shared, sharedBaseOf(space), base, current)\n+\t\t\t\t: differenceSet(current, base),\n+\t\t\town,\n+\t\t),\n+\t\tspace.own,\n+\t);\n \t// A pluck is checked as the draft's base plus only the plucked changes.\n-\tconst draftView = host.view(pick ? new Set([...base, ...changes]) : host.setOf(space));\n+\tconst draftView = pick\n+\t\t? host.viewAt(shared, sharedBaseOf(space), changes)\n+\t\t: host.viewAt(space, space.versions.length - 1);\n \tconst describeLand = (p: Pair): Collision => host.describe(p, draftView, host.sharedView(), SHARED);\n \tconst collisions = [\n \t\t...host.pairs(changes, newer, union).map(describeLand),\n \t\t...host\n \t\t\t.definitionRule()\n-\t\t\t.collisions(own, draftView, host.view(base), host.sharedView(), newer, SHARED)\n+\t\t\t.collisions(own, draftView, host.viewAt(shared, sharedBaseOf(space)), host.sharedView(), newer, SHARED)\n \t\t\t.map((d) => d.collision),\n \t];\n \treturn { collisions, newer, union };\n@@ -107,9 +120,15 @@\n \tif (changes.length === 0) return { ok: true, version: host.version(), changes: 0 };\n \tconst { collisions, newer, union } = landCollisions(host, space, changes, !!pick);\n \tif (collisions.length > 0) return host.refuse(agent, space, \"land\", time, collisions, entries);\n-\tconst seen = host.pairs(changes, new Set([...shared.own].filter((id) => !newer.has(id))), union);\n+\tconst seen = host.pairs(changes, differenceSet(host.at(shared, host.version()), newer), union);\n \tconst resolves = [...new Set(seen.flatMap((p) => [p.yours, p.theirs]))];\n-\tconst tie = buildAtom(host.view(union), { author: agent.name, message, time, needs: changes, resolves });\n+\tconst tie = buildAtom(host.viewAt(shared, host.version(), changes), {\n+\t\tauthor: agent.name,\n+\t\tmessage,\n+\t\ttime,\n+\t\tneeds: changes,\n+\t\tresolves,\n+\t});\n \thost.requireClosed(tie, union);\n \tconst version = host.version() + 1;\n \t// A pluck leaves the draft where it is: the rest of it lands later."},{"path":"worker/project/news.ts","added":11,"removed":7,"diff":"--- a/worker/project/news.ts\n+++ b/worker/project/news.ts\n@@ -280,18 +280,22 @@\n \tentries: Entry[],\n ): void {\n \tconst just = new Set(space.versions[version]!.atoms);\n-\t// Most publishes change no definition; then only the same-lines rule can bring news.\n-\tconst touched = touchedFiles(host.graph, just, [host.viewAt(space, version - 1), host.viewAt(space, last(space))]);\n-\tconst before = definitionsIn(host.viewAt(space, version - 1), touched);\n-\tconst after = definitionsIn(host.viewAt(space, last(space)), touched);\n-\tconst changedDefinitions = [...new Set([...before.keys(), ...after.keys()])].some(\n-\t\t(name) => !before.has(name) || signature(before.get(name)!) !== signature(after.get(name) ?? []),\n-\t);\n+\tlet changedDefinitions: boolean | undefined;\n+\tconst compareDefinitions = () => {\n+\t\t// Most publishes change no definition; then only the same-lines rule can bring news.\n+\t\tconst touched = touchedFiles(host.graph, just, [host.viewAt(space, version - 1), host.viewAt(space, last(space))]);\n+\t\tconst before = definitionsIn(host.viewAt(space, version - 1), touched);\n+\t\tconst after = definitionsIn(host.viewAt(space, last(space)), touched);\n+\t\treturn [...new Set([...before.keys(), ...after.keys()])].some(\n+\t\t\t(name) => !before.has(name) || signature(before.get(name)!) !== signature(after.get(name) ?? []),\n+\t\t);\n+\t};\n \tfor (const agent of [...host.agents.values()].toSorted((a, b) => (a.name < b.name ? -1 : 1))) {\n \t\tif (agent === publisher || agent.space !== space.name) continue;\n \t\tconst draft = host.draft(agent);\n \t\tif (draft.length === 0) continue;\n \t\tconst lines = pairsIn(host.graph, draft, just, unionOverlay(host.setOf(space), draft));\n+\t\tchangedDefinitions ??= compareDefinitions();\n \t\tconst defs = changedDefinitions\n \t\t\t? host.definitionCollisions(agent, host.newerFor(agent)).filter((d) => just.has(d.by))\n \t\t\t: [];"},{"path":"worker/project/project.ts","added":151,"removed":9,"diff":"--- a/worker/project/project.ts\n+++ b/worker/project/project.ts\n@@ -228,6 +228,19 @@\n \tready: boolean;\n }\n \n+/** A decoded entry is supplied by a host that binds its bytes to canonical authority. */\n+export type WriterAdoptionFrame = { seq: number; json: string } | { seq: number; bytes: number; entry: Entry };\n+function adoptionFrameBytes(frame: WriterAdoptionFrame): number {\n+\treturn \"json\" in frame\n+\t\t? typeof frame.json === \"string\"\n+\t\t\t? new TextEncoder().encode(frame.json).byteLength\n+\t\t\t: NaN\n+\t\t: frame.bytes;\n+}\n+function adoptionFrameEntry(frame: WriterAdoptionFrame): Entry {\n+\treturn \"json\" in frame ? (JSON.parse(frame.json) as Entry) : frame.entry;\n+}\n+\n export class Project {\n \treadonly #store: ProjectStore;\n \treadonly #writerStorage?: GraphStateStorage;\n@@ -480,6 +493,46 @@\n \t\treturn new Project(store, { ...options, writerStorage: storage }, WRITER_REOPEN);\n \t}\n \n+\t/** Open a host-verified historical prefix. Its state must be immutable and\n+\t * scoped to canonical authority; adoption readiness describes the live writer,\n+\t * not whether this individual prefix has a complete checkpoint. */\n+\tstatic openHistorical(\n+\t\tstorage: GraphStateStorage,\n+\t\tlogLength: number,\n+\t\tscratch: GraphStateStorage,\n+\t\tassertScope: () => void = () => {\n+\t\t\tstorage.read(\"project:meta\", \"checkpoint\");\n+\t\t},\n+\t\treadViewProvider?: ProjectOptions[\"readViewProvider\"],\n+\t): Project {\n+\t\tconst refuse = (): never => {\n+\t\t\tthrow new Error(\"historical project is read-only\");\n+\t\t};\n+\t\tconst selected = (collection: string) => {\n+\t\t\t// Revalidate the historical scope even when accessing derived scratch.\n+\t\t\tassertScope();\n+\t\t\treturn collection.startsWith(\"projection-scratch:\") ? scratch : storage;\n+\t\t};\n+\t\treturn Project.#openWriter(\n+\t\t\t{ append: refuse },\n+\t\t\t{\n+\t\t\t\tread: (collection, key) => selected(collection).read(collection, key),\n+\t\t\t\tentries: (collection) => selected(collection).entries(collection),\n+\t\t\t\twrite: (collection, key, value) => {\n+\t\t\t\t\tif (selected(collection) !== scratch) refuse();\n+\t\t\t\t\tscratch.write(collection, key, value);\n+\t\t\t\t},\n+\t\t\t\tremove: (collection, key) => {\n+\t\t\t\t\tif (selected(collection) !== scratch) refuse();\n+\t\t\t\t\tscratch.remove(collection, key);\n+\t\t\t\t},\n+\t\t\t\ttransaction: (body) => storage.transaction(() => scratch.transaction(body)),\n+\t\t\t},\n+\t\t\tlogLength,\n+\t\t\t{ readViewProvider },\n+\t\t);\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@@ -490,10 +543,15 @@\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\tframes: Iterable<WriterAdoptionFrame>;\n \t\t\tmaxEntries: number;\n \t\t\tmaxBytes: number;\n+\t\t\t/** The host supplies disk-backed decoded entries and verified byte counts. */\n+\t\t\tdecodedFrames?: boolean;\n \t\t\tcurrentSource(): WriterSource;\n+\t\t\t/** Select the host's derived historical revision before applying a frame.\n+\t\t\t * Each selected revision receives a complete Project checkpoint. */\n+\t\t\tbeginRevision?(logLength: number): void;\n \t\t},\n \t\toptions: Omit<ProjectOptions, \"writerStorage\"> = {},\n \t): { next: number; ready: boolean; entries: number; bytes: number } {\n@@ -509,7 +567,7 @@\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\t(input.maxBytes > 8_000_000 && input.decodedFrames !== true)\n \t\t)\n \t\t\tthrow new Error(\"invalid writer adoption bounds or source\");\n \t\treturn storage.transaction(() => {\n@@ -533,19 +591,24 @@\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 (input.decodedFrames && \"json\" in frame) throw new Error(\"decoded adoption requires decoded frames\");\n+\t\t\t\tconst size = adoptionFrameBytes(frame);\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\t!Number.isSafeInteger(size) ||\n+\t\t\t\t\tsize < 1 ||\n+\t\t\t\t\tsize > 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\tbytes += size;\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\tinput.beginRevision?.(frame.seq + 1);\n+\t\t\t\tproject.#apply(adoptionFrameEntry(frame));\n \t\t\t\tproject.#stored++;\n \t\t\t\tproject.#persistMutable();\n+\t\t\t\tif (input.beginRevision) project.#writeCheckpoint();\n \t\t\t\tcount++;\n \t\t\t}\n \t\t\tif (count === 0) throw new Error(\"writer adoption page must advance\");\n@@ -563,9 +626,81 @@\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 * Extend derived historical indexes from an already checkpointed prefix.\n+\t * The host supplies only new canonical frames inside its commit transaction.\n \t */\n+\tstatic extendHistoricalPage(\n+\t\tstorage: GraphStateStorage,\n+\t\tinput: {\n+\t\t\tfrom: number;\n+\t\t\tframes: Iterable<WriterAdoptionFrame>;\n+\t\t\tmaxEntries: number;\n+\t\t\tmaxBytes: number;\n+\t\t\t/** The host supplies disk-backed decoded entries and verified byte counts. */\n+\t\t\tdecodedFrames?: boolean;\n+\t\t\tbeginRevision(logLength: number): void;\n+\t\t\t/** Verify both the saved prefix and the new frames against canonical authority. */\n+\t\t\tvalidateAuthority(): void;\n+\t\t},\n+\t): { next: number; entries: number; bytes: number } {\n+\t\tif (\n+\t\t\t!Number.isSafeInteger(input.from) ||\n+\t\t\tinput.from < 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\t(input.maxBytes > 8_000_000 && input.decodedFrames !== true)\n+\t\t)\n+\t\t\tthrow new Error(\"invalid historical extension bounds\");\n+\t\tconst validate = () => {\n+\t\t\tconst result: unknown = input.validateAuthority();\n+\t\t\tif (result && (typeof result === \"object\" || typeof result === \"function\") && \"then\" in result)\n+\t\t\t\tthrow new Error(\"historical authority must be synchronous\");\n+\t\t};\n+\t\treturn storage.transaction(() => {\n+\t\t\tvalidate();\n+\t\t\tconst project = Project.#openWriter(\n+\t\t\t\t{\n+\t\t\t\t\tappend: () => {\n+\t\t\t\t\t\tthrow new Error(\"history derivation cannot append canonical entries\");\n+\t\t\t\t\t},\n+\t\t\t\t},\n+\t\t\t\tstorage,\n+\t\t\t\tinput.from,\n+\t\t\t\t{},\n+\t\t\t);\n+\t\t\tproject.#loading = true;\n+\t\t\tlet entries = 0,\n+\t\t\t\tbytes = 0;\n+\t\t\tfor (const frame of input.frames) {\n+\t\t\t\tif (input.decodedFrames && \"json\" in frame) throw new Error(\"decoded adoption requires decoded frames\");\n+\t\t\t\tconst size = adoptionFrameBytes(frame);\n+\t\t\t\tif (\n+\t\t\t\t\tentries >= input.maxEntries ||\n+\t\t\t\t\tframe.seq !== input.from + entries ||\n+\t\t\t\t\t!Number.isSafeInteger(size) ||\n+\t\t\t\t\tsize < 1 ||\n+\t\t\t\t\tsize > input.maxBytes - bytes\n+\t\t\t\t)\n+\t\t\t\t\tthrow new Error(\"historical extension exceeds bounds or is not contiguous\");\n+\t\t\t\tbytes += size;\n+\t\t\t\tif (bytes > input.maxBytes) throw new Error(\"historical extension exceeds byte bound\");\n+\t\t\t\tinput.beginRevision(frame.seq + 1);\n+\t\t\t\tproject.#apply(adoptionFrameEntry(frame));\n+\t\t\t\tproject.#stored++;\n+\t\t\t\tproject.#persistMutable();\n+\t\t\t\tproject.#writeCheckpoint();\n+\t\t\t\tentries++;\n+\t\t\t}\n+\t\t\tif (!entries) throw new Error(\"historical extension must advance\");\n+\t\t\tvalidate();\n+\t\t\treturn { next: input.from + entries, entries, bytes };\n+\t\t});\n+\t}\n+\n+\t/** Apply more entries to a replay copy. Never for the live project. */\n \tcatchUp(entries: Iterable<Entry>): void {\n \t\tthis.#loading = true;\n \t\ttry {\n@@ -896,6 +1031,7 @@\n \n \t/** The project's reviewers per area (#44): avcs.json's `\"review\": [{\"paths\": [...], \"reviewer\": \"...\"}]` in shared. */\n \t#reviewRules(): ReviewRule[] {\n+\t\tif ([\"abso.json\", \"avcs.json\"].every((path) => this.#graph.startCodeOf(path) === undefined)) return [];\n \t\treturn reviewRulesIn(projectFileIn(this.#sharedView())?.text);\n \t}\n \n@@ -1325,7 +1461,7 @@\n \t\tspace: Space,\n \t\tchanges: AtomId[],\n \t\tpick: boolean,\n-\t): { collisions: Collision[]; newer: Set<AtomId>; union: Set<AtomId> } {\n+\t): { collisions: Collision[]; newer: ReadonlySet<AtomId>; union: ReadonlySet<AtomId> } {\n \t\treturn hostedLandCollisions(this.#landHost, space, changes, pick);\n \t}\n \n@@ -2043,6 +2179,12 @@\n \t#landers?: LandHost;\n \tget #landHost(): LandHost {\n \t\tthis.#landers ??= {\n+\t\t\tviewAt: (space, version, changes) =>\n+\t\t\t\tchanges?.length\n+\t\t\t\t\t? this.#viewKeyed(`a ${space.name}@${version}+${changes.join(\",\")}`, () =>\n+\t\t\t\t\t\t\tunionOverlay(this.#at(space, version), changes),\n+\t\t\t\t\t\t)\n+\t\t\t\t\t: this.#viewAt(space, version),\n \t\t\tagents: this.#agents,\n \t\t\tgraph: this.#graph,\n \t\t\tspaces: this.#spaces,"},{"path":"worker/project/projection-provider.ts","added":10,"removed":4,"diff":"--- a/worker/project/projection-provider.ts\n+++ b/worker/project/projection-provider.ts\n@@ -17,6 +17,7 @@\n \tcommitted(): { version: number; handle: ProjectionHandle };\n \tat(version: number): ProjectionHandle | undefined;\n \tdelta(version: number): Published | undefined;\n+\tnamedVersion?(name: string, version: number): { sharedBase: number; atoms: Iterable<string> } | undefined;\n \t/** Read-through overlay owned and cleaned by the current transaction. */\n \tallocate(): GraphStateStorage;\n \t/** Checks this exact transaction, graph revision and verified source binding. */\n@@ -41,9 +42,13 @@\n \t\t\tthrow Error(\"expired projection source binding\");\n \t};\n \tassertLive();\n-\tconst match = /^(v|a) @(0|[1-9]\\d*)(?:\\+(.+))?$/.exec(key);\n-\tif (!match || (match[1] === \"v\" && match[3])) throw Error(`unsupported projection key: ${key}`);\n-\tconst version = Number(match[2]);\n+\tconst match = /^(v|a) (.*)@(0|[1-9]\\d*)(?:\\+(.+))?$/.exec(key);\n+\tif (!match || (match[1] === \"v\" && match[4])) throw Error(`unsupported projection key: ${key}`);\n+\tconst requested = Number(match[3]);\n+\tif (!Number.isSafeInteger(requested)) throw Error(\"projection version outside authority\");\n+\tconst named = match[2] ? binding.namedVersion?.(match[2], requested) : undefined;\n+\tif (match[2] && !named) throw Error(\"named projection version outside authority\");\n+\tconst version = named?.sharedBase ?? requested;\n \tif (!Number.isSafeInteger(version) || version > binding.version())\n \t\tthrow Error(\"projection version outside authority\");\n \tconst exact = binding.at(version);\n@@ -74,7 +79,8 @@\n \t\tfor (const atom of delta.atoms.map((id) => binding.graph.atom(id)).sort((a, b) => a.seq - b.seq))\n \t\t\tstate = adapter.apply(state, atom);\n \t}\n-\tfor (const id of match[3]?.split(\",\") ?? []) state = adapter.apply(state, binding.graph.atom(id));\n+\tfor (const id of named?.atoms ?? []) state = adapter.apply(state, binding.graph.atom(id));\n+\tfor (const id of match[4]?.split(\",\") ?? []) state = adapter.apply(state, binding.graph.atom(id));\n \tassertLive();\n \treturn new ProjectionReader(adapter, state, assertLive);\n }"},{"path":"worker/project/test/collision-streaming.test.ts","added":48,"removed":0,"diff":"--- a/worker/project/test/collision-streaming.test.ts\n+++ b/worker/project/test/collision-streaming.test.ts\n@@ -107,3 +107,51 @@\n \t\tsource.db.close();\n \t}\n });\n+\n+test(\"wide claim merging reads each stream head once and closes streams on failure\", () => {\n+\tconst count = 256;\n+\tlet reads = 0,\n+\t\topened = 0,\n+\t\tclosed = 0;\n+\tlet fail = false;\n+\tconst draft = {\n+\t\tseq: 3,\n+\t\twrites: Array.from({ length: count }, (_, n) => `L:a0.${n}`),\n+\t\treads: [],\n+\t\tholds: [],\n+\t\tinserts: [],\n+\t\tdeletes: [],\n+\t\tdeps: [],\n+\t\tresolves: [],\n+\t\tneeds: [],\n+\t\treasons: [],\n+\t};\n+\tconst stream = function* () {\n+\t\topened++;\n+\t\ttry {\n+\t\t\tyield \"a0\";\n+\t\t\tyield \"a1\";\n+\t\t\tif (fail) throw Error(\"claim stream failure\");\n+\t\t\tyield \"a2\";\n+\t\t} finally {\n+\t\t\tclosed++;\n+\t\t}\n+\t};\n+\tconst graph = {\n+\t\tatom: (id: string) => {\n+\t\t\treads++;\n+\t\t\treturn id === \"a3\" ? draft : { seq: Number(id.slice(1)) };\n+\t\t},\n+\t\teachWriterOf: stream,\n+\t\teachReaderOf: stream,\n+\t\teachHolderOf: stream,\n+\t} as unknown as Graph;\n+\tassert.deepEqual(pairsIn(graph, [\"a3\"], new Set(), new Set()), []);\n+\tassert.ok(reads <= count * 12 + 1, `Unexpected repeated head reads: ${reads}`);\n+\tassert.equal(closed, opened);\n+\tfail = true;\n+\topened = 0;\n+\tclosed = 0;\n+\tassert.throws(() => pairsIn(graph, [\"a3\"], new Set(), new Set()), /claim stream failure/);\n+\tassert.equal(closed, opened);\n+});"},{"path":"worker/project/test/land-streaming.test.ts","added":83,"removed":0,"diff":"--- /dev/null\n+++ b/worker/project/test/land-streaming.test.ts\n@@ -0,0 +1,83 @@\n+import assert from \"node:assert/strict\";\n+import { test } from \"node:test\";\n+import { StableOverlaySet, StableSet } from \"../../../src/engine/state-source.ts\";\n+import { SqlState } from \"../../../src/engine/test/storage-helper.ts\";\n+import { type LandHost, landCollisions } from \"../land.ts\";\n+import { addVersion, Membership, type Space } from \"../spaces.ts\";\n+\n+test(\"landing collision setup does not enumerate shared history\", () => {\n+\tclass History extends StableSet<string> {\n+\t\treadonly retainedBytes = 0;\n+\t\treadonly end: number;\n+\t\tconstructor(end: number) {\n+\t\t\tsuper();\n+\t\t\tthis.end = end;\n+\t\t}\n+\t\thas(id: string) {\n+\t\t\treturn /^a\\d+$/.test(id) && Number(id.slice(1)) < this.end;\n+\t\t}\n+\t\tvalues(): SetIterator<string> {\n+\t\t\tthrow Error(\"shared history enumeration forbidden during setup\");\n+\t\t}\n+\t}\n+\tfor (const size of [32, 8192, 1_000_000]) {\n+\t\tconst shared = { name: \"\", own: new History(size) } as unknown as Space;\n+\t\tconst draft = {\n+\t\t\tname: \"draft\",\n+\t\t\town: new StableOverlaySet([\"draft-change\"]),\n+\t\t\tversions: [{ sharedBase: 0 }],\n+\t\t} as unknown as Space;\n+\t\tconst host = {\n+\t\t\tshared: () => shared,\n+\t\t\tversion: () => 1,\n+\t\t\tat: (_space: Space, version: number) => new History(version === 0 ? size - 1 : size),\n+\t\t\tviewAt: () => ({}),\n+\t\t\tsharedView: () => ({}),\n+\t\t\tpairs: (_changes: string[], newer: ReadonlySet<string>, union: ReadonlySet<string>) => {\n+\t\t\t\tassert.equal(newer.has(`a${size - 1}`), true);\n+\t\t\t\tassert.equal(newer.has(\"a0\"), false);\n+\t\t\t\tassert.equal(union.has(\"a0\"), true);\n+\t\t\t\tassert.equal(union.has(\"draft-change\"), true);\n+\t\t\t\treturn [];\n+\t\t\t},\n+\t\t\tdefinitionRule: () => ({ collisions: () => [] }),\n+\t\t} as unknown as LandHost;\n+\t\tassert.deepEqual(landCollisions(host, draft, [\"draft-change\"], false).collisions, []);\n+\t}\n+});\n+\n+test(\"landing uses real stored membership without enumerating shared ownership\", (t) => {\n+\tconst storage = new SqlState();\n+\ttry {\n+\t\tconst membership = new Membership(storage);\n+\t\tconst shared = membership.shared;\n+\t\tfor (let version = 0; version < 40; version++) {\n+\t\t\taddVersion(shared, { version, agent: \"test\", message: \"version\", time: 0, atoms: [`a${version}`] });\n+\t\t}\n+\t\tt.mock.method(shared.own, \"values\", () => {\n+\t\t\tthrow Error(\"stored shared history enumeration forbidden\");\n+\t\t});\n+\t\tconst draft = {\n+\t\t\tname: \"draft\",\n+\t\t\town: new StableOverlaySet([\"draft-change\"]),\n+\t\t\tversions: [{ sharedBase: 38 }],\n+\t\t} as unknown as Space;\n+\t\tconst host = {\n+\t\t\tshared: () => shared,\n+\t\t\tversion: () => 39,\n+\t\t\tat: (space: Space, version: number) => membership.at(space, version),\n+\t\t\tviewAt: () => ({}),\n+\t\t\tsharedView: () => ({}),\n+\t\t\tpairs: (_changes: string[], newer: ReadonlySet<string>, union: ReadonlySet<string>) => {\n+\t\t\t\tassert.deepEqual([...newer], [\"a39\"]);\n+\t\t\t\tassert.equal(union.has(\"a0\"), true);\n+\t\t\t\tassert.equal(union.has(\"draft-change\"), true);\n+\t\t\t\treturn [];\n+\t\t\t},\n+\t\t\tdefinitionRule: () => ({ collisions: () => [] }),\n+\t\t} as unknown as LandHost;\n+\t\tassert.deepEqual(landCollisions(host, draft, [\"draft-change\"], false).collisions, []);\n+\t} finally {\n+\t\tstorage.db.close();\n+\t}\n+});"},{"path":"worker/project/test/news-lazy.test.ts","added":35,"removed":0,"diff":"--- /dev/null\n+++ b/worker/project/test/news-lazy.test.ts\n@@ -0,0 +1,35 @@\n+import assert from \"node:assert/strict\";\n+import { test } from \"node:test\";\n+import { type NewsHost, newsForOthers } from \"../news.ts\";\n+import type { AgentState } from \"../project-types.ts\";\n+import type { Space } from \"../spaces.ts\";\n+\n+test(\"news skips historical views when no other agent has a draft in the space\", () => {\n+\tconst publisher = { name: \"alice\", space: \"\" } as AgentState;\n+\tconst idle = { name: \"bob\", space: \"\" } as AgentState;\n+\tconst elsewhere = { name: \"carol\", space: \"branch\" } as AgentState;\n+\tconst space = { name: \"\", versions: [{ atoms: [] }] } as unknown as Space;\n+\tlet draftReads = 0;\n+\tconst host = new Proxy(\n+\t\t{\n+\t\t\tagents: new Map([\n+\t\t\t\t[\"alice\", publisher],\n+\t\t\t\t[\"bob\", idle],\n+\t\t\t\t[\"carol\", elsewhere],\n+\t\t\t]),\n+\t\t\tdraft: (agent: AgentState) => {\n+\t\t\t\tassert.equal(agent, idle);\n+\t\t\t\tdraftReads++;\n+\t\t\t\treturn [];\n+\t\t\t},\n+\t\t},\n+\t\t{\n+\t\t\tget(target, key) {\n+\t\t\t\tif (key in target) return Reflect.get(target, key);\n+\t\t\t\tthrow Error(`Unexpected news work: ${String(key)}`);\n+\t\t\t},\n+\t\t},\n+\t) as unknown as NewsHost;\n+\tnewsForOthers(host, publisher, space, 0, []);\n+\tassert.equal(draftReads, 1);\n+});"},{"path":"worker/project/test/reviewers.test.ts","added":22,"removed":0,"diff":"--- a/worker/project/test/reviewers.test.ts\n+++ b/worker/project/test/reviewers.test.ts\n@@ -92,3 +92,25 @@\n \tplain.publish(\"b\", \"x\", 2);\n \tassert.equal(plain.news(\"c\").news.length, 0);\n });\n+\n+test(\"review rules added after an absent configuration are honored and removal clears them\", () => {\n+\tfor (const name of [\"abso.json\", \"avcs.json\"]) {\n+\t\tconst project = new Project(new MemoryStore());\n+\t\tproject.init({ \"a.txt\": \"one\\n\" }, 0);\n+\t\tproject.sync(\"builder\");\n+\t\tproject.sync(\"reviewer\");\n+\t\tproject.record(\"builder\", { \"a.txt\": \"two\\n\" }, 1);\n+\t\tproject.publish(\"builder\", \"No configuration\", 2);\n+\t\tassert.equal(project.news(\"reviewer\").news.length, 0);\n+\t\tproject.record(\n+\t\t\t\"builder\",\n+\t\t\t{ [name]: JSON.stringify({ review: [{ paths: [\"a.txt\"], reviewer: \"reviewer\" }] }), \"a.txt\": \"three\\n\" },\n+\t\t\t3,\n+\t\t);\n+\t\tproject.publish(\"builder\", \"Add rules\", 4);\n+\t\tassert.ok(project.news(\"reviewer\").news.some((text) => text.includes(\"in your review area\")));\n+\t\tproject.record(\"builder\", { [name]: null, \"a.txt\": \"four\\n\" }, 5);\n+\t\tproject.publish(\"builder\", \"Remove rules\", 6);\n+\t\tassert.equal(project.news(\"reviewer\").news.length, 0);\n+\t}\n+});"},{"path":"worker/project/test/where-many-agents.test.ts","added":10,"removed":0,"diff":"--- a/worker/project/test/where-many-agents.test.ts\n+++ b/worker/project/test/where-many-agents.test.ts\n@@ -7,6 +7,16 @@\n import { MemoryStore, Project } from \"../project.ts\";\n import { where } from \"../where.ts\";\n \n+test(\"where does not construct shared history when every draft is empty\", (t) => {\n+\tconst project = new Project(new MemoryStore());\n+\tproject.init({ \"a.txt\": \"one\\n\" }, 0);\n+\tproject.sync(\"idle\");\n+\tt.mock.method(project, \"sharedView\", () => {\n+\t\tthrow Error(\"unnecessary shared history construction\");\n+\t});\n+\tassert.deepEqual(where(project), { version: 0, files: {}, starting: [] });\n+});\n+\n test(\"where answers right with more agents than the view cache holds, and lays out no view for an empty draft\", () => {\n \tconst store = new MemoryStore();\n \tconst project = new Project(store);"},{"path":"worker/project/where.ts","added":2,"removed":1,"diff":"--- a/worker/project/where.ts\n+++ b/worker/project/where.ts\n@@ -30,8 +30,9 @@\n \n export function where(project: Project) {\n \tconst graph = project.graph;\n-\tconst shared = project.sharedView();\n+\tlet shared: ReturnType<Project[\"sharedView\"]> | undefined;\n \tconst sharedNumber = (file: string, id: LineId): number | undefined => {\n+\t\tshared ??= project.sharedView();\n \t\tif (!shared.hasFile(file)) return undefined;\n \t\tconst i = shared.lines(file).findIndex((l) => l.id === id);\n \t\treturn i >= 0 ? i + 1 : undefined;"}],"ci":null}