{"version":157,"agent":"codex-capacity-chair","message":"Share the SQLite writer and projection host with the open server","time":1791915928641,"timeIso":"2026-10-13T18:25:28.641Z","changes":13,"change":2001,"files":["scripts/check-changed.mjs","scripts/check-changed.test.ts","server/src/engine-project.ts","server/src/projection-store.ts","server/src/writer-host.ts","server/test/helpers.ts","server/test/writer-host.test.ts","src/engine/graph.ts","src/engine/test/graph-metadata-indexed.test.ts"],"draft":null,"diff":[{"path":"scripts/check-changed.mjs","added":8,"removed":2,"diff":"--- a/scripts/check-changed.mjs\n+++ b/scripts/check-changed.mjs\n@@ -26,12 +26,18 @@\n const TESTS = [\n \t{\n \t\tcwd: \".\",\n-\t\tglobs: [\"src/**/*.test.ts\", \"worker/project/**/*.test.ts\", \"client/test/**/*.test.ts\", \"scripts/**/*.test.ts\"],\n+\t\tglobs: [\n+\t\t\t\"src/**/*.test.ts\",\n+\t\t\t\"worker/project/**/*.test.ts\",\n+\t\t\t\"client/test/**/*.test.ts\",\n+\t\t\t\"scripts/**/*.test.ts\",\n+\t\t\t\"server/test/**/*.test.ts\",\n+\t\t],\n \t\targs: [\"--import\", \"./client/test/setup.ts\"],\n \t},\n ];\n /** Typechecks: a tsconfig, from the repo root. */\n-const TYPECHECKS = [{ tsconfig: \"tsconfig.json\" }];\n+const TYPECHECKS = [{ tsconfig: \"tsconfig.json\" }, { tsconfig: \"server/tsconfig.json\" }];\n /** Files whose change can reach anything: the full check runs instead. */\n const SETUP = [\n \t\"**/package.json\","},{"path":"scripts/check-changed.test.ts","added":7,"removed":1,"diff":"--- a/scripts/check-changed.test.ts\n+++ b/scripts/check-changed.test.ts\n@@ -14,7 +14,7 @@\n \tassert.ok(!files.includes(\"scripts/check-changed.test.ts\"), \"a test that doesn't reach the file stays out\");\n \tassert.deepEqual(\n \t\tp.typechecks.map((c: { tsconfig: string }) => c.tsconfig),\n-\t\t[\"tsconfig.json\"],\n+\t\t[\"tsconfig.json\", \"server/tsconfig.json\"],\n \t);\n \tassert.deepEqual(p.lint, [\"src/engine/text.ts\"]);\n });\n@@ -32,3 +32,9 @@\n \tassert.deepEqual(plan([\"src/engine/text.ts\", \"package.json\"]).full, [\"package.json\"]);\n \tassert.deepEqual(plan([\"tsconfig.json\"]).full, [\"tsconfig.json\"]);\n });\n+\n+test(\"server changes include their tests and worker types\", () => {\n+\tconst p = plan([\"server/src/engine-project.ts\"]);\n+\tassert.ok(p.tests.flatMap((t: { files: string[] }) => t.files).includes(\"server/test/engine-project.test.ts\"));\n+\tassert.ok(p.typechecks.some((c: { tsconfig: string }) => c.tsconfig === \"server/tsconfig.json\"));\n+});"},{"path":"server/src/engine-project.ts","added":38,"removed":3,"diff":"--- a/server/src/engine-project.ts\n+++ b/server/src/engine-project.ts\n@@ -17,14 +17,14 @@\n \n // Characters per row. SQLite's 2 MB cap is in bytes, and a character is at\n // most 3 bytes of UTF-8 (an emoji is 2 characters and 4 bytes), so 600,000 stays under it.\n-const PART = 600_000;\n+export const LOG_PART_CHARACTERS = 600_000;\n \n-/** An entry's JSON in rows of at most PART characters, never cutting an emoji's two halves apart. */\n+/** An entry's JSON in rows of at most LOG_PART_CHARACTERS characters, never cutting an emoji's two halves apart. */\n export function logParts(text: string): string[] {\n \tconst parts: string[] = [];\n \tlet at = 0;\n \tdo {\n-\t\tlet end = Math.min(at + PART, text.length);\n+\t\tlet end = Math.min(at + LOG_PART_CHARACTERS, text.length);\n \t\tconst c = text.charCodeAt(end - 1);\n \t\tif (end < text.length && c >= 0xd800 && c <= 0xdbff) end--;\n \t\tparts.push(text.slice(at, end));\n@@ -95,6 +95,41 @@\n \t\treturn this.next;\n \t}\n \n+\t/** Reject an oversized canonical frame before loading its text into JavaScript. */\n+\tboundedFrame(seq: number, maxBytes: number): string {\n+\t\tif (\n+\t\t\t!Number.isSafeInteger(seq) ||\n+\t\t\tseq < 0 ||\n+\t\t\t!Number.isSafeInteger(maxBytes) ||\n+\t\t\tmaxBytes < 1 ||\n+\t\t\tmaxBytes > 8_000_000\n+\t\t)\n+\t\t\tthrow new Error(\"invalid canonical frame bound\");\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 > maxBytes)\n+\t\t\tthrow new Error(\"canonical frame exceeds adoption bound or is missing\");\n+\t\tconst rows = this.storage.sql.exec(\"SELECT part, text FROM log WHERE seq = ? ORDER BY part\", seq).toArray() as {\n+\t\t\tpart: number;\n+\t\t\ttext: string;\n+\t\t}[];\n+\t\tif (rows.length !== size.parts || rows.some((row, part) => row.part !== part))\n+\t\t\tthrow new Error(\"canonical frame parts are incomplete\");\n+\t\treturn rows.map((row) => row.text).join(\"\");\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+\t\t\tlast: number;\n+\t\t}[];\n+\t\tthis.next = (rows[0]?.last ?? -1) + 1;\n+\t}\n+\n \t/** Monotonic cache invalidation epoch for every canonical log mutation. */\n \tgeneration(): number {\n \t\tconst rows = this.storage.sql.exec(\"SELECT value FROM marks WHERE name = ?\", \"generation\").toArray() as {"},{"path":"server/src/projection-store.ts","added":410,"removed":0,"diff":"--- /dev/null\n+++ b/server/src/projection-store.ts\n@@ -0,0 +1,410 @@\n+import { ProjectionAtomAdoption } from \"../../src/engine/experimental/projection-atom-adoption.ts\";\n+import { ProjectionAtomIndex } from \"../../src/engine/experimental/projection-atom-index.ts\";\n+import { ExperimentalMarkerProjection, type MarkerState } from \"../../src/engine/experimental/projection-marker.ts\";\n+import { ProjectionOverlayStorage } from \"../../src/engine/experimental/projection-overlay-storage.ts\";\n+import { ProjectionReadScope } from \"../../src/engine/experimental/projection-read-scope.ts\";\n+import {\n+\tassertProjectionIdentity,\n+\ttype ProjectionHandle,\n+\ttype ProjectionIdentity,\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 { 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+import {\n+\tadvanceWriterRoot,\n+\ttype SqliteWriterState,\n+\ttype WriterProjectionHost,\n+\ttype WriterProjectionSession,\n+\ttype WriterRoot,\n+} from \"./writer-host.ts\";\n+\n+type Context = Pick<ProjectionIdentity, \"database\" | \"namespace\" | \"registry\" | \"defaultFile\">;\n+interface Cursor {\n+\tsource: WriterRoot;\n+\tversion: number;\n+\toffset: number;\n+\tordered: boolean;\n+\tstate: MarkerState;\n+\tready: boolean;\n+}\n+interface Head {\n+\tversion: number;\n+\thandle: ProjectionHandle;\n+\tsource: WriterRoot;\n+}\n+const integer = (value: unknown): value is number => Number.isSafeInteger(value) && Number(value) >= 0;\n+function shape(value: unknown, fields: string): asserts value is Record<string, unknown> {\n+\tconst keys = fields.split(\" \");\n+\tif (\n+\t\t!value ||\n+\t\ttypeof value !== \"object\" ||\n+\t\tArray.isArray(value) ||\n+\t\tObject.keys(value).length !== keys.length ||\n+\t\tkeys.some((key) => !Object.hasOwn(value, key))\n+\t)\n+\t\tthrow Error(\"invalid projection host record\");\n+}\n+function source(value: unknown): asserts value is WriterRoot {\n+\tshape(value, \"format generation logLength sharedVersion digest\");\n+\tif (\n+\t\tvalue.format !== 1 ||\n+\t\t!integer(value.generation) ||\n+\t\t!integer(value.logLength) ||\n+\t\t!integer(value.sharedVersion) ||\n+\t\ttypeof value.digest !== \"string\" ||\n+\t\t!/^[a-f0-9]{64}$/.test(value.digest)\n+\t)\n+\t\tthrow Error(\"invalid projection source root\");\n+}\n+\n+/** Private format experiment. Constructor injection only; production has no selection path. */\n+export class SqliteProjectionStore implements WriterProjectionHost {\n+\treadonly #context: Context;\n+\treadonly #generation: number;\n+\treadonly #indexedAtoms: boolean;\n+\treadonly #meta: string;\n+\t#active = false;\n+\t#nextOverlay = 0;\n+\tconstructor(context: Context, namespaceGeneration: number, options: { indexedAtoms?: boolean } = {}) {\n+\t\tif (!Number.isSafeInteger(namespaceGeneration) || namespaceGeneration < 0)\n+\t\t\tthrow Error(\"invalid projection namespace generation\");\n+\t\tthis.#context = Object.freeze({ ...context });\n+\t\tthis.#generation = namespaceGeneration;\n+\t\tthis.#indexedAtoms = options.indexedAtoms ?? false;\n+\t\tthis.#meta = `projection-host:${JSON.stringify(context.namespace)}`;\n+\t}\n+\t#bind(state: SqliteWriterState): void {\n+\t\tconst mode = state.read(\"host\", \"projection-atom-index-mode\");\n+\t\tif (this.#indexedAtoms ? mode !== 1 : mode === 1) throw Error(\"projection atom indexing mode mismatch\");\n+\t\tconst expected = {\n+\t\t\t...this.#context,\n+\t\t\tgeneration: this.#generation,\n+\t\t\t...(this.#indexedAtoms ? { atomIndexFormat: 1 } : {}),\n+\t\t};\n+\t\tconst found = state.read(this.#meta, \"binding\");\n+\t\tif (found !== undefined && canonicalJson(found) !== canonicalJson(expected))\n+\t\t\tthrow Error(\"projection namespace identity mismatch\");\n+\t\tif (found === undefined) state.write(this.#meta, \"binding\", expected);\n+\t}\n+\t#firstPending(state: SqliteWriterState, collection: string): readonly [string, unknown] | undefined {\n+\t\tconst iterator = state.entries(collection)[Symbol.iterator]();\n+\t\ttry {\n+\t\t\tconst next = iterator.next();\n+\t\t\treturn next.done ? undefined : next.value;\n+\t\t} finally {\n+\t\t\titerator.return?.();\n+\t\t}\n+\t}\n+\t#identity(source: WriterRoot, version: number): ProjectionIdentity {\n+\t\treturn {\n+\t\t\t...this.#context,\n+\t\t\tsourceGeneration: this.#generation,\n+\t\t\tsourceLength: source.logLength,\n+\t\t\tsourceDigest: source.digest,\n+\t\t\tmembership: String(version),\n+\t\t};\n+\t}\n+\t#cursor(value: unknown): Cursor | undefined {\n+\t\tif (value === undefined) return undefined;\n+\t\tshape(value, \"source version offset ordered state ready\");\n+\t\tsource(value.source);\n+\t\tif (\n+\t\t\t!integer(value.version) ||\n+\t\t\tvalue.version > value.source.sharedVersion + 1 ||\n+\t\t\t!integer(value.offset) ||\n+\t\t\ttypeof value.ordered !== \"boolean\" ||\n+\t\t\ttypeof value.ready !== \"boolean\" ||\n+\t\t\tvalue.ready !== (value.version === value.source.sharedVersion + 1) ||\n+\t\t\t(value.ready && (value.offset !== 0 || value.ordered))\n+\t\t)\n+\t\t\tthrow Error(\"invalid projection adoption cursor\");\n+\t\tshape(value.state, \"context sequence locator membership children attributeFiles\");\n+\t\tif (value.state.context !== JSON.stringify([this.#context.namespace, this.#context.defaultFile]))\n+\t\t\tthrow Error(\"projection adoption context mismatch\");\n+\t\tfor (const key of [\"locator\", \"membership\", \"children\", \"attributeFiles\"])\n+\t\t\tif (value.state[key] !== null && !integer(value.state[key])) throw Error(\"invalid adoption page reference\");\n+\t\tshape(value.state.sequence, \"map root next\");\n+\t\tconst seq = value.state.sequence;\n+\t\tif (\n+\t\t\t!integer(seq.next) ||\n+\t\t\tseq.next > 2 ** 32 ||\n+\t\t\t(seq.map !== null && !integer(seq.map)) ||\n+\t\t\t(seq.root !== null && (!integer(seq.root) || seq.root >= seq.next)) ||\n+\t\t\t(seq.root === null) !== (seq.next === 0) ||\n+\t\t\t(seq.map === null) !== (seq.root === null)\n+\t\t)\n+\t\t\tthrow Error(\"invalid adoption sequence state\");\n+\t\treturn value as unknown as Cursor;\n+\t}\n+\t#head(value: unknown, expected: WriterRoot): Head | undefined {\n+\t\tif (value === undefined) return undefined;\n+\t\tshape(value, \"version handle source\");\n+\t\tsource(value.source);\n+\t\tif (\n+\t\t\t!integer(value.version) ||\n+\t\t\tvalue.version !== expected.sharedVersion ||\n+\t\t\tcanonicalJson(value.source) !== canonicalJson(expected)\n+\t\t)\n+\t\t\tthrow Error(\"projection head is stale\");\n+\t\tshape(value.handle, \"format id identity\");\n+\t\tif (value.handle.format !== 1 || !integer(value.handle.id)) throw Error(\"invalid projection head handle\");\n+\t\tassertProjectionIdentity(value.handle.identity as ProjectionIdentity, this.#identity(expected, value.version));\n+\t\treturn value as unknown as Head;\n+\t}\n+\t#save(\n+\t\tstate: SqliteWriterState,\n+\t\tsnapshots: ProjectionSnapshots,\n+\t\tvalue: MarkerState,\n+\t\tsource: WriterRoot,\n+\t\tversion: number,\n+\t): ProjectionHandle {\n+\t\tconst stored = state.read(this.#meta, \"next-root\");\n+\t\tconst next = stored === undefined ? 0 : stored;\n+\t\tif (!integer(next) || !Number.isSafeInteger(next + 1)) throw Error(\"invalid projection root allocation\");\n+\t\tconst handle = snapshots.save(next, this.#identity(source, version), value);\n+\t\tstate.write(this.#meta, \"next-root\", next + 1);\n+\t\tstate.write(`${this.#meta}:versions`, String(version), handle);\n+\t\tstate.write(`${this.#meta}:prefixes`, String(source.logLength), source.digest);\n+\t\tstate.write(this.#meta, \"head\", { version, handle, source } satisfies Head);\n+\t\treturn handle;\n+\t}\n+\t#atoms(graph: Graph, delta: Published): { id: string; remove: boolean }[] {\n+\t\treturn [\n+\t\t\t...[...(delta.dropped ?? [])]\n+\t\t\t\t.sort((a, b) => graph.atom(b).seq - graph.atom(a).seq)\n+\t\t\t\t.map((id) => ({ id, remove: true })),\n+\t\t\t...[...delta.atoms].sort((a, b) => graph.atom(a).seq - graph.atom(b).seq).map((id) => ({ id, remove: false })),\n+\t\t];\n+\t}\n+\t/** Each page is bounded in atoms and completed versions; the writer root is rechecked before commit. */\n+\tadopt(input: {\n+\t\tstate: SqliteWriterState;\n+\t\texpected: WriterRoot;\n+\t\tcurrentRoot(): WriterRoot;\n+\t\tmaxAtoms: number;\n+\t\tmaxVersions: number;\n+\t\tmaxSteps?: number;\n+\t}): { ready: boolean; version: number; applied: number; prepared: number; steps: number; atomicMoveWork: boolean } {\n+\t\tif (this.#active) throw Error(\"projection writer is active\");\n+\t\tsource(input.expected);\n+\t\tconst maxSteps = input.maxSteps ?? 64;\n+\t\tif (![input.maxAtoms, input.maxVersions, maxSteps].every((n) => Number.isSafeInteger(n) && n > 0 && n <= 256))\n+\t\t\tthrow Error(\"invalid projection adoption bounds\");\n+\t\treturn input.state.transaction(() => {\n+\t\t\tconst check = () => {\n+\t\t\t\tif (canonicalJson(input.currentRoot()) !== canonicalJson(input.expected))\n+\t\t\t\t\tthrow Error(\"projection adoption source changed\");\n+\t\t\t};\n+\t\t\tcheck();\n+\t\t\tthis.#bind(input.state);\n+\t\t\t// One bounded cache per adoption page; no cache survives a return or rollback.\n+\t\t\tconst pageStorage = new CachedStateStorage(input.state, 262_144, 2048);\n+\t\t\tconst graph = new Graph({ storage: pageStorage });\n+\t\t\tconst atomIndex = this.#indexedAtoms ? new ProjectionAtomIndex(pageStorage) : undefined;\n+\t\t\tconst atomSeq = (id: string) => {\n+\t\t\t\tif (!graph.has(id)) throw Error(\"missing projection atom\");\n+\t\t\t\treturn Number(id.slice(1));\n+\t\t\t};\n+\t\t\tconst adapter = new ExperimentalMarkerProjection(\n+\t\t\t\tpageStorage,\n+\t\t\t\tgraph,\n+\t\t\t\tthis.#context.defaultFile,\n+\t\t\t\tthis.#context.namespace,\n+\t\t\t);\n+\t\t\tconst snapshots = new ProjectionSnapshots(pageStorage, adapter, this.#context);\n+\t\t\tconst versions = new Membership(pageStorage).shared.versions;\n+\t\t\tlet cursor = this.#cursor(input.state.read(this.#meta, \"adoption\"));\n+\t\t\tif (cursor && canonicalJson(cursor.source) !== canonicalJson(input.expected))\n+\t\t\t\tthrow Error(\"projection adoption cursor changed\");\n+\t\t\tcursor ??= {\n+\t\t\t\tsource: input.expected,\n+\t\t\t\tversion: 0,\n+\t\t\t\toffset: 0,\n+\t\t\t\tordered: false,\n+\t\t\t\tstate: adapter.empty(),\n+\t\t\t\tready: false,\n+\t\t\t};\n+\t\t\tlet applied = 0,\n+\t\t\t\tprepared = 0,\n+\t\t\t\tcompleted = 0,\n+\t\t\t\tsteps = 0,\n+\t\t\t\tatomicMoveWork = false;\n+\t\t\tconst pending = `${this.#meta}:adoption-order`;\n+\t\t\twhile (\n+\t\t\t\t!cursor.ready &&\n+\t\t\t\tapplied + prepared < input.maxAtoms &&\n+\t\t\t\tcompleted < input.maxVersions &&\n+\t\t\t\tsteps < maxSteps\n+\t\t\t) {\n+\t\t\t\tconst delta = versions[cursor.version];\n+\t\t\t\tif (!delta || delta.version !== cursor.version) throw Error(\"missing projection adoption version\");\n+\t\t\t\tconst drops = delta.dropped ?? [];\n+\t\t\t\tconst count = drops.length + delta.atoms.length;\n+\t\t\t\tif (cursor.offset > count || (cursor.ordered && cursor.offset !== count))\n+\t\t\t\t\tthrow Error(\"invalid projection adoption offset\");\n+\t\t\t\twhile (!cursor.ordered && cursor.offset < count && applied + prepared < input.maxAtoms) {\n+\t\t\t\t\tconst remove = cursor.offset < drops.length;\n+\t\t\t\t\tconst id = remove ? drops[cursor.offset]! : delta.atoms[cursor.offset - drops.length]!;\n+\t\t\t\t\tconst seq = atomSeq(id);\n+\t\t\t\t\tif (!Number.isSafeInteger(seq) || seq < 0) throw Error(\"invalid adoption atom sequence\");\n+\t\t\t\t\tconst rank = remove ? Number.MAX_SAFE_INTEGER - seq : seq;\n+\t\t\t\t\tconst key = `${remove ? \"0\" : \"1\"}:${rank.toString(16).padStart(14, \"0\")}`;\n+\t\t\t\t\tinput.state.write(pending, key, { id, remove, version: cursor.version, index: cursor.offset });\n+\t\t\t\t\tcursor.offset++;\n+\t\t\t\t\tprepared++;\n+\t\t\t\t}\n+\t\t\t\tif (cursor.offset === count) cursor.ordered = true;\n+\t\t\t\tif (!cursor.ordered) break;\n+\t\t\t\twhile (applied + prepared < input.maxAtoms && steps < maxSteps) {\n+\t\t\t\t\tconst next = this.#firstPending(input.state, pending);\n+\t\t\t\t\tif (!next) break;\n+\t\t\t\t\tconst [key, value] = next;\n+\t\t\t\t\tshape(value, \"id remove version index\");\n+\t\t\t\t\tif (\n+\t\t\t\t\t\ttypeof value.id !== \"string\" ||\n+\t\t\t\t\t\t!value.id.length ||\n+\t\t\t\t\t\tvalue.id.length > 4096 ||\n+\t\t\t\t\t\ttypeof value.remove !== \"boolean\" ||\n+\t\t\t\t\t\tvalue.version !== cursor.version ||\n+\t\t\t\t\t\t!integer(value.index) ||\n+\t\t\t\t\t\tvalue.index >= count ||\n+\t\t\t\t\t\tvalue.remove !== value.index < drops.length ||\n+\t\t\t\t\t\tvalue.id !== (value.remove ? drops[value.index] : delta.atoms[value.index - drops.length])\n+\t\t\t\t\t)\n+\t\t\t\t\t\tthrow Error(\"invalid projection pending atom\");\n+\t\t\t\t\tconst item = value as { id: string; remove: boolean };\n+\t\t\t\t\tconst seq = atomSeq(item.id);\n+\t\t\t\t\tconst rank = item.remove ? Number.MAX_SAFE_INTEGER - seq : seq;\n+\t\t\t\t\tif (key !== `${item.remove ? \"0\" : \"1\"}:${rank.toString(16).padStart(14, \"0\")}`)\n+\t\t\t\t\t\tthrow Error(\"projection pending order mismatch\");\n+\t\t\t\t\tconst task = `${cursor.version}:${key}`;\n+\t\t\t\t\tconst page = new ProjectionAtomAdoption(adapter, task).page({\n+\t\t\t\t\t\tprevious: cursor.state,\n+\t\t\t\t\t\tatom: atomIndex ? atomIndex.openAccepted(item.id) : graph.atom(item.id),\n+\t\t\t\t\t\tremove: item.remove,\n+\t\t\t\t\t\tsource: input.expected.digest,\n+\t\t\t\t\t\tmaxSteps: maxSteps - steps,\n+\t\t\t\t\t\tvalidateSource: check,\n+\t\t\t\t\t});\n+\t\t\t\t\tsteps += page.steps;\n+\t\t\t\t\tatomicMoveWork ||= page.atomicMoveWork;\n+\t\t\t\t\tif (!page.done) break;\n+\t\t\t\t\tcursor.state = page.state;\n+\t\t\t\t\tadapter.storage.remove(`atom-adoption:${task}`, \"cursor\");\n+\t\t\t\t\tinput.state.remove(pending, key);\n+\t\t\t\t\tapplied++;\n+\t\t\t\t}\n+\t\t\t\tif (!this.#firstPending(input.state, pending)) {\n+\t\t\t\t\tthis.#save(input.state, snapshots, cursor.state, input.expected, cursor.version);\n+\t\t\t\t\tcursor.version++;\n+\t\t\t\t\tcursor.offset = 0;\n+\t\t\t\t\tcursor.ordered = false;\n+\t\t\t\t\tcompleted++;\n+\t\t\t\t\tcursor.ready = cursor.version > input.expected.sharedVersion;\n+\t\t\t\t}\n+\t\t\t}\n+\t\t\tcheck();\n+\t\t\tinput.state.write(this.#meta, \"adoption\", cursor);\n+\t\t\treturn { ready: cursor.ready, version: cursor.version - 1, applied, prepared, steps, atomicMoveWork };\n+\t\t});\n+\t}\n+\topen({ state, log, root }: Parameters<WriterProjectionHost[\"open\"]>[0]): WriterProjectionSession {\n+\t\tif (this.#active) throw Error(\"nested projection writers are not supported\");\n+\t\tthis.#bind(state);\n+\t\tsource(root);\n+\t\tconst adoption = this.#cursor(state.read(this.#meta, \"adoption\"));\n+\t\tconst head = this.#head(state.read(this.#meta, \"head\"), root);\n+\t\tif (!adoption?.ready || !head || canonicalJson(head.source) !== canonicalJson(root))\n+\t\t\tthrow Error(\"projection head is missing, incomplete or stale\");\n+\t\tthis.#active = true;\n+\t\tlet live = true,\n+\t\t\tobserved = root;\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 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+\t\t\t\tthrow Error(\"projection source changed without an append\");\n+\t\t\tif (log.seq() !== observed.logLength)\n+\t\t\t\tobserved = advanceWriterRoot(log, observed, {\n+\t\t\t\t\tgeneration: log.generation(),\n+\t\t\t\t\tlogLength: log.seq(),\n+\t\t\t\t\tsharedVersion: versions.length - 1,\n+\t\t\t\t});\n+\t\t\treturn observed;\n+\t\t};\n+\t\treturn {\n+\t\t\treadViewProvider: (graph) => {\n+\t\t\t\tconst scope = new ProjectionReadScope(graph, () => (live ? token : undefined));\n+\t\t\t\tscopes.push(scope);\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\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),\n+\t\t\t\t};\n+\t\t\t},\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 adapter = new ExperimentalMarkerProjection(\n+\t\t\t\t\tstate,\n+\t\t\t\t\tproject.graph,\n+\t\t\t\t\tthis.#context.defaultFile,\n+\t\t\t\t\tthis.#context.namespace,\n+\t\t\t\t);\n+\t\t\t\tconst snapshots = new ProjectionSnapshots(state, adapter, this.#context);\n+\t\t\t\tlet value = snapshots.load(head.handle, this.#identity(head.source, head.version));\n+\t\t\t\tlet saved = false;\n+\t\t\t\tfor (let version = head.version + 1; version <= project.version; version++) {\n+\t\t\t\t\tfor (const item of this.#atoms(project.graph, versions[version]!))\n+\t\t\t\t\t\tvalue = item.remove\n+\t\t\t\t\t\t\t? adapter.removeAtom(value, project.graph.atom(item.id))\n+\t\t\t\t\t\t\t: adapter.apply(value, project.graph.atom(item.id));\n+\t\t\t\t\tthis.#save(state, snapshots, value, committed, version);\n+\t\t\t\t\tsaved = true;\n+\t\t\t\t}\n+\t\t\t\tif (!saved) this.#save(state, snapshots, value, committed, project.version);\n+\t\t\t},\n+\t\t\tclose: () => {\n+\t\t\t\tif (!live) return;\n+\t\t\t\tlive = false;\n+\t\t\t\ttry {\n+\t\t\t\t\tfor (const scope of scopes) scope.close();\n+\t\t\t\t\tfor (const overlay of overlays) overlay.close();\n+\t\t\t\t} finally {\n+\t\t\t\t\tthis.#active = false;\n+\t\t\t\t}\n+\t\t\t},\n+\t\t};\n+\t}\n+}"},{"path":"server/src/writer-host.ts","added":429,"removed":0,"diff":"--- /dev/null\n+++ b/server/src/writer-host.ts\n@@ -0,0 +1,429 @@\n+// Shared SQLite writer host.\n+// Callers provide current authority and own activation; this module adds no route.\n+import { createHash } from \"node:crypto\";\n+import { indexAcceptedProjectionAtom } from \"../../src/engine/experimental/projection-atom-index.ts\";\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 {\n+\tEngineProject,\n+\tlogParts,\n+\tLOG_PART_CHARACTERS as PART,\n+\tSqliteLog,\n+\ttype SqliteStorage,\n+} from \"./engine-project.ts\";\n+\n+export class SqliteWriterState implements GraphStateStorage {\n+\treadonly #storage: SqliteStorage;\n+\treadonly #namespace: string;\n+\tstatic readonly maxValueBytes = 8_000_000;\n+\tconstructor(storage: SqliteStorage, namespace: string) {\n+\t\tif (!namespace || namespace.length > 128) throw new Error(\"invalid writer-state namespace\");\n+\t\tthis.#storage = storage;\n+\t\tthis.#namespace = namespace;\n+\t}\n+\t/** Explicit schema setup, reserved for an authorized adoption host. */\n+\tstatic initialize(storage: SqliteStorage): void {\n+\t\tstorage.sql.exec(\n+\t\t\t\"CREATE TABLE IF NOT EXISTS writer_state (namespace TEXT NOT NULL, collection TEXT NOT NULL, key TEXT NOT NULL, part INTEGER NOT NULL, value TEXT NOT NULL, PRIMARY KEY(namespace, collection, key, part))\",\n+\t\t);\n+\t}\n+\tread(collection: string, key: string): unknown {\n+\t\tconst header = this.#storage.sql\n+\t\t\t.exec(\n+\t\t\t\t\"SELECT value FROM writer_state WHERE namespace = ? AND collection = ? AND key = ? AND part = -1\",\n+\t\t\t\tthis.#namespace,\n+\t\t\t\tcollection,\n+\t\t\t\tkey,\n+\t\t\t)\n+\t\t\t.toArray() as { value: string }[];\n+\t\tif (!header.length) return undefined;\n+\t\tconst meta = JSON.parse(header[0]!.value) as { parts: number; characters: number; bytes: number };\n+\t\tif (\n+\t\t\t!Number.isSafeInteger(meta.parts) ||\n+\t\t\tmeta.parts < 1 ||\n+\t\t\tmeta.parts > Math.ceil(SqliteWriterState.maxValueBytes / (PART - 1)) ||\n+\t\t\t!Number.isSafeInteger(meta.characters) ||\n+\t\t\tmeta.characters < 1 ||\n+\t\t\tmeta.characters > SqliteWriterState.maxValueBytes ||\n+\t\t\t!Number.isSafeInteger(meta.bytes) ||\n+\t\t\tmeta.bytes < 1 ||\n+\t\t\tmeta.bytes > SqliteWriterState.maxValueBytes\n+\t\t)\n+\t\t\tthrow new Error(\"invalid writer-state value header\");\n+\t\tconst rows = this.#storage.sql\n+\t\t\t.exec(\n+\t\t\t\t\"SELECT part, value FROM writer_state WHERE namespace = ? AND collection = ? AND key = ? AND part >= 0 ORDER BY part LIMIT ?\",\n+\t\t\t\tthis.#namespace,\n+\t\t\t\tcollection,\n+\t\t\t\tkey,\n+\t\t\t\tmeta.parts + 1,\n+\t\t\t)\n+\t\t\t.toArray() as { part: number; value: string }[];\n+\t\tif (rows.length !== meta.parts || rows.some((row, index) => row.part !== index || row.value.length > PART))\n+\t\t\tthrow new Error(\"incomplete writer-state value\");\n+\t\tconst json = rows.map((row) => row.value).join(\"\");\n+\t\tif (json.length !== meta.characters || new TextEncoder().encode(json).byteLength !== meta.bytes)\n+\t\t\tthrow new Error(\"writer-state value length mismatch\");\n+\t\treturn (JSON.parse(json) as { value?: unknown }).value;\n+\t}\n+\twrite(collection: string, key: string, value: unknown): void {\n+\t\tconst json = JSON.stringify({ value });\n+\t\tif (json.length > SqliteWriterState.maxValueBytes) throw new Error(\"writer-state value exceeds byte bound\");\n+\t\tconst bytes = new TextEncoder().encode(json).byteLength;\n+\t\tif (bytes > SqliteWriterState.maxValueBytes) throw new Error(\"writer-state value exceeds byte bound\");\n+\t\tconst parts = logParts(json);\n+\t\tthis.transaction(() => {\n+\t\t\tthis.remove(collection, key);\n+\t\t\tthis.#storage.sql.exec(\n+\t\t\t\t\"INSERT INTO writer_state VALUES (?, ?, ?, -1, ?)\",\n+\t\t\t\tthis.#namespace,\n+\t\t\t\tcollection,\n+\t\t\t\tkey,\n+\t\t\t\tJSON.stringify({ parts: parts.length, characters: json.length, bytes }),\n+\t\t\t);\n+\t\t\tfor (const [part, text] of parts.entries())\n+\t\t\t\tthis.#storage.sql.exec(\n+\t\t\t\t\t\"INSERT INTO writer_state VALUES (?, ?, ?, ?, ?)\",\n+\t\t\t\t\tthis.#namespace,\n+\t\t\t\t\tcollection,\n+\t\t\t\t\tkey,\n+\t\t\t\t\tpart,\n+\t\t\t\t\ttext,\n+\t\t\t\t);\n+\t\t});\n+\t}\n+\tremove(collection: string, key: string): void {\n+\t\tthis.#storage.sql.exec(\n+\t\t\t\"DELETE FROM writer_state WHERE namespace = ? AND collection = ? AND key = ?\",\n+\t\t\tthis.#namespace,\n+\t\t\tcollection,\n+\t\t\tkey,\n+\t\t);\n+\t}\n+\t/** Delete one owned temporary projection collection without reading its values. */\n+\tclearProjectionOverlay(collection: string): void {\n+\t\tif (!collection.startsWith(\"projection:temporary:\") || collection === \"projection:temporary:\")\n+\t\t\tthrow Error(\"invalid temporary projection collection\");\n+\t\tthis.#storage.sql.exec(\n+\t\t\t\"DELETE FROM writer_state WHERE namespace = ? AND collection = ?\",\n+\t\t\tthis.#namespace,\n+\t\t\tcollection,\n+\t\t);\n+\t}\n+\t*entries(collection: string): Iterable<readonly [string, unknown]> {\n+\t\tlet after: string | undefined;\n+\t\tfor (;;) {\n+\t\t\tconst rows = (\n+\t\t\t\tafter === undefined\n+\t\t\t\t\t? this.#storage.sql.exec(\n+\t\t\t\t\t\t\t\"SELECT key FROM writer_state WHERE namespace = ? AND collection = ? AND part = -1 ORDER BY key LIMIT 1\",\n+\t\t\t\t\t\t\tthis.#namespace,\n+\t\t\t\t\t\t\tcollection,\n+\t\t\t\t\t\t)\n+\t\t\t\t\t: this.#storage.sql.exec(\n+\t\t\t\t\t\t\t\"SELECT key FROM writer_state WHERE namespace = ? AND collection = ? AND part = -1 AND key > ? ORDER BY key LIMIT 1\",\n+\t\t\t\t\t\t\tthis.#namespace,\n+\t\t\t\t\t\t\tcollection,\n+\t\t\t\t\t\t\tafter,\n+\t\t\t\t\t\t)\n+\t\t\t).toArray() as { key: string }[];\n+\t\t\tif (!rows.length) return;\n+\t\t\tafter = rows[0]!.key;\n+\t\t\tyield [after, this.read(collection, after)];\n+\t\t}\n+\t}\n+\ttransaction<T>(body: () => T): T {\n+\t\treturn this.#storage.transactionSync(body);\n+\t}\n+}\n+\n+export interface WriterRoot extends WriterSource {\n+\treadonly format: 1;\n+\treadonly digest: string;\n+}\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+\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+}\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+\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+\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+}\n+\n+/** Private integration hook. No endpoint or persisted setting enables it. */\n+export interface WriterProjectionHost {\n+\topen(input: { state: SqliteWriterState; log: SqliteLog; root: WriterRoot }): WriterProjectionSession;\n+}\n+\n+export class SqliteWriterHost {\n+\treadonly #storage: SqliteStorage;\n+\treadonly #state: SqliteWriterState;\n+\treadonly #log: SqliteLog;\n+\treadonly #projection?: WriterProjectionHost;\n+\treadonly #indexProjectionAtoms: boolean;\n+\tconstructor(\n+\t\tstorage: SqliteStorage,\n+\t\tnamespace: string,\n+\t\tprojection?: WriterProjectionHost,\n+\t\toptions: { indexProjectionAtoms?: boolean } = {},\n+\t) {\n+\t\tthis.#storage = storage;\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}\n+\t#indexOptions(adopting = false) {\n+\t\tconst mode = this.#state.read(\"host\", \"projection-atom-index-mode\");\n+\t\tconst expected = this.#indexProjectionAtoms ? 1 : 0;\n+\t\tif (mode !== undefined && mode !== expected) throw Error(\"writer atom indexing mode mismatch\");\n+\t\tif (mode === undefined && this.#indexProjectionAtoms && (!adopting || this.#state.read(\"atoms:meta\", \"length\")))\n+\t\t\tthrow Error(\"writer atom indexing requires fresh adoption\");\n+\t\tif (mode === undefined && adopting) this.#state.write(\"host\", \"projection-atom-index-mode\", expected);\n+\t\treturn { indexAcceptedAtom: this.#indexProjectionAtoms ? indexAcceptedProjectionAtom : undefined };\n+\t}\n+\n+\tsource(): WriterSource {\n+\t\tthis.#log.refreshSequence();\n+\t\tconst shared = this.#storage.sql.exec(\"SELECT value FROM counts WHERE name = 'shared'\").toArray() as {\n+\t\t\tvalue: number;\n+\t\t}[];\n+\t\tif (!Number.isSafeInteger(shared[0]?.value) || shared[0]!.value < 0)\n+\t\t\tthrow new Error(\"canonical shared head must be established before writer adoption\");\n+\t\treturn { generation: this.#log.generation(), logLength: this.#log.seq(), sharedVersion: shared[0]!.value };\n+\t}\n+\tstatic #same(a: WriterSource | undefined, b: WriterSource): boolean {\n+\t\treturn a?.generation === b.generation && a.logLength === b.logLength && a.sharedVersion === b.sharedVersion;\n+\t}\n+\troot(): WriterRoot {\n+\t\tconst root = this.#state.read(\"host\", \"canonical-root\") as WriterRoot | undefined;\n+\t\tif (root?.format !== 1 || !/^[a-f0-9]{64}$/.test(root.digest) || !SqliteWriterHost.#same(root, this.source()))\n+\t\t\tthrow new Error(\"writer canonical root is missing or stale\");\n+\t\treturn root;\n+\t}\n+\tstatic #sync(value: unknown): void {\n+\t\tif (value && (typeof value === \"object\" || typeof value === \"function\") && \"then\" in value)\n+\t\t\tthrow new Error(\"writer transaction callbacks must be synchronous\");\n+\t}\n+\t/** Resume one bounded adoption page against an exact source and prior digest. */\n+\tadoptVerifiedPage(\n+\t\tinput: {\n+\t\t\texpected: WriterSource;\n+\t\t\tfrom: number;\n+\t\t\tdigest: string;\n+\t\t\tmaxEntries: number;\n+\t\t\tmaxBytes: number;\n+\t\t},\n+\t\tvalidateAuthority: () => void,\n+\t) {\n+\t\treturn this.#storage.transactionSync(() => {\n+\t\t\tSqliteWriterHost.#sync(validateAuthority());\n+\t\t\tif (!SqliteWriterHost.#same(input.expected, this.source())) throw new Error(\"adoption source changed\");\n+\t\t\tif (\n+\t\t\t\t!Number.isSafeInteger(input.from) ||\n+\t\t\t\tinput.from < 0 ||\n+\t\t\t\t!Number.isSafeInteger(input.maxEntries) ||\n+\t\t\t\tinput.maxEntries < 1 ||\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+\t\t\tconst request = JSON.stringify([\n+\t\t\t\tinput.expected.generation,\n+\t\t\t\tinput.expected.logLength,\n+\t\t\t\tinput.expected.sharedVersion,\n+\t\t\t\tinput.from,\n+\t\t\t\tinput.digest,\n+\t\t\t\tinput.maxEntries,\n+\t\t\t\tinput.maxBytes,\n+\t\t\t]);\n+\t\t\tconst previous = this.#state.read(\"host\", \"adoption-page-receipt\") as\n+\t\t\t\t| { request: string; result: { next: number; ready: boolean; digest: string } }\n+\t\t\t\t| undefined;\n+\t\t\tif (previous?.request === request) return previous.result;\n+\t\t\tconst cursor = this.#state.read(\"host\", \"adoption-root\") as { next: number; digest: string } | undefined;\n+\t\t\tif ((cursor?.next ?? 0) !== input.from || (cursor?.digest ?? \"\") !== input.digest)\n+\t\t\t\tthrow new Error(\"adoption cursor or digest changed\");\n+\t\t\tconst page = this.adoptPage(input.from, input, validateAuthority);\n+\t\t\tconst root = this.#state.read(\"host\", \"adoption-root\") as { digest: string };\n+\t\t\tconst result = { next: page.next, ready: page.ready, digest: root.digest };\n+\t\t\tthis.#state.write(\"host\", \"adoption-page-receipt\", { request, result });\n+\t\t\treturn result;\n+\t\t});\n+\t}\n+\tadoptPage(from: number, limits: { maxEntries: number; maxBytes: number }, validateAuthority: () => void) {\n+\t\treturn this.#storage.transactionSync(() => {\n+\t\t\tSqliteWriterHost.#sync(validateAuthority());\n+\t\t\tconst source = this.source();\n+\t\t\tconst indexOptions = this.#indexOptions(true);\n+\t\t\tconst log = this.#log;\n+\t\t\tconst previous = this.#state.read(\"host\", \"adoption-root\") as\n+\t\t\t\t| { source: WriterSource; next: number; digest: string }\n+\t\t\t\t| undefined;\n+\t\t\tif (\n+\t\t\t\t(from === 0 && previous) ||\n+\t\t\t\t(from > 0 && (!previous || previous.next !== from || !SqliteWriterHost.#same(previous.source, source)))\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\t\t},\n+\t\t\t\tindexOptions,\n+\t\t\t);\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+\t\t\t\tthis.#state.write(\"host\", \"canonical\", source);\n+\t\t\t\tthis.#state.write(\"host\", \"canonical-root\", { format: 1, ...source, digest } satisfies WriterRoot);\n+\t\t\t}\n+\t\t\treturn result;\n+\t\t});\n+\t}\n+\t/** Read through the existing call adapter with persistent mutations forbidden. */\n+\treadCalls<T>(input: {\n+\t\texpected: WriterSource;\n+\t\tvalidateAuthority(): void;\n+\t\tservices?: Pick<ProjectOptions, \"hasBlob\" | \"whole\">;\n+\t\toperation(calls: EngineProject): T;\n+\t}): T {\n+\t\treturn this.#storage.transactionSync(() => {\n+\t\t\tSqliteWriterHost.#sync(input.validateAuthority());\n+\t\t\tconst source = this.source();\n+\t\t\tthis.root();\n+\t\t\tif (!SqliteWriterHost.#same(input.expected, source)) throw new Error(\"reader source is stale\");\n+\t\t\tconst refuse = () => {\n+\t\t\t\tthrow new Error(\"indexed read attempted to mutate persistent state\");\n+\t\t\t};\n+\t\t\tconst readOnly: GraphStateStorage = {\n+\t\t\t\tread: (collection, key) => this.#state.read(collection, key),\n+\t\t\t\tentries: (collection) => this.#state.entries(collection),\n+\t\t\t\twrite: refuse,\n+\t\t\t\tremove: refuse,\n+\t\t\t\ttransaction: (body) => this.#storage.transactionSync(body),\n+\t\t\t};\n+\t\t\tconst projection = this.#projection?.open({ state: this.#state, log: this.#log, root: this.root() });\n+\t\t\ttry {\n+\t\t\t\tconst project = Project.openWriter({ append: refuse }, readOnly, source.logLength, {\n+\t\t\t\t\t...input.services,\n+\t\t\t\t\t...(input.services?.whole ? { whole: { read: input.services.whole.read, keep: refuse } } : {}),\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));\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+\t\t\t\treturn result;\n+\t\t\t} finally {\n+\t\t\t\tSqliteWriterHost.#sync(projection?.close());\n+\t\t\t}\n+\t\t});\n+\t}\n+\n+\t/** Reuse the existing call adapter within one fenced writer transaction. */\n+\trunCalls<T>(input: {\n+\t\texpected: WriterSource;\n+\t\tvalidateAuthority(): void;\n+\t\tcheckerReady: boolean;\n+\t\tservices?: Pick<ProjectOptions, \"hasBlob\" | \"whole\">;\n+\t\toperation(calls: EngineProject): T;\n+\t\tcommitReceipt(result: NoInfer<T>, source: WriterSource): void;\n+\t}): T {\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\tcalls.setCheckerReady(input.checkerReady);\n+\t\t\t\treturn input.operation(calls);\n+\t\t\t},\n+\t\t});\n+\t}\n+\t/** No asynchronous gap is permitted between authority validation and commit. */\n+\trun<T>(input: {\n+\t\texpected: WriterSource;\n+\t\tvalidateAuthority(): void;\n+\t\toperation(project: Project): T;\n+\t\tservices?: Pick<ProjectOptions, \"hasBlob\" | \"whole\">;\n+\t\tcommitReceipt(result: NoInfer<T>, source: WriterSource): void;\n+\t}): T {\n+\t\ttry {\n+\t\t\treturn this.#storage.transactionSync(() => {\n+\t\t\t\tSqliteWriterHost.#sync(input.validateAuthority());\n+\t\t\t\tconst source = this.source();\n+\t\t\t\tconst root = this.root();\n+\t\t\t\tconst bound = this.#state.read(\"host\", \"canonical\") as WriterSource | undefined;\n+\t\t\t\tif (!SqliteWriterHost.#same(input.expected, source) || !SqliteWriterHost.#same(bound, source))\n+\t\t\t\t\tthrow new Error(\"writer source or adopted generation is stale\");\n+\t\t\t\tconst projection = this.#projection?.open({ state: this.#state, log: this.#log, root });\n+\t\t\t\ttry {\n+\t\t\t\t\tconst project = Project.openWriter(this.#log, this.#state, source.logLength, {\n+\t\t\t\t\t\t...input.services,\n+\t\t\t\t\t\t...this.#indexOptions(),\n+\t\t\t\t\t\treadViewProvider: projection?.readViewProvider,\n+\t\t\t\t\t\tshapes: this.#log.shapes(),\n+\t\t\t\t\t\tnow: () => Date.now(),\n+\t\t\t\t\t});\n+\t\t\t\t\tconst result = input.operation(project);\n+\t\t\t\t\tSqliteWriterHost.#sync(result);\n+\t\t\t\t\tSqliteWriterHost.#sync(input.validateAuthority());\n+\t\t\t\t\tconst committed = this.source();\n+\t\t\t\t\tthis.#state.write(\"host\", \"canonical\", committed);\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\tSqliteWriterHost.#sync(input.commitReceipt(result, committed));\n+\t\t\t\t\treturn result;\n+\t\t\t\t} finally {\n+\t\t\t\t\tSqliteWriterHost.#sync(projection?.close());\n+\t\t\t\t}\n+\t\t\t});\n+\t\t} catch (error) {\n+\t\t\t// The Project was scoped to the transaction and is discarded. Restore\n+\t\t\t// SqliteLog's cached sequence after an enclosing rollback as well.\n+\t\t\tthis.#log.refreshSequence();\n+\t\t\tthrow error;\n+\t\t}\n+\t}\n+}"},{"path":"server/test/helpers.ts","added":2,"removed":2,"diff":"--- a/server/test/helpers.ts\n+++ b/server/test/helpers.ts\n@@ -5,8 +5,8 @@\n import { DatabaseSync } from \"node:sqlite\";\n import type { SqliteStorage } from \"../src/engine-project.ts\";\n \n-export function memoryStorage(): SqliteStorage & { db: DatabaseSync } {\n-\tconst db = new DatabaseSync(\":memory:\");\n+export function memoryStorage(filename = \":memory:\"): SqliteStorage & { db: DatabaseSync } {\n+\tconst db = new DatabaseSync(filename);\n \tlet depth = 0;\n \treturn {\n \t\tdb,"},{"path":"server/test/writer-host.test.ts","added":136,"removed":0,"diff":"--- /dev/null\n+++ b/server/test/writer-host.test.ts\n@@ -0,0 +1,136 @@\n+import assert from \"node:assert/strict\";\n+import { mkdtempSync, rmdirSync, unlinkSync } from \"node:fs\";\n+import { tmpdir } from \"node:os\";\n+import { join } from \"node:path\";\n+import { test } from \"node:test\";\n+import { answer } from \"../../worker/project/http.ts\";\n+import { MemoryStore, Project } from \"../../worker/project/project.ts\";\n+import { 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(\"open server adopts and records through its call adapter without full-history loading\", (t) => {\n+\tconst directory = mkdtempSync(join(tmpdir(), \"abso-core-writer-\"));\n+\tconst filename = join(directory, \"state.sqlite\");\n+\tlet storage = memoryStorage(filename);\n+\tconst reopen = () => {\n+\t\tstorage.db.close();\n+\t\tstorage = memoryStorage(filename);\n+\t};\n+\tt.after(() => {\n+\t\tstorage.db.close();\n+\t\tunlinkSync(filename);\n+\t\trmdirSync(directory);\n+\t});\n+\tconst memory = new MemoryStore();\n+\tconst oracle = new Project(memory);\n+\toracle.init({ \"a.txt\": \"one\\ntwo\\n\" }, 0);\n+\toracle.record(\"alice\", { \"a.txt\": \"ONE\\ntwo\\n\" }, 1);\n+\toracle.publish(\"alice\", \"First\", 2);\n+\toracle.move(\"alice\", \"a.txt\", \"b.txt\", 3);\n+\toracle.publish(\"alice\", \"Move\", 4);\n+\tnew SqliteLog(storage).append(memory.entries);\n+\tSqliteWriterState.initialize(storage);\n+\tconst namespace = \"open-server-capacity\";\n+\tconst host = () => new SqliteWriterHost(storage, namespace, undefined, { indexProjectionAtoms: true });\n+\tconst expected = host().source();\n+\tconst canonicalBefore = storage.db.prepare(\"SELECT * FROM log ORDER BY seq, part\").all();\n+\tt.mock.method(Project, \"load\", () => {\n+\t\tthrow Error(\"full-history loading forbidden\");\n+\t});\n+\tlet from = 0,\n+\t\tdigest = \"\",\n+\t\tready = false;\n+\twhile (!ready) {\n+\t\tconst page = host().adoptVerifiedPage({ expected, from, digest, maxEntries: 2, maxBytes: 16384 }, () => {});\n+\t\tassert.deepEqual(\n+\t\t\thost().adoptVerifiedPage({ expected, from, digest, maxEntries: 2, maxBytes: 16384 }, () => {}),\n+\t\t\tpage,\n+\t\t);\n+\t\tfrom = page.next;\n+\t\tdigest = page.digest;\n+\t\tready = page.ready;\n+\t\treopen();\n+\t}\n+\tassert.deepEqual(storage.db.prepare(\"SELECT * FROM log ORDER BY seq, part\").all(), canonicalBefore);\n+\tlet state = new SqliteWriterState(storage, namespace);\n+\tconst projection = new SqliteProjectionStore(\n+\t\t{ database: \"project\", namespace: \"views\", registry: \"roots\", defaultFile: \"a.txt\" },\n+\t\t1,\n+\t\t{ indexedAtoms: true },\n+\t);\n+\tlet pages = 0;\n+\twhile (\n+\t\t!projection.adopt({\n+\t\t\tstate,\n+\t\t\texpected: host().root(),\n+\t\t\tcurrentRoot: () => host().root(),\n+\t\t\tmaxAtoms: 1,\n+\t\t\tmaxVersions: 1,\n+\t\t\tmaxSteps: 2,\n+\t\t}).ready\n+\t)\n+\t\tassert.ok(++pages < 1000);\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+\t\t\texpected: writer().source(),\n+\t\t\tvalidateAuthority: () => {},\n+\t\t\tcheckerReady: false,\n+\t\t\toperation: (calls) => answer(calls, operation, \"alice\", body),\n+\t\t\tcommitReceipt: (result, source) => {\n+\t\t\t\tstate.write(\"receipts\", operation, { result, source });\n+\t\t\t\tif (failReceipt) throw Error(\"receipt failure\");\n+\t\t\t},\n+\t\t});\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});\n+\tconst before = rows();\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 published = run(\"publish\", { message: \"Disk first\" });\n+\tassert.equal(published.status, 200);\n+\tassert.equal((published.body as { ok: boolean }).ok, true);\n+\treopen();\n+\tstate = new SqliteWriterState(storage, namespace);\n+\tconst beforeRead = rows();\n+\tassert.equal(\n+\t\twriter().readCalls({\n+\t\t\texpected: writer().source(),\n+\t\t\tvalidateAuthority: () => {},\n+\t\t\toperation: (calls) => calls.shared().files[\"b.txt\"],\n+\t\t}),\n+\t\t\"finished\\n\",\n+\t);\n+\tassert.deepEqual(rows(), beforeRead);\n+\tassert.throws(\n+\t\t() =>\n+\t\t\twriter().runCalls({\n+\t\t\t\texpected,\n+\t\t\t\tvalidateAuthority: () => {},\n+\t\t\t\tcheckerReady: false,\n+\t\t\t\toperation: () => undefined,\n+\t\t\t\tcommitReceipt: () => {},\n+\t\t\t}),\n+\t\t/stale/,\n+\t);\n+\tconst committed = rows();\n+\tassert.throws(\n+\t\t() =>\n+\t\t\twriter().runCalls({\n+\t\t\t\texpected: writer().source(),\n+\t\t\t\tvalidateAuthority: () => {\n+\t\t\t\t\tthrow Error(\"revoked authority\");\n+\t\t\t\t},\n+\t\t\t\tcheckerReady: false,\n+\t\t\t\toperation: () => undefined,\n+\t\t\t\tcommitReceipt: () => {},\n+\t\t\t}),\n+\t\t/revoked authority/,\n+\t);\n+\tassert.deepEqual(rows(), committed);\n+});"},{"path":"src/engine/graph.ts","added":1,"removed":1,"diff":"--- a/src/engine/graph.ts\n+++ b/src/engine/graph.ts\n@@ -1089,7 +1089,7 @@\n \t\t// Accept.\n \t\tconst frozen = freezeAtom(\n \t\t\tatom,\n-\t\t\t(id) => this.#atoms[seqOf(id)]!.id,\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);"},{"path":"src/engine/test/graph-metadata-indexed.test.ts","added":25,"removed":0,"diff":"--- a/src/engine/test/graph-metadata-indexed.test.ts\n+++ b/src/engine/test/graph-metadata-indexed.test.ts\n@@ -31,3 +31,28 @@\n \t\tdb.db.close();\n \t}\n });\n+\n+test(\"accepting an edit does not decode historical atoms to canonicalize identities\", () => {\n+\tconst db = new SqlState();\n+\ttry {\n+\t\tconst repo = Repo.init({ \"a.txt\": `first\\n${\"old\\n\".repeat(8191)}` });\n+\t\tconst graph = new Graph({ storage: db });\n+\t\tgraph.add(repo.graph.atom(\"a0\"));\n+\t\tconst edit = repo.edit({ edits: [{ file: \"a.txt\", old: \"first\\n\", new: \"changed\\n\" }] });\n+\t\tassert.ok(edit.deps.includes(\"a0\"));\n+\t\tconst read = db.read.bind(db);\n+\t\tdb.read = (collection, key) => {\n+\t\t\tif (collection === \"atoms\") throw Error(\"historical atom payload read forbidden\");\n+\t\t\treturn read(collection, key);\n+\t\t};\n+\t\tgraph.add(edit);\n+\t\tassert.equal(graph.size, 2);\n+\t\tassert.equal(graph.idOfSeq(1), edit.id);\n+\t\tassert.equal(graph.lamport(edit.id), repo.graph.lamport(edit.id));\n+\t\tassert.deepEqual(graph.filesOf(edit.id), repo.graph.filesOf(edit.id));\n+\t\tdb.read = read;\n+\t\tassert.deepEqual(graph.atom(edit.id), repo.graph.atom(edit.id));\n+\t} finally {\n+\t\tdb.db.close();\n+\t}\n+});"}],"ci":null}