{"draft":null,"from":80,"to":318,"files":[{"path":"server/test/project-object-disk-first.test.ts","added":670,"removed":0,"diff":"--- /dev/null\n+++ b/server/test/project-object-disk-first.test.ts\n@@ -0,0 +1,670 @@\n+import assert from \"node:assert/strict\";\n+import { createRequire, 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 { GitDiskIntake } from \"../src/git-disk-intake.ts\";\n+import { GitIntakeLimitError } from \"../src/git-intake-limit.ts\";\n+import { MemoryFS } from \"../src/memory-fs.ts\";\n+import { memoryStorage } from \"./helpers.ts\";\n+\n+const hooks = registerHooks({\n+\tresolve(specifier, context, next) {\n+\t\tif (specifier === \"cloudflare:workers\")\n+\t\t\treturn {\n+\t\t\t\turl: `data:text/javascript,${encodeURIComponent(\"export class DurableObject { constructor(ctx, env) { this.ctx = ctx; this.env = env; } }\")}`,\n+\t\t\t\tshortCircuit: true,\n+\t\t\t};\n+\t\treturn next(specifier, context);\n+\t},\n+});\n+const { ProjectObject } = await import(\"../src/project-object.ts\");\n+hooks.deregister();\n+\n+for (const disk of [false, true])\n+\ttest(`failed intake retries across cold objects 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\tlet alarm: number | null = null;\n+\t\tconst context = {\n+\t\t\tid: { toString: () => \"retry\" },\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 [name, item] of Object.entries(key)) values.set(name, item);\n+\t\t\t\t},\n+\t\t\t\tdelete: async (key: string) => values.delete(key),\n+\t\t\t\tgetAlarm: async () => alarm,\n+\t\t\t\tsetAlarm: async (value: number) => {\n+\t\t\t\t\talarm = value;\n+\t\t\t\t},\n+\t\t\t},\n+\t\t};\n+\t\tconst object = (enabled: boolean) =>\n+\t\t\tnew ProjectObject(\n+\t\t\t\tcontext as never,\n+\t\t\t\t{\n+\t\t\t\t\tABSO_DISK_FIRST: disk ? \"on\" : \"off\",\n+\t\t\t\t\tABSO_ARTIFACTS: enabled ? \"on\" : \"off\",\n+\t\t\t\t\tARTIFACTS: {},\n+\t\t\t\t} as never,\n+\t\t\t);\n+\t\tassert.equal((await object(false).call(\"retry\", \"init\", undefined, { files: { \"a.txt\": \"first\\n\" } })).status, 200);\n+\t\tlet ready = false;\n+\t\tfor (let page = 0; page < 100; page++) {\n+\t\t\tif ((await object(false).call(\"retry\", \"status\", undefined, {})).status === 200) {\n+\t\t\t\tready = true;\n+\t\t\t\tbreak;\n+\t\t\t}\n+\t\t}\n+\t\tassert.equal(ready, true);\n+\t\tlet fails = true;\n+\t\tt.mock.method(ProjectObject.prototype, \"gitSync\", async () => {\n+\t\t\tif (fails) throw Error(\"transient intake failure\");\n+\t\t\treturn null;\n+\t\t});\n+\t\tfor (const [index, minutes] of [1, 5, 15, 15].entries()) {\n+\t\t\talarm = null;\n+\t\t\tconst before = Date.now();\n+\t\t\tawait object(true).alarm();\n+\t\t\tassert.equal(values.get(\"git:retry-attempts\"), index + 1);\n+\t\t\tassert.ok(alarm !== null && alarm >= before + minutes * 60000 && alarm <= Date.now() + minutes * 60000);\n+\t\t\tassert.equal(values.get(\"pushed\"), undefined);\n+\t\t}\n+\t\tfails = false;\n+\t\tvalues.set(\"pushed\", { version: Number.MAX_SAFE_INTEGER });\n+\t\talarm = null;\n+\t\tawait object(true).alarm();\n+\t\tassert.equal(values.has(\"git:retry-attempts\"), false);\n+\t\tassert.equal(values.has(\"git:error\"), false);\n+\t});\n+\n+test(\"size refusals survive cold objects, retry changed heads or policy, and prevent outgoing pushes\", async (t) => {\n+\tlet scheduled = 0;\n+\tconst storage = memoryStorage();\n+\tt.after(() => storage.db.close());\n+\tconst values = new Map<string, unknown>();\n+\tconst context = {\n+\t\tid: { toString: () => \"size-refusal\" },\n+\t\tstorage: {\n+\t\t\t...storage,\n+\t\t\tget: async (key: string) => values.get(key),\n+\t\t\tput: async (key: string | Record<string, unknown>, value?: unknown) => {\n+\t\t\t\tif (typeof key === \"string\") values.set(key, value);\n+\t\t\t\telse for (const [name, item] of Object.entries(key)) values.set(name, item);\n+\t\t\t},\n+\t\t\tdelete: async (key: string) => values.delete(key),\n+\t\t\tgetAlarm: async () => null,\n+\t\t\tsetAlarm: async (value: number) => {\n+\t\t\t\tscheduled = value;\n+\t\t\t},\n+\t\t},\n+\t};\n+\tconst artifacts = {\n+\t\tget: async () => ({\n+\t\t\tinfo: async () => ({ remote: \"https://artifacts.invalid/size\" }),\n+\t\t\tcreateToken: async () => ({ plaintext: \"invented-test-token\" }),\n+\t\t\t[Symbol.dispose]() {},\n+\t\t}),\n+\t};\n+\tconst object = (enabled = true) =>\n+\t\tnew ProjectObject(\n+\t\t\tcontext as never,\n+\t\t\t{\n+\t\t\t\tABSO_DISK_FIRST: \"on\",\n+\t\t\t\tABSO_ARTIFACTS: enabled ? \"on\" : \"off\",\n+\t\t\t\tARTIFACTS: artifacts,\n+\t\t\t} as never,\n+\t\t);\n+\tassert.equal(\n+\t\t(await object(false).call(\"size-refusal\", \"init\", undefined, { files: { \"a.txt\": \"original\\n\" } })).status,\n+\t\t200,\n+\t);\n+\tlet ready = false;\n+\tfor (let page = 0; page < 100; page++) {\n+\t\tconst result = await object(false).call(\"size-refusal\", \"status\", undefined, {});\n+\t\tif (result.status === 200) {\n+\t\t\tready = true;\n+\t\t\tbreak;\n+\t\t}\n+\t\tassert.equal(result.status, 503);\n+\t}\n+\tassert.equal(ready, true, \"project indexing must finish before testing intake refusals\");\n+\tlet head = \"a\".repeat(40),\n+\t\tdownloads = 0,\n+\t\tpushes = 0,\n+\t\ttransient = false;\n+\tt.mock.method(git, \"listServerRefs\", async () => [{ ref: \"refs/heads/main\", oid: head }]);\n+\tt.mock.method(git, \"clone\", async () => {\n+\t\tdownloads++;\n+\t\tif (transient) throw Error(\"temporary network failure\");\n+\t\tthrow new GitIntakeLimitError(\"decoded\", \"Git pack exceeds total decoded byte limit\");\n+\t});\n+\tt.mock.method(git, \"push\", async () => {\n+\t\tpushes++;\n+\t\treturn { ok: true };\n+\t});\n+\tawait assert.rejects(() => object().gitSync(), /decoded byte limit/);\n+\tawait assert.rejects(() => object().gitSync(), /decoded byte limit/);\n+\tassert.equal(downloads, 1);\n+\tassert.equal(values.get(\"git:head\"), undefined);\n+\tassert.equal((await object().out()).version, 0);\n+\tassert.match(JSON.stringify((await object().out()).git.error), /decoded byte limit/);\n+\tawait object().alarm();\n+\tassert.ok(scheduled >= Date.now() + 59_000);\n+\tassert.equal(values.get(\"git:retry-attempts\"), 1);\n+\tassert.equal(downloads, 1);\n+\tassert.equal(pushes, 0);\n+\thead = \"b\".repeat(40);\n+\tawait assert.rejects(() => object().gitSync(), /decoded byte limit/);\n+\tassert.equal(downloads, 2);\n+\tvalues.set(\"git:size-refusal\", { ...(values.get(\"git:size-refusal\") as object), policy: \"old-policy\" });\n+\tawait assert.rejects(() => object().gitSync(), /decoded byte limit/);\n+\tassert.equal(downloads, 3);\n+\thead = \"c\".repeat(40);\n+\ttransient = true;\n+\tawait assert.rejects(() => object().gitSync(), /temporary network failure/);\n+\tawait assert.rejects(() => object().gitSync(), /temporary network failure/);\n+\tassert.equal(downloads, 5);\n+\tassert.equal(values.has(\"git:size-refusal\"), false);\n+\tawait object().alarm();\n+\tassert.equal(pushes, 0);\n+\tassertGitScratchEmpty(storage);\n+});\n+\n+function assertGitScratchEmpty(storage: ReturnType<typeof memoryStorage>) {\n+\tfor (const table of [\n+\t\t\"git_pack_spool\",\n+\t\t\"git_pack_resolve\",\n+\t\t\"git_object_meta\",\n+\t\t\"git_object_bytes\",\n+\t\t\"git_object_budget\",\n+\t])\n+\t\tassert.equal(storage.db.prepare(`SELECT COUNT(*) AS n FROM ${table}`).get()!.n, 0, table);\n+}\n+\n+/** Keep transport synthetic while exercising the real disk pack decoder and cache. */\n+async function cloneFixture(remote: MemoryFS, options: Parameters<typeof git.clone>[0]) {\n+\tconst intake = (options.cache as Record<symbol, GitDiskIntake> | undefined)?.[Symbol.for(\"abso.git.disk-pack\")];\n+\tif (!intake) {\n+\t\t(options.fs as MemoryFS).entries = structuredClone(remote.entries);\n+\t\treturn;\n+\t}\n+\tconst oids = [...remote.entries.keys()].flatMap((path) => {\n+\t\tconst match = /\\/objects\\/([0-9a-f]{2})\\/([0-9a-f]{38})$/.exec(path);\n+\t\treturn match ? [match[1]! + match[2]!] : [];\n+\t});\n+\tconst pack = (await git.packObjects({ fs: remote, dir: \"/repo\", oids, write: false })).packfile!;\n+\tconst { Inflate } = createRequire(import.meta.url)(\"pako\");\n+\tawait intake.ingest([pack], () => new Inflate({ chunkSize: 16384 }));\n+\tawait git.init({ fs: options.fs, dir: options.dir, defaultBranch: \"main\" });\n+\tawait git.writeRef({\n+\t\tfs: options.fs,\n+\t\tdir: options.dir,\n+\t\tref: \"main\",\n+\t\tvalue: await git.resolveRef({ fs: remote, dir: \"/repo\", ref: \"main\" }),\n+\t});\n+}\n+\n+test(\"empty disk projects and unloadable legacy projects preserve lookup fallbacks\", async (t) => {\n+\tconst storage = memoryStorage();\n+\tt.after(() => storage.db.close());\n+\tconst context = { id: { toString: () => \"empty\" }, storage: { ...storage, get: async () => undefined } };\n+\tconst disk = new ProjectObject(context as never, { ABSO_DISK_FIRST: \"on\" } as never);\n+\tassert.deepEqual(await disk.call(\"empty\", \"status\", undefined, {}), {\n+\t\tstatus: 404,\n+\t\tbody: { error: \"no such project; run init first\" },\n+\t});\n+\tassert.deepEqual(await disk.agents(\"empty\"), []);\n+\tassert.deepEqual(await disk.news(\"empty\", [{ from: \"alice\", issue: null, text: \"Hello\" }]), [{ to: [] }]);\n+\tawait disk.alarm();\n+\tt.mock.method(EngineProject, \"open\", () => {\n+\t\tthrow Error(\"unloadable legacy log\");\n+\t});\n+\tconst legacy = new ProjectObject(context as never, {} as never);\n+\tassert.deepEqual(await legacy.agents(\"empty\"), []);\n+\tassert.deepEqual(await legacy.news(\"empty\", [{ from: \"alice\", issue: null, text: \"Hello\" }]), [{ to: [] }]);\n+\tawait legacy.alarm();\n+});\n+\n+test(\"ProjectObject disk-first calls survive cold objects without replay\", async (t) => {\n+\tconst storage = memoryStorage();\n+\tt.after(() => storage.db.close());\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+\t\t\t...storage,\n+\t\t\tget: async (key: string) => {\n+\t\t\t\tif (key === \"readers\" && onReaders) {\n+\t\t\t\t\tconst action = onReaders;\n+\t\t\t\t\tonReaders = undefined;\n+\t\t\t\t\tawait action();\n+\t\t\t\t}\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+\t\t\tdelete: async (key: string) => values.delete(key),\n+\t\t\tgetAlarm: async () => alarm,\n+\t\t\tsetAlarm: async (value: number) => {\n+\t\t\t\talarm = value;\n+\t\t\t},\n+\t\t},\n+\t};\n+\tconst object = () =>\n+\t\tnew ProjectObject(\n+\t\t\tcontext as never,\n+\t\t\t{ ABSO_DISK_FIRST: \"on\", ABSO_ARTIFACTS: \"off\", KEY_HMAC_SECRET: \"invented-test-secret\" } as never,\n+\t\t);\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, requestId?: string) => {\n+\t\tfor (let page = 0; page < 100; page++) {\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+\t\t\t}\n+\t\t\tassert.notEqual(alarm, null);\n+\t\t\tawait object().alarm();\n+\t\t}\n+\t\tthrow Error(\"adoption did not finish\");\n+\t};\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+\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+\tconst feed = await call(\"feed\", undefined, { from: \"0\", limit: \"2\" });\n+\tassert.equal(feed.status, 200);\n+\tassert.ok((feed.body as { next: number }).next > 0);\n+\tassert.deepEqual(await object().agents(\"project\"), [\"alice\"]);\n+\tassert.equal((await object().out()).version, 1);\n+\tassert.deepEqual(await object().news(\"project\", [{ from: \"bob\", issue: null, text: \"Hello\", to: [\"alice\"] }]), [\n+\t\t{ to: [\"alice\"] },\n+\t]);\n+\tassert.equal((await call(\"status\", undefined, {})).status, 200);\n+\tfor (const agent of [\"alice\", \"bob\"]) assert.equal((await call(\"sync\", agent, {})).status, 200);\n+\tassert.equal((await call(\"record\", \"alice\", { files: { \"a.txt\": \"Alice's change\\n\" } })).status, 200);\n+\tassert.equal((await call(\"record\", \"bob\", { files: { \"a.txt\": \"Bob's change\\n\" } })).status, 200);\n+\tassert.equal((await call(\"publish\", \"alice\", { message: \"Alice wins first\" })).status, 200);\n+\tconst collision = await call(\"publish\", \"bob\", { message: \"Bob conflicts\" });\n+\tassert.equal((collision.body as { ok: boolean }).ok, false);\n+\tassert.equal((collision.body as { collisions: unknown[] }).collisions.length, 1);\n+\tconst historical = await call(\"file\", undefined, { path: \"a.txt\", version: \"1\" });\n+\tassert.equal(historical.status, 200);\n+\tassert.match(JSON.stringify(historical.body), /changed/);\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 stable = rows();\n+\tconst disabled = new ProjectObject(context as never, { ABSO_DISK_FIRST: \"off\" } as never);\n+\tconst held = await disabled.call(\"project\", \"record\", \"alice\", { files: { \"a.txt\": \"legacy write\\n\" } });\n+\tassert.equal(held.status, 409);\n+\tassert.match(JSON.stringify(held.body), /enable ABSO_DISK_FIRST/);\n+\tassert.equal(await disabled.gitSync(), null);\n+\tassert.deepEqual(rows(), stable);\n+\tassert.equal((await call(\"status\", undefined, {})).status, 200, \"re-enabling disk mode preserves the valid root\");\n+\tconst originalAnnounce = EngineProject.prototype.announce;\n+\tconst failingAnnounce = t.mock.method(\n+\t\tEngineProject.prototype,\n+\t\t\"announce\",\n+\t\tfunction (this: EngineProject, ...args: Parameters<EngineProject[\"announce\"]>) {\n+\t\t\toriginalAnnounce.apply(this, args);\n+\t\t\tthrow Error(\"injected after announce\");\n+\t\t},\n+\t);\n+\tawait assert.rejects(\n+\t\t() => object().news(\"project\", [{ from: \"bob\", issue: null, text: \"Must roll back\", to: [\"alice\"] }]),\n+\t\t/injected after announce/,\n+\t);\n+\tassert.deepEqual(rows(), stable);\n+\tfailingAnnounce.mock.restore();\n+\tconst current = object();\n+\tonReaders = async () => {\n+\t\tawait current.revokeAgentKey(\"missing-test-key\", \"127.0.0.1\");\n+\t};\n+\tconst revoked = await current.call(\"project\", \"record\", \"alice\", { files: { \"a.txt\": \"unauthorized\\n\" } });\n+\tassert.equal(revoked.status, 409);\n+\tassert.equal((revoked.body as { retryable: boolean }).retryable, true);\n+\tassert.deepEqual(rows(), stable);\n+\tconst original = EngineProject.prototype.record;\n+\tt.mock.method(\n+\t\tEngineProject.prototype,\n+\t\t\"record\",\n+\t\tfunction (this: EngineProject, ...args: Parameters<EngineProject[\"record\"]>) {\n+\t\t\toriginal.apply(this, args);\n+\t\t\tthrow Error(\"injected after record\");\n+\t\t},\n+\t);\n+\tawait assert.rejects(\n+\t\t() => object().call(\"project\", \"record\", \"alice\", { files: { \"a.txt\": \"failed\\n\" } }),\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 failPush = true;\n+\tlet remoteFiles: MemoryFS | undefined;\n+\tt.mock.method(git, \"push\", async (options: Parameters<typeof git.push>[0]) => {\n+\t\tif (failPush) {\n+\t\t\tfailPush = false;\n+\t\t\tthrow Error(\"injected Artifacts transport failure\");\n+\t\t}\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\t// The remote owns its copy; the export's scratch files expire when push returns.\n+\t\tremoteFiles = new MemoryFS();\n+\t\tfor (const [path, entry] of (options.fs as MemoryFS).entries) {\n+\t\t\tremoteFiles.entries.set(\n+\t\t\t\tpath,\n+\t\t\t\tentry.kind === \"file\"\n+\t\t\t\t\t? { ...entry, data: new Uint8Array((await (options.fs as MemoryFS).readFile(path)) as Uint8Array) }\n+\t\t\t\t\t: { ...entry },\n+\t\t\t);\n+\t\t}\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+\t// Deliver the pending alarm: the fake storage must clear it as the host does.\n+\talarm = null;\n+\tawait bound().alarm();\n+\tassert.equal(pushed, 0);\n+\tassert.equal(values.get(\"pushed\"), undefined, \"failed transport must not acknowledge a push\");\n+\tassert.match(JSON.stringify(values.get(\"pushError\")), /injected Artifacts transport failure/);\n+\tassert.deepEqual(rows(), stable, \"failed remote transport leaves canonical state unchanged\");\n+\tassert.ok(alarm !== null && alarm > Date.now(), \"failed transport schedules a retry\");\n+\tawait bound().alarm();\n+\tassert.equal(pushed, 1);\n+\tassert.equal(values.get(\"pushError\"), undefined, \"cold retry clears the transport error\");\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\tawait cloneFixture(remote, options);\n+\t});\n+\tconst beforeIntake = rows();\n+\tconst originalRead = GitDiskIntake.prototype.read;\n+\tt.mock.method(GitDiskIntake.prototype, \"read\", function (this: GitDiskIntake, oid: string) {\n+\t\tif (oid === blob) throw Error(\"whole intake text blob forbidden\");\n+\t\treturn originalRead.call(this, oid);\n+\t});\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+\tassertGitScratchEmpty(storage);\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+\tassertGitScratchEmpty(storage);\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+\tassertGitScratchEmpty(storage);\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\tawait cloneFixture(remote, options);\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+}"}],"unmatched":[]}