{"version":178,"agent":"codex-capacity-chair","message":"Use disk-backed Git intake behind disk-first switch; cleared in review ask 56","time":1791973284309,"timeIso":"2026-10-14T10:21:24.309Z","changes":30,"change":2815,"files":["package-lock.json","package.json","server/package-lock.json","server/package.json","server/scripts/capacity-git-bounded-fifo.mjs","server/scripts/capacity-install-git-runtime.mjs","server/scripts/capacity-patch-git-fetch.mjs","server/scripts/capacity-patch-git-progress.mjs","server/scripts/capacity-patch-git-pump.mjs","server/scripts/capacity-patch-git-push.mjs","server/scripts/capacity-patch-git-sideband.mjs","server/src/git-blob-text.ts","server/src/git-delta-stream.ts","server/src/git-disk-intake.ts","server/src/git-http.ts","server/src/git-intake-trees.ts","server/src/git-object-bytes.ts","server/src/git-pack-decode.ts","server/src/git-pack-resolver.ts","server/src/git-pack-spool.ts","server/src/ingest.ts","server/src/project-object.ts","server/test/git-blob-text.test.ts","server/test/git-budget-recovery.test.ts","server/test/git-delta-stream.test.ts","server/test/git-disk-clone.test.ts","server/test/git-intake-trees.test.ts","server/test/git-object-bytes.test.ts","server/test/git-pack-decode.test.ts","server/test/git-pack-resolver.test.ts","server/test/git-pack-spool.test.ts","server/test/project-object-disk-first.test.ts"],"draft":null,"diff":[{"path":"package-lock.json","blob":{"before":"8a30a196a1270253ff8b9c65c2606f037369c8a2d3b653575eba4fc6ae3ed5e6","after":"346745f531bc59196aaa2f352eeb1ae5701160178ab9fb04f4f7d33f4b9acf49"},"added":0,"removed":0,"diff":"Binary file package-lock.json changed: 8a30a196a127 -> 346745f531bc"},{"path":"package.json","added":10,"removed":3,"diff":"--- a/package.json\n+++ b/package.json\n@@ -11,13 +11,20 @@\n \t\"scripts\": {\n \t\t\"test\": \"node --import ./client/test/setup.ts --test \\\"src/**/*.test.ts\\\" \\\"worker/project/**/*.test.ts\\\" \\\"client/test/**/*.test.ts\\\" \\\"scripts/**/*.test.ts\\\" \\\"server/test/**/*.test.ts\\\"\",\n \t\t\"typecheck\": \"tsc --noEmit -p tsconfig.json\",\n-\t\t\"check\": \"npm run typecheck && npm run typecheck:server && npm test\",\n+\t\t\"check\": \"npm run check:git-runtime && npm run typecheck && npm run typecheck:server && npm test\",\n \t\t\"build\": \"node scripts/build-client.mjs\",\n \t\t\"pack:npm\": \"node scripts/pack-npm.mjs\",\n \t\t\"check:changed\": \"node scripts/check-changed.mjs\",\n \t\t\"format\": \"biome check --write .\",\n \t\t\"lint\": \"biome ci .\",\n-\t\t\"typecheck:server\": \"tsc --noEmit -p server/tsconfig.json\"\n+\t\t\"typecheck:server\": \"tsc --noEmit -p server/tsconfig.json\",\n+\t\t\"install:git-runtime\": \"node server/scripts/capacity-install-git-runtime.mjs --root node_modules/isomorphic-git\",\n+\t\t\"check:git-runtime\": \"node server/scripts/capacity-install-git-runtime.mjs --root node_modules/isomorphic-git --check\",\n+\t\t\"postinstall\": \"npm run install:git-runtime\",\n+\t\t\"prebuild\": \"npm run check:git-runtime\",\n+\t\t\"pretest\": \"npm run check:git-runtime\",\n+\t\t\"pretypecheck\": \"npm run check:git-runtime\",\n+\t\t\"pretypecheck:server\": \"npm run check:git-runtime\"\n \t},\n \t\"devDependencies\": {\n \t\t\"@biomejs/biome\": \"2.5.15\",\n@@ -27,7 +34,7 @@\n \t\t\"typescript\": \"^5.9.3\"\n \t},\n \t\"dependencies\": {\n-\t\t\"isomorphic-git\": \"^1.43.0\",\n+\t\t\"isomorphic-git\": \"1.44.2\",\n \t\t\"yaml\": \"^2.9.1\"\n \t}\n }"},{"path":"server/package-lock.json","blob":{"before":"f5cebad6e233fae6b9d2ca0f5a1af43e25387f52e0f1760e8d1f35551bcacd81","after":"68f93bb4aa9764c0cbeb1c71f9072470af089ff604359a3b16b1e581e04cca3f"},"added":0,"removed":0,"diff":"Binary file server/package-lock.json changed: f5cebad6e233 -> 68f93bb4aa97"},{"path":"server/package.json","added":7,"removed":2,"diff":"--- a/server/package.json\n+++ b/server/package.json\n@@ -8,10 +8,15 @@\n \t\"scripts\": {\n \t\t\"dev\": \"wrangler dev --local\",\n \t\t\"deploy\": \"wrangler deploy\",\n-\t\t\"typecheck\": \"tsc --noEmit -p tsconfig.json\"\n+\t\t\"typecheck\": \"tsc --noEmit -p tsconfig.json\",\n+\t\t\"install:git-runtime\": \"node scripts/capacity-install-git-runtime.mjs --root node_modules/isomorphic-git\",\n+\t\t\"check:git-runtime\": \"node scripts/capacity-install-git-runtime.mjs --root node_modules/isomorphic-git --check\",\n+\t\t\"postinstall\": \"npm run install:git-runtime\",\n+\t\t\"predev\": \"npm run check:git-runtime\",\n+\t\t\"predeploy\": \"npm run check:git-runtime\"\n \t},\n \t\"dependencies\": {\n-\t\t\"isomorphic-git\": \"^1.43.0\"\n+\t\t\"isomorphic-git\": \"1.44.2\"\n \t},\n \t\"devDependencies\": {\n \t\t\"@cloudflare/workers-types\": \"^5.20261001.1\","},{"path":"server/scripts/capacity-git-bounded-fifo.mjs","added":61,"removed":0,"diff":"--- /dev/null\n+++ b/server/scripts/capacity-git-bounded-fifo.mjs\n@@ -0,0 +1,61 @@\n+/** One pending chunk; a producer cannot advance until the consumer takes it. */\n+export class BoundedPackFIFO {\n+\tconstructor(cancel = async () => {}) {\n+\t\tthis.cancel = cancel;\n+\t\tthis.ended = false;\n+\t\tthis.error = undefined;\n+\t\tthis.pending = undefined;\n+\t\tthis.reader = undefined;\n+\t\tthis.writer = undefined;\n+\t}\n+\tasync write(value) {\n+\t\tif (this.ended) throw this.error ?? Error(\"Pack stream is closed\");\n+\t\tif (this.pending !== undefined || this.writer) throw Error(\"Concurrent pack writes\");\n+\t\tif (this.reader) {\n+\t\t\tconst reader = this.reader;\n+\t\t\tthis.reader = undefined;\n+\t\t\treader.resolve({ value, done: false });\n+\t\t\treturn;\n+\t\t}\n+\t\tthis.pending = value;\n+\t\tawait new Promise((resolve, reject) => {\n+\t\t\tthis.writer = { resolve, reject };\n+\t\t});\n+\t}\n+\tasync next() {\n+\t\tif (this.error) throw this.error;\n+\t\tif (this.pending !== undefined) {\n+\t\t\tconst value = this.pending;\n+\t\t\tthis.pending = undefined;\n+\t\t\tthis.writer?.resolve();\n+\t\t\tthis.writer = undefined;\n+\t\t\treturn { value, done: false };\n+\t\t}\n+\t\tif (this.ended) return { done: true };\n+\t\tif (this.reader) throw Error(\"Concurrent pack reads\");\n+\t\treturn new Promise((resolve, reject) => {\n+\t\t\tthis.reader = { resolve, reject };\n+\t\t});\n+\t}\n+\tend() {\n+\t\tthis.ended = true;\n+\t\tthis.reader?.resolve({ done: true });\n+\t\tthis.reader = undefined;\n+\t}\n+\tdestroy(error) {\n+\t\tthis.error = error;\n+\t\tthis.ended = true;\n+\t\tthis.pending = undefined;\n+\t\tthis.reader?.reject(error);\n+\t\tthis.writer?.reject(error);\n+\t\tthis.reader = this.writer = undefined;\n+\t}\n+\tasync return() {\n+\t\tthis.destroy(Error(\"Pack consumer cancelled\"));\n+\t\tawait this.cancel();\n+\t\treturn { done: true };\n+\t}\n+\t[Symbol.asyncIterator]() {\n+\t\treturn this;\n+\t}\n+}"},{"path":"server/scripts/capacity-install-git-runtime.mjs","added":61,"removed":0,"diff":"--- /dev/null\n+++ b/server/scripts/capacity-install-git-runtime.mjs\n@@ -0,0 +1,61 @@\n+import { execFileSync } from \"node:child_process\";\n+import { createHash } from \"node:crypto\";\n+import { copyFileSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from \"node:fs\";\n+import { tmpdir } from \"node:os\";\n+import { basename, dirname, join, resolve } from \"node:path\";\n+import { fileURLToPath } from \"node:url\";\n+\n+const scripts = dirname(fileURLToPath(import.meta.url));\n+const rootIndex = process.argv.indexOf(\"--root\");\n+if (rootIndex < 0 || !process.argv[rootIndex + 1])\n+\tthrow Error(\"Pass --root with the exact isomorphic-git package directory\");\n+const root = resolve(process.argv[rootIndex + 1]);\n+const hash = (bytes) => createHash(\"sha256\").update(bytes).digest(\"hex\");\n+const original = {\n+\t\"index.js\": \"66c20b7d890a6d48819f0be5f7bb1c5aab69937e6318ec912295c501028a5084\",\n+\t\"index.cjs\": \"b2142bba9e651fce83d6c1d266d32fc5eefa748544c452f9f22fada4e33dc367\",\n+};\n+const expected = {\n+\t\"index.js\": \"50ada141b506bff7cced797098f5ea70a6e40cda859884cc25b0dea985b10592\",\n+\t\"index.cjs\": \"3b8a78b7145330038cf56e057f7726004a78d0af9a55845b685cf1f65443bae0\",\n+};\n+if (JSON.parse(readFileSync(join(root, \"package.json\"), \"utf8\")).version !== \"1.44.2\")\n+\tthrow Error(\"Unsupported Git version\");\n+const installed = Object.fromEntries(Object.keys(original).map((file) => [file, readFileSync(join(root, file))]));\n+if (Object.entries(expected).every(([file, digest]) => hash(installed[file]) === digest)) {\n+\tconsole.log(\"Verified the complete Git capacity runtime patch.\");\n+\tprocess.exit(0);\n+}\n+if (process.argv.includes(\"--check\")) throw Error(\"Complete Git capacity runtime patch is absent or modified\");\n+for (const [file, digest] of Object.entries(original)) {\n+\tif (hash(installed[file]) !== digest) throw Error(`Unrecognized or partially patched Git bundle: ${file}`);\n+}\n+const temporary = mkdtempSync(join(tmpdir(), \"abso-git-patch-\"));\n+if (dirname(resolve(temporary)) !== resolve(tmpdir()) || !basename(temporary).startsWith(\"abso-git-patch-\"))\n+\tthrow Error(\"Unexpected temporary cleanup path\");\n+try {\n+\tconst staged = join(temporary, \"capacity-git-dependency-sandbox/node_modules/isomorphic-git\");\n+\tmkdirSync(staged, { recursive: true });\n+\tcopyFileSync(join(root, \"package.json\"), join(staged, \"package.json\"));\n+\tfor (const [file, bytes] of Object.entries(installed)) writeFileSync(join(staged, file), bytes);\n+\tcopyFileSync(join(scripts, \"capacity-git-bounded-fifo.mjs\"), join(temporary, \"capacity-git-bounded-fifo.mjs\"));\n+\tfor (const stage of [\"push\", \"fetch\", \"sideband\", \"progress\", \"pump\"]) {\n+\t\texecFileSync(process.execPath, [join(scripts, `capacity-patch-git-${stage}.mjs`)], {\n+\t\t\tcwd: temporary,\n+\t\t\tstdio: \"pipe\",\n+\t\t});\n+\t}\n+\tconst outputs = Object.fromEntries(Object.keys(expected).map((file) => [file, readFileSync(join(staged, file))]));\n+\tfor (const [file, digest] of Object.entries(expected)) {\n+\t\tif (hash(outputs[file]) !== digest) throw Error(`Unexpected complete Git patch: ${file}`);\n+\t}\n+\t// All stages and both final hashes pass before touching the installed package.\n+\tfor (const [file, bytes] of Object.entries(outputs)) writeFileSync(join(root, file), bytes);\n+\tconsole.log(\"Installed and verified the complete Git capacity runtime patch.\");\n+} finally {\n+\ttry {\n+\t\trmSync(temporary, { recursive: true, force: true });\n+\t} catch {\n+\t\tconsole.warn(\"Could not remove the Git patch staging directory.\");\n+\t}\n+}"},{"path":"server/scripts/capacity-patch-git-fetch.mjs","added":91,"removed":0,"diff":"--- /dev/null\n+++ b/server/scripts/capacity-patch-git-fetch.mjs\n@@ -0,0 +1,91 @@\n+import { createHash } from \"node:crypto\";\n+import { readFileSync, writeFileSync } from \"node:fs\";\n+import { join } from \"node:path\";\n+\n+// Extends only the reviewed-version push prototype in this isolated dependency tree.\n+const root = \"capacity-git-dependency-sandbox/node_modules/isomorphic-git\";\n+const inputs = {\n+\t\"index.js\": \"0bd051b1a38bf8d593bf37b5acf9ee453ddab33d48950c84e2c2c3f3ec449fc8\",\n+\t\"index.cjs\": \"6c9f6eab37a10c9311f2b7aa8d24b0772d4ba2703d848525a0519e1454d016e7\",\n+};\n+const hash = (source) => createHash(\"sha256\").update(source).digest(\"hex\");\n+const expectedOutputs = {\n+\t\"index.js\": \"eebe6911fa660d4b95857768ea2308be74435dd5f9a796bb7b2491a31bdd109d\",\n+\t\"index.cjs\": \"33364e3ed7f3a1a6cf17a1ecabbfc5d6de6a8494f31a524d8ac293402ad4e447\",\n+};\n+function once(source, before, after) {\n+\tif (source.split(before).length !== 2) throw Error(\"Fetch patch anchor mismatch\");\n+\treturn source.replace(before, after);\n+}\n+if (JSON.parse(readFileSync(join(root, \"package.json\"), \"utf8\")).version !== \"1.44.2\") {\n+\tthrow Error(\"Unsupported Git version\");\n+}\n+const outputs = [];\n+const installed = Object.fromEntries(Object.keys(inputs).map((file) => [file, readFileSync(join(root, file), \"utf8\")]));\n+if (Object.entries(expectedOutputs).every(([file, expected]) => hash(installed[file]) === expected)) {\n+\tconsole.log(\n+\t\tJSON.stringify({\n+\t\t\tverified: true,\n+\t\t\tscope: \"Isolated fetch prototype\",\n+\t\t\tbundles: expectedOutputs,\n+\t\t}),\n+\t);\n+\tprocess.exit(0);\n+}\n+for (const [file, expected] of Object.entries(inputs)) {\n+\tconst source = installed[file];\n+\tif (hash(source) !== expected) throw Error(`Unrecognized input: ${file}`);\n+\tlet result = once(\n+\t\tsource,\n+\t\t\"  const packfile = Buffer.from(await collect(response.packfile));\",\n+\t\t`  const diskPack = cache && cache[Symbol.for('abso.git.disk-pack')];\n+  if (diskPack) {\n+    await diskPack.ingest(response.packfile, () => new pako.Inflate({ chunkSize: 16384 }));\n+    if (raw.body.error) throw raw.body.error\n+    const result = {\n+      defaultBranch: response.HEAD,\n+      fetchHead: response.FETCH_HEAD.oid,\n+      fetchHeadDescription: response.FETCH_HEAD.description,\n+    };\n+    if (response.headers) result.headers = response.headers;\n+    if (prune) result.pruned = response.pruned;\n+    return result\n+  }\n+  const packfile = Buffer.from(await collect(response.packfile));`,\n+\t);\n+\tconst readStart = result.indexOf(\"async function _readObject({\");\n+\tconst readEnd = result.indexOf(\"\\nclass AlreadyExistsError\", readStart);\n+\tif (readStart < 0 || readEnd < 0) throw Error(\"Missing object reader boundary\");\n+\tconst readFunction = once(\n+\t\tresult.slice(readStart, readEnd),\n+\t\t\"  // Curry the current read method so that the packfile un-deltification\",\n+\t\t`  const diskPack = cache && cache[Symbol.for('abso.git.disk-pack')];\n+  if (diskPack && format === 'content') {\n+    const stored = await diskPack.read(oid);\n+    if (stored) return stored\n+  }\n+\n+  // Curry the current read method so that the packfile un-deltification`,\n+\t);\n+\tresult = result.slice(0, readStart) + readFunction + result.slice(readEnd);\n+\tif (hash(result) !== expectedOutputs[file]) throw Error(`Unexpected fetch patch output: ${file}`);\n+\toutputs.push({ file, result, sha256: hash(result) });\n+}\n+// Validate both installed bundles and every anchor before either write.\n+if (!process.argv.includes(\"--check\")) {\n+\tfor (const { file, result } of outputs) writeFileSync(join(root, file), result);\n+\twriteFileSync(\n+\t\t\"capacity-git-fetch-patch-manifest.json\",\n+\t\tJSON.stringify(\n+\t\t\toutputs.map(({ file, sha256 }) => ({ file, sha256 })),\n+\t\t\tnull,\n+\t\t\t2,\n+\t\t),\n+\t);\n+}\n+console.log(\n+\tJSON.stringify({\n+\t\tscope: \"Isolated fetch prototype; runtime adapter and transport acceptance still required\",\n+\t\toutputs: outputs.map(({ file, sha256 }) => ({ file, sha256 })),\n+\t}),\n+);"},{"path":"server/scripts/capacity-patch-git-progress.mjs","added":53,"removed":0,"diff":"--- /dev/null\n+++ b/server/scripts/capacity-patch-git-progress.mjs\n@@ -0,0 +1,53 @@\n+import { createHash } from \"node:crypto\";\n+import { readFileSync, writeFileSync } from \"node:fs\";\n+import { join } from \"node:path\";\n+\n+const root = \"capacity-git-dependency-sandbox/node_modules/isomorphic-git\";\n+const inputs = {\n+\t\"index.js\": \"20512aae32eb8dd64b798c0dd4ba666ea801bec6c9de37d259527c93ce3e48ec\",\n+\t\"index.cjs\": \"b4cd8c52f3fa945b553dbb7a740c965b48b93dfc2469f10849e111abd00c7460\",\n+};\n+const hash = (value) => createHash(\"sha256\").update(value).digest(\"hex\");\n+function once(source, before, after) {\n+\tif (source.split(before).length !== 2) throw Error(`Progress anchor mismatch: ${before}`);\n+\treturn source.replace(before, after);\n+}\n+const outputs = [];\n+for (const [file, expected] of Object.entries(inputs)) {\n+\tlet source = readFileSync(join(root, file), \"utf8\");\n+\tif (hash(source) !== expected) throw Error(`Unrecognized input: ${file}`);\n+\tsource = once(\n+\t\tsource,\n+\t\t\"  static demux(input, bounded = false) {\",\n+\t\t\"  static demux(input, bounded = false, discardProgress = false) {\",\n+\t);\n+\tsource = once(\n+\t\tsource,\n+\t\t\"          progress.write(line.slice(1));\",\n+\t\t\"          if (!discardProgress) progress.write(line.slice(1));\",\n+\t);\n+\tsource = once(source, \"          progress.write(error);\", \"          if (!discardProgress) progress.write(error);\");\n+\tsource = once(\n+\t\tsource,\n+\t\t\"async function parseUploadPackResponse(stream, bounded = false) {\\n  const { packetlines, packfile, progress } = GitSideBand.demux(stream, bounded);\",\n+\t\t\"async function parseUploadPackResponse(stream, bounded = false, discardProgress = false) {\\n  const { packetlines, packfile, progress } = GitSideBand.demux(stream, bounded, discardProgress);\",\n+\t);\n+\tsource = once(\n+\t\tsource,\n+\t\t\"  const response = await parseUploadPackResponse(raw.body, Boolean(cache && cache[Symbol.for('abso.git.disk-pack')]));\",\n+\t\t\"  const response = await parseUploadPackResponse(raw.body, Boolean(cache && cache[Symbol.for('abso.git.disk-pack')]), Boolean(cache && cache[Symbol.for('abso.git.disk-pack')]) && !onProgress && !onMessage);\",\n+\t);\n+\toutputs.push({ file, source, sha256: hash(source) });\n+}\n+if (!process.argv.includes(\"--check\")) {\n+\tfor (const { file, source } of outputs) writeFileSync(join(root, file), source);\n+\twriteFileSync(\n+\t\t\"capacity-git-progress-patch-manifest.json\",\n+\t\tJSON.stringify(\n+\t\t\toutputs.map(({ file, sha256 }) => ({ file, sha256 })),\n+\t\t\tnull,\n+\t\t\t2,\n+\t\t),\n+\t);\n+}\n+console.log(JSON.stringify(outputs.map(({ file, sha256 }) => ({ file, sha256 }))));"},{"path":"server/scripts/capacity-patch-git-pump.mjs","added":31,"removed":0,"diff":"--- /dev/null\n+++ b/server/scripts/capacity-patch-git-pump.mjs\n@@ -0,0 +1,31 @@\n+import { createHash } from \"node:crypto\";\n+import { readFileSync, writeFileSync } from \"node:fs\";\n+import { join } from \"node:path\";\n+\n+const root = \"capacity-git-dependency-sandbox/node_modules/isomorphic-git\";\n+const inputs = {\n+\t\"index.js\": \"4e0e9ee5a21754ebd718864dba2705385fc8254ed0c9e0d4ff56c8a2ff6fccf8\",\n+\t\"index.cjs\": \"fe66bb236ed6d95bf720e646afc9fff1dbe3efbc441b194efde09b1b698cd583\",\n+};\n+const hash = (value) => createHash(\"sha256\").update(value).digest(\"hex\");\n+function once(source, before, after) {\n+\tif (source.split(before).length !== 2) throw Error(\"Git pump anchor mismatch\");\n+\treturn source.replace(before, after);\n+}\n+const outputs = [];\n+for (const [file, expected] of Object.entries(inputs)) {\n+\tlet source = readFileSync(join(root, file), \"utf8\");\n+\tif (hash(source) !== expected) throw Error(`Unrecognized pump input: ${file}`);\n+\tsource = once(\n+\t\tsource,\n+\t\t\"    const nextBit = async function () {\",\n+\t\t\"    const nextBit = async function () {\\n      while (true) {\",\n+\t);\n+\tsource = once(source, \"      if (line === null) return nextBit()\", \"      if (line === null) continue\");\n+\tsource = once(source, \"      return nextBit();\\n    };\", \"      }\\n    };\");\n+\toutputs.push({ file, source, sha256: hash(source) });\n+}\n+if (!process.argv.includes(\"--check\")) {\n+\tfor (const { file, source } of outputs) writeFileSync(join(root, file), source);\n+}\n+console.log(JSON.stringify(outputs.map(({ file, sha256 }) => ({ file, sha256 }))));"},{"path":"server/scripts/capacity-patch-git-push.mjs","added":94,"removed":0,"diff":"--- /dev/null\n+++ b/server/scripts/capacity-patch-git-push.mjs\n@@ -0,0 +1,94 @@\n+import { createHash } from \"node:crypto\";\n+import { readFileSync, writeFileSync } from \"node:fs\";\n+import { join } from \"node:path\";\n+\n+const root = \"capacity-git-dependency-sandbox/node_modules/isomorphic-git\";\n+const hashes = {\n+\t\"index.js\": \"66c20b7d890a6d48819f0be5f7bb1c5aab69937e6318ec912295c501028a5084\",\n+\t\"index.cjs\": \"b2142bba9e651fce83d6c1d266d32fc5eefa748544c452f9f22fada4e33dc367\",\n+};\n+const patched = {\n+\t\"index.js\": \"0bd051b1a38bf8d593bf37b5acf9ee453ddab33d48950c84e2c2c3f3ec449fc8\",\n+\t\"index.cjs\": \"6c9f6eab37a10c9311f2b7aa8d24b0772d4ba2703d848525a0519e1454d016e7\",\n+};\n+if (JSON.parse(readFileSync(join(root, \"package.json\"), \"utf8\")).version !== \"1.44.2\")\n+\tthrow Error(\"Unsupported Git version\");\n+const installed = Object.fromEntries(\n+\tObject.keys(hashes).map((file) => [\n+\t\tfile,\n+\t\tcreateHash(\"sha256\")\n+\t\t\t.update(readFileSync(join(root, file)))\n+\t\t\t.digest(\"hex\"),\n+\t]),\n+);\n+if (Object.keys(patched).every((file) => installed[file] === patched[file])) {\n+\tconsole.log(JSON.stringify({ verified: true, version: \"1.44.2\", bundles: installed }));\n+\tprocess.exit(0);\n+}\n+if (process.argv.includes(\"--check\")) throw Error(\"Git runtime patch is absent or modified\");\n+function replaceOnce(source, before, after) {\n+\tif (source.split(before).length !== 2) throw Error(\"Patch anchor mismatch\");\n+\treturn source.replace(before, after);\n+}\n+const outputs = [];\n+for (const [file, expected] of Object.entries(hashes)) {\n+\tconst original = readFileSync(join(root, file), \"utf8\");\n+\tif (createHash(\"sha256\").update(original).digest(\"hex\") !== expected) throw Error(`Unrecognized source: ${file}`);\n+\tconst start = original.indexOf(\"async function _pack({\");\n+\tconst end = original.indexOf(\"\\n// @ts-check\", start);\n+\tif (start < 0 || end < 0) throw Error(\"Missing pack implementation\");\n+\tconst old = original.slice(start, end);\n+\tlet streamed = replaceOnce(old, \"async function _pack({\", \"async function* _packStream({\");\n+\tstreamed = replaceOnce(\n+\t\tstreamed,\n+\t\t\"  for (const oid of oids) {\",\n+\t\t\"  yield* outputStream;\\n  outputStream.length = 0;\\n  for (const oid of oids) {\",\n+\t);\n+\tstreamed = replaceOnce(\n+\t\tstreamed,\n+\t\t\"    await writeObject({ write, object, stype: type });\",\n+\t\t\"    await writeObject({ write, object, stype: type });\\n    yield* outputStream;\\n    outputStream.length = 0;\",\n+\t);\n+\tstreamed = replaceOnce(streamed, \"  outputStream.push(digest);\\n  return outputStream\", \"  yield digest;\");\n+\tlet result =\n+\t\toriginal.slice(0, start) +\n+\t\tstreamed +\n+\t\t\"\\nasync function _pack(options) {\\n  const output = [];\\n  for await (const chunk of _packStream(options)) output.push(chunk);\\n  return output;\\n}\\n\" +\n+\t\toriginal.slice(end);\n+\tconst begin = result.indexOf(\"  const packstream2 = _delete\");\n+\tconst finish = result.indexOf(\"  const res = await GitRemoteHTTP.connect({\", begin);\n+\tif (begin < 0 || finish < 0) throw Error(\"Missing push implementation\");\n+\tresult =\n+\t\tresult.slice(0, begin) +\n+\t\t`  const packoids = [...objects];\n+  // Recreate the stream for every authentication retry; never retain a whole pack.\n+  const packbody = {\n+    async *[Symbol.asyncIterator]() {\n+      yield* packstream1;\n+      if (!_delete) yield* _packStream({ fs, cache, gitdir, oids: packoids });\n+    }\n+  };\n+` +\n+\t\tresult.slice(finish);\n+\tresult = replaceOnce(result, \"    body: [...packstream1, ...packstream2],\", \"    body: packbody,\");\n+\tconst sha256 = createHash(\"sha256\").update(result).digest(\"hex\");\n+\tif (sha256 !== patched[file]) throw Error(`Unexpected patch output: ${file}`);\n+\toutputs.push({ file, result, sha256 });\n+}\n+// Validate every input before changing either runtime bundle.\n+for (const output of outputs) writeFileSync(join(root, output.file), output.result);\n+writeFileSync(\n+\t\"capacity-git-push-patch-manifest.json\",\n+\tJSON.stringify(\n+\t\toutputs.map(({ file, sha256 }) => ({ file, sha256 })),\n+\t\tnull,\n+\t\t2,\n+\t),\n+);\n+console.log(\n+\tJSON.stringify({\n+\t\tversion: \"1.44.2\",\n+\t\tpatched: outputs.map(({ file, sha256 }) => ({ file, sha256 })),\n+\t\tscope: \"Isolated push patch; fetch and install integration incomplete\",\n+\t}),\n+);"},{"path":"server/scripts/capacity-patch-git-sideband.mjs","added":58,"removed":0,"diff":"--- /dev/null\n+++ b/server/scripts/capacity-patch-git-sideband.mjs\n@@ -0,0 +1,58 @@\n+import { createHash } from \"node:crypto\";\n+import { readFileSync, writeFileSync } from \"node:fs\";\n+import { join } from \"node:path\";\n+\n+const root = \"capacity-git-dependency-sandbox/node_modules/isomorphic-git\";\n+const inputs = {\n+\t\"index.js\": \"eebe6911fa660d4b95857768ea2308be74435dd5f9a796bb7b2491a31bdd109d\",\n+\t\"index.cjs\": \"33364e3ed7f3a1a6cf17a1ecabbfc5d6de6a8494f31a524d8ac293402ad4e447\",\n+};\n+const hash = (value) => createHash(\"sha256\").update(value).digest(\"hex\");\n+const queue = readFileSync(\"capacity-git-bounded-fifo.mjs\", \"utf8\").replace(\"export class\", \"class\");\n+function once(source, before, after) {\n+\tif (source.split(before).length !== 2) throw Error(`Sideband anchor mismatch: ${before}`);\n+\treturn source.replace(before, after);\n+}\n+const outputs = [];\n+for (const [file, expected] of Object.entries(inputs)) {\n+\tlet source = readFileSync(join(root, file), \"utf8\");\n+\tif (hash(source) !== expected) throw Error(`Unrecognized input: ${file}`);\n+\tsource = once(source, \"class GitSideBand {\", `${queue}\\nclass GitSideBand {`);\n+\tsource = once(source, \"  static demux(input) {\", \"  static demux(input, bounded = false) {\");\n+\tsource = once(\n+\t\tsource,\n+\t\t\"    const packfile = new FIFO();\",\n+\t\t\"    const packfile = bounded ? new BoundedPackFIFO(async () => { await getIterator(input).return?.(); }) : new FIFO();\",\n+\t);\n+\tsource = once(source, \"          packfile.write(line.slice(1));\", \"          await packfile.write(line.slice(1));\");\n+\tsource = once(\n+\t\tsource,\n+\t\t\"      nextBit();\\n    };\\n    nextBit();\",\n+\t\t`      return nextBit();\n+    };\n+    nextBit().catch(error => { packetlines.destroy(error); progress.destroy(error); packfile.destroy(error); });`,\n+\t);\n+\tsource = once(\n+\t\tsource,\n+\t\t\"async function parseUploadPackResponse(stream) {\\n  const { packetlines, packfile, progress } = GitSideBand.demux(stream);\",\n+\t\t\"async function parseUploadPackResponse(stream, bounded = false) {\\n  const { packetlines, packfile, progress } = GitSideBand.demux(stream, bounded);\",\n+\t);\n+\tsource = once(\n+\t\tsource,\n+\t\t\"  const response = await parseUploadPackResponse(raw.body);\",\n+\t\t\"  const response = await parseUploadPackResponse(raw.body, Boolean(cache && cache[Symbol.for('abso.git.disk-pack')]));\",\n+\t);\n+\toutputs.push({ file, source, sha256: hash(source) });\n+}\n+if (!process.argv.includes(\"--check\")) {\n+\tfor (const { file, source } of outputs) writeFileSync(join(root, file), source);\n+\twriteFileSync(\n+\t\t\"capacity-git-sideband-patch-manifest.json\",\n+\t\tJSON.stringify(\n+\t\t\toutputs.map(({ file, sha256 }) => ({ file, sha256 })),\n+\t\t\tnull,\n+\t\t\t2,\n+\t\t),\n+\t);\n+}\n+console.log(JSON.stringify(outputs.map(({ file, sha256 }) => ({ file, sha256 }))));"},{"path":"server/src/git-blob-text.ts","added":22,"removed":0,"diff":"--- /dev/null\n+++ b/server/src/git-blob-text.ts\n@@ -0,0 +1,22 @@\n+import type { GitByteRanges } from \"./git-delta-stream.ts\";\n+\n+export class InvalidGitUtf8 extends Error {}\n+\n+/** Strict UTF-8 decoding with the same BOM handling as whole-file intake. */\n+export function* gitBlobText(bytes: GitByteRanges): IterableIterator<string> {\n+\tconst decoder = new TextDecoder(\"utf-8\", { fatal: true, ignoreBOM: false });\n+\tconst size = 16384;\n+\tconst decode = (chunk?: Uint8Array, stream = false) => {\n+\t\ttry {\n+\t\t\treturn decoder.decode(chunk, { stream });\n+\t\t} catch (error) {\n+\t\t\tthrow new InvalidGitUtf8(\"Git blob is not UTF-8\", { cause: error });\n+\t\t}\n+\t};\n+\tfor (let at = 0; at < bytes.byteLength; at += size) {\n+\t\tconst text = decode(bytes.read(at, Math.min(size, bytes.byteLength - at)), true);\n+\t\tfor (let offset = 0; offset < text.length; offset += size) yield text.slice(offset, offset + size);\n+\t}\n+\tconst tail = decode();\n+\tif (tail) yield tail;\n+}"},{"path":"server/src/git-delta-stream.ts","added":73,"removed":0,"diff":"--- /dev/null\n+++ b/server/src/git-delta-stream.ts\n@@ -0,0 +1,73 @@\n+export interface GitByteRanges {\n+\treadonly byteLength: number;\n+\tread(start: number, length: number): Uint8Array;\n+}\n+\n+/** Decode without retaining the base or complete result. Caller must roll back output if decoding throws. */\n+export function applyGitDeltaChunks(\n+\tdelta: GitByteRanges,\n+\tbase: GitByteRanges,\n+\twrite: (chunk: Uint8Array) => void,\n+\tmaxResultBytes: number,\n+): number {\n+\tif (!Number.isSafeInteger(maxResultBytes) || maxResultBytes < 0) throw Error(\"invalid delta result limit\");\n+\tlet position = 0,\n+\t\tproduced = 0;\n+\tlet cached: Uint8Array = new Uint8Array(0),\n+\t\tcacheStart = 0;\n+\tconst byte = () => {\n+\t\tif (position >= delta.byteLength) throw Error(\"truncated Git delta\");\n+\t\tif (position < cacheStart || position >= cacheStart + cached.length) {\n+\t\t\tcacheStart = position;\n+\t\t\tconst count = Math.min(65536, delta.byteLength - position);\n+\t\t\tcached = delta.read(position, count);\n+\t\t\tif (cached.length !== count) throw Error(\"missing delta bytes\");\n+\t\t}\n+\t\treturn cached[position++ - cacheStart]!;\n+\t};\n+\tconst integer = () => {\n+\t\tlet value = 0,\n+\t\t\tmultiplier = 1;\n+\t\tfor (let i = 0; i < 8; i++) {\n+\t\t\tconst next = byte();\n+\t\t\tvalue += (next & 127) * multiplier;\n+\t\t\tif (!Number.isSafeInteger(value)) throw Error(\"Git delta integer overflow\");\n+\t\t\tif (!(next & 128)) return value;\n+\t\t\tmultiplier *= 128;\n+\t\t}\n+\t\tthrow Error(\"Git delta integer overflow\");\n+\t};\n+\tif (integer() !== base.byteLength) throw Error(\"Git delta base length mismatch\");\n+\tconst size = integer();\n+\tif (size > maxResultBytes) throw Error(\"Git delta result exceeds bound\");\n+\tconst emit = (chunk: Uint8Array) => {\n+\t\tif (produced + chunk.length > size) throw Error(\"Git delta result length mismatch\");\n+\t\twrite(chunk);\n+\t\tproduced += chunk.length;\n+\t};\n+\twhile (position < delta.byteLength) {\n+\t\tconst instruction = byte();\n+\t\tif (instruction & 128) {\n+\t\t\tlet offset = 0,\n+\t\t\t\tlength = 0;\n+\t\t\tfor (let i = 0; i < 4; i++) if (instruction & (1 << i)) offset += byte() * 2 ** (8 * i);\n+\t\t\tfor (let i = 0; i < 3; i++) if (instruction & (16 << i)) length += byte() * 2 ** (8 * i);\n+\t\t\tif (!length) length = 65536;\n+\t\t\tif (offset + length > base.byteLength) throw Error(\"Git delta copy exceeds base\");\n+\t\t\tif (produced + length > size) throw Error(\"Git delta result length mismatch\");\n+\t\t\tfor (let at = 0; at < length; at += 65536) {\n+\t\t\t\tconst count = Math.min(65536, length - at),\n+\t\t\t\t\tchunk = base.read(offset + at, count);\n+\t\t\t\tif (chunk.length !== count) throw Error(\"missing delta base bytes\");\n+\t\t\t\temit(chunk);\n+\t\t\t}\n+\t\t} else {\n+\t\t\tif (!instruction) throw Error(\"invalid Git delta instruction\");\n+\t\t\tconst literal = new Uint8Array(instruction);\n+\t\t\tfor (let i = 0; i < instruction; i++) literal[i] = byte();\n+\t\t\temit(literal);\n+\t\t}\n+\t}\n+\tif (produced !== size) throw Error(\"Git delta result length mismatch\");\n+\treturn size;\n+}"},{"path":"server/src/git-disk-intake.ts","added":102,"removed":0,"diff":"--- /dev/null\n+++ b/server/src/git-disk-intake.ts\n@@ -0,0 +1,102 @@\n+import type { SqliteStorage } from \"./engine-project.ts\";\n+import type { StoredGitBytes } from \"./git-object-bytes.ts\";\n+import { decodeGitPack, type PackInflater } from \"./git-pack-decode.ts\";\n+import { GitPackResolver } from \"./git-pack-resolver.ts\";\n+import { GitPackSpool } from \"./git-pack-spool.ts\";\n+\n+/** One clone's temporary pack store. The caller must dispose it in finally. */\n+export class GitDiskIntake {\n+\t/** Cold object construction only, before any intake or reader is created. */\n+\tstatic recover(storage: SqliteStorage): void {\n+\t\t// Constructors establish scratch tables only; they do not alter project state.\n+\t\tconst resolver = new GitPackResolver(storage, 0);\n+\t\tstorage.transactionSync(() => {\n+\t\t\tGitPackSpool.recover(storage);\n+\t\t\tstorage.sql.exec(\"DELETE FROM git_pack_resolve\");\n+\t\t\tstorage.sql.exec(\"DELETE FROM git_object_bytes\");\n+\t\t\tstorage.sql.exec(\"DELETE FROM git_object_meta\");\n+\t\t\tstorage.sql.exec(\"DELETE FROM git_object_budget\");\n+\t\t});\n+\t\tresolver.dispose();\n+\t}\n+\tprivate readonly spool: GitPackSpool;\n+\tprivate readonly resolver: GitPackResolver;\n+\tprivate readonly maxPackBytes: number;\n+\tprivate state: \"new\" | \"loading\" | \"ready\" | \"closed\" = \"new\";\n+\tconstructor(storage: SqliteStorage, maxPackBytes: number, maxObjectBytes: number, maxDecodedBytes = maxPackBytes) {\n+\t\tif (!Number.isSafeInteger(maxPackBytes) || maxPackBytes < 32) throw Error(\"invalid pack limit\");\n+\t\tthis.maxPackBytes = maxPackBytes;\n+\t\tthis.resolver = new GitPackResolver(storage, maxObjectBytes, maxDecodedBytes);\n+\t\tthis.spool = new GitPackSpool(storage);\n+\t}\n+\tattach(cache: object): void {\n+\t\tconst key = Symbol.for(\"abso.git.disk-pack\");\n+\t\tif (key in cache) throw Error(\"Git disk intake already attached\");\n+\t\tObject.defineProperty(cache, key, { value: this });\n+\t}\n+\tasync ingest(\n+\t\tchunks: AsyncIterable<Uint8Array> | Iterable<Uint8Array> | AsyncIterator<Uint8Array>,\n+\t\tcreateInflater: () => PackInflater,\n+\t): Promise<void> {\n+\t\tif (this.state !== \"new\") throw Error(\"Git disk intake already used\");\n+\t\tthis.state = \"loading\";\n+\t\tconst iterator =\n+\t\t\tSymbol.asyncIterator in chunks\n+\t\t\t\t? chunks[Symbol.asyncIterator]()\n+\t\t\t\t: Symbol.iterator in chunks\n+\t\t\t\t\t? chunks[Symbol.iterator]()\n+\t\t\t\t\t: chunks;\n+\t\ttry {\n+\t\t\tconst source = {\n+\t\t\t\t[Symbol.asyncIterator]: () => ({\n+\t\t\t\t\tnext: async () => iterator.next(),\n+\t\t\t\t\treturn: async () => (iterator.return ? iterator.return() : { done: true as const, value: undefined }),\n+\t\t\t\t}),\n+\t\t\t};\n+\t\t\tawait this.spool.ingest(source, this.maxPackBytes);\n+\t\t\tif (this.state !== \"loading\") throw Error(\"Git disk intake closed during download\");\n+\t\t\tdecodeGitPack(this.spool, this.resolver, createInflater);\n+\t\t\tthis.spool.dispose();\n+\t\t\tthis.state = \"ready\";\n+\t\t} catch (error) {\n+\t\t\ttry {\n+\t\t\t\tawait iterator.return?.();\n+\t\t\t} catch {\n+\t\t\t\t/* Preserve the intake failure. */\n+\t\t\t}\n+\t\t\tthis.dispose();\n+\t\t\tthrow error;\n+\t\t}\n+\t}\n+\tbytes(oid: string): StoredGitBytes | undefined {\n+\t\tif (this.state === \"closed\") throw Error(\"Git disk intake is closed\");\n+\t\tif (this.state !== \"ready\") return undefined;\n+\t\treturn this.resolver.find(oid);\n+\t}\n+\tread(oid: string): { format: \"content\"; type: string; object: Buffer } | undefined {\n+\t\tconst stored = this.bytes(oid);\n+\t\tif (!stored) return undefined;\n+\t\t// Existing Git consumers require one complete object. This does not claim\n+\t\t// bounded blob consumption; it removes whole-pack retention and caching.\n+\t\tconst object = Buffer.alloc(stored.byteLength);\n+\t\tfor (let at = 0; at < stored.byteLength; at += 65536) {\n+\t\t\tobject.set(stored.read(at, Math.min(65536, stored.byteLength - at)), at);\n+\t\t}\n+\t\treturn { format: \"content\", type: stored.type, object };\n+\t}\n+\tassertReady(): void {\n+\t\tif (this.state !== \"ready\") throw Error(\"Git disk intake was not used by the installed runtime\");\n+\t}\n+\t[Symbol.dispose](): void {\n+\t\tthis.dispose();\n+\t}\n+\tdispose(): void {\n+\t\tif (this.state === \"closed\") return;\n+\t\tthis.state = \"closed\";\n+\t\ttry {\n+\t\t\tthis.resolver.dispose();\n+\t\t} finally {\n+\t\t\tthis.spool.dispose();\n+\t\t}\n+\t}\n+}"},{"path":"server/src/git-http.ts","added":58,"removed":0,"diff":"--- /dev/null\n+++ b/server/src/git-http.ts\n@@ -0,0 +1,58 @@\n+import type { HttpClient } from \"isomorphic-git\";\n+\n+/** Stream Git HTTP request chunks without a second complete upload buffer. */\n+export function gitHttp(fetcher: typeof fetch = fetch): HttpClient {\n+\treturn {\n+\t\tasync request({ url, method = \"GET\", headers = {}, body, signal, fetchOptions = {} }) {\n+\t\t\tconst input = body as AsyncIterable<Uint8Array> | Iterable<Uint8Array> | undefined;\n+\t\t\tconst iterator = input\n+\t\t\t\t? Symbol.asyncIterator in input\n+\t\t\t\t\t? input[Symbol.asyncIterator]()\n+\t\t\t\t\t: input[Symbol.iterator]()\n+\t\t\t\t: undefined;\n+\t\t\tconst stream = iterator\n+\t\t\t\t? new ReadableStream<Uint8Array>(\n+\t\t\t\t\t\t{\n+\t\t\t\t\t\t\tasync pull(controller) {\n+\t\t\t\t\t\t\t\ttry {\n+\t\t\t\t\t\t\t\t\tconst next = await iterator.next();\n+\t\t\t\t\t\t\t\t\tif (next.done) controller.close();\n+\t\t\t\t\t\t\t\t\telse controller.enqueue(next.value);\n+\t\t\t\t\t\t\t\t} catch (error) {\n+\t\t\t\t\t\t\t\t\tcontroller.error(error);\n+\t\t\t\t\t\t\t\t}\n+\t\t\t\t\t\t\t},\n+\t\t\t\t\t\t\tasync cancel() {\n+\t\t\t\t\t\t\t\tawait iterator.return?.();\n+\t\t\t\t\t\t\t},\n+\t\t\t\t\t\t},\n+\t\t\t\t\t\t{ highWaterMark: 0 },\n+\t\t\t\t\t)\n+\t\t\t\t: undefined;\n+\t\t\tlet response: Response;\n+\t\t\ttry {\n+\t\t\t\tconst options: RequestInit & { duplex?: string } = {\n+\t\t\t\t\t...fetchOptions,\n+\t\t\t\t\tmethod,\n+\t\t\t\t\theaders,\n+\t\t\t\t\tbody: stream,\n+\t\t\t\t\tsignal: signal ?? fetchOptions.signal,\n+\t\t\t\t\t...(stream ? { duplex: \"half\" } : {}),\n+\t\t\t\t};\n+\t\t\t\tresponse = await fetcher(url, options);\n+\t\t\t} catch (error) {\n+\t\t\t\tawait iterator?.return?.();\n+\t\t\t\tthrow error;\n+\t\t\t}\n+\t\t\tconst responseBody = response.body;\n+\t\t\treturn {\n+\t\t\t\turl: response.url,\n+\t\t\t\tmethod,\n+\t\t\t\tstatusCode: response.status,\n+\t\t\t\tstatusMessage: response.statusText,\n+\t\t\t\theaders: Object.fromEntries(response.headers.entries()),\n+\t\t\t\tbody: responseBody ? responseBody[Symbol.asyncIterator]() : (async function* () {})(),\n+\t\t\t};\n+\t\t},\n+\t};\n+}"},{"path":"server/src/git-intake-trees.ts","added":77,"removed":0,"diff":"--- /dev/null\n+++ b/server/src/git-intake-trees.ts\n@@ -0,0 +1,77 @@\n+import { StoredText } from \"../../src/engine/stored-text.ts\";\n+import type { SqliteStorage } from \"./engine-project.ts\";\n+import type { PushedCommits } from \"./ingest.ts\";\n+import { SqliteWriterState } from \"./writer-host.ts\";\n+\n+type Tree = Pick<PushedCommits[\"commits\"][number], \"files\" | \"modes\" | \"blobs\">;\n+\n+/** Keeps earlier Git trees on disk while later commits are decoded. */\n+export class GitIntakeTrees {\n+\t/** Only at a cold Durable Object start, before any intake can be active. */\n+\tstatic recover(storage: SqliteStorage): void {\n+\t\tSqliteWriterState.initialize(storage);\n+\t\tstorage.sql.exec(\"DELETE FROM writer_state WHERE namespace GLOB 'git-intake:*'\");\n+\t}\n+\treadonly namespace = `git-intake:${crypto.randomUUID()}`;\n+\treadonly storage: SqliteStorage;\n+\treadonly text: StoredText;\n+\tprivate next = 0;\n+\tprivate active = true;\n+\tconstructor(storage: SqliteStorage) {\n+\t\tthis.storage = storage;\n+\t\tSqliteWriterState.initialize(storage);\n+\t\tthis.text = new StoredText(new SqliteWriterState(storage, this.namespace), \"files\");\n+\t}\n+\t/** Created outside any scope containing decoded file text or a whole tree. */\n+\tprivate getter(key: string): () => string {\n+\t\treturn () => {\n+\t\t\tif (!this.active) throw Error(\"Git intake trees are closed\");\n+\t\t\treturn this.text.read(key);\n+\t\t};\n+\t}\n+\tretainFile(files: Record<string, string>, path: string, body: string, oid?: string): void {\n+\t\tthis.retainChunks(\n+\t\t\tfiles,\n+\t\t\tpath,\n+\t\t\t(function* () {\n+\t\t\t\tfor (let at = 0; at < body.length; at += StoredText.chunkCharacters)\n+\t\t\t\t\tyield body.slice(at, at + StoredText.chunkCharacters);\n+\t\t\t})(),\n+\t\t\toid,\n+\t\t);\n+\t}\n+\tretainChunks(files: Record<string, string>, path: string, chunks: Iterable<string>, oid?: string): void {\n+\t\tif (!this.active) throw Error(\"Git intake trees are closed\");\n+\t\tif (oid !== undefined && !/^[0-9a-f]{40}$/.test(oid)) throw Error(\"Invalid Git blob id\");\n+\t\tconst key = oid === undefined ? String(this.next++) : `blob:${oid}`;\n+\t\tthis.storage.transactionSync(() => {\n+\t\t\tif (this.text.storage.read(this.text.collection, key) === undefined) this.text.writeChunks(key, chunks);\n+\t\t});\n+\t\tObject.defineProperty(files, path, {\n+\t\t\tenumerable: true,\n+\t\t\tget: this.getter(key),\n+\t\t});\n+\t}\n+\tretain(tree: Tree): Tree {\n+\t\tif (!this.active) throw Error(\"Git intake trees are closed\");\n+\t\tconst files: Record<string, string> = Object.create(null);\n+\t\tthis.storage.transactionSync(() => {\n+\t\t\tfor (const path of Object.keys(tree.files)) {\n+\t\t\t\tconst key = String(this.next++);\n+\t\t\t\tthis.text.write(key, tree.files[path]!);\n+\t\t\t\tObject.defineProperty(files, path, {\n+\t\t\t\t\tenumerable: true,\n+\t\t\t\t\tget: this.getter(key),\n+\t\t\t\t});\n+\t\t\t}\n+\t\t});\n+\t\treturn { files, modes: tree.modes, blobs: tree.blobs };\n+\t}\n+\t[Symbol.dispose](): void {\n+\t\tthis.dispose();\n+\t}\n+\tdispose(): void {\n+\t\tthis.active = false;\n+\t\tthis.storage.sql.exec(\"DELETE FROM writer_state WHERE namespace = ?\", this.namespace);\n+\t}\n+}"},{"path":"server/src/git-object-bytes.ts","added":146,"removed":0,"diff":"--- /dev/null\n+++ b/server/src/git-object-bytes.ts\n@@ -0,0 +1,146 @@\n+import { createHash } from \"node:crypto\";\n+import type { SqliteStorage } from \"./engine-project.ts\";\n+import type { GitByteRanges } from \"./git-delta-stream.ts\";\n+\n+export type StoredGitBytes = GitByteRanges & {\n+\tid: string;\n+\toid: string;\n+\ttype: string;\n+};\n+\n+/** Intake-local object bytes; callers own this store's lifetime. */\n+export class GitObjectBytes {\n+\treadonly scope = crypto.randomUUID();\n+\tprivate closed = false;\n+\tprivate readonly storage: SqliteStorage;\n+\tprivate readonly maxDecodedBytes: number;\n+\tconstructor(storage: SqliteStorage, maxDecodedBytes = Number.MAX_SAFE_INTEGER) {\n+\t\tif (!Number.isSafeInteger(maxDecodedBytes) || maxDecodedBytes < 0) throw Error(\"invalid decoded byte limit\");\n+\t\tthis.storage = storage;\n+\t\tthis.maxDecodedBytes = maxDecodedBytes;\n+\t\tstorage.sql.exec(\n+\t\t\t\"CREATE TABLE IF NOT EXISTS git_object_bytes (scope TEXT, id TEXT, part INTEGER, data BLOB NOT NULL, PRIMARY KEY(scope,id,part))\",\n+\t\t);\n+\t\tstorage.sql.exec(\n+\t\t\t\"CREATE TABLE IF NOT EXISTS git_object_meta (scope TEXT, id TEXT, type TEXT, bytes INTEGER, oid TEXT, PRIMARY KEY(scope,id))\",\n+\t\t);\n+\t\tstorage.sql.exec(\"CREATE TABLE IF NOT EXISTS git_object_budget (scope TEXT PRIMARY KEY, decoded INTEGER NOT NULL)\");\n+\t\tstorage.sql.exec(\"INSERT INTO git_object_budget VALUES (?, 0)\", this.scope);\n+\t}\n+\tprivate active(): void {\n+\t\tif (this.closed) throw Error(\"Git object store is closed\");\n+\t}\n+\tput(type: string, produce: (write: (bytes: Uint8Array) => void) => void, maxBytes: number): StoredGitBytes {\n+\t\tthis.active();\n+\t\tif (![\"blob\", \"tree\", \"commit\", \"tag\"].includes(type) || !Number.isSafeInteger(maxBytes) || maxBytes < 0)\n+\t\t\tthrow Error(\"invalid Git object limits or type\");\n+\t\tconst id = crypto.randomUUID();\n+\t\tthis.storage.transactionSync(() => {\n+\t\t\tconst budget = this.storage.sql\n+\t\t\t\t.exec(\"SELECT decoded FROM git_object_budget WHERE scope = ?\", this.scope)\n+\t\t\t\t.toArray() as { decoded: number }[];\n+\t\t\tif (budget.length !== 1) throw Error(\"missing Git decoded budget\");\n+\t\t\tconst remaining = this.maxDecodedBytes - budget[0]!.decoded;\n+\t\t\tlet length = 0,\n+\t\t\t\tpart = 0,\n+\t\t\t\tused = 0;\n+\t\t\tconst pending = new Uint8Array(65536);\n+\t\t\tconst flush = () => {\n+\t\t\t\tthis.storage.sql.exec(\n+\t\t\t\t\t\"INSERT INTO git_object_bytes VALUES (?, ?, ?, ?)\",\n+\t\t\t\t\tthis.scope,\n+\t\t\t\t\tid,\n+\t\t\t\t\tpart++,\n+\t\t\t\t\tpending.slice(0, used),\n+\t\t\t\t);\n+\t\t\t\tused = 0;\n+\t\t\t};\n+\t\t\tproduce((bytes) => {\n+\t\t\t\tif (length + bytes.length > maxBytes) throw Error(\"Git object exceeds byte limit\");\n+\t\t\t\tif (length + bytes.length > remaining) throw Error(\"Git pack exceeds total decoded byte limit\");\n+\t\t\t\tlength += bytes.length;\n+\t\t\t\tfor (let at = 0; at < bytes.length; ) {\n+\t\t\t\t\tconst count = Math.min(pending.length - used, bytes.length - at);\n+\t\t\t\t\tpending.set(bytes.subarray(at, at + count), used);\n+\t\t\t\t\tat += count;\n+\t\t\t\t\tused += count;\n+\t\t\t\t\tif (used === pending.length) flush();\n+\t\t\t\t}\n+\t\t\t});\n+\t\t\tif (used) flush();\n+\t\t\tconst hash = createHash(\"sha1\").update(`${type} ${length}\\0`);\n+\t\t\tfor (let index = 0; index < part; index++) hash.update(this.chunk(id, index));\n+\t\t\tthis.storage.sql.exec(\n+\t\t\t\t\"INSERT INTO git_object_meta VALUES (?, ?, ?, ?, ?)\",\n+\t\t\t\tthis.scope,\n+\t\t\t\tid,\n+\t\t\t\ttype,\n+\t\t\t\tlength,\n+\t\t\t\thash.digest(\"hex\"),\n+\t\t\t);\n+\t\t\tthis.storage.sql.exec(\"UPDATE git_object_budget SET decoded = decoded + ? WHERE scope = ?\", length, this.scope);\n+\t\t});\n+\t\treturn this.get(id);\n+\t}\n+\tprivate chunk(id: string, part: number): Uint8Array {\n+\t\tthis.active();\n+\t\tconst rows = this.storage.sql\n+\t\t\t.exec(\"SELECT data FROM git_object_bytes WHERE scope = ? AND id = ? AND part = ?\", this.scope, id, part)\n+\t\t\t.toArray() as { data: ArrayBuffer }[];\n+\t\tif (rows.length !== 1) throw Error(\"missing Git object chunk\");\n+\t\tconst bytes = new Uint8Array(rows[0]!.data);\n+\t\tif (!bytes.length || bytes.length > 65536) throw Error(\"invalid Git object chunk\");\n+\t\treturn bytes;\n+\t}\n+\tget(id: string): StoredGitBytes {\n+\t\tthis.active();\n+\t\tconst rows = this.storage.sql\n+\t\t\t.exec(\"SELECT type, bytes, oid FROM git_object_meta WHERE scope = ? AND id = ?\", this.scope, id)\n+\t\t\t.toArray() as { type: string; bytes: number; oid: string }[];\n+\t\tif (rows.length !== 1) throw Error(\"missing Git object\");\n+\t\tconst meta = rows[0]!;\n+\t\treturn {\n+\t\t\tid,\n+\t\t\toid: meta.oid,\n+\t\t\ttype: meta.type,\n+\t\t\tbyteLength: meta.bytes,\n+\t\t\tread: (start, length) => {\n+\t\t\t\tthis.active();\n+\t\t\t\tif (\n+\t\t\t\t\t!Number.isSafeInteger(start) ||\n+\t\t\t\t\t!Number.isSafeInteger(length) ||\n+\t\t\t\t\tstart < 0 ||\n+\t\t\t\t\tlength < 0 ||\n+\t\t\t\t\tlength > 65536 ||\n+\t\t\t\t\tstart + length > meta.bytes\n+\t\t\t\t)\n+\t\t\t\t\tthrow Error(\"invalid Git object range\");\n+\t\t\t\tconst result = new Uint8Array(length);\n+\t\t\t\tfor (let copied = 0; copied < length; ) {\n+\t\t\t\t\tconst position = start + copied,\n+\t\t\t\t\t\tchunk = this.chunk(id, Math.floor(position / 65536));\n+\t\t\t\t\tconst offset = position % 65536,\n+\t\t\t\t\t\tcount = Math.min(length - copied, chunk.length - offset);\n+\t\t\t\t\tif (count <= 0) throw Error(\"truncated Git object chunk\");\n+\t\t\t\t\tresult.set(chunk.subarray(offset, offset + count), copied);\n+\t\t\t\t\tcopied += count;\n+\t\t\t\t}\n+\t\t\t\treturn result;\n+\t\t\t},\n+\t\t};\n+\t}\n+\t/** Remove obsolete delta instructions without refunding their decoded-work budget. */\n+\tremove(id: string): void {\n+\t\tthis.active();\n+\t\tthis.storage.sql.exec(\"DELETE FROM git_object_bytes WHERE scope = ? AND id = ?\", this.scope, id);\n+\t\tthis.storage.sql.exec(\"DELETE FROM git_object_meta WHERE scope = ? AND id = ?\", this.scope, id);\n+\t}\n+\tdispose(): void {\n+\t\tthis.closed = true;\n+\t\tthis.storage.transactionSync(() => {\n+\t\t\tthis.storage.sql.exec(\"DELETE FROM git_object_bytes WHERE scope = ?\", this.scope);\n+\t\t\tthis.storage.sql.exec(\"DELETE FROM git_object_meta WHERE scope = ?\", this.scope);\n+\t\t\tthis.storage.sql.exec(\"DELETE FROM git_object_budget WHERE scope = ?\", this.scope);\n+\t\t});\n+\t}\n+}"},{"path":"server/src/git-pack-decode.ts","added":100,"removed":0,"diff":"--- /dev/null\n+++ b/server/src/git-pack-decode.ts\n@@ -0,0 +1,100 @@\n+import type { GitPackResolver } from \"./git-pack-resolver.ts\";\n+import type { GitPackSpool } from \"./git-pack-spool.ts\";\n+\n+/** Structural adapter for the pinned Git dependency's streaming inflater. */\n+export interface PackInflater {\n+\tonData: (bytes: Uint8Array) => void;\n+\tpush(bytes: Uint8Array, final: boolean): unknown;\n+\tended: boolean;\n+\terr: number;\n+\tmsg: string;\n+\tstrm: { avail_in: number };\n+}\n+\n+/** Decode verified disk bytes without collecting a pack or decoded object in memory. */\n+export function decodeGitPack(\n+\tspool: GitPackSpool,\n+\tresolver: GitPackResolver,\n+\tcreateInflater: () => PackInflater,\n+): void {\n+\ttry {\n+\t\tdecodeVerifiedPack(spool, resolver, createInflater);\n+\t} catch (error) {\n+\t\t// Intake owns this resolver. Never expose earlier objects from a rejected pack.\n+\t\tresolver.dispose();\n+\t\tthrow error;\n+\t}\n+}\n+\n+function decodeVerifiedPack(spool: GitPackSpool, resolver: GitPackResolver, createInflater: () => PackInflater): void {\n+\tconst end = spool.byteLength - 20;\n+\tconst header = spool.read(0, 12);\n+\tconst count = new DataView(header.buffer, header.byteOffset, header.byteLength).getUint32(8);\n+\tlet position = 12;\n+\tlet cached: Uint8Array = new Uint8Array(0),\n+\t\tcachedAt = 0;\n+\tconst byte = () => {\n+\t\tif (position >= end) throw Error(\"truncated Git pack header\");\n+\t\tif (position < cachedAt || position >= cachedAt + cached.length) {\n+\t\t\tcachedAt = position;\n+\t\t\tcached = spool.read(position, Math.min(65536, end - position));\n+\t\t}\n+\t\treturn cached[position++ - cachedAt]!;\n+\t};\n+\tfor (let index = 0; index < count; index++) {\n+\t\tconst offset = position;\n+\t\tlet current = byte();\n+\t\tconst kind = (current >> 4) & 7;\n+\t\tlet length = current & 15,\n+\t\t\tfactor = 16;\n+\t\twhile (current & 128) {\n+\t\t\tcurrent = byte();\n+\t\t\tlength += (current & 127) * factor;\n+\t\t\tfactor *= 128;\n+\t\t\tif (!Number.isSafeInteger(length) || !Number.isSafeInteger(factor)) throw Error(\"invalid Git object size\");\n+\t\t}\n+\t\tlet base: number | string | undefined;\n+\t\tif (kind === 6) {\n+\t\t\tcurrent = byte();\n+\t\t\tlet distance = current & 127;\n+\t\t\twhile (current & 128) {\n+\t\t\t\tcurrent = byte();\n+\t\t\t\tdistance = (distance + 1) * 128 + (current & 127);\n+\t\t\t\tif (!Number.isSafeInteger(distance)) throw Error(\"invalid Git delta distance\");\n+\t\t\t}\n+\t\t\tbase = offset - distance;\n+\t\t} else if (kind === 7) {\n+\t\t\tlet reference = \"\";\n+\t\t\tfor (let i = 0; i < 20; i++) reference += byte().toString(16).padStart(2, \"0\");\n+\t\t\tbase = reference;\n+\t\t}\n+\t\tconst type = [\"\", \"commit\", \"tree\", \"blob\", \"tag\", \"\", \"delta\", \"delta\"][kind];\n+\t\tif (!type) throw Error(\"unsupported Git object type\");\n+\t\tresolver.addChunks(\n+\t\t\toffset,\n+\t\t\ttype,\n+\t\t\t(write) => {\n+\t\t\t\tconst inflater = createInflater();\n+\t\t\t\tlet decoded = 0;\n+\t\t\t\tinflater.onData = (bytes) => {\n+\t\t\t\t\tdecoded += bytes.length;\n+\t\t\t\t\tif (bytes.length > 65536 || decoded > length) throw Error(\"invalid inflated Git object size\");\n+\t\t\t\t\twrite(bytes);\n+\t\t\t\t};\n+\t\t\t\twhile (!inflater.ended) {\n+\t\t\t\t\tif (position >= end) throw Error(\"truncated compressed Git object\");\n+\t\t\t\t\tconst chunk = spool.read(position, Math.min(65536, end - position));\n+\t\t\t\t\tinflater.push(chunk, false);\n+\t\t\t\t\tif (inflater.err) throw Error(`Git inflate failed: ${inflater.msg}`);\n+\t\t\t\t\tconst consumed = chunk.length - inflater.strm.avail_in;\n+\t\t\t\t\tif (consumed <= 0 || consumed > chunk.length) throw Error(\"Git inflater made no progress\");\n+\t\t\t\t\tposition += consumed;\n+\t\t\t\t}\n+\t\t\t\tif (decoded !== length) throw Error(\"inflated Git object size mismatch\");\n+\t\t\t},\n+\t\t\tbase,\n+\t\t);\n+\t}\n+\tif (position !== end) throw Error(\"unexpected bytes after Git pack objects\");\n+\tresolver.resolve();\n+}"},{"path":"server/src/git-pack-resolver.ts","added":133,"removed":0,"diff":"--- /dev/null\n+++ b/server/src/git-pack-resolver.ts\n@@ -0,0 +1,133 @@\n+import type { SqliteStorage } from \"./engine-project.ts\";\n+import { applyGitDeltaChunks } from \"./git-delta-stream.ts\";\n+import { GitObjectBytes, type StoredGitBytes } from \"./git-object-bytes.ts\";\n+\n+/** Scratch index and decoded objects for one pack. No in-memory object map. */\n+export class GitPackResolver {\n+\treadonly scope = crypto.randomUUID();\n+\treadonly objects: GitObjectBytes;\n+\tprivate readonly storage: SqliteStorage;\n+\tprivate readonly maxObjectBytes: number;\n+\tprivate closed = false;\n+\tconstructor(storage: SqliteStorage, maxObjectBytes: number, maxDecodedBytes = maxObjectBytes) {\n+\t\tif (!Number.isSafeInteger(maxObjectBytes) || maxObjectBytes < 0) throw Error(\"invalid object limit\");\n+\t\tthis.storage = storage;\n+\t\tthis.maxObjectBytes = maxObjectBytes;\n+\t\tthis.objects = new GitObjectBytes(storage, maxDecodedBytes);\n+\t\tstorage.sql.exec(\n+\t\t\t\"CREATE TABLE IF NOT EXISTS git_pack_resolve (scope TEXT, offset INTEGER, raw TEXT, base_offset INTEGER, base_oid TEXT, result TEXT, oid TEXT, depth INTEGER, PRIMARY KEY(scope,offset))\",\n+\t\t);\n+\t\tstorage.sql.exec(\"CREATE INDEX IF NOT EXISTS git_pack_resolve_oid ON git_pack_resolve(scope,oid)\");\n+\t\tstorage.sql.exec(\n+\t\t\t\"CREATE INDEX IF NOT EXISTS git_pack_unresolved ON git_pack_resolve(scope,offset) WHERE result IS NULL\",\n+\t\t);\n+\t}\n+\tprivate active(): void {\n+\t\tif (this.closed) throw Error(\"pack resolver is closed\");\n+\t}\n+\tadd(offset: number, type: string, data: Uint8Array, base?: number | string): void {\n+\t\tthis.addChunks(offset, type, (write) => write(data), base);\n+\t}\n+\t/** The inflater writes bounded output directly into the transactional object store. */\n+\taddChunks(\n+\t\toffset: number,\n+\t\ttype: string,\n+\t\tproduce: (write: (bytes: Uint8Array) => void) => void,\n+\t\tbase?: number | string,\n+\t): void {\n+\t\tthis.active();\n+\t\tif (!Number.isSafeInteger(offset) || offset < 12) throw Error(\"invalid pack offset\");\n+\t\tif (type === \"delta\") {\n+\t\t\tif (\n+\t\t\t\ttypeof base === \"number\"\n+\t\t\t\t\t? !Number.isSafeInteger(base) || base < 12 || base >= offset\n+\t\t\t\t\t: typeof base !== \"string\" || !/^[0-9a-f]{40}$/.test(base)\n+\t\t\t)\n+\t\t\t\tthrow Error(\"invalid delta base reference\");\n+\t\t} else if (base !== undefined) throw Error(\"ordinary object has delta base\");\n+\t\tthis.storage.transactionSync(() => {\n+\t\t\tconst stored = this.objects.put(type === \"delta\" ? \"blob\" : type, produce, this.maxObjectBytes);\n+\t\t\tthis.storage.sql.exec(\n+\t\t\t\t\"INSERT INTO git_pack_resolve VALUES (?, ?, ?, ?, ?, ?, ?, ?)\",\n+\t\t\t\tthis.scope,\n+\t\t\t\toffset,\n+\t\t\t\tstored.id,\n+\t\t\t\ttypeof base === \"number\" ? base : null,\n+\t\t\t\ttypeof base === \"string\" ? base : null,\n+\t\t\t\ttype === \"delta\" ? null : stored.id,\n+\t\t\t\ttype === \"delta\" ? null : stored.oid,\n+\t\t\t\ttype === \"delta\" ? null : 0,\n+\t\t\t);\n+\t\t});\n+\t}\n+\tresolve(): void {\n+\t\tthis.active();\n+\t\tthis.storage.transactionSync(() => {\n+\t\t\tfor (;;) {\n+\t\t\t\tconst rows = this.storage.sql\n+\t\t\t\t\t.exec(\n+\t\t\t\t\t\t`SELECT p.offset, p.raw, COALESCE(b.result, r.result) AS base, COALESCE(b.depth, r.depth) AS depth\n+FROM git_pack_resolve p\n+LEFT JOIN git_pack_resolve b ON b.scope = p.scope AND b.offset = p.base_offset\n+LEFT JOIN git_pack_resolve r ON r.scope = p.scope AND r.oid = p.base_oid\n+WHERE p.scope = ? AND p.result IS NULL AND (b.result IS NOT NULL OR r.result IS NOT NULL)\n+ORDER BY p.offset LIMIT 1`,\n+\t\t\t\t\t\tthis.scope,\n+\t\t\t\t\t)\n+\t\t\t\t\t.toArray() as {\n+\t\t\t\t\toffset: number;\n+\t\t\t\t\traw: string;\n+\t\t\t\t\tbase: string;\n+\t\t\t\t\tdepth: number;\n+\t\t\t\t}[];\n+\t\t\t\tif (!rows.length) break;\n+\t\t\t\tconst row = rows[0]!;\n+\t\t\t\tif (row.depth >= 64) throw Error(\"Git delta chain exceeds depth limit\");\n+\t\t\t\tconst base = this.objects.get(row.base),\n+\t\t\t\t\tdelta = this.objects.get(row.raw);\n+\t\t\t\tconst result = this.objects.put(\n+\t\t\t\t\tbase.type,\n+\t\t\t\t\t(write) => {\n+\t\t\t\t\t\tapplyGitDeltaChunks(delta, base, write, this.maxObjectBytes);\n+\t\t\t\t\t},\n+\t\t\t\t\tthis.maxObjectBytes,\n+\t\t\t\t);\n+\t\t\t\tthis.storage.sql.exec(\n+\t\t\t\t\t\"UPDATE git_pack_resolve SET result = ?, oid = ?, depth = ? WHERE scope = ? AND offset = ?\",\n+\t\t\t\t\tresult.id,\n+\t\t\t\t\tresult.oid,\n+\t\t\t\t\trow.depth + 1,\n+\t\t\t\t\tthis.scope,\n+\t\t\t\t\trow.offset,\n+\t\t\t\t);\n+\t\t\t\tthis.objects.remove(row.raw);\n+\t\t\t}\n+\t\t\tif (\n+\t\t\t\tthis.storage.sql\n+\t\t\t\t\t.exec(\"SELECT offset FROM git_pack_resolve WHERE scope = ? AND result IS NULL LIMIT 1\", this.scope)\n+\t\t\t\t\t.toArray().length\n+\t\t\t)\n+\t\t\t\tthrow Error(\"unresolved or cyclic Git delta base\");\n+\t\t});\n+\t}\n+\tget(oid: string): StoredGitBytes {\n+\t\tconst value = this.find(oid);\n+\t\tif (!value) throw Error(\"missing packed Git object\");\n+\t\treturn value;\n+\t}\n+\tfind(oid: string): StoredGitBytes | undefined {\n+\t\tthis.active();\n+\t\tconst rows = this.storage.sql\n+\t\t\t.exec(\"SELECT result FROM git_pack_resolve WHERE scope = ? AND oid = ? LIMIT 1\", this.scope, oid)\n+\t\t\t.toArray() as { result: string }[];\n+\t\tif (!rows.length) return undefined;\n+\t\treturn this.objects.get(rows[0]!.result);\n+\t}\n+\tdispose(): void {\n+\t\tthis.closed = true;\n+\t\tthis.storage.transactionSync(() => {\n+\t\t\tthis.storage.sql.exec(\"DELETE FROM git_pack_resolve WHERE scope = ?\", this.scope);\n+\t\t\tthis.objects.dispose();\n+\t\t});\n+\t}\n+}"},{"path":"server/src/git-pack-spool.ts","added":119,"removed":0,"diff":"--- /dev/null\n+++ b/server/src/git-pack-spool.ts\n@@ -0,0 +1,119 @@\n+import { createHash } from \"node:crypto\";\n+import type { SqliteStorage } from \"./engine-project.ts\";\n+\n+/** Temporary verified pack bytes. No whole-pack read API is exposed. */\n+export class GitPackSpool {\n+\tstatic readonly chunkBytes = 65536;\n+\t/** Cold Durable Object construction only, before any intake starts. */\n+\tstatic recover(storage: SqliteStorage): void {\n+\t\tGitPackSpool.initialize(storage);\n+\t\tstorage.sql.exec(\"DELETE FROM git_pack_spool\");\n+\t}\n+\tprivate static initialize(storage: SqliteStorage): void {\n+\t\tstorage.sql.exec(\n+\t\t\t\"CREATE TABLE IF NOT EXISTS git_pack_spool (id TEXT NOT NULL, part INTEGER NOT NULL, data BLOB NOT NULL, PRIMARY KEY (id, part))\",\n+\t\t);\n+\t}\n+\treadonly id = crypto.randomUUID();\n+\tprivate size = 0;\n+\tprivate sealed = false;\n+\tprivate closed = false;\n+\tprivate readonly storage: SqliteStorage;\n+\tconstructor(storage: SqliteStorage) {\n+\t\tthis.storage = storage;\n+\t\tGitPackSpool.initialize(storage);\n+\t}\n+\tget byteLength(): number {\n+\t\tthis.assertReadable();\n+\t\treturn this.size;\n+\t}\n+\tprivate assertReadable(): void {\n+\t\tif (!this.sealed || this.closed) throw Error(\"pack spool is not readable\");\n+\t}\n+\tasync ingest(chunks: AsyncIterable<Uint8Array> | Iterable<Uint8Array>, maxBytes: number): Promise<string> {\n+\t\tif (this.size || this.sealed || this.closed) throw Error(\"pack spool already used\");\n+\t\tif (!Number.isSafeInteger(maxBytes) || maxBytes < 32) throw Error(\"invalid pack byte limit\");\n+\t\tconst hash = createHash(\"sha1\");\n+\t\tlet tail = new Uint8Array(0);\n+\t\tlet pending = new Uint8Array(GitPackSpool.chunkBytes),\n+\t\t\tused = 0,\n+\t\t\tpart = 0;\n+\t\tconst save = () => {\n+\t\t\tif (this.closed) throw Error(\"pack spool is closed\");\n+\t\t\tthis.storage.sql.exec(\"INSERT INTO git_pack_spool VALUES (?, ?, ?)\", this.id, part++, pending.slice(0, used));\n+\t\t\tused = 0;\n+\t\t};\n+\t\ttry {\n+\t\t\tfor await (const chunk of chunks) {\n+\t\t\t\tif (this.closed) throw Error(\"pack spool is closed\");\n+\t\t\t\tif (!(chunk instanceof Uint8Array)) throw Error(\"invalid pack chunk\");\n+\t\t\t\tfor (let at = 0; at < chunk.length; ) {\n+\t\t\t\t\tconst count = Math.min(GitPackSpool.chunkBytes - used, chunk.length - at);\n+\t\t\t\t\tif (this.size + count > maxBytes) throw Error(\"pack exceeds byte limit\");\n+\t\t\t\t\tconst piece = chunk.subarray(at, at + count);\n+\t\t\t\t\tconst joined = new Uint8Array(tail.length + piece.length);\n+\t\t\t\t\tjoined.set(tail);\n+\t\t\t\t\tjoined.set(piece, tail.length);\n+\t\t\t\t\tconst end = Math.max(0, joined.length - 20);\n+\t\t\t\t\thash.update(joined.subarray(0, end));\n+\t\t\t\t\ttail = joined.slice(end);\n+\t\t\t\t\tpending.set(piece, used);\n+\t\t\t\t\tused += count;\n+\t\t\t\t\tat += count;\n+\t\t\t\t\tthis.size += count;\n+\t\t\t\t\tif (used === pending.length) save();\n+\t\t\t\t}\n+\t\t\t}\n+\t\t\tif (used) save();\n+\t\t\tif (this.size < 32 || tail.length !== 20) throw Error(\"truncated pack\");\n+\t\t\tconst digest = hash.digest(\"hex\");\n+\t\t\tif (digest !== Buffer.from(tail).toString(\"hex\")) throw Error(\"pack checksum mismatch\");\n+\t\t\tthis.sealed = true;\n+\t\t\tconst header = this.read(0, 12);\n+\t\t\tif (new TextDecoder().decode(header.subarray(0, 4)) !== \"PACK\" || new DataView(header.buffer).getUint32(4) !== 2)\n+\t\t\t\tthrow Error(\"unsupported pack header\");\n+\t\t\treturn digest;\n+\t\t} catch (error) {\n+\t\t\tthis.dispose();\n+\t\t\tthrow error;\n+\t\t}\n+\t}\n+\tread(start: number, length: number): Uint8Array {\n+\t\tthis.assertReadable();\n+\t\tif (\n+\t\t\t!Number.isSafeInteger(start) ||\n+\t\t\t!Number.isSafeInteger(length) ||\n+\t\t\tstart < 0 ||\n+\t\t\tlength < 0 ||\n+\t\t\tlength > GitPackSpool.chunkBytes ||\n+\t\t\tstart + length > this.size\n+\t\t)\n+\t\t\tthrow Error(\"invalid pack byte range\");\n+\t\tconst result = new Uint8Array(length);\n+\t\tlet copied = 0;\n+\t\twhile (copied < length) {\n+\t\t\tconst position = start + copied,\n+\t\t\t\tpart = Math.floor(position / GitPackSpool.chunkBytes);\n+\t\t\tconst rows = this.storage.sql\n+\t\t\t\t.exec(\"SELECT data FROM git_pack_spool WHERE id = ? AND part = ?\", this.id, part)\n+\t\t\t\t.toArray() as { data: ArrayBuffer }[];\n+\t\t\tif (rows.length !== 1) throw Error(\"missing pack chunk\");\n+\t\t\tconst data = new Uint8Array(rows[0]!.data),\n+\t\t\t\toffset = position % GitPackSpool.chunkBytes;\n+\t\t\tconst count = Math.min(length - copied, data.length - offset);\n+\t\t\tif (count <= 0 || data.length > GitPackSpool.chunkBytes) throw Error(\"invalid pack chunk\");\n+\t\t\tresult.set(data.subarray(offset, offset + count), copied);\n+\t\t\tcopied += count;\n+\t\t}\n+\t\treturn result;\n+\t}\n+\t*chunks(): IterableIterator<Uint8Array> {\n+\t\tthis.assertReadable();\n+\t\tfor (let start = 0; start < this.size; start += GitPackSpool.chunkBytes)\n+\t\t\tyield this.read(start, Math.min(GitPackSpool.chunkBytes, this.size - start));\n+\t}\n+\tdispose(): void {\n+\t\tthis.closed = true;\n+\t\tthis.storage.sql.exec(\"DELETE FROM git_pack_spool WHERE id = ?\", this.id);\n+\t}\n+}"},{"path":"server/src/ingest.ts","added":106,"removed":14,"diff":"--- a/server/src/ingest.ts\n+++ b/server/src/ingest.ts\n@@ -2,12 +2,17 @@\n // project's Artifacts repo, read back for project.ingest. Every commit the\n // Worker pushes ends \"abso-version: N\" (\"avcs-version: N\" before the rename); the commits above the newest such\n // commit that haven't been taken in yet are the person's, and N is their base.\n-import git from \"isomorphic-git\";\n-import http from \"isomorphic-git/http/web\";\n+import git, { type HttpClient } from \"isomorphic-git\";\n import type { FileModes } from \"../../worker/project/project-api.ts\";\n+import type { SqliteStorage } from \"./engine-project.ts\";\n+import { gitBlobText, InvalidGitUtf8 } from \"./git-blob-text.ts\";\n+import { GitDiskIntake } from \"./git-disk-intake.ts\";\n+import { gitHttp } from \"./git-http.ts\";\n import { MemoryFS } from \"./memory-fs.ts\";\n import { repoName } from \"./push.ts\";\n \n+const http = gitHttp();\n+\n const EXEC = 0o100755;\n const LINK = 0o120000;\n \n@@ -40,7 +45,10 @@\n async function readAccess(\n \tartifacts: Artifacts,\n \tproject: string,\n-): Promise<{ url: string; onAuth: () => { username: string; password: string } } | null> {\n+): Promise<{\n+\turl: string;\n+\tonAuth: () => { username: string; password: string };\n+} | null> {\n \tlet repo: Awaited<ReturnType<Artifacts[\"get\"]>>;\n \ttry {\n \t\trepo = await artifacts.get(repoName(project));\n@@ -57,7 +65,12 @@\n export async function remoteHead(artifacts: Artifacts, project: string): Promise<string | null> {\n \tconst access = await readAccess(artifacts, project);\n \tif (!access) return null;\n-\tconst refs = await git.listServerRefs({ http, url: access.url, onAuth: access.onAuth, prefix: \"refs/heads/main\" });\n+\tconst refs = await git.listServerRefs({\n+\t\thttp,\n+\t\turl: access.url,\n+\t\tonAuth: access.onAuth,\n+\t\tprefix: \"refs/heads/main\",\n+\t});\n \treturn refs.find((r) => r.ref === \"refs/heads/main\")?.oid ?? null;\n }\n \n@@ -67,6 +80,12 @@\n  */\n /** Stores a binary file's bytes and answers their SHA-256, or null when they're over the limit. */\n export type StoreBlob = (bytes: Uint8Array) => Promise<string | null>;\n+export type RetainFileChunks = (\n+\tfiles: Record<string, string>,\n+\tpath: string,\n+\tchunks: Iterable<string>,\n+\toid: string,\n+) => void;\n \n /**\n  * `oldBlob` gives shared's blob for a path: a binary file over the limit\n@@ -78,14 +97,35 @@\n \tseen: string | undefined,\n \tstoreBlob?: StoreBlob,\n \toldBlob: (path: string) => string | undefined = () => undefined,\n+\tretainFile: (files: Record<string, string>, path: string, body: string, oid?: string) => void = (\n+\t\tfiles,\n+\t\tpath,\n+\t\tbody,\n+\t) => {\n+\t\tfiles[path] = body;\n+\t},\n+\tdisk?: {\n+\t\tstorage: SqliteStorage;\n+\t\tmaxPackBytes: number;\n+\t\tmaxObjectBytes: number;\n+\t\tmaxDecodedBytes?: number;\n+\t\thttp?: HttpClient;\n+\t\tretainFileChunks?: RetainFileChunks;\n+\t},\n ): Promise<PushedCommits | null> {\n \tconst access = await readAccess(artifacts, project);\n \tif (!access) return null;\n \tconst fs = new MemoryFS();\n \tconst dir = \"/repo\";\n+\tusing intake = disk\n+\t\t? new GitDiskIntake(disk.storage, disk.maxPackBytes, disk.maxObjectBytes, disk.maxDecodedBytes)\n+\t\t: undefined;\n+\tconst cache = disk ? {} : undefined;\n+\tif (intake && cache) intake.attach(cache);\n \tawait git.clone({\n \t\tfs,\n-\t\thttp,\n+\t\tcache,\n+\t\thttp: disk?.http ?? http,\n \t\tdir,\n \t\turl: access.url,\n \t\tonAuth: access.onAuth,\n@@ -94,7 +134,8 @@\n \t\tdepth: DEPTH,\n \t\tnoCheckout: true,\n \t});\n-\tconst log = await git.log({ fs, dir, ref: \"main\", depth: DEPTH });\n+\tintake?.assertReady();\n+\tconst log = await git.log({ fs, dir, cache, ref: \"main\", depth: DEPTH });\n \tif (log.length === 0) return null;\n \tconst head = log[0]!.oid;\n \tconst fresh: typeof log = [];\n@@ -113,9 +154,26 @@\n \t\tcommits.push({\n \t\t\tsha: c.oid,\n \t\t\tmessage: c.commit.message.trim(),\n-\t\t\t...(await treeText(fs, dir, c.oid, storeBlob, tooBig, oldBlob)),\n+\t\t\t...(await treeText(\n+\t\t\t\tfs,\n+\t\t\t\tdir,\n+\t\t\t\tc.oid,\n+\t\t\t\tstoreBlob,\n+\t\t\t\ttooBig,\n+\t\t\t\toldBlob,\n+\t\t\t\tretainFile,\n+\t\t\t\tcache,\n+\t\t\t\tintake,\n+\t\t\t\tdisk?.retainFileChunks,\n+\t\t\t)),\n \t\t});\n-\treturn { head, author: fresh.at(-1)?.commit.author.name ?? \"git\", base, commits, tooBig: [...tooBig] };\n+\treturn {\n+\t\thead,\n+\t\tauthor: fresh.at(-1)?.commit.author.name ?? \"git\",\n+\t\tbase,\n+\t\tcommits,\n+\t\ttooBig: [...tooBig],\n+\t};\n }\n \n /**\n@@ -123,24 +181,59 @@\n  * a link (120000) is \"\" with its target in modes. Files that aren't UTF-8\n  * are left out.\n  */\n-async function treeText(\n+export async function treeText(\n \tfs: MemoryFS,\n \tdir: string,\n \toid: string,\n \tstoreBlob: StoreBlob | undefined,\n \ttooBig: Set<string>,\n \toldBlob: (path: string) => string | undefined,\n-): Promise<{ files: Record<string, string>; modes: FileModes; blobs: Record<string, string> }> {\n+\tretainFile: (files: Record<string, string>, path: string, body: string, oid?: string) => void,\n+\tcache: object = {},\n+\tintake?: GitDiskIntake,\n+\tretainFileChunks?: RetainFileChunks,\n+): Promise<{\n+\tfiles: Record<string, string>;\n+\tmodes: FileModes;\n+\tblobs: Record<string, string>;\n+}> {\n \tconst files: Record<string, string> = {};\n \tconst modes: FileModes = {};\n \tconst blobs: Record<string, string> = {};\n \tawait git.walk({\n \t\tfs,\n+\t\tcache,\n \t\tdir,\n \t\ttrees: [git.TREE({ ref: oid })],\n+\t\titerate: async (walk, children) => {\n+\t\t\tfor (const child of children) await walk(child);\n+\t\t\treturn [];\n+\t\t},\n+\t\treduce: async () => undefined,\n \t\tmap: async (path, [entry]) => {\n \t\t\tif (!entry || path === \".\") return true;\n \t\t\tif ((await entry.type()) !== \"blob\") return true;\n+\t\t\tconst mode = await entry.mode();\n+\t\t\tconst blobOid = await entry.oid();\n+\t\t\tif (intake && retainFileChunks && mode !== LINK) {\n+\t\t\t\tconst stored = intake.bytes(blobOid);\n+\t\t\t\tif (stored?.type !== \"blob\") throw Error(\"Git intake blob is missing\");\n+\t\t\t\tlet valid = true;\n+\t\t\t\ttry {\n+\t\t\t\t\t// Validate before retaining: a late invalid byte must take the binary path.\n+\t\t\t\t\tfor (const _ of gitBlobText(stored)) {\n+\t\t\t\t\t\t/* Retain no decoded text. */\n+\t\t\t\t\t}\n+\t\t\t\t} catch (error) {\n+\t\t\t\t\tif (!(error instanceof InvalidGitUtf8)) throw error;\n+\t\t\t\t\tvalid = false;\n+\t\t\t\t}\n+\t\t\t\tif (valid) {\n+\t\t\t\t\tretainFileChunks(files, path, gitBlobText(stored), blobOid);\n+\t\t\t\t\tmodes[path] = { exec: mode === EXEC, link: null };\n+\t\t\t\t\treturn true;\n+\t\t\t\t}\n+\t\t\t}\n \t\t\tconst bytes = await entry.content();\n \t\t\tif (!bytes) return true;\n \t\t\tlet body: string;\n@@ -151,7 +244,7 @@\n \t\t\t\tconst sha = storeBlob ? await storeBlob(bytes) : null;\n \t\t\t\tif (sha) {\n \t\t\t\t\tblobs[path] = sha;\n-\t\t\t\t\tmodes[path] = { exec: (await entry.mode()) === EXEC, link: null };\n+\t\t\t\t\tmodes[path] = { exec: mode === EXEC, link: null };\n \t\t\t\t} else if (storeBlob) {\n \t\t\t\t\ttooBig.add(path);\n \t\t\t\t\tconst kept = oldBlob(path);\n@@ -159,12 +252,11 @@\n \t\t\t\t}\n \t\t\t\treturn true;\n \t\t\t}\n-\t\t\tconst mode = await entry.mode();\n \t\t\tif (mode === LINK) {\n-\t\t\t\tfiles[path] = \"\";\n+\t\t\t\tretainFile(files, path, \"\");\n \t\t\t\tmodes[path] = { exec: false, link: body };\n \t\t\t} else {\n-\t\t\t\tfiles[path] = body;\n+\t\t\t\tretainFile(files, path, body, blobOid);\n \t\t\t\tmodes[path] = { exec: mode === EXEC, link: null };\n \t\t\t}\n \t\t\treturn true;"},{"path":"server/src/project-object.ts","added":21,"removed":0,"diff":"--- a/server/src/project-object.ts\n+++ b/server/src/project-object.ts\n@@ -12,6 +12,8 @@\n import { DiskFirstRuntime } from \"./disk-first-runtime.ts\";\n import { EngineProject, SqliteLog } from \"./engine-project.ts\";\n import { artifactsOf, type Env } from \"./env.ts\";\n+import { GitDiskIntake } from \"./git-disk-intake.ts\";\n+import { GitIntakeTrees } from \"./git-intake-trees.ts\";\n import { pushedSince, remoteHead } from \"./ingest.ts\";\n import {\n \tcheckKey,\n@@ -59,6 +61,10 @@\n export const PUSH_EVERY_MS = 60_000;\n /** While agents are working, how often a call looks for plain-git pushes to the repo. */\n const GIT_CHECK_MS = 15_000;\n+// Disk scratch admission limits, independent of the Worker's resident memory.\n+const GIT_PACK_MAX_BYTES = 128 * 1024 * 1024;\n+const GIT_OBJECT_MAX_BYTES = 64 * 1024 * 1024;\n+const GIT_DECODED_MAX_BYTES = 256 * 1024 * 1024;\n \n /**\n  * The load guard (platform issue 46): an estimate of a loaded project's memory from its log entries, lines and claim\n@@ -119,6 +125,10 @@\n \tconstructor(ctx: DurableObjectState, env: Env) {\n \t\tsuper(ctx, env);\n \t\tthis.blobs = new BlobStore(ctx.storage);\n+\t\tif (env.ABSO_DISK_FIRST === \"on\") {\n+\t\t\tGitDiskIntake.recover(ctx.storage);\n+\t\t\tGitIntakeTrees.recover(ctx.storage);\n+\t\t}\n \t}\n \n \t/** Where files kept whole go: the project's blob store. */\n@@ -533,12 +543,23 @@\n \t\tconst head = await remoteHead(artifacts, name);\n \t\tif (!head || head === seen || head === pushed?.commit) return null;\n \t\tconst sharedBlobs = this.useProject((p) => p.shared().blobs ?? {});\n+\t\tusing trees = this.diskRuntime() ? new GitIntakeTrees(this.ctx.storage) : undefined;\n \t\tconst found = await pushedSince(\n \t\t\tartifacts,\n \t\t\tname,\n \t\t\tseen,\n \t\t\tasync (bytes) => (bytes.byteLength > BLOB_MAX ? null : this.blobs.putBytes(bytes)),\n \t\t\t(path) => sharedBlobs[path],\n+\t\t\ttrees ? (files, path, body, oid) => trees.retainFile(files, path, body, oid) : undefined,\n+\t\t\ttrees\n+\t\t\t\t? {\n+\t\t\t\t\t\tstorage: this.ctx.storage,\n+\t\t\t\t\t\tmaxPackBytes: GIT_PACK_MAX_BYTES,\n+\t\t\t\t\t\tmaxObjectBytes: GIT_OBJECT_MAX_BYTES,\n+\t\t\t\t\t\tmaxDecodedBytes: GIT_DECODED_MAX_BYTES,\n+\t\t\t\t\t\tretainFileChunks: (files, path, chunks, oid) => trees.retainChunks(files, path, chunks, oid),\n+\t\t\t\t\t}\n+\t\t\t\t: undefined,\n \t\t);\n \t\tif (!found || found.commits.length === 0) {\n \t\t\tif (found) await this.ctx.storage.put(\"git:head\", found.head);"},{"path":"server/test/git-blob-text.test.ts","added":58,"removed":0,"diff":"--- /dev/null\n+++ b/server/test/git-blob-text.test.ts\n@@ -0,0 +1,58 @@\n+import assert from \"node:assert/strict\";\n+import { test } from \"node:test\";\n+import { gitBlobText, InvalidGitUtf8 } from \"../src/git-blob-text.ts\";\n+import { GitIntakeTrees } from \"../src/git-intake-trees.ts\";\n+import { memoryStorage } from \"./helpers.ts\";\n+\n+function source(bytes: Uint8Array) {\n+\treturn {\n+\t\tbyteLength: bytes.length,\n+\t\tread(start: number, length: number) {\n+\t\t\tassert.ok(length <= 16384);\n+\t\t\treturn bytes.slice(start, start + length);\n+\t\t},\n+\t};\n+}\n+\n+test(\"Git text chunks preserve BOM and split UTF-8 semantics with bounded pieces\", () => {\n+\tfor (const text of [\"\", \"\\ufefftext\", \"x\".repeat(16383) + \"🚀é中\".repeat(20000), \"nul\\0text\"]) {\n+\t\tconst bytes = new TextEncoder().encode(text);\n+\t\tconst chunks = [...gitBlobText(source(bytes))];\n+\t\tassert.ok(chunks.every((chunk) => chunk.length <= 16384));\n+\t\tassert.equal(chunks.join(\"\"), new TextDecoder(\"utf-8\", { fatal: true, ignoreBOM: false }).decode(bytes));\n+\t}\n+});\n+\n+test(\"late invalid UTF-8 rolls back retained chunks without publishing a file\", (t) => {\n+\tconst storage = memoryStorage();\n+\tt.after(() => storage.db.close());\n+\tconst trees = new GitIntakeTrees(storage);\n+\tconst files: Record<string, string> = {};\n+\tconst bytes = new Uint8Array(100000).fill(97);\n+\tbytes[bytes.length - 1] = 0xf0;\n+\tassert.throws(() => trees.retainChunks(files, \"bad\", gitBlobText(source(bytes)), \"a\".repeat(40)), InvalidGitUtf8);\n+\tassert.deepEqual(Object.keys(files), []);\n+\tassert.equal(\n+\t\tstorage.db.prepare(\"SELECT COUNT(*) AS n FROM writer_state WHERE namespace = ?\").get(trees.namespace)!.n,\n+\t\t0,\n+\t);\n+\tbytes[bytes.length - 1] = 98;\n+\ttrees.retainChunks(files, \"good\", gitBlobText(source(bytes)), \"a\".repeat(40));\n+\tassert.equal(files.good, new TextDecoder().decode(bytes));\n+\ttrees.dispose();\n+});\n+\n+test(\"Git text reading preserves storage errors instead of classifying them as binary\", () => {\n+\tconst failure = new TypeError(\"storage failure\");\n+\tassert.throws(\n+\t\t() => [\n+\t\t\t...gitBlobText({\n+\t\t\t\tbyteLength: 1,\n+\t\t\t\tread: () => {\n+\t\t\t\t\tthrow failure;\n+\t\t\t\t},\n+\t\t\t}),\n+\t\t],\n+\t\t(error) => error === failure,\n+\t);\n+});"},{"path":"server/test/git-budget-recovery.test.ts","added":31,"removed":0,"diff":"--- /dev/null\n+++ b/server/test/git-budget-recovery.test.ts\n@@ -0,0 +1,31 @@\n+import assert from \"node:assert/strict\";\n+import { test } from \"node:test\";\n+import { GitDiskIntake } from \"../src/git-disk-intake.ts\";\n+import { GitPackResolver } from \"../src/git-pack-resolver.ts\";\n+import { memoryStorage } from \"./helpers.ts\";\n+\n+test(\"cold Git recovery removes abandoned byte budgets without touching canonical data\", (t) => {\n+\tconst storage = memoryStorage();\n+\tt.after(() => storage.db.close());\n+\tstorage.sql.exec(\"CREATE TABLE canonical_budget_fixture (value TEXT)\");\n+\tstorage.sql.exec(\"INSERT INTO canonical_budget_fixture VALUES ('preserved')\");\n+\tconst abandoned = new GitPackResolver(storage, 100, 100);\n+\tabandoned.add(12, \"blob\", new TextEncoder().encode(\"abandoned\"));\n+\tassert.equal(storage.db.prepare(\"SELECT decoded FROM git_object_budget\").get()!.decoded, 9);\n+\tGitDiskIntake.recover(storage);\n+\tGitDiskIntake.recover(storage);\n+\tfor (const table of [\n+\t\t\"git_pack_spool\",\n+\t\t\"git_pack_resolve\",\n+\t\t\"git_object_bytes\",\n+\t\t\"git_object_meta\",\n+\t\t\"git_object_budget\",\n+\t])\n+\t\tassert.equal(storage.db.prepare(`SELECT COUNT(*) AS n FROM ${table}`).get()!.n, 0);\n+\tassert.equal(storage.db.prepare(\"SELECT value FROM canonical_budget_fixture\").get()!.value, \"preserved\");\n+\tconst retry = new GitPackResolver(storage, 3, 3);\n+\tretry.add(12, \"blob\", new TextEncoder().encode(\"new\"));\n+\tassert.equal(storage.db.prepare(\"SELECT decoded FROM git_object_budget\").get()!.decoded, 3);\n+\tretry.dispose();\n+\tassert.equal(storage.db.prepare(\"SELECT COUNT(*) AS n FROM git_object_budget\").get()!.n, 0);\n+});"},{"path":"server/test/git-delta-stream.test.ts","added":64,"removed":0,"diff":"--- /dev/null\n+++ b/server/test/git-delta-stream.test.ts\n@@ -0,0 +1,64 @@\n+import assert from \"node:assert/strict\";\n+import { test } from \"node:test\";\n+import { applyGitDeltaChunks, type GitByteRanges } from \"../src/git-delta-stream.ts\";\n+\n+const ranges = (bytes: Uint8Array): GitByteRanges => ({\n+\tbyteLength: bytes.length,\n+\tread(start, length) {\n+\t\tassert.ok(length <= 65536);\n+\t\treturn bytes.slice(start, start + length);\n+\t},\n+});\n+const integer = (value: number) => {\n+\tconst bytes = [];\n+\tdo {\n+\t\tconst next = value % 128;\n+\t\tvalue = Math.floor(value / 128);\n+\t\tbytes.push(next | (value ? 128 : 0));\n+\t} while (value);\n+\treturn bytes;\n+};\n+test(\"delta copy and literal instructions use bounded base reads and output\", () => {\n+\tconst base = Uint8Array.from({ length: 200000 }, (_, i) => i % 251);\n+\t// Copy 131072 bytes from offset zero, then append three literal bytes.\n+\tconst delta = Uint8Array.from([...integer(base.length), ...integer(131075), 0xc0, 2, 3, 4, 5, 6]);\n+\tconst output: Uint8Array[] = [];\n+\tassert.equal(\n+\t\tapplyGitDeltaChunks(\n+\t\t\tranges(delta),\n+\t\t\tranges(base),\n+\t\t\t(chunk) => {\n+\t\t\t\tassert.ok(chunk.length <= 65536);\n+\t\t\t\toutput.push(chunk);\n+\t\t\t},\n+\t\t\t200000,\n+\t\t),\n+\t\t131075,\n+\t);\n+\tassert.deepEqual(Buffer.concat(output), Buffer.concat([base.subarray(0, 131072), new Uint8Array([4, 5, 6])]));\n+});\n+test(\"delta refuses malformed instructions, bounds and truncated input\", () => {\n+\tfor (const bytes of [\n+\t\t[1, 0],\n+\t\t[0, 1, 0],\n+\t\t[0, 1, 1],\n+\t\t[0, 1, 0x80],\n+\t\t[0, 2, 1, 7],\n+\t\t[0, 0, 1, 7],\n+\t])\n+\t\tassert.throws(() => applyGitDeltaChunks(ranges(Uint8Array.from(bytes)), ranges(new Uint8Array()), () => {}, 10));\n+\tlet writes = 0;\n+\tassert.throws(\n+\t\t() =>\n+\t\t\tapplyGitDeltaChunks(\n+\t\t\t\tranges(new Uint8Array([0, 11])),\n+\t\t\t\tranges(new Uint8Array()),\n+\t\t\t\t() => {\n+\t\t\t\t\twrites++;\n+\t\t\t\t},\n+\t\t\t\t10,\n+\t\t\t),\n+\t\t/exceeds bound/,\n+\t);\n+\tassert.equal(writes, 0);\n+});"},{"path":"server/test/git-disk-clone.test.ts","added":213,"removed":0,"diff":"--- /dev/null\n+++ b/server/test/git-disk-clone.test.ts\n@@ -0,0 +1,213 @@\n+import assert from \"node:assert/strict\";\n+import { randomBytes } from \"node:crypto\";\n+import { test } from \"node:test\";\n+import git, { type HttpClient } from \"isomorphic-git\";\n+import { GitDiskIntake } from \"../src/git-disk-intake.ts\";\n+import { GitIntakeTrees } from \"../src/git-intake-trees.ts\";\n+import { pushedSince } from \"../src/ingest.ts\";\n+import { MemoryFS } from \"../src/memory-fs.ts\";\n+import { memoryStorage } from \"./helpers.ts\";\n+\n+const packet = (text: string | Uint8Array) => {\n+\tconst body = Buffer.from(text);\n+\treturn Buffer.concat([Buffer.from((body.length + 4).toString(16).padStart(4, \"0\")), body]);\n+};\n+\n+for (const mode of [\"success\", \"limit\", \"fatal\", \"server-intake\", \"text-intake\"])\n+\ttest(`actual disk clone handles ${mode}`, async (t) => {\n+\t\tconst rejectPack = mode === \"limit\";\n+\t\tconst source = new MemoryFS(),\n+\t\t\tdir = \"/repo\";\n+\t\tawait git.init({ fs: source, dir, defaultBranch: \"main\" });\n+\t\tconst blob = mode === \"text-intake\" ? Buffer.from(\"x\".repeat(16383) + \"🚀é中\".repeat(20000)) : randomBytes(400000);\n+\t\tconst blobOid = await git.writeBlob({ fs: source, dir, blob });\n+\t\tconst tree = await git.writeTree({\n+\t\t\tfs: source,\n+\t\t\tdir,\n+\t\t\ttree: [{ mode: \"100644\", path: \"large.bin\", oid: blobOid, type: \"blob\" }],\n+\t\t});\n+\t\tconst author = {\n+\t\t\tname: \"Capacity fixture\",\n+\t\t\temail: \"fixture@example.invalid\",\n+\t\t\ttimestamp: 1,\n+\t\t\ttimezoneOffset: 0,\n+\t\t};\n+\t\tconst base = await git.writeCommit({\n+\t\t\tfs: source,\n+\t\t\tdir,\n+\t\t\tcommit: {\n+\t\t\t\ttree,\n+\t\t\t\tparent: [],\n+\t\t\t\tauthor,\n+\t\t\t\tcommitter: author,\n+\t\t\t\tmessage: \"Base\\n\\nabso-version: 0\\n\",\n+\t\t\t},\n+\t\t});\n+\t\tconst head = await git.writeCommit({\n+\t\t\tfs: source,\n+\t\t\tdir,\n+\t\t\tcommit: {\n+\t\t\t\ttree,\n+\t\t\t\tparent: [base],\n+\t\t\t\tauthor,\n+\t\t\t\tcommitter: author,\n+\t\t\t\tmessage: \"Fixture\\n\",\n+\t\t\t},\n+\t\t});\n+\t\tconst packed = (\n+\t\t\tawait git.packObjects({\n+\t\t\t\tfs: source,\n+\t\t\t\tdir,\n+\t\t\t\toids: [head, base, tree, blobOid],\n+\t\t\t\twrite: false,\n+\t\t\t})\n+\t\t).packfile!;\n+\t\tconst advertisement = Buffer.concat([\n+\t\t\tpacket(\"# service=git-upload-pack\\n\"),\n+\t\t\tBuffer.from(\"0000\"),\n+\t\t\tpacket(`${head} HEAD\\0symref=HEAD:refs/heads/main side-band-64k shallow\\n`),\n+\t\t\tpacket(`${head} refs/heads/main\\n`),\n+\t\t\tBuffer.from(\"0000\"),\n+\t\t]);\n+\t\tlet uploads = 0;\n+\t\tlet uploadChunksRead = 0;\n+\t\tlet uploadClosed = false;\n+\t\tconst uploadParts = [packet(\"NAK\\n\")];\n+\t\tfor (let at = 0; at < packed.length; at += 16000) {\n+\t\t\tuploadParts.push(packet(Buffer.concat([Buffer.from([1]), packed.subarray(at, at + 16000)])));\n+\t\t\tuploadParts.push(\n+\t\t\t\tpacket(Buffer.concat([Buffer.from([2]), Buffer.from(\"Counting objects: 50% (1/2)\\n\".repeat(200))])),\n+\t\t\t);\n+\t\t\tif (mode === \"fatal\" && at === 16000) {\n+\t\t\t\tuploadParts.push(packet(Buffer.concat([Buffer.from([3]), Buffer.from(\"fixture remote failure\")])));\n+\t\t\t\tbreak;\n+\t\t\t}\n+\t\t}\n+\t\tuploadParts.push(Buffer.from(\"0000\"));\n+\t\tconst http: HttpClient = {\n+\t\t\trequest: async ({ url, method }) => {\n+\t\t\t\tconst body = method === \"POST\" ? Buffer.concat(uploadParts) : advertisement;\n+\t\t\t\tif (method === \"POST\") uploads++;\n+\t\t\t\treturn {\n+\t\t\t\t\turl,\n+\t\t\t\t\tmethod: method ?? \"GET\",\n+\t\t\t\t\tstatusCode: 200,\n+\t\t\t\t\tstatusMessage: \"OK\",\n+\t\t\t\t\theaders: {},\n+\t\t\t\t\tbody: (async function* () {\n+\t\t\t\t\t\ttry {\n+\t\t\t\t\t\t\tfor (let at = 0; at < body.length; at += 997) {\n+\t\t\t\t\t\t\t\tif (method === \"POST\") uploadChunksRead++;\n+\t\t\t\t\t\t\t\tyield body.subarray(at, at + 997);\n+\t\t\t\t\t\t\t}\n+\t\t\t\t\t\t} finally {\n+\t\t\t\t\t\t\tif (method === \"POST\") uploadClosed = true;\n+\t\t\t\t\t\t}\n+\t\t\t\t\t})(),\n+\t\t\t\t};\n+\t\t\t},\n+\t\t};\n+\t\tconst storage = memoryStorage();\n+\t\tconst intake = new GitDiskIntake(storage, rejectPack ? 70000 : 2000000, 1000000);\n+\t\tconst ingest = intake.ingest.bind(intake);\n+\t\tintake.ingest = async (...args) => {\n+\t\t\tawait new Promise((resolve) => setTimeout(resolve, 25));\n+\t\t\tassert.ok(uploadChunksRead < 64, `pack source read ahead ${uploadChunksRead} chunks before disk consumption`);\n+\t\t\treturn ingest(...args);\n+\t\t};\n+\t\tconst cache = {};\n+\t\tintake.attach(cache);\n+\t\tconst fs = new MemoryFS();\n+\t\tconst write = fs.promises.writeFile;\n+\t\tfs.promises.writeFile = async (path, ...args) => {\n+\t\t\tassert.ok(!/\\.(pack|idx)$/.test(path), \"clone must not persist a collected pack or index\");\n+\t\t\treturn write(path, ...args);\n+\t\t};\n+\t\ttry {\n+\t\t\tif (mode === \"server-intake\" || mode === \"text-intake\") {\n+\t\t\t\tconst trees = new GitIntakeTrees(storage);\n+\t\t\t\tif (mode === \"text-intake\") {\n+\t\t\t\t\tconst original = GitDiskIntake.prototype.read;\n+\t\t\t\t\tt.mock.method(GitDiskIntake.prototype, \"read\", function (this: GitDiskIntake, oid: string) {\n+\t\t\t\t\t\tif (oid === blobOid) throw Error(\"whole text blob read forbidden\");\n+\t\t\t\t\t\treturn original.call(this, oid);\n+\t\t\t\t\t});\n+\t\t\t\t}\n+\t\t\t\tconst artifacts = {\n+\t\t\t\t\tget: async () => ({\n+\t\t\t\t\t\tinfo: async () => ({ remote: \"https://fixture.invalid/repo\" }),\n+\t\t\t\t\t\tcreateToken: async () => ({ plaintext: \"invented-test-token\" }),\n+\t\t\t\t\t\t[Symbol.dispose]() {},\n+\t\t\t\t\t}),\n+\t\t\t\t};\n+\t\t\t\tconst found = await pushedSince(\n+\t\t\t\t\tartifacts as never,\n+\t\t\t\t\t\"fixture\",\n+\t\t\t\t\tundefined,\n+\t\t\t\t\tasync (bytes) => {\n+\t\t\t\t\t\tassert.deepEqual(Buffer.from(bytes), blob);\n+\t\t\t\t\t\treturn \"fixture-blob\";\n+\t\t\t\t\t},\n+\t\t\t\t\tundefined,\n+\t\t\t\t\tundefined,\n+\t\t\t\t\t{\n+\t\t\t\t\t\tstorage,\n+\t\t\t\t\t\tmaxPackBytes: 2000000,\n+\t\t\t\t\t\tmaxObjectBytes: 1000000,\n+\t\t\t\t\t\thttp,\n+\t\t\t\t\t\tretainFileChunks: (files, path, chunks, oid) => trees.retainChunks(files, path, chunks, oid),\n+\t\t\t\t\t},\n+\t\t\t\t);\n+\t\t\t\tassert.equal(found!.base, 0);\n+\t\t\t\tassert.equal(found!.commits.length, 1);\n+\t\t\t\tif (mode === \"text-intake\") assert.equal(found!.commits[0]!.files[\"large.bin\"], blob.toString(\"utf8\"));\n+\t\t\t\telse assert.equal(found!.commits[0]!.blobs[\"large.bin\"], \"fixture-blob\");\n+\t\t\t\ttrees.dispose();\n+\t\t\t\tfor (const table of [\"git_pack_spool\", \"git_pack_resolve\", \"git_object_meta\", \"git_object_bytes\"])\n+\t\t\t\t\tassert.equal(storage.db.prepare(`SELECT COUNT(*) AS n FROM ${table}`).get()!.n, 0);\n+\t\t\t\treturn;\n+\t\t\t}\n+\t\t\tconst clone = git.clone({\n+\t\t\t\tfs,\n+\t\t\t\tdir,\n+\t\t\t\thttp,\n+\t\t\t\tcache,\n+\t\t\t\turl: \"https://fixture.invalid/repo\",\n+\t\t\t\tref: \"main\",\n+\t\t\t\tsingleBranch: true,\n+\t\t\t\tnoCheckout: true,\n+\t\t\t});\n+\t\t\tif (mode !== \"success\") {\n+\t\t\t\tawait assert.rejects(clone, rejectPack ? /pack exceeds byte limit/ : /fixture remote failure/);\n+\t\t\t\tassert.equal(uploadClosed, true);\n+\t\t\t\tfor (const table of [\"git_pack_spool\", \"git_pack_resolve\", \"git_object_meta\", \"git_object_bytes\"])\n+\t\t\t\t\tassert.equal(storage.db.prepare(`SELECT COUNT(*) AS n FROM ${table}`).get()!.n, 0);\n+\t\t\t\treturn;\n+\t\t\t}\n+\t\t\tawait clone;\n+\t\t\tintake.assertReady();\n+\t\t\tassert.equal((await git.log({ fs, dir, cache, ref: \"main\" })).length, 2);\n+\t\t\tlet walked = 0;\n+\t\t\tawait git.walk({\n+\t\t\t\tfs,\n+\t\t\t\tdir,\n+\t\t\t\tcache,\n+\t\t\t\ttrees: [git.TREE({ ref: head })],\n+\t\t\t\tmap: async (path, [entry]) => {\n+\t\t\t\t\tif (path === \"large.bin\") {\n+\t\t\t\t\t\tassert.deepEqual(Buffer.from((await entry!.content())!), blob);\n+\t\t\t\t\t\twalked++;\n+\t\t\t\t\t}\n+\t\t\t\t\treturn true;\n+\t\t\t\t},\n+\t\t\t});\n+\t\t\tassert.equal(walked, 1);\n+\t\t\tassert.equal(uploads, 1);\n+\t\t\tassert.equal(await git.resolveRef({ fs, dir, ref: \"main\" }), head);\n+\t\t\tassert.equal((await git.readCommit({ fs, dir, cache, oid: head })).commit.tree, tree);\n+\t\t\tassert.deepEqual(Buffer.from((await git.readBlob({ fs, dir, cache, oid: blobOid })).blob), blob);\n+\t\t} finally {\n+\t\t\tintake.dispose();\n+\t\t\tstorage.db.close();\n+\t\t}\n+\t});"},{"path":"server/test/git-intake-trees.test.ts","added":118,"removed":0,"diff":"--- /dev/null\n+++ b/server/test/git-intake-trees.test.ts\n@@ -0,0 +1,118 @@\n+import assert from \"node:assert/strict\";\n+import { test } from \"node:test\";\n+import { GitIntakeTrees } from \"../src/git-intake-trees.ts\";\n+import { SqliteWriterState } from \"../src/writer-host.ts\";\n+import { memoryStorage } from \"./helpers.ts\";\n+\n+test(\"unchanged Git blobs share stored text across paths and commits\", (t) => {\n+\tconst storage = memoryStorage();\n+\tt.after(() => storage.db.close());\n+\tconst trees = new GitIntakeTrees(storage);\n+\tconst body = \"unchanged\\n\".repeat(10000);\n+\tconst oid = \"a\".repeat(40);\n+\tconst count = () =>\n+\t\tstorage.db.prepare(\"SELECT COUNT(*) AS n FROM writer_state WHERE namespace = ?\").get(trees.namespace)!.n;\n+\tconst first: Record<string, string> = {};\n+\ttrees.retainFile(first, \"original\", body, oid);\n+\tconst initialRows = count();\n+\tfor (let i = 0; i < 100; i++) {\n+\t\tconst files: Record<string, string> = {};\n+\t\ttrees.retainFile(files, `renamed-${i}`, body, oid);\n+\t\tassert.equal(files[`renamed-${i}`], body);\n+\t}\n+\tassert.equal(count(), initialRows);\n+\ttrees.retainFile(first, \"changed\", \"new text\", \"b\".repeat(40));\n+\tassert.equal(first.original, body);\n+\tassert.equal(first.changed, \"new text\");\n+\tassert.ok(Number(count()) > Number(initialRows));\n+\tassert.throws(() => trees.retainFile(first, \"bad\", \"text\", \"bad-id\"), /Invalid Git blob id/);\n+\ttrees.dispose();\n+\tassert.equal(count(), 0);\n+});\n+\n+test(\"Git intake stores each decoded file before the next file arrives\", (t) => {\n+\tconst storage = memoryStorage();\n+\tt.after(() => storage.db.close());\n+\tconst trees = new GitIntakeTrees(storage);\n+\tconst files: Record<string, string> = Object.create(null);\n+\tfor (let i = 0; i < 20; i++) {\n+\t\ttrees.retainFile(files, `file-${i}`, `${i}:${\"x\".repeat(50000)}`);\n+\t\tassert.equal(Object.getOwnPropertyDescriptor(files, `file-${i}`)?.value, undefined);\n+\t\tassert.equal(files[`file-${i}`], `${i}:${\"x\".repeat(50000)}`);\n+\t}\n+\tassert.equal(Object.keys(files).length, 20);\n+\ttrees.dispose();\n+\tassert.throws(() => files[\"file-0\"], /closed/);\n+\tassert.throws(() => trees.retainFile(files, \"later\", \"text\"), /closed/);\n+});\n+\n+test(\"Git intake retains independent trees on disk and releases their text rows\", (t) => {\n+\tconst storage = memoryStorage();\n+\tt.after(() => storage.db.close());\n+\tconst trees = new GitIntakeTrees(storage);\n+\tconst retained: ReturnType<GitIntakeTrees[\"retain\"]>[] = [];\n+\tfor (let i = 0; i < 50; i++) {\n+\t\tconst files = {\n+\t\t\t\"a.txt\": `${i}:${\"\\ud83d\\ude80\".repeat(20000)}\\n`,\n+\t\t\t\"empty.txt\": \"\",\n+\t\t};\n+\t\tretained.push(\n+\t\t\ttrees.retain({\n+\t\t\t\tfiles,\n+\t\t\t\tmodes: { \"a.txt\": { exec: true, link: null } },\n+\t\t\t\tblobs: {},\n+\t\t\t}),\n+\t\t);\n+\t\tfiles[\"a.txt\"] = \"changed after retention\";\n+\t}\n+\tfor (let i = 0; i < retained.length; i++) {\n+\t\tconst tree = retained[i]!;\n+\t\tassert.deepEqual(Object.keys(tree.files), [\"a.txt\", \"empty.txt\"]);\n+\t\tassert.equal(Object.getOwnPropertyDescriptor(tree.files, \"a.txt\")?.value, undefined);\n+\t\tassert.equal(tree.files[\"a.txt\"], `${i}:${\"\\ud83d\\ude80\".repeat(20000)}\\n`);\n+\t\tassert.equal(tree.files[\"empty.txt\"], \"\");\n+\t\tassert.equal(tree.modes[\"a.txt\"]?.exec, true);\n+\t}\n+\tconst count = () =>\n+\t\tstorage.db.prepare(\"SELECT COUNT(*) AS n FROM writer_state WHERE namespace = ?\").get(trees.namespace)!.n;\n+\tassert.ok(Number(count()) > 0);\n+\ttrees.dispose();\n+\tassert.equal(count(), 0);\n+\tassert.throws(() => retained[0]!.files[\"a.txt\"], /closed/);\n+\tassert.throws(() => trees.retain({ files: {}, modes: {}, blobs: {} }), /closed/);\n+\ttrees.dispose();\n+});\n+\n+test(\"disposing one intake does not delete another concurrent intake\", (t) => {\n+\tconst storage = memoryStorage();\n+\tt.after(() => storage.db.close());\n+\tconst first = new GitIntakeTrees(storage);\n+\tconst second = new GitIntakeTrees(storage);\n+\tfirst.retain({ files: { a: \"first\" }, modes: {}, blobs: {} });\n+\tconst retained = second.retain({\n+\t\tfiles: { a: \"second\" },\n+\t\tmodes: {},\n+\t\tblobs: {},\n+\t});\n+\tfirst.dispose();\n+\tassert.equal(retained.files.a, \"second\");\n+\tsecond.dispose();\n+});\n+\n+test(\"cold recovery removes abandoned intake text and preserves canonical writer state\", (t) => {\n+\tconst storage = memoryStorage();\n+\tt.after(() => storage.db.close());\n+\tconst abandoned = new GitIntakeTrees(storage);\n+\tabandoned.retain({ files: { a: \"abandoned text\" }, modes: {}, blobs: {} });\n+\tconst canonical = new SqliteWriterState(storage, \"server-disk-v1\");\n+\tcanonical.write(\"receipt\", \"operation\", { committed: true });\n+\tGitIntakeTrees.recover(storage);\n+\tassert.deepEqual(canonical.read(\"receipt\", \"operation\"), { committed: true });\n+\tassert.equal(\n+\t\tstorage.db.prepare(\"SELECT COUNT(*) AS n FROM writer_state WHERE namespace = ?\").get(abandoned.namespace)!.n,\n+\t\t0,\n+\t);\n+\tconst retry = new GitIntakeTrees(storage);\n+\tassert.equal(retry.retain({ files: { a: \"retry\" }, modes: {}, blobs: {} }).files.a, \"retry\");\n+\tretry.dispose();\n+});"},{"path":"server/test/git-object-bytes.test.ts","added":74,"removed":0,"diff":"--- /dev/null\n+++ b/server/test/git-object-bytes.test.ts\n@@ -0,0 +1,74 @@\n+import assert from \"node:assert/strict\";\n+import { createHash } from \"node:crypto\";\n+import { test } from \"node:test\";\n+import { applyGitDeltaChunks } from \"../src/git-delta-stream.ts\";\n+import { GitObjectBytes } from \"../src/git-object-bytes.ts\";\n+import { memoryStorage } from \"./helpers.ts\";\n+\n+const integer = (value: number) => {\n+\tconst bytes = [];\n+\tdo {\n+\t\tconst part = value % 128;\n+\t\tvalue = Math.floor(value / 128);\n+\t\tbytes.push(part | (value ? 128 : 0));\n+\t} while (value);\n+\treturn bytes;\n+};\n+test(\"disk delta output has exact Git identity and partial failures roll back\", (t) => {\n+\tconst storage = memoryStorage();\n+\tt.after(() => storage.db.close());\n+\tconst objects = new GitObjectBytes(storage);\n+\tconst bytes = Uint8Array.from({ length: 200000 }, (_, i) => i % 251);\n+\tconst base = objects.put(\"blob\", (write) => write(bytes), 200000);\n+\tconst instructions = Uint8Array.from([...integer(bytes.length), ...integer(131075), 0xc0, 2, 3, 4, 5, 6]);\n+\tconst delta = objects.put(\"blob\", (write) => write(instructions), 100);\n+\tconst result = objects.put(\n+\t\t\"blob\",\n+\t\t(write) => {\n+\t\t\tapplyGitDeltaChunks(delta, base, write, 200000);\n+\t\t},\n+\t\t200000,\n+\t);\n+\tconst expected = Buffer.concat([bytes.subarray(0, 131072), new Uint8Array([4, 5, 6])]);\n+\tassert.equal(result.oid, createHash(\"sha1\").update(`blob ${expected.length}\\0`).update(expected).digest(\"hex\"));\n+\tassert.deepEqual(result.read(65530, 100), new Uint8Array(expected.subarray(65530, 65630)));\n+\tassert.equal(result.byteLength, expected.length);\n+\tconst counts = () => [\n+\t\tstorage.db.prepare(\"SELECT COUNT(*) AS n FROM git_object_bytes\").get()!.n,\n+\t\tstorage.db.prepare(\"SELECT COUNT(*) AS n FROM git_object_meta\").get()!.n,\n+\t];\n+\tconst bad = objects.put(\"blob\", (write) => write(Uint8Array.from([...instructions, 0])), 101);\n+\tconst before = counts();\n+\tassert.throws(\n+\t\t() =>\n+\t\t\tobjects.put(\n+\t\t\t\t\"blob\",\n+\t\t\t\t(write) => {\n+\t\t\t\t\tapplyGitDeltaChunks(bad, base, write, 200000);\n+\t\t\t\t},\n+\t\t\t\t200000,\n+\t\t\t),\n+\t\t/invalid Git delta instruction/,\n+\t);\n+\tassert.deepEqual(counts(), before);\n+\tassert.throws(\n+\t\t() =>\n+\t\t\tobjects.put(\n+\t\t\t\t\"blob\",\n+\t\t\t\t(write) => {\n+\t\t\t\t\twrite(bytes);\n+\t\t\t\t\tthrow Error(\"injected producer failure\");\n+\t\t\t\t},\n+\t\t\t\t200000,\n+\t\t\t),\n+\t\t/injected producer failure/,\n+\t);\n+\tassert.deepEqual(counts(), before);\n+\tassert.throws(() => objects.put(\"blob\", (write) => write(bytes), 100000), /exceeds byte limit/);\n+\tassert.deepEqual(counts(), before);\n+\tassert.deepEqual(base.read(0, 100), bytes.slice(0, 100));\n+\tassert.equal(objects.put(\"blob\", () => {}, 0).oid, \"e69de29bb2d1d6434b8b29ae775ad8c2e48c5391\");\n+\tobjects.dispose();\n+\tassert.deepEqual(counts(), [0, 0]);\n+\tassert.throws(() => base.read(0, 1), /closed/);\n+});"},{"path":"server/test/git-pack-decode.test.ts","added":183,"removed":0,"diff":"--- /dev/null\n+++ b/server/test/git-pack-decode.test.ts\n@@ -0,0 +1,183 @@\n+import assert from \"node:assert/strict\";\n+import { createHash, randomBytes } from \"node:crypto\";\n+import { createRequire } from \"node:module\";\n+import { test } from \"node:test\";\n+import { deflateSync } from \"node:zlib\";\n+import { GitDiskIntake } from \"../src/git-disk-intake.ts\";\n+import { decodeGitPack, type PackInflater } from \"../src/git-pack-decode.ts\";\n+import { GitPackResolver } from \"../src/git-pack-resolver.ts\";\n+import { GitPackSpool } from \"../src/git-pack-spool.ts\";\n+import { memoryStorage } from \"./helpers.ts\";\n+\n+const require = createRequire(import.meta.url);\n+const { Inflate } = require(\"pako\") as {\n+\tInflate: new (options: { chunkSize: number }) => PackInflater;\n+};\n+\n+test(\"cold intake recovery removes abandoned scratch and preserves project rows\", () => {\n+\tconst storage = memoryStorage();\n+\ttry {\n+\t\tGitDiskIntake.recover(storage);\n+\t\tstorage.sql.exec(\"CREATE TABLE canonical_fixture (value TEXT)\");\n+\t\tstorage.sql.exec(\"INSERT INTO canonical_fixture VALUES (?)\", \"preserved\");\n+\t\tconst resolver = new GitPackResolver(storage, 1000);\n+\t\tresolver.add(12, \"blob\", new TextEncoder().encode(\"abc\"));\n+\t\tstorage.sql.exec(\"INSERT INTO git_pack_spool VALUES (?, ?, ?)\", \"abandoned\", 0, new Uint8Array([1]));\n+\t\tGitDiskIntake.recover(storage);\n+\t\tGitDiskIntake.recover(storage);\n+\t\tfor (const table of [\"git_pack_spool\", \"git_pack_resolve\", \"git_object_meta\", \"git_object_bytes\"])\n+\t\t\tassert.equal(storage.db.prepare(`SELECT COUNT(*) AS n FROM ${table}`).get()!.n, 0);\n+\t\tassert.equal(storage.db.prepare(\"SELECT value FROM canonical_fixture\").get()!.value, \"preserved\");\n+\t} finally {\n+\t\tstorage.db.close();\n+\t}\n+});\n+\n+test(\"disk intake exposes only verified objects and disposes all scratch\", async () => {\n+\tconst storage = memoryStorage();\n+\ttry {\n+\t\tfor (const corrupt of [false, true]) {\n+\t\t\tconst intake = new GitDiskIntake(storage, 1000000, 1000000);\n+\t\t\tconst cache = {};\n+\t\t\tintake.attach(cache);\n+\t\t\tassert.equal(Reflect.get(cache, Symbol.for(\"abso.git.disk-pack\")), intake);\n+\t\t\tassert.throws(() => intake.attach(cache), /already attached/);\n+\t\t\tassert.equal(intake.read(\"0\".repeat(40)), undefined);\n+\t\t\tconst bytes = pack([Buffer.concat([objectHeader(3, 3), deflateSync(Buffer.from(\"abc\"))])]);\n+\t\t\tif (corrupt) bytes[bytes.length - 1]! ^= 1;\n+\t\t\ttry {\n+\t\t\t\tif (corrupt) {\n+\t\t\t\t\tawait assert.rejects(\n+\t\t\t\t\t\tintake.ingest([bytes], () => new Inflate({ chunkSize: 16384 })),\n+\t\t\t\t\t\t/checksum/,\n+\t\t\t\t\t);\n+\t\t\t\t\tassert.throws(() => intake.read(\"0\".repeat(40)), /closed/);\n+\t\t\t\t} else {\n+\t\t\t\t\tawait intake.ingest([bytes], () => new Inflate({ chunkSize: 16384 }));\n+\t\t\t\t\tconst oid = createHash(\"sha1\").update(\"blob 3\\0abc\").digest(\"hex\");\n+\t\t\t\t\tassert.equal(intake.read(oid)!.object.toString(), \"abc\");\n+\t\t\t\t\tassert.equal(intake.read(\"0\".repeat(40)), undefined);\n+\t\t\t\t\tassert.equal(storage.db.prepare(\"SELECT COUNT(*) AS n FROM git_pack_spool\").get()!.n, 0);\n+\t\t\t\t}\n+\t\t\t} finally {\n+\t\t\t\tintake.dispose();\n+\t\t\t}\n+\t\t\tfor (const table of [\"git_pack_spool\", \"git_pack_resolve\", \"git_object_meta\", \"git_object_bytes\"])\n+\t\t\t\tassert.equal(storage.db.prepare(`SELECT COUNT(*) AS n FROM ${table}`).get()!.n, 0);\n+\t\t}\n+\t} finally {\n+\t\tstorage.db.close();\n+\t}\n+});\n+test(\"late input cannot recreate scratch after intake disposal\", async () => {\n+\tconst storage = memoryStorage();\n+\tconst intake = new GitDiskIntake(storage, 1000000, 1000000);\n+\tlet sourceClosed = false;\n+\tasync function* source() {\n+\t\ttry {\n+\t\t\tyield new Uint8Array(65536);\n+\t\t\tintake.dispose();\n+\t\t\tyield new Uint8Array(65536);\n+\t\t} finally {\n+\t\t\tsourceClosed = true;\n+\t\t}\n+\t}\n+\ttry {\n+\t\tawait assert.rejects(\n+\t\t\tintake.ingest(source(), () => new Inflate({ chunkSize: 16384 })),\n+\t\t\t/closed/,\n+\t\t);\n+\t\tassert.equal(sourceClosed, true);\n+\t\tfor (const table of [\"git_pack_spool\", \"git_pack_resolve\", \"git_object_meta\", \"git_object_bytes\"])\n+\t\t\tassert.equal(storage.db.prepare(`SELECT COUNT(*) AS n FROM ${table}`).get()!.n, 0);\n+\t} finally {\n+\t\tintake.dispose();\n+\t\tstorage.db.close();\n+\t}\n+});\n+\n+function objectHeader(kind: number, size: number): Uint8Array {\n+\tconst bytes = [(kind << 4) | (size & 15)];\n+\tsize = Math.floor(size / 16);\n+\twhile (size) {\n+\t\tbytes[bytes.length - 1]! |= 128;\n+\t\tbytes.push(size & 127);\n+\t\tsize = Math.floor(size / 128);\n+\t}\n+\treturn Uint8Array.from(bytes);\n+}\n+function pack(entries: Uint8Array[]): Uint8Array {\n+\tconst header = Buffer.alloc(12);\n+\theader.write(\"PACK\");\n+\theader.writeUInt32BE(2, 4);\n+\theader.writeUInt32BE(entries.length, 8);\n+\tconst body = Buffer.concat([header, ...entries]);\n+\treturn Buffer.concat([body, createHash(\"sha1\").update(body).digest()]);\n+}\n+\n+test(\"verified disk pack inflates large objects and forward deltas without collected output\", async () => {\n+\tconst storage = memoryStorage();\n+\tconst spool = new GitPackSpool(storage);\n+\tconst resolver = new GitPackResolver(storage, 2000000);\n+\ttry {\n+\t\tconst large = randomBytes(800000);\n+\t\tconst base = Buffer.from(\"abc\");\n+\t\tconst baseId = createHash(\"sha1\").update(\"blob 3\\0\").update(base).digest();\n+\t\tconst delta = Uint8Array.from([3, 4, 0x90, 3, 1, 100]);\n+\t\tconst bytes = pack([\n+\t\t\tBuffer.concat([objectHeader(7, delta.length), baseId, deflateSync(delta)]),\n+\t\t\tBuffer.concat([objectHeader(3, large.length), deflateSync(large)]),\n+\t\t\tBuffer.concat([objectHeader(3, base.length), deflateSync(base)]),\n+\t\t]);\n+\t\tawait spool.ingest([bytes], 2000000);\n+\t\tdecodeGitPack(spool, resolver, () => {\n+\t\t\tconst inflater = new Inflate({ chunkSize: 16384 });\n+\t\t\tObject.defineProperty(inflater, \"result\", {\n+\t\t\t\tset(value: Uint8Array) {\n+\t\t\t\t\tassert.equal(value.length, 0, \"inflater must not collect decoded bytes\");\n+\t\t\t\t},\n+\t\t\t});\n+\t\t\treturn inflater;\n+\t\t});\n+\t\tconst largeId = createHash(\"sha1\").update(`blob ${large.length}\\0`).update(large).digest(\"hex\");\n+\t\tconst stored = resolver.get(largeId);\n+\t\tfor (let at = 0; at < large.length; at += 65536) {\n+\t\t\tconst n = Math.min(65536, large.length - at);\n+\t\t\tassert.deepEqual(stored.read(at, n), new Uint8Array(large.subarray(at, at + n)));\n+\t\t}\n+\t\tconst deltaId = createHash(\"sha1\").update(\"blob 4\\0abcd\").digest(\"hex\");\n+\t\tassert.equal(new TextDecoder().decode(resolver.get(deltaId).read(0, 4)), \"abcd\");\n+\t} finally {\n+\t\tresolver.dispose();\n+\t\tspool.dispose();\n+\t\tstorage.db.close();\n+\t}\n+});\n+\n+test(\"invalid later pack entries clear earlier decoded objects and close the resolver\", async () => {\n+\tconst valid = Buffer.concat([objectHeader(3, 3), deflateSync(Buffer.from(\"abc\"))]);\n+\tconst cases = [\n+\t\tBuffer.concat([objectHeader(3, 4), deflateSync(Buffer.from(\"abc\"))]),\n+\t\tBuffer.concat([objectHeader(3, 2), deflateSync(Buffer.from(\"abc\"))]),\n+\t\tBuffer.concat([objectHeader(3, 3), deflateSync(Buffer.from(\"abc\")).subarray(0, 3)]),\n+\t\tUint8Array.from([0]),\n+\t\tBuffer.concat([objectHeader(6, 0), Uint8Array.from([0]), deflateSync(new Uint8Array())]),\n+\t\tBuffer.concat([objectHeader(7, 2), Buffer.alloc(20, 255), deflateSync(Uint8Array.from([0, 0]))]),\n+\t];\n+\tfor (const invalid of cases) {\n+\t\tconst storage = memoryStorage();\n+\t\tconst spool = new GitPackSpool(storage);\n+\t\tconst resolver = new GitPackResolver(storage, 1000000);\n+\t\ttry {\n+\t\t\tawait spool.ingest([pack([valid, invalid])], 1000000);\n+\t\t\tassert.throws(() => decodeGitPack(spool, resolver, () => new Inflate({ chunkSize: 16384 })));\n+\t\t\tassert.throws(() => resolver.get(\"0\".repeat(40)), /closed/);\n+\t\t\tfor (const table of [\"git_pack_resolve\", \"git_object_meta\", \"git_object_bytes\"])\n+\t\t\t\tassert.equal(storage.db.prepare(`SELECT COUNT(*) AS n FROM ${table}`).get()!.n, 0);\n+\t\t} finally {\n+\t\t\tresolver.dispose();\n+\t\t\tspool.dispose();\n+\t\t\tstorage.db.close();\n+\t\t}\n+\t}\n+});"},{"path":"server/test/git-pack-resolver.test.ts","added":117,"removed":0,"diff":"--- /dev/null\n+++ b/server/test/git-pack-resolver.test.ts\n@@ -0,0 +1,117 @@\n+import assert from \"node:assert/strict\";\n+import { createHash } from \"node:crypto\";\n+import { test } from \"node:test\";\n+import { GitPackResolver } from \"../src/git-pack-resolver.ts\";\n+import { memoryStorage } from \"./helpers.ts\";\n+\n+const oid = (text: string) => createHash(\"sha1\").update(`blob ${text.length}\\0${text}`).digest(\"hex\");\n+const text = (value: ReturnType<GitPackResolver[\"get\"]>) => new TextDecoder().decode(value.read(0, value.byteLength));\n+\n+test(\"decoded budget spans objects and rolls back failed additions\", (t) => {\n+\tconst storage = memoryStorage();\n+\tt.after(() => storage.db.close());\n+\tconst resolver = new GitPackResolver(storage, 10, 8);\n+\tresolver.add(12, \"blob\", new TextEncoder().encode(\"abc\"));\n+\tassert.throws(() => resolver.add(12, \"blob\", new Uint8Array(4)), /UNIQUE/);\n+\tresolver.add(30, \"blob\", new TextEncoder().encode(\"defgh\"));\n+\tassert.throws(() => resolver.add(50, \"blob\", new Uint8Array(1)), /total decoded byte limit/);\n+\tassert.equal(text(resolver.get(oid(\"defgh\"))), \"defgh\");\n+\tassert.equal(storage.db.prepare(\"SELECT decoded FROM git_object_budget\").get()!.decoded, 8);\n+\tresolver.dispose();\n+\tassert.equal(storage.db.prepare(\"SELECT COUNT(*) AS n FROM git_object_budget\").get()!.n, 0);\n+});\n+\n+test(\"delta results consume budget and failed resolution rolls back all accounting\", (t) => {\n+\tconst storage = memoryStorage();\n+\tt.after(() => storage.db.close());\n+\tconst resolver = new GitPackResolver(storage, 100, 12);\n+\tresolver.add(12, \"blob\", new TextEncoder().encode(\"abc\"));\n+\tresolver.add(30, \"delta\", new Uint8Array([3, 4, 0x90, 3, 1, 100]), 12);\n+\tassert.throws(() => resolver.resolve(), /total decoded byte limit/);\n+\tassert.equal(storage.db.prepare(\"SELECT decoded FROM git_object_budget\").get()!.decoded, 9);\n+\tassert.equal(storage.db.prepare(\"SELECT COUNT(*) AS n FROM git_object_meta\").get()!.n, 2);\n+\tassert.throws(() => resolver.get(oid(\"abcd\")), /missing/);\n+\tresolver.dispose();\n+});\n+\n+test(\"resolved delta instructions are deleted without refunding decoded work\", (t) => {\n+\tconst storage = memoryStorage();\n+\tt.after(() => storage.db.close());\n+\tconst resolver = new GitPackResolver(storage, 100, 13);\n+\tresolver.add(12, \"blob\", new TextEncoder().encode(\"abc\"));\n+\tresolver.add(30, \"delta\", new Uint8Array([3, 4, 0x90, 3, 1, 100]), 12);\n+\tresolver.resolve();\n+\tassert.equal(text(resolver.get(oid(\"abcd\"))), \"abcd\");\n+\tassert.equal(storage.db.prepare(\"SELECT SUM(bytes) AS n FROM git_object_meta\").get()!.n, 7);\n+\tassert.equal(storage.db.prepare(\"SELECT decoded FROM git_object_budget\").get()!.decoded, 13);\n+\tassert.throws(() => resolver.add(50, \"blob\", new Uint8Array(1)), /total decoded byte limit/);\n+\tresolver.resolve();\n+\tresolver.dispose();\n+});\n+\n+test(\"disk pack resolver handles forward ID bases and offset delta chains\", (t) => {\n+\tconst storage = memoryStorage();\n+\tt.after(() => storage.db.close());\n+\tconst resolver = new GitPackResolver(storage, 1000);\n+\tresolver.add(12, \"delta\", new Uint8Array([3, 4, 0x90, 3, 1, 100]), oid(\"abc\"));\n+\tresolver.add(40, \"blob\", new TextEncoder().encode(\"abc\"));\n+\tresolver.add(80, \"delta\", new Uint8Array([4, 5, 0x90, 4, 1, 101]), 12);\n+\tresolver.resolve();\n+\tfor (const expected of [\"abc\", \"abcd\", \"abcde\"]) assert.equal(text(resolver.get(oid(expected))), expected);\n+\tresolver.resolve();\n+\tresolver.dispose();\n+\tassert.throws(() => resolver.get(oid(\"abc\")), /closed/);\n+\tfor (const table of [\"git_pack_resolve\", \"git_object_meta\", \"git_object_bytes\"])\n+\t\tassert.equal(storage.db.prepare(`SELECT COUNT(*) AS n FROM ${table}`).get()!.n, 0);\n+});\n+\n+test(\"unresolved references roll back earlier resolutions in the same pass\", (t) => {\n+\tconst storage = memoryStorage();\n+\tt.after(() => storage.db.close());\n+\tconst resolver = new GitPackResolver(storage, 1000);\n+\tresolver.add(12, \"blob\", new TextEncoder().encode(\"abc\"));\n+\tresolver.add(40, \"delta\", new Uint8Array([3, 4, 0x90, 3, 1, 100]), 12);\n+\tresolver.add(80, \"delta\", new Uint8Array([0, 0]), \"f\".repeat(40));\n+\tconst before = storage.db.prepare(\"SELECT COUNT(*) AS n FROM git_object_meta\").get()!.n;\n+\tassert.throws(() => resolver.resolve(), /unresolved or cyclic/);\n+\tassert.equal(storage.db.prepare(\"SELECT COUNT(*) AS n FROM git_object_meta\").get()!.n, before);\n+\tassert.throws(() => resolver.get(oid(\"abcd\")), /missing/);\n+\tassert.equal(text(resolver.get(oid(\"abc\"))), \"abc\");\n+\tresolver.dispose();\n+});\n+\n+test(\"decoded objects stream into the resolver and producer failures roll back\", (t) => {\n+\tconst storage = memoryStorage();\n+\tconst resolver = new GitPackResolver(storage, 1000000);\n+\tt.after(() => {\n+\t\ttry {\n+\t\t\tresolver.dispose();\n+\t\t} finally {\n+\t\t\tstorage.db.close();\n+\t\t}\n+\t});\n+\tconst expected = createHash(\"sha1\").update(\"blob 800000\\0\");\n+\tresolver.addChunks(12, \"blob\", (write) => {\n+\t\tfor (let i = 0; i < 100; i++) {\n+\t\t\tconst chunk = new Uint8Array(8000).fill(i);\n+\t\t\texpected.update(chunk);\n+\t\t\twrite(chunk);\n+\t\t}\n+\t});\n+\tresolver.resolve();\n+\tconst object = resolver.get(expected.digest(\"hex\"));\n+\tassert.equal(object.byteLength, 800000);\n+\tassert.deepEqual(object.read(799990, 10), new Uint8Array(10).fill(99));\n+\tassert.ok(Number(storage.db.prepare(\"SELECT MAX(length(data)) AS n FROM git_object_bytes\").get()!.n) <= 65536);\n+\tconst before = storage.db.prepare(\"SELECT COUNT(*) AS n FROM git_object_meta\").get()!.n;\n+\tassert.throws(\n+\t\t() =>\n+\t\t\tresolver.addChunks(40, \"blob\", (write) => {\n+\t\t\t\twrite(new Uint8Array(70000));\n+\t\t\t\tthrow Error(\"inflate failed\");\n+\t\t\t}),\n+\t\t/inflate failed/,\n+\t);\n+\tassert.equal(storage.db.prepare(\"SELECT COUNT(*) AS n FROM git_object_meta\").get()!.n, before);\n+\tassert.equal(storage.db.prepare(\"SELECT COUNT(*) AS n FROM git_pack_resolve WHERE offset = 40\").get()!.n, 0);\n+});"},{"path":"server/test/git-pack-spool.test.ts","added":70,"removed":0,"diff":"--- /dev/null\n+++ b/server/test/git-pack-spool.test.ts\n@@ -0,0 +1,70 @@\n+import assert from \"node:assert/strict\";\n+import { randomBytes } from \"node:crypto\";\n+import { test } from \"node:test\";\n+import git from \"isomorphic-git\";\n+import { GitPackSpool } from \"../src/git-pack-spool.ts\";\n+import { MemoryFS } from \"../src/memory-fs.ts\";\n+import { memoryStorage } from \"./helpers.ts\";\n+\n+test(\"cold pack recovery clears abandoned scratch without changing canonical tables\", (t) => {\n+\tconst storage = memoryStorage();\n+\tt.after(() => storage.db.close());\n+\tGitPackSpool.recover(storage);\n+\tstorage.sql.exec(\"CREATE TABLE canonical_test (value TEXT)\");\n+\tstorage.sql.exec(\"INSERT INTO canonical_test VALUES (?)\", \"preserved\");\n+\tstorage.sql.exec(\"INSERT INTO git_pack_spool VALUES (?, ?, ?)\", \"abandoned\", 0, new Uint8Array([1, 2]));\n+\tGitPackSpool.recover(storage);\n+\tassert.equal(storage.db.prepare(\"SELECT COUNT(*) AS n FROM git_pack_spool\").get()!.n, 0);\n+\tassert.equal(storage.db.prepare(\"SELECT value FROM canonical_test\").get()!.value, \"preserved\");\n+\tGitPackSpool.recover(storage);\n+});\n+\n+test(\"pack spool verifies real pack bytes and serves bounded ranges across chunk boundaries\", async (t) => {\n+\tconst storage = memoryStorage();\n+\tt.after(() => storage.db.close());\n+\tconst fs = new MemoryFS(),\n+\t\tdir = \"/repo\";\n+\tawait git.init({ fs, dir });\n+\tconst oids = [];\n+\tfor (let i = 0; i < 4; i++) oids.push(await git.writeBlob({ fs, dir, blob: randomBytes(180000) }));\n+\tconst packed = await git.packObjects({ fs, dir, oids, write: false });\n+\tconst bytes = packed.packfile!;\n+\tconst spool = new GitPackSpool(storage);\n+\tassert.throws(() => spool.read(0, 0), /not readable/);\n+\tasync function* source() {\n+\t\tfor (let at = 0; at < bytes.length; at += 997) yield bytes.subarray(at, at + 997);\n+\t}\n+\tassert.equal(await spool.ingest(source(), 1000000), Buffer.from(bytes.subarray(-20)).toString(\"hex\"));\n+\tassert.equal(spool.byteLength, bytes.length);\n+\tfor (const start of [0, 65530, 65536, 131070, bytes.length - 101]) {\n+\t\tconst length = Math.min(101, bytes.length - start);\n+\t\tassert.deepEqual(spool.read(start, length), new Uint8Array(bytes.subarray(start, start + length)));\n+\t}\n+\tassert.deepEqual(Buffer.concat([...spool.chunks()]), Buffer.from(bytes));\n+\tassert.throws(() => spool.read(0, 65537), /invalid pack byte range/);\n+\tassert.throws(() => spool.read(bytes.length, 1), /invalid pack byte range/);\n+\tconst max = storage.db.prepare(\"SELECT MAX(length(data)) AS n FROM git_pack_spool\").get()!.n;\n+\tassert.ok(Number(max) <= 65536);\n+\tspool.dispose();\n+\tassert.throws(() => spool.read(0, 0), /not readable/);\n+\tassert.equal(storage.db.prepare(\"SELECT COUNT(*) AS n FROM git_pack_spool\").get()!.n, 0);\n+\tfor (const mode of [\"corrupt\", \"limit\", \"source-error\"]) {\n+\t\tconst bad = new GitPackSpool(storage);\n+\t\tlet closed = false;\n+\t\tasync function* broken() {\n+\t\t\ttry {\n+\t\t\t\tconst data = Uint8Array.from(bytes);\n+\t\t\t\tif (mode === \"corrupt\") data[20]! ^= 1;\n+\t\t\t\tyield data.subarray(0, 100000);\n+\t\t\t\tif (mode === \"source-error\") throw Error(\"injected source failure\");\n+\t\t\t\tyield data.subarray(100000);\n+\t\t\t} finally {\n+\t\t\t\tclosed = true;\n+\t\t\t}\n+\t\t}\n+\t\tawait assert.rejects(bad.ingest(broken(), mode === \"limit\" ? 70000 : 1000000));\n+\t\tassert.equal(closed, true);\n+\t\tassert.throws(() => bad.read(0, 0), /not readable/);\n+\t\tassert.equal(storage.db.prepare(\"SELECT COUNT(*) AS n FROM git_pack_spool\").get()!.n, 0);\n+\t}\n+});"},{"path":"server/test/project-object-disk-first.test.ts","added":46,"removed":3,"diff":"--- a/server/test/project-object-disk-first.test.ts\n+++ b/server/test/project-object-disk-first.test.ts\n@@ -1,9 +1,10 @@\n import assert from \"node:assert/strict\";\n-import { registerHooks } from \"node:module\";\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 { MemoryFS } from \"../src/memory-fs.ts\";\n import { memoryStorage } from \"./helpers.ts\";\n \n@@ -20,6 +21,40 @@\n const { ProjectObject } = await import(\"../src/project-object.ts\");\n hooks.deregister();\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@@ -344,9 +379,14 @@\n \tawait git.writeRef({ fs: remote, dir: \"/repo\", ref: \"main\", value: incoming, force: true });\n \tt.mock.method(git, \"listServerRefs\", async () => [{ ref: \"refs/heads/main\", oid: incoming }]);\n \tt.mock.method(git, \"clone\", async (options: Parameters<typeof git.clone>[0]) => {\n-\t\t(options.fs as MemoryFS).entries = structuredClone(remote.entries);\n+\t\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@@ -357,15 +397,18 @@\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@@ -443,7 +486,7 @@\n \t\tlet head = await commit({ \"A.TXT\": \"clash\\n\", \"a.txt\": \"original\\n\" }, \"Refused\", [base]);\n \t\tt.mock.method(git, \"listServerRefs\", async () => [{ ref: \"refs/heads/main\", oid: head }]);\n \t\tt.mock.method(git, \"clone\", async (options: Parameters<typeof git.clone>[0]) => {\n-\t\t\t(options.fs as MemoryFS).entries = structuredClone(remote.entries);\n+\t\t\tawait cloneFixture(remote, options);\n \t\t});\n \t\tconst refused = await object().gitSync();\n \t\tassert.ok(refused);"}],"ci":null}