{"version":108,"agent":"codex-prose-authorship-1","message":"Implement bounded sequential client recording for #606","time":1791788591360,"timeIso":"2026-10-12T07:03:11.360Z","changes":13,"change":1265,"files":["client/src/api.ts","client/src/commands.ts","client/src/record-batches.ts","client/test/record-batches.test.ts","worker/project/test/record-idempotence.test.ts"],"draft":null,"diff":[{"path":"client/src/api.ts","added":7,"removed":1,"diff":"--- a/client/src/api.ts\n+++ b/client/src/api.ts\n@@ -231,7 +231,13 @@\n \t\t\t\tawait new Promise((ok) => setTimeout(ok, 500));\n \t\t\t}\n \t\t}\n-\t\tconst text = await res.text();\n+\t\tlet text: string;\n+\t\ttry {\n+\t\t\ttext = await res.text();\n+\t\t} catch (err) {\n+\t\t\tconst reason = err instanceof Error ? err.message : String(err);\n+\t\t\tthrow new ApiError(`${method} ${path} response body ended unexpectedly: ${reason}`, res.status);\n+\t\t}\n \t\t// 409 is a refusal that says what to do (a drop took out lines your work builds on): print it as it is.\n \t\tif (!res.ok)\n \t\t\tthrow new ApiError("},{"path":"client/src/commands.ts","added":71,"removed":31,"diff":"--- a/client/src/commands.ts\n+++ b/client/src/commands.ts\n@@ -41,6 +41,7 @@\n import { withFolderLock } from \"./lock.ts\";\n import type { OnDisk } from \"./modes.ts\";\n import { applyMode, type FullMode, foldModes, onDisk, PLAIN, readKnownModes, writeKnownModes } from \"./modes.ts\";\n+import { batchRecordItems, sendRecordBatches } from \"./record-batches.ts\";\n import { type Refused, screenAnswer, unsafePath } from \"./safety.ts\";\n \n export {\n@@ -213,38 +214,77 @@\n \t\t.map(([rel]) => rel)\n \t\t.sort();\n \tif (sent === 0) return { sent: 0, paths, deleted, changed: [], news: undefined, leftOut, turnedBinary };\n-\tawait uploadBlobs(api, blobs);\n-\tconst answer = await api.record(\n-\t\tObject.fromEntries(files),\n-\t\t{},\n-\t\tmodes,\n-\t\tObject.fromEntries([...blobs].map(([rel, b]) => [rel, b.sha])),\n+\tconst items = paths.map((path) => ({\n+\t\tpath,\n+\t\t...(files.has(path) ? { text: files.get(path) } : {}),\n+\t\t...(modes[path] !== undefined ? { mode: modes[path] } : {}),\n+\t\t...(blobs.has(path) ? { blob: blobs.get(path)?.sha } : {}),\n+\t}));\n+\tconst batches = batchRecordItems(items);\n+\tlet batchBlobs = new Map<string, BlobToSend>();\n+\tconst uploaded = new Set<string>();\n+\tconst answers = await sendRecordBatches(\n+\t\tapi,\n+\t\tbatches,\n+\t\tasync (batch) => {\n+\t\t\tbatchBlobs = new Map(\n+\t\t\t\tbatch.paths.flatMap((path) => {\n+\t\t\t\t\tconst blob = blobs.get(path);\n+\t\t\t\t\treturn blob === undefined ? [] : [[path, blob] as const];\n+\t\t\t\t}),\n+\t\t\t);\n+\t\t\tfor (const [path, blob] of batchBlobs) {\n+\t\t\t\tif (uploaded.has(blob.sha)) continue;\n+\t\t\t\tawait uploadBlobs(api, new Map([[path, blob]]));\n+\t\t\t\tuploaded.add(blob.sha);\n+\t\t\t}\n+\t\t},\n+\t\tasync (batch, answer) => {\n+\t\t\tconst batchFiles = new Map(Object.entries(batch.files));\n+\t\t\t// Commit known state only after this batch is confirmed; earlier successful batches stay committed on later failure.\n+\t\t\tfor (const [rel, text] of batchFiles) if (text === null) forgetKnown(root, rel);\n+\t\t\tfor (const [rel, text] of batchFiles) if (text !== null) writeKnown(root, rel, text);\n+\t\t\tconst knownBlobs = readKnownBlobs(root);\n+\t\t\tif (Object.keys(batch.blobs).length > 0 || batch.paths.some((rel) => knownBlobs.has(rel))) {\n+\t\t\t\tfor (const rel of new Set([...Object.keys(batch.files), ...Object.keys(batch.blobs)])) knownBlobs.delete(rel);\n+\t\t\t\tfor (const [rel, sha] of Object.entries(batch.blobs)) {\n+\t\t\t\t\tforgetKnown(root, rel);\n+\t\t\t\t\tknownBlobs.set(rel, sha);\n+\t\t\t\t}\n+\t\t\t\twriteKnownBlobs(root, knownBlobs);\n+\t\t\t}\n+\t\t\tconst gone = Object.entries(batch.files)\n+\t\t\t\t.filter(([, text]) => text === null)\n+\t\t\t\t.map(([rel]) => rel);\n+\t\t\tconst knownModes = readKnownModes(root);\n+\t\t\tif (Object.keys(batch.modes).length > 0 || gone.some((rel) => knownModes.has(rel))) {\n+\t\t\t\tfoldModes(knownModes, batch.modes, gone);\n+\t\t\t\twriteKnownModes(root, knownModes);\n+\t\t\t}\n+\t\t\theard(root, [\n+\t\t\t\t...newsLines(answer.news),\n+\t\t\t\t...(answer.spelling ?? []).map(spellingText),\n+\t\t\t\t...(answer.uncomposed ?? []).map(uncomposedText),\n+\t\t\t]);\n+\t\t},\n \t);\n-\tif (!answer.ok) throw new Error(`the server refused the record: ${answer.reason ?? \"no reason given\"}`);\n-\t// Forget before writing: after a rename that changes only case, known/a.ts and known/A.ts are one file on Windows and macOS.\n-\tfor (const [rel, text] of files) if (text === null) forgetKnown(root, rel);\n-\tfor (const [rel, text] of files) if (text !== null) writeKnown(root, rel, text);\n-\tconst knownBlobs = readKnownBlobs(root);\n-\tif (blobs.size > 0 || [...files.keys()].some((rel) => knownBlobs.has(rel))) {\n-\t\tfor (const rel of files.keys()) knownBlobs.delete(rel);\n-\t\tfor (const [rel, b] of blobs) {\n-\t\t\tforgetKnown(root, rel);\n-\t\t\tknownBlobs.set(rel, b.sha);\n-\t\t}\n-\t\twriteKnownBlobs(root, knownBlobs);\n-\t}\n-\tconst gone = [...files].filter(([, text]) => text === null).map(([rel]) => rel);\n-\tconst knownModes = readKnownModes(root);\n-\tif (Object.keys(modes).length > 0 || gone.some((rel) => knownModes.has(rel))) {\n-\t\tfoldModes(knownModes, modes, gone);\n-\t\twriteKnownModes(root, knownModes);\n-\t}\n-\t// Another spelling of an existing file went in as that file (#49); a new name not in composed form gets a gentle word.\n-\theard(root, [\n-\t\t...newsLines(answer.news),\n-\t\t...(answer.spelling ?? []).map(spellingText),\n-\t\t...(answer.uncomposed ?? []).map(uncomposedText),\n-\t]);\n+\tconst changed = answers.flatMap((answer) => (Array.isArray(answer.changed) ? answer.changed : []));\n+\tconst changedCount = answers.some((answer) => typeof answer.changed === \"number\")\n+\t\t? answers.reduce(\n+\t\t\t\t(sum, answer) =>\n+\t\t\t\t\tsum +\n+\t\t\t\t\t(typeof answer.changed === \"number\"\n+\t\t\t\t\t\t? answer.changed\n+\t\t\t\t\t\t: Array.isArray(answer.changed)\n+\t\t\t\t\t\t\t? answer.changed.length\n+\t\t\t\t\t\t\t: 0),\n+\t\t\t\t0,\n+\t\t\t)\n+\t\t: changed;\n+\tconst news = answers.flatMap((answer) => newsLines(answer.news));\n+\tconst spelling = answers.flatMap((answer) => answer.spelling ?? []);\n+\tconst uncomposed = answers.flatMap((answer) => answer.uncomposed ?? []);\n+\tconst answer = { changed: changedCount, news, spelling, uncomposed };\n \tconst longPaths = longPathsOf(\n \t\troot,\n \t\t[...files].filter(([, text]) => text !== null).map(([path]) => path),"},{"path":"client/src/record-batches.ts","added":125,"removed":0,"diff":"--- /dev/null\n+++ b/client/src/record-batches.ts\n@@ -0,0 +1,125 @@\n+import { ApiError, type RecordAnswer } from \"./api.ts\";\n+import type { Mode, Modes } from \"./modes.ts\";\n+\n+/** One atomic path entry from the folder scan. */\n+export interface RecordItem {\n+\treadonly path: string;\n+\treadonly text?: string | null;\n+\treadonly mode?: Modes[string];\n+\treadonly blob?: string;\n+}\n+\n+/** A record request; a path's text, mode, and blob reference always travel together. */\n+export interface RecordBatch {\n+\treadonly files: Record<string, string | null>;\n+\treadonly modes: Modes;\n+\treadonly blobs: Record<string, string>;\n+\treadonly paths: readonly string[];\n+}\n+\n+export const RECORD_BODY_BUDGET = 8 * 1024 * 1024;\n+\n+export class RecordItemTooLargeError extends Error {\n+\treadonly path: string;\n+\treadonly bytes: number;\n+\treadonly budget: number;\n+\tconstructor(path: string, bytes: number, budget: number) {\n+\t\tsuper(`Not recorded: ${path} needs a ${bytes}-byte record request by itself, over the ${budget}-byte limit.`);\n+\t\tthis.name = \"RecordItemTooLargeError\";\n+\t\tthis.path = path;\n+\t\tthis.bytes = bytes;\n+\t\tthis.budget = budget;\n+\t}\n+}\n+\n+function bodyFor(items: readonly RecordItem[]): RecordBatch {\n+\tconst files: Record<string, string | null> = {};\n+\tconst modes: Record<string, Mode> = {};\n+\tconst blobs: Record<string, string> = {};\n+\tfor (const item of items) {\n+\t\tif (item.text !== undefined) files[item.path] = item.text;\n+\t\tif (item.mode !== undefined) modes[item.path] = item.mode;\n+\t\tif (item.blob !== undefined) blobs[item.path] = item.blob;\n+\t}\n+\treturn { files, modes, blobs, paths: items.map((item) => item.path) };\n+}\n+\n+/** Exact serialized UTF-8 size of the API record body. */\n+export function serializedRecordBytes(batch: RecordBatch): number {\n+\treturn Buffer.byteLength(\n+\t\tJSON.stringify({\n+\t\t\tfiles: batch.files,\n+\t\t\t...(Object.keys(batch.modes).length ? { modes: batch.modes } : {}),\n+\t\t\t...(Object.keys(batch.blobs).length ? { blobs: batch.blobs } : {}),\n+\t\t}),\n+\t\t\"utf8\",\n+\t);\n+}\n+\n+/** Deterministically split sorted atomic path entries under the serialized body budget. */\n+export function batchRecordItems(items: readonly RecordItem[], budget = RECORD_BODY_BUDGET): RecordBatch[] {\n+\tif (!Number.isSafeInteger(budget) || budget <= 0)\n+\t\tthrow new RangeError(\"record body budget must be a positive safe integer\");\n+\tconst sorted = [...items].sort((a, b) => (a.path < b.path ? -1 : a.path > b.path ? 1 : 0));\n+\tconst batches: RecordBatch[] = [];\n+\tlet current: RecordItem[] = [];\n+\tfor (const item of sorted) {\n+\t\tconst candidate = bodyFor([...current, item]);\n+\t\tif (serializedRecordBytes(candidate) <= budget) {\n+\t\t\tcurrent.push(item);\n+\t\t\tcontinue;\n+\t\t}\n+\t\tif (current.length === 0) throw new RecordItemTooLargeError(item.path, serializedRecordBytes(candidate), budget);\n+\t\tbatches.push(bodyFor(current));\n+\t\tcurrent = [item];\n+\t\tconst single = bodyFor(current);\n+\t\tconst bytes = serializedRecordBytes(single);\n+\t\tif (bytes > budget) throw new RecordItemTooLargeError(item.path, bytes, budget);\n+\t}\n+\tif (current.length > 0) batches.push(bodyFor(current));\n+\treturn batches;\n+}\n+\n+export interface RecordApi {\n+\trecord(\n+\t\tfiles: Record<string, string | null>,\n+\t\textra?: { session?: string; subagent?: string },\n+\t\tmodes?: Modes,\n+\t\tblobs?: Readonly<Record<string, string>>,\n+\t): Promise<RecordAnswer>;\n+}\n+\n+/** Retry only an outcome that may have been accepted; an identical record is a no-op once its state landed. */\n+export async function sendRecordBatch(api: RecordApi, batch: RecordBatch): Promise<RecordAnswer> {\n+\tconst blobMap = batch.blobs;\n+\ttry {\n+\t\treturn await api.record(batch.files, {}, batch.modes, blobMap);\n+\t} catch (error) {\n+\t\tif (\n+\t\t\t!(error instanceof ApiError) ||\n+\t\t\terror.notSent ||\n+\t\t\t(error.status !== undefined && (error.status < 200 || (error.status >= 300 && error.status < 500)))\n+\t\t)\n+\t\t\tthrow error;\n+\t\t// The server diffs whole-file state against the agent's current view. Replaying these exact maps is idempotent.\n+\t\treturn api.record(batch.files, {}, batch.modes, blobMap);\n+\t}\n+}\n+\n+/** Run batches in order and expose only confirmed batches to local bookkeeping. */\n+export async function sendRecordBatches(\n+\tapi: RecordApi,\n+\tbatches: readonly RecordBatch[],\n+\tbeforeSend: (batch: RecordBatch) => Promise<void>,\n+\tonConfirmed: (batch: RecordBatch, answer: RecordAnswer) => Promise<void>,\n+): Promise<RecordAnswer[]> {\n+\tconst answers: RecordAnswer[] = [];\n+\tfor (const batch of batches) {\n+\t\tawait beforeSend(batch);\n+\t\tconst answer = await sendRecordBatch(api, batch);\n+\t\tif (!answer.ok) throw new Error(`the server refused the record: ${answer.reason ?? \"no reason given\"}`);\n+\t\tawait onConfirmed(batch, answer);\n+\t\tanswers.push(answer);\n+\t}\n+\treturn answers;\n+}"},{"path":"client/test/record-batches.test.ts","added":161,"removed":0,"diff":"--- /dev/null\n+++ b/client/test/record-batches.test.ts\n@@ -0,0 +1,161 @@\n+import assert from \"node:assert/strict\";\n+import test from \"node:test\";\n+import { Api, ApiError, type RecordAnswer } from \"../src/api.ts\";\n+import {\n+\tbatchRecordItems,\n+\tRECORD_BODY_BUDGET,\n+\ttype RecordBatch,\n+\ttype RecordItem,\n+\tRecordItemTooLargeError,\n+\tsendRecordBatch,\n+\tsendRecordBatches,\n+\tserializedRecordBytes,\n+} from \"../src/record-batches.ts\";\n+\n+test(\"batches use serialized UTF-8 bytes and keep text, mode, blob, and deletion entries atomic\", () => {\n+\tconst items: RecordItem[] = [\n+\t\t{ path: \"delete.txt\", text: null },\n+\t\t{ path: \"blob.bin\", text: \"\", mode: { exec: true }, blob: \"a\".repeat(64) },\n+\t\t{ path: \"emoji.txt\", text: \"🙂\".repeat(80) },\n+\t];\n+\tconst onePath = batchRecordItems([items[2]!], 10_000)[0]!;\n+\tconst exact = serializedRecordBytes(onePath);\n+\tassert.equal(batchRecordItems([items[2]!], exact).length, 1);\n+\tassert.throws(() => batchRecordItems([items[2]!], exact - 1), RecordItemTooLargeError);\n+\n+\tconst batches = batchRecordItems(items, exact + 100);\n+\tassert.deepEqual(\n+\t\tbatches.flatMap((batch) => batch.paths),\n+\t\t[\"blob.bin\", \"delete.txt\", \"emoji.txt\"],\n+\t);\n+\tassert.ok(batches.every((batch) => serializedRecordBytes(batch) <= exact + 100));\n+\tconst blobBatch = batches.find((batch) => batch.paths.includes(\"blob.bin\"))!;\n+\tassert.deepEqual(blobBatch.files, { \"blob.bin\": \"\", \"delete.txt\": null });\n+\tassert.deepEqual(blobBatch.modes, { \"blob.bin\": { exec: true } });\n+\tassert.deepEqual(blobBatch.blobs, { \"blob.bin\": \"a\".repeat(64) });\n+\tassert.ok(blobBatch.paths.includes(\"delete.txt\"));\n+});\n+\n+test(\"a single entry over the budget is refused before any request can be sent\", () => {\n+\tassert.throws(() => batchRecordItems([{ path: \"big.txt\", text: \"x\".repeat(100) }], 20), /Not recorded: big\\.txt/);\n+\tassert.equal(RECORD_BODY_BUDGET, 8 * 1024 * 1024);\n+});\n+\n+test(\"an ambiguous lost reply retries the exact batch once, then returns the accepted result\", async () => {\n+\tconst batch: RecordBatch = {\n+\t\tfiles: { \"a.txt\": \"same\\n\" },\n+\t\tmodes: {},\n+\t\tblobs: {},\n+\t\tpaths: [\"a.txt\"],\n+\t};\n+\tconst calls: unknown[][] = [];\n+\tlet accepted = false;\n+\tconst api = {\n+\t\tasync record(...args: unknown[]): Promise<RecordAnswer> {\n+\t\t\tcalls.push(args);\n+\t\t\tif (!accepted) {\n+\t\t\t\taccepted = true;\n+\t\t\t\tthrow new ApiError(\"response ended before confirmation\", 200);\n+\t\t\t}\n+\t\t\treturn { ok: true, changed: [], news: [] };\n+\t\t},\n+\t};\n+\tassert.deepEqual(await sendRecordBatch(api, batch), { ok: true, changed: [], news: [] });\n+\tassert.equal(calls.length, 2);\n+\tassert.deepEqual(calls[0], calls[1]);\n+});\n+\n+test(\"the real Api transport retries an accepted request when reading its response stream fails\", async () => {\n+\tconst api = new Api({ server: \"https://example.test\", project: \"p\", agent: \"a\", token: \"t\" });\n+\tlet requests = 0;\n+\tapi.send = async () => {\n+\t\trequests += 1;\n+\t\tif (requests === 1) {\n+\t\t\treturn new Response(\n+\t\t\t\tnew ReadableStream({\n+\t\t\t\t\tstart(controller) {\n+\t\t\t\t\t\tcontroller.error(new Error(\"lost response stream\"));\n+\t\t\t\t\t},\n+\t\t\t\t}),\n+\t\t\t\t{ status: 200 },\n+\t\t\t);\n+\t\t}\n+\t\treturn new Response(JSON.stringify({ ok: true, changed: [] }), {\n+\t\t\tstatus: 200,\n+\t\t\theaders: { \"content-type\": \"application/json\" },\n+\t\t});\n+\t};\n+\tconst answer = await sendRecordBatch(api, {\n+\t\tfiles: { \"a.txt\": \"same\\n\" },\n+\t\tmodes: {},\n+\t\tblobs: {},\n+\t\tpaths: [\"a.txt\"],\n+\t});\n+\tassert.equal(answer.ok, true);\n+\tassert.equal(requests, 2);\n+});\n+\n+test(\"the real Api transport does not retry a definite refusal with a broken response stream\", async () => {\n+\tconst api = new Api({ server: \"https://example.test\", project: \"p\", agent: \"a\", token: \"t\" });\n+\tlet requests = 0;\n+\tapi.send = async () => {\n+\t\trequests += 1;\n+\t\treturn new Response(\n+\t\t\tnew ReadableStream({\n+\t\t\t\tstart(controller) {\n+\t\t\t\t\tcontroller.error(new Error(\"broken refusal response\"));\n+\t\t\t\t},\n+\t\t\t}),\n+\t\t\t{ status: 413 },\n+\t\t);\n+\t};\n+\tawait assert.rejects(\n+\t\tsendRecordBatch(api, { files: { \"a.txt\": \"x\" }, modes: {}, blobs: {}, paths: [\"a.txt\"] }),\n+\t\t(error: unknown) => error instanceof ApiError && error.status === 413,\n+\t);\n+\tassert.equal(requests, 1);\n+});\n+\n+test(\"a definite server refusal is not retried\", async () => {\n+\tlet calls = 0;\n+\tconst api = {\n+\t\tasync record(): Promise<RecordAnswer> {\n+\t\t\tcalls += 1;\n+\t\t\tthrow new ApiError(\"bad request\", 413);\n+\t\t},\n+\t};\n+\tawait assert.rejects(sendRecordBatch(api, { files: { \"a.txt\": \"x\" }, modes: {}, blobs: {}, paths: [\"a.txt\"] }));\n+\tassert.equal(calls, 1);\n+});\n+\n+test(\"later batch failure stops the sequence and confirms only successful batches\", async () => {\n+\tconst batches: RecordBatch[] = [\"a.txt\", \"b.txt\", \"c.txt\"].map((path) => ({\n+\t\tfiles: { [path]: path },\n+\t\tmodes: {},\n+\t\tblobs: {},\n+\t\tpaths: [path],\n+\t}));\n+\tconst sent: string[] = [];\n+\tconst confirmed: string[] = [];\n+\tconst api = {\n+\t\tasync record(files: Record<string, string | null>): Promise<RecordAnswer> {\n+\t\t\tconst path = Object.keys(files)[0]!;\n+\t\t\tsent.push(path);\n+\t\t\tif (path === \"b.txt\") throw new ApiError(\"request rejected\", 413);\n+\t\t\treturn { ok: true, changed: [path] };\n+\t\t},\n+\t};\n+\tawait assert.rejects(\n+\t\tsendRecordBatches(\n+\t\t\tapi,\n+\t\t\tbatches,\n+\t\t\tasync () => {},\n+\t\t\tasync (batch) => {\n+\t\t\t\tconfirmed.push(batch.paths[0]!);\n+\t\t\t},\n+\t\t),\n+\t\t/request rejected/,\n+\t);\n+\tassert.deepEqual(sent, [\"a.txt\", \"b.txt\"]);\n+\tassert.deepEqual(confirmed, [\"a.txt\"]);\n+});"},{"path":"worker/project/test/record-idempotence.test.ts","added":35,"removed":0,"diff":"--- /dev/null\n+++ b/worker/project/test/record-idempotence.test.ts\n@@ -0,0 +1,35 @@\n+import assert from \"node:assert/strict\";\n+import { test } from \"node:test\";\n+import { MemoryStore, Project } from \"../project.ts\";\n+\n+const BLOB_A = \"a\".repeat(64);\n+const BLOB_B = \"b\".repeat(64);\n+\n+test(\"replaying identical recorded text, deletion, blob, and mode changes adds no semantic events\", () => {\n+\tconst heldBlobs = new Set([BLOB_A, BLOB_B]);\n+\tconst store = new MemoryStore();\n+\tconst project = new Project(store, { hasBlob: (sha) => heldBlobs.has(sha) });\n+\tproject.init(\n+\t\t{ \"text.txt\": \"old text\\n\", \"delete.txt\": \"remove me\\n\", \"run.sh\": \"echo hi\\n\" },\n+\t\t0,\n+\t\t{},\n+\t\t{ \"image.bin\": BLOB_A },\n+\t);\n+\tproject.sync(\"ann\");\n+\n+\tconst replay = (record: () => { changed?: readonly string[] }) => {\n+\t\tconst before = store.entries.length;\n+\t\tconst first = record();\n+\t\tconst afterFirst = store.entries.length;\n+\t\tassert.ok(afterFirst > before, \"the initial recording creates semantic events\");\n+\t\tconst second = record();\n+\t\tassert.deepEqual(second.changed, []);\n+\t\tassert.equal(store.entries.length, afterFirst, \"an identical replay appends no semantic events\");\n+\t\treturn first;\n+\t};\n+\n+\treplay(() => project.record(\"ann\", { \"text.txt\": \"new text\\n\" }, 1));\n+\treplay(() => project.record(\"ann\", { \"delete.txt\": null }, 2));\n+\treplay(() => project.record(\"ann\", {}, 3, {}, { \"image.bin\": BLOB_B }));\n+\treplay(() => project.record(\"ann\", {}, 4, { \"run.sh\": { exec: true } }));\n+});"}],"ci":null}