Skip to content

abso-core

Public

abso is version control for agents: the client, the engine and a server you can run on your own Cloudflare account.

Check passed
MCP
show on this site's /mcp
CLI
abso show 178 --json
JSON
/christopher/abso-core/versions/178?format=json

Use disk-backed Git intake behind disk-first switch; cleared in review ask 56

of shared·codex-capacity-chair··Not checked

Version 177 · Files at version 178

32 files, 2397 lines added, 22 removed.

Binary file package-lock.json changed: 8a30a196a127 -> 346745f531bc
--- a/package.json
+++ b/package.json
@@ -11,13 +11,20 @@
1111 "scripts": {
1212 "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\"",
1313 "typecheck": "tsc --noEmit -p tsconfig.json",
14− "check": "npm run typecheck && npm run typecheck:server && npm test",
14+ "check": "npm run check:git-runtime && npm run typecheck && npm run typecheck:server && npm test",
1515 "build": "node scripts/build-client.mjs",
1616 "pack:npm": "node scripts/pack-npm.mjs",
1717 "check:changed": "node scripts/check-changed.mjs",
1818 "format": "biome check --write .",
1919 "lint": "biome ci .",
20− "typecheck:server": "tsc --noEmit -p server/tsconfig.json"
20+ "typecheck:server": "tsc --noEmit -p server/tsconfig.json",
21+ "install:git-runtime": "node server/scripts/capacity-install-git-runtime.mjs --root node_modules/isomorphic-git",
22+ "check:git-runtime": "node server/scripts/capacity-install-git-runtime.mjs --root node_modules/isomorphic-git --check",
23+ "postinstall": "npm run install:git-runtime",
24+ "prebuild": "npm run check:git-runtime",
25+ "pretest": "npm run check:git-runtime",
26+ "pretypecheck": "npm run check:git-runtime",
27+ "pretypecheck:server": "npm run check:git-runtime"
2128 },
2229 "devDependencies": {
2330 "@biomejs/biome": "2.5.15",
@@ -27,7 +34,7 @@
2734 "typescript": "^5.9.3"
2835 },
2936 "dependencies": {
30− "isomorphic-git": "^1.43.0",
37+ "isomorphic-git": "1.44.2",
3138 "yaml": "^2.9.1"
3239 }
3340}
Binary file server/package-lock.json changed: f5cebad6e233 -> 68f93bb4aa97
--- a/server/package.json
+++ b/server/package.json
@@ -8,10 +8,15 @@
88 "scripts": {
99 "dev": "wrangler dev --local",
1010 "deploy": "wrangler deploy",
11− "typecheck": "tsc --noEmit -p tsconfig.json"
11+ "typecheck": "tsc --noEmit -p tsconfig.json",
12+ "install:git-runtime": "node scripts/capacity-install-git-runtime.mjs --root node_modules/isomorphic-git",
13+ "check:git-runtime": "node scripts/capacity-install-git-runtime.mjs --root node_modules/isomorphic-git --check",
14+ "postinstall": "npm run install:git-runtime",
15+ "predev": "npm run check:git-runtime",
16+ "predeploy": "npm run check:git-runtime"
1217 },
1318 "dependencies": {
14− "isomorphic-git": "^1.43.0"
19+ "isomorphic-git": "1.44.2"
1520 },
1621 "devDependencies": {
1722 "@cloudflare/workers-types": "^5.20261001.1",
--- /dev/null
+++ b/server/scripts/capacity-git-bounded-fifo.mjs
@@ -0,0 +1,61 @@
1+/** One pending chunk; a producer cannot advance until the consumer takes it. */
2+export class BoundedPackFIFO {
3+ constructor(cancel = async () => {}) {
4+ this.cancel = cancel;
5+ this.ended = false;
6+ this.error = undefined;
7+ this.pending = undefined;
8+ this.reader = undefined;
9+ this.writer = undefined;
10+ }
11+ async write(value) {
12+ if (this.ended) throw this.error ?? Error("Pack stream is closed");
13+ if (this.pending !== undefined || this.writer) throw Error("Concurrent pack writes");
14+ if (this.reader) {
15+ const reader = this.reader;
16+ this.reader = undefined;
17+ reader.resolve({ value, done: false });
18+ return;
19+ }
20+ this.pending = value;
21+ await new Promise((resolve, reject) => {
22+ this.writer = { resolve, reject };
23+ });
24+ }
25+ async next() {
26+ if (this.error) throw this.error;
27+ if (this.pending !== undefined) {
28+ const value = this.pending;
29+ this.pending = undefined;
30+ this.writer?.resolve();
31+ this.writer = undefined;
32+ return { value, done: false };
33+ }
34+ if (this.ended) return { done: true };
35+ if (this.reader) throw Error("Concurrent pack reads");
36+ return new Promise((resolve, reject) => {
37+ this.reader = { resolve, reject };
38+ });
39+ }
40+ end() {
41+ this.ended = true;
42+ this.reader?.resolve({ done: true });
43+ this.reader = undefined;
44+ }
45+ destroy(error) {
46+ this.error = error;
47+ this.ended = true;
48+ this.pending = undefined;
49+ this.reader?.reject(error);
50+ this.writer?.reject(error);
51+ this.reader = this.writer = undefined;
52+ }
53+ async return() {
54+ this.destroy(Error("Pack consumer cancelled"));
55+ await this.cancel();
56+ return { done: true };
57+ }
58+ [Symbol.asyncIterator]() {
59+ return this;
60+ }
61+}
--- /dev/null
+++ b/server/scripts/capacity-install-git-runtime.mjs
@@ -0,0 +1,61 @@
1+import { execFileSync } from "node:child_process";
2+import { createHash } from "node:crypto";
3+import { copyFileSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";
4+import { tmpdir } from "node:os";
5+import { basename, dirname, join, resolve } from "node:path";
6+import { fileURLToPath } from "node:url";
7+
8+const scripts = dirname(fileURLToPath(import.meta.url));
9+const rootIndex = process.argv.indexOf("--root");
10+if (rootIndex < 0 || !process.argv[rootIndex + 1])
11+ throw Error("Pass --root with the exact isomorphic-git package directory");
12+const root = resolve(process.argv[rootIndex + 1]);
13+const hash = (bytes) => createHash("sha256").update(bytes).digest("hex");
14+const original = {
15+ "index.js": "66c20b7d890a6d48819f0be5f7bb1c5aab69937e6318ec912295c501028a5084",
16+ "index.cjs": "b2142bba9e651fce83d6c1d266d32fc5eefa748544c452f9f22fada4e33dc367",
17+};
18+const expected = {
19+ "index.js": "50ada141b506bff7cced797098f5ea70a6e40cda859884cc25b0dea985b10592",
20+ "index.cjs": "3b8a78b7145330038cf56e057f7726004a78d0af9a55845b685cf1f65443bae0",
21+};
22+if (JSON.parse(readFileSync(join(root, "package.json"), "utf8")).version !== "1.44.2")
23+ throw Error("Unsupported Git version");
24+const installed = Object.fromEntries(Object.keys(original).map((file) => [file, readFileSync(join(root, file))]));
25+if (Object.entries(expected).every(([file, digest]) => hash(installed[file]) === digest)) {
26+ console.log("Verified the complete Git capacity runtime patch.");
27+ process.exit(0);
28+}
29+if (process.argv.includes("--check")) throw Error("Complete Git capacity runtime patch is absent or modified");
30+for (const [file, digest] of Object.entries(original)) {
31+ if (hash(installed[file]) !== digest) throw Error(`Unrecognized or partially patched Git bundle: ${file}`);
32+}
33+const temporary = mkdtempSync(join(tmpdir(), "abso-git-patch-"));
34+if (dirname(resolve(temporary)) !== resolve(tmpdir()) || !basename(temporary).startsWith("abso-git-patch-"))
35+ throw Error("Unexpected temporary cleanup path");
36+try {
37+ const staged = join(temporary, "capacity-git-dependency-sandbox/node_modules/isomorphic-git");
38+ mkdirSync(staged, { recursive: true });
39+ copyFileSync(join(root, "package.json"), join(staged, "package.json"));
40+ for (const [file, bytes] of Object.entries(installed)) writeFileSync(join(staged, file), bytes);
41+ copyFileSync(join(scripts, "capacity-git-bounded-fifo.mjs"), join(temporary, "capacity-git-bounded-fifo.mjs"));
42+ for (const stage of ["push", "fetch", "sideband", "progress", "pump"]) {
43+ execFileSync(process.execPath, [join(scripts, `capacity-patch-git-${stage}.mjs`)], {
44+ cwd: temporary,
45+ stdio: "pipe",
46+ });
47+ }
48+ const outputs = Object.fromEntries(Object.keys(expected).map((file) => [file, readFileSync(join(staged, file))]));
49+ for (const [file, digest] of Object.entries(expected)) {
50+ if (hash(outputs[file]) !== digest) throw Error(`Unexpected complete Git patch: ${file}`);
51+ }
52+ // All stages and both final hashes pass before touching the installed package.
53+ for (const [file, bytes] of Object.entries(outputs)) writeFileSync(join(root, file), bytes);
54+ console.log("Installed and verified the complete Git capacity runtime patch.");
55+} finally {
56+ try {
57+ rmSync(temporary, { recursive: true, force: true });
58+ } catch {
59+ console.warn("Could not remove the Git patch staging directory.");
60+ }
61+}
--- /dev/null
+++ b/server/scripts/capacity-patch-git-fetch.mjs
@@ -0,0 +1,91 @@
1+import { createHash } from "node:crypto";
2+import { readFileSync, writeFileSync } from "node:fs";
3+import { join } from "node:path";
4+
5+// Extends only the reviewed-version push prototype in this isolated dependency tree.
6+const root = "capacity-git-dependency-sandbox/node_modules/isomorphic-git";
7+const inputs = {
8+ "index.js": "0bd051b1a38bf8d593bf37b5acf9ee453ddab33d48950c84e2c2c3f3ec449fc8",
9+ "index.cjs": "6c9f6eab37a10c9311f2b7aa8d24b0772d4ba2703d848525a0519e1454d016e7",
10+};
11+const hash = (source) => createHash("sha256").update(source).digest("hex");
12+const expectedOutputs = {
13+ "index.js": "eebe6911fa660d4b95857768ea2308be74435dd5f9a796bb7b2491a31bdd109d",
14+ "index.cjs": "33364e3ed7f3a1a6cf17a1ecabbfc5d6de6a8494f31a524d8ac293402ad4e447",
15+};
16+function once(source, before, after) {
17+ if (source.split(before).length !== 2) throw Error("Fetch patch anchor mismatch");
18+ return source.replace(before, after);
19+}
20+if (JSON.parse(readFileSync(join(root, "package.json"), "utf8")).version !== "1.44.2") {
21+ throw Error("Unsupported Git version");
22+}
23+const outputs = [];
24+const installed = Object.fromEntries(Object.keys(inputs).map((file) => [file, readFileSync(join(root, file), "utf8")]));
25+if (Object.entries(expectedOutputs).every(([file, expected]) => hash(installed[file]) === expected)) {
26+ console.log(
27+ JSON.stringify({
28+ verified: true,
29+ scope: "Isolated fetch prototype",
30+ bundles: expectedOutputs,
31+ }),
32+ );
33+ process.exit(0);
34+}
35+for (const [file, expected] of Object.entries(inputs)) {
36+ const source = installed[file];
37+ if (hash(source) !== expected) throw Error(`Unrecognized input: ${file}`);
38+ let result = once(
39+ source,
40+ " const packfile = Buffer.from(await collect(response.packfile));",
41+ ` const diskPack = cache && cache[Symbol.for('abso.git.disk-pack')];
42+ if (diskPack) {
43+ await diskPack.ingest(response.packfile, () => new pako.Inflate({ chunkSize: 16384 }));
44+ if (raw.body.error) throw raw.body.error
45+ const result = {
46+ defaultBranch: response.HEAD,
47+ fetchHead: response.FETCH_HEAD.oid,
48+ fetchHeadDescription: response.FETCH_HEAD.description,
49+ };
50+ if (response.headers) result.headers = response.headers;
51+ if (prune) result.pruned = response.pruned;
52+ return result
53+ }
54+ const packfile = Buffer.from(await collect(response.packfile));`,
55+ );
56+ const readStart = result.indexOf("async function _readObject({");
57+ const readEnd = result.indexOf("\nclass AlreadyExistsError", readStart);
58+ if (readStart < 0 || readEnd < 0) throw Error("Missing object reader boundary");
59+ const readFunction = once(
60+ result.slice(readStart, readEnd),
61+ " // Curry the current read method so that the packfile un-deltification",
62+ ` const diskPack = cache && cache[Symbol.for('abso.git.disk-pack')];
63+ if (diskPack && format === 'content') {
64+ const stored = await diskPack.read(oid);
65+ if (stored) return stored
66+ }
68+ // Curry the current read method so that the packfile un-deltification`,
69+ );
70+ result = result.slice(0, readStart) + readFunction + result.slice(readEnd);
71+ if (hash(result) !== expectedOutputs[file]) throw Error(`Unexpected fetch patch output: ${file}`);
72+ outputs.push({ file, result, sha256: hash(result) });
73+}
74+// Validate both installed bundles and every anchor before either write.
75+if (!process.argv.includes("--check")) {
76+ for (const { file, result } of outputs) writeFileSync(join(root, file), result);
77+ writeFileSync(
78+ "capacity-git-fetch-patch-manifest.json",
79+ JSON.stringify(
80+ outputs.map(({ file, sha256 }) => ({ file, sha256 })),
81+ null,
82+ 2,
83+ ),
84+ );
85+}
86+console.log(
87+ JSON.stringify({
88+ scope: "Isolated fetch prototype; runtime adapter and transport acceptance still required",
89+ outputs: outputs.map(({ file, sha256 }) => ({ file, sha256 })),
90+ }),
91+);
--- /dev/null
+++ b/server/scripts/capacity-patch-git-progress.mjs
@@ -0,0 +1,53 @@
1+import { createHash } from "node:crypto";
2+import { readFileSync, writeFileSync } from "node:fs";
3+import { join } from "node:path";
4+
5+const root = "capacity-git-dependency-sandbox/node_modules/isomorphic-git";
6+const inputs = {
7+ "index.js": "20512aae32eb8dd64b798c0dd4ba666ea801bec6c9de37d259527c93ce3e48ec",
8+ "index.cjs": "b4cd8c52f3fa945b553dbb7a740c965b48b93dfc2469f10849e111abd00c7460",
9+};
10+const hash = (value) => createHash("sha256").update(value).digest("hex");
11+function once(source, before, after) {
12+ if (source.split(before).length !== 2) throw Error(`Progress anchor mismatch: ${before}`);
13+ return source.replace(before, after);
14+}
15+const outputs = [];
16+for (const [file, expected] of Object.entries(inputs)) {
17+ let source = readFileSync(join(root, file), "utf8");
18+ if (hash(source) !== expected) throw Error(`Unrecognized input: ${file}`);
19+ source = once(
20+ source,
21+ " static demux(input, bounded = false) {",
22+ " static demux(input, bounded = false, discardProgress = false) {",
23+ );
24+ source = once(
25+ source,
26+ " progress.write(line.slice(1));",
27+ " if (!discardProgress) progress.write(line.slice(1));",
28+ );
29+ source = once(source, " progress.write(error);", " if (!discardProgress) progress.write(error);");
30+ source = once(
31+ source,
32+ "async function parseUploadPackResponse(stream, bounded = false) {\n const { packetlines, packfile, progress } = GitSideBand.demux(stream, bounded);",
33+ "async function parseUploadPackResponse(stream, bounded = false, discardProgress = false) {\n const { packetlines, packfile, progress } = GitSideBand.demux(stream, bounded, discardProgress);",
34+ );
35+ source = once(
36+ source,
37+ " const response = await parseUploadPackResponse(raw.body, Boolean(cache && cache[Symbol.for('abso.git.disk-pack')]));",
38+ " 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);",
39+ );
40+ outputs.push({ file, source, sha256: hash(source) });
41+}
42+if (!process.argv.includes("--check")) {
43+ for (const { file, source } of outputs) writeFileSync(join(root, file), source);
44+ writeFileSync(
45+ "capacity-git-progress-patch-manifest.json",
46+ JSON.stringify(
47+ outputs.map(({ file, sha256 }) => ({ file, sha256 })),
48+ null,
49+ 2,
50+ ),
51+ );
52+}
53+console.log(JSON.stringify(outputs.map(({ file, sha256 }) => ({ file, sha256 }))));
--- /dev/null
+++ b/server/scripts/capacity-patch-git-pump.mjs
@@ -0,0 +1,31 @@
1+import { createHash } from "node:crypto";
2+import { readFileSync, writeFileSync } from "node:fs";
3+import { join } from "node:path";
4+
5+const root = "capacity-git-dependency-sandbox/node_modules/isomorphic-git";
6+const inputs = {
7+ "index.js": "4e0e9ee5a21754ebd718864dba2705385fc8254ed0c9e0d4ff56c8a2ff6fccf8",
8+ "index.cjs": "fe66bb236ed6d95bf720e646afc9fff1dbe3efbc441b194efde09b1b698cd583",
9+};
10+const hash = (value) => createHash("sha256").update(value).digest("hex");
11+function once(source, before, after) {
12+ if (source.split(before).length !== 2) throw Error("Git pump anchor mismatch");
13+ return source.replace(before, after);
14+}
15+const outputs = [];
16+for (const [file, expected] of Object.entries(inputs)) {
17+ let source = readFileSync(join(root, file), "utf8");
18+ if (hash(source) !== expected) throw Error(`Unrecognized pump input: ${file}`);
19+ source = once(
20+ source,
21+ " const nextBit = async function () {",
22+ " const nextBit = async function () {\n while (true) {",
23+ );
24+ source = once(source, " if (line === null) return nextBit()", " if (line === null) continue");
25+ source = once(source, " return nextBit();\n };", " }\n };");
26+ outputs.push({ file, source, sha256: hash(source) });
27+}
28+if (!process.argv.includes("--check")) {
29+ for (const { file, source } of outputs) writeFileSync(join(root, file), source);
30+}
31+console.log(JSON.stringify(outputs.map(({ file, sha256 }) => ({ file, sha256 }))));
--- /dev/null
+++ b/server/scripts/capacity-patch-git-push.mjs
@@ -0,0 +1,94 @@
1+import { createHash } from "node:crypto";
2+import { readFileSync, writeFileSync } from "node:fs";
3+import { join } from "node:path";
4+
5+const root = "capacity-git-dependency-sandbox/node_modules/isomorphic-git";
6+const hashes = {
7+ "index.js": "66c20b7d890a6d48819f0be5f7bb1c5aab69937e6318ec912295c501028a5084",
8+ "index.cjs": "b2142bba9e651fce83d6c1d266d32fc5eefa748544c452f9f22fada4e33dc367",
9+};
10+const patched = {
11+ "index.js": "0bd051b1a38bf8d593bf37b5acf9ee453ddab33d48950c84e2c2c3f3ec449fc8",
12+ "index.cjs": "6c9f6eab37a10c9311f2b7aa8d24b0772d4ba2703d848525a0519e1454d016e7",
13+};
14+if (JSON.parse(readFileSync(join(root, "package.json"), "utf8")).version !== "1.44.2")
15+ throw Error("Unsupported Git version");
16+const installed = Object.fromEntries(
17+ Object.keys(hashes).map((file) => [
18+ file,
19+ createHash("sha256")
20+ .update(readFileSync(join(root, file)))
21+ .digest("hex"),
22+ ]),
23+);
24+if (Object.keys(patched).every((file) => installed[file] === patched[file])) {
25+ console.log(JSON.stringify({ verified: true, version: "1.44.2", bundles: installed }));
26+ process.exit(0);
27+}
28+if (process.argv.includes("--check")) throw Error("Git runtime patch is absent or modified");
29+function replaceOnce(source, before, after) {
30+ if (source.split(before).length !== 2) throw Error("Patch anchor mismatch");
31+ return source.replace(before, after);
32+}
33+const outputs = [];
34+for (const [file, expected] of Object.entries(hashes)) {
35+ const original = readFileSync(join(root, file), "utf8");
36+ if (createHash("sha256").update(original).digest("hex") !== expected) throw Error(`Unrecognized source: ${file}`);
37+ const start = original.indexOf("async function _pack({");
38+ const end = original.indexOf("\n// @ts-check", start);
39+ if (start < 0 || end < 0) throw Error("Missing pack implementation");
40+ const old = original.slice(start, end);
41+ let streamed = replaceOnce(old, "async function _pack({", "async function* _packStream({");
42+ streamed = replaceOnce(
43+ streamed,
44+ " for (const oid of oids) {",
45+ " yield* outputStream;\n outputStream.length = 0;\n for (const oid of oids) {",
46+ );
47+ streamed = replaceOnce(
48+ streamed,
49+ " await writeObject({ write, object, stype: type });",
50+ " await writeObject({ write, object, stype: type });\n yield* outputStream;\n outputStream.length = 0;",
51+ );
52+ streamed = replaceOnce(streamed, " outputStream.push(digest);\n return outputStream", " yield digest;");
53+ let result =
54+ original.slice(0, start) +
55+ streamed +
56+ "\nasync function _pack(options) {\n const output = [];\n for await (const chunk of _packStream(options)) output.push(chunk);\n return output;\n}\n" +
57+ original.slice(end);
58+ const begin = result.indexOf(" const packstream2 = _delete");
59+ const finish = result.indexOf(" const res = await GitRemoteHTTP.connect({", begin);
60+ if (begin < 0 || finish < 0) throw Error("Missing push implementation");
61+ result =
62+ result.slice(0, begin) +
63+ ` const packoids = [...objects];
64+ // Recreate the stream for every authentication retry; never retain a whole pack.
65+ const packbody = {
66+ async *[Symbol.asyncIterator]() {
67+ yield* packstream1;
68+ if (!_delete) yield* _packStream({ fs, cache, gitdir, oids: packoids });
69+ }
70+ };
71+` +
72+ result.slice(finish);
73+ result = replaceOnce(result, " body: [...packstream1, ...packstream2],", " body: packbody,");
74+ const sha256 = createHash("sha256").update(result).digest("hex");
75+ if (sha256 !== patched[file]) throw Error(`Unexpected patch output: ${file}`);
76+ outputs.push({ file, result, sha256 });
77+}
78+// Validate every input before changing either runtime bundle.
79+for (const output of outputs) writeFileSync(join(root, output.file), output.result);
80+writeFileSync(
81+ "capacity-git-push-patch-manifest.json",
82+ JSON.stringify(
83+ outputs.map(({ file, sha256 }) => ({ file, sha256 })),
84+ null,
85+ 2,
86+ ),
87+);
88+console.log(
89+ JSON.stringify({
90+ version: "1.44.2",
91+ patched: outputs.map(({ file, sha256 }) => ({ file, sha256 })),
92+ scope: "Isolated push patch; fetch and install integration incomplete",
93+ }),
94+);
--- /dev/null
+++ b/server/scripts/capacity-patch-git-sideband.mjs
@@ -0,0 +1,58 @@
1+import { createHash } from "node:crypto";
2+import { readFileSync, writeFileSync } from "node:fs";
3+import { join } from "node:path";
4+
5+const root = "capacity-git-dependency-sandbox/node_modules/isomorphic-git";
6+const inputs = {
7+ "index.js": "eebe6911fa660d4b95857768ea2308be74435dd5f9a796bb7b2491a31bdd109d",
8+ "index.cjs": "33364e3ed7f3a1a6cf17a1ecabbfc5d6de6a8494f31a524d8ac293402ad4e447",
9+};
10+const hash = (value) => createHash("sha256").update(value).digest("hex");
11+const queue = readFileSync("capacity-git-bounded-fifo.mjs", "utf8").replace("export class", "class");
12+function once(source, before, after) {
13+ if (source.split(before).length !== 2) throw Error(`Sideband anchor mismatch: ${before}`);
14+ return source.replace(before, after);
15+}
16+const outputs = [];
17+for (const [file, expected] of Object.entries(inputs)) {
18+ let source = readFileSync(join(root, file), "utf8");
19+ if (hash(source) !== expected) throw Error(`Unrecognized input: ${file}`);
20+ source = once(source, "class GitSideBand {", `${queue}\nclass GitSideBand {`);
21+ source = once(source, " static demux(input) {", " static demux(input, bounded = false) {");
22+ source = once(
23+ source,
24+ " const packfile = new FIFO();",
25+ " const packfile = bounded ? new BoundedPackFIFO(async () => { await getIterator(input).return?.(); }) : new FIFO();",
26+ );
27+ source = once(source, " packfile.write(line.slice(1));", " await packfile.write(line.slice(1));");
28+ source = once(
29+ source,
30+ " nextBit();\n };\n nextBit();",
31+ ` return nextBit();
32+ };
33+ nextBit().catch(error => { packetlines.destroy(error); progress.destroy(error); packfile.destroy(error); });`,
34+ );
35+ source = once(
36+ source,
37+ "async function parseUploadPackResponse(stream) {\n const { packetlines, packfile, progress } = GitSideBand.demux(stream);",
38+ "async function parseUploadPackResponse(stream, bounded = false) {\n const { packetlines, packfile, progress } = GitSideBand.demux(stream, bounded);",
39+ );
40+ source = once(
41+ source,
42+ " const response = await parseUploadPackResponse(raw.body);",
43+ " const response = await parseUploadPackResponse(raw.body, Boolean(cache && cache[Symbol.for('abso.git.disk-pack')]));",
44+ );
45+ outputs.push({ file, source, sha256: hash(source) });
46+}
47+if (!process.argv.includes("--check")) {
48+ for (const { file, source } of outputs) writeFileSync(join(root, file), source);
49+ writeFileSync(
50+ "capacity-git-sideband-patch-manifest.json",
51+ JSON.stringify(
52+ outputs.map(({ file, sha256 }) => ({ file, sha256 })),
53+ null,
54+ 2,
55+ ),
56+ );
57+}
58+console.log(JSON.stringify(outputs.map(({ file, sha256 }) => ({ file, sha256 }))));
--- /dev/null
+++ b/server/src/git-blob-text.ts
@@ -0,0 +1,22 @@
1+import type { GitByteRanges } from "./git-delta-stream.ts";
2+
3+export class InvalidGitUtf8 extends Error {}
4+
5+/** Strict UTF-8 decoding with the same BOM handling as whole-file intake. */
6+export function* gitBlobText(bytes: GitByteRanges): IterableIterator<string> {
7+ const decoder = new TextDecoder("utf-8", { fatal: true, ignoreBOM: false });
8+ const size = 16384;
9+ const decode = (chunk?: Uint8Array, stream = false) => {
10+ try {
11+ return decoder.decode(chunk, { stream });
12+ } catch (error) {
13+ throw new InvalidGitUtf8("Git blob is not UTF-8", { cause: error });
14+ }
15+ };
16+ for (let at = 0; at < bytes.byteLength; at += size) {
17+ const text = decode(bytes.read(at, Math.min(size, bytes.byteLength - at)), true);
18+ for (let offset = 0; offset < text.length; offset += size) yield text.slice(offset, offset + size);
19+ }
20+ const tail = decode();
21+ if (tail) yield tail;
22+}
--- /dev/null
+++ b/server/src/git-delta-stream.ts
@@ -0,0 +1,73 @@
1+export interface GitByteRanges {
2+ readonly byteLength: number;
3+ read(start: number, length: number): Uint8Array;
4+}
5+
6+/** Decode without retaining the base or complete result. Caller must roll back output if decoding throws. */
7+export function applyGitDeltaChunks(
8+ delta: GitByteRanges,
9+ base: GitByteRanges,
10+ write: (chunk: Uint8Array) => void,
11+ maxResultBytes: number,
12+): number {
13+ if (!Number.isSafeInteger(maxResultBytes) || maxResultBytes < 0) throw Error("invalid delta result limit");
14+ let position = 0,
15+ produced = 0;
16+ let cached: Uint8Array = new Uint8Array(0),
17+ cacheStart = 0;
18+ const byte = () => {
19+ if (position >= delta.byteLength) throw Error("truncated Git delta");
20+ if (position < cacheStart || position >= cacheStart + cached.length) {
21+ cacheStart = position;
22+ const count = Math.min(65536, delta.byteLength - position);
23+ cached = delta.read(position, count);
24+ if (cached.length !== count) throw Error("missing delta bytes");
25+ }
26+ return cached[position++ - cacheStart]!;
27+ };
28+ const integer = () => {
29+ let value = 0,
30+ multiplier = 1;
31+ for (let i = 0; i < 8; i++) {
32+ const next = byte();
33+ value += (next & 127) * multiplier;
34+ if (!Number.isSafeInteger(value)) throw Error("Git delta integer overflow");
35+ if (!(next & 128)) return value;
36+ multiplier *= 128;
37+ }
38+ throw Error("Git delta integer overflow");
39+ };
40+ if (integer() !== base.byteLength) throw Error("Git delta base length mismatch");
41+ const size = integer();
42+ if (size > maxResultBytes) throw Error("Git delta result exceeds bound");
43+ const emit = (chunk: Uint8Array) => {
44+ if (produced + chunk.length > size) throw Error("Git delta result length mismatch");
45+ write(chunk);
46+ produced += chunk.length;
47+ };
48+ while (position < delta.byteLength) {
49+ const instruction = byte();
50+ if (instruction & 128) {
51+ let offset = 0,
52+ length = 0;
53+ for (let i = 0; i < 4; i++) if (instruction & (1 << i)) offset += byte() * 2 ** (8 * i);
54+ for (let i = 0; i < 3; i++) if (instruction & (16 << i)) length += byte() * 2 ** (8 * i);
55+ if (!length) length = 65536;
56+ if (offset + length > base.byteLength) throw Error("Git delta copy exceeds base");
57+ if (produced + length > size) throw Error("Git delta result length mismatch");
58+ for (let at = 0; at < length; at += 65536) {
59+ const count = Math.min(65536, length - at),
60+ chunk = base.read(offset + at, count);
61+ if (chunk.length !== count) throw Error("missing delta base bytes");
62+ emit(chunk);
63+ }
64+ } else {
65+ if (!instruction) throw Error("invalid Git delta instruction");
66+ const literal = new Uint8Array(instruction);
67+ for (let i = 0; i < instruction; i++) literal[i] = byte();
68+ emit(literal);
69+ }
70+ }
71+ if (produced !== size) throw Error("Git delta result length mismatch");
72+ return size;
73+}
--- /dev/null
+++ b/server/src/git-disk-intake.ts
@@ -0,0 +1,102 @@
1+import type { SqliteStorage } from "./engine-project.ts";
2+import type { StoredGitBytes } from "./git-object-bytes.ts";
3+import { decodeGitPack, type PackInflater } from "./git-pack-decode.ts";
4+import { GitPackResolver } from "./git-pack-resolver.ts";
5+import { GitPackSpool } from "./git-pack-spool.ts";
6+
7+/** One clone's temporary pack store. The caller must dispose it in finally. */
8+export class GitDiskIntake {
9+ /** Cold object construction only, before any intake or reader is created. */
10+ static recover(storage: SqliteStorage): void {
11+ // Constructors establish scratch tables only; they do not alter project state.
12+ const resolver = new GitPackResolver(storage, 0);
13+ storage.transactionSync(() => {
14+ GitPackSpool.recover(storage);
15+ storage.sql.exec("DELETE FROM git_pack_resolve");
16+ storage.sql.exec("DELETE FROM git_object_bytes");
17+ storage.sql.exec("DELETE FROM git_object_meta");
18+ storage.sql.exec("DELETE FROM git_object_budget");
19+ });
20+ resolver.dispose();
21+ }
22+ private readonly spool: GitPackSpool;
23+ private readonly resolver: GitPackResolver;
24+ private readonly maxPackBytes: number;
25+ private state: "new" | "loading" | "ready" | "closed" = "new";
26+ constructor(storage: SqliteStorage, maxPackBytes: number, maxObjectBytes: number, maxDecodedBytes = maxPackBytes) {
27+ if (!Number.isSafeInteger(maxPackBytes) || maxPackBytes < 32) throw Error("invalid pack limit");
28+ this.maxPackBytes = maxPackBytes;
29+ this.resolver = new GitPackResolver(storage, maxObjectBytes, maxDecodedBytes);
30+ this.spool = new GitPackSpool(storage);
31+ }
32+ attach(cache: object): void {
33+ const key = Symbol.for("abso.git.disk-pack");
34+ if (key in cache) throw Error("Git disk intake already attached");
35+ Object.defineProperty(cache, key, { value: this });
36+ }
37+ async ingest(
38+ chunks: AsyncIterable<Uint8Array> | Iterable<Uint8Array> | AsyncIterator<Uint8Array>,
39+ createInflater: () => PackInflater,
40+ ): Promise<void> {
41+ if (this.state !== "new") throw Error("Git disk intake already used");
42+ this.state = "loading";
43+ const iterator =
44+ Symbol.asyncIterator in chunks
45+ ? chunks[Symbol.asyncIterator]()
46+ : Symbol.iterator in chunks
47+ ? chunks[Symbol.iterator]()
48+ : chunks;
49+ try {
50+ const source = {
51+ [Symbol.asyncIterator]: () => ({
52+ next: async () => iterator.next(),
53+ return: async () => (iterator.return ? iterator.return() : { done: true as const, value: undefined }),
54+ }),
55+ };
56+ await this.spool.ingest(source, this.maxPackBytes);
57+ if (this.state !== "loading") throw Error("Git disk intake closed during download");
58+ decodeGitPack(this.spool, this.resolver, createInflater);
59+ this.spool.dispose();
60+ this.state = "ready";
61+ } catch (error) {
62+ try {
63+ await iterator.return?.();
64+ } catch {
65+ /* Preserve the intake failure. */
66+ }
67+ this.dispose();
68+ throw error;
69+ }
70+ }
71+ bytes(oid: string): StoredGitBytes | undefined {
72+ if (this.state === "closed") throw Error("Git disk intake is closed");
73+ if (this.state !== "ready") return undefined;
74+ return this.resolver.find(oid);
75+ }
76+ read(oid: string): { format: "content"; type: string; object: Buffer } | undefined {
77+ const stored = this.bytes(oid);
78+ if (!stored) return undefined;
79+ // Existing Git consumers require one complete object. This does not claim
80+ // bounded blob consumption; it removes whole-pack retention and caching.
81+ const object = Buffer.alloc(stored.byteLength);
82+ for (let at = 0; at < stored.byteLength; at += 65536) {
83+ object.set(stored.read(at, Math.min(65536, stored.byteLength - at)), at);
84+ }
85+ return { format: "content", type: stored.type, object };
86+ }
87+ assertReady(): void {
88+ if (this.state !== "ready") throw Error("Git disk intake was not used by the installed runtime");
89+ }
90+ [Symbol.dispose](): void {
91+ this.dispose();
92+ }
93+ dispose(): void {
94+ if (this.state === "closed") return;
95+ this.state = "closed";
96+ try {
97+ this.resolver.dispose();
98+ } finally {
99+ this.spool.dispose();
100+ }
101+ }
102+}
--- /dev/null
+++ b/server/src/git-http.ts
@@ -0,0 +1,58 @@
1+import type { HttpClient } from "isomorphic-git";
2+
3+/** Stream Git HTTP request chunks without a second complete upload buffer. */
4+export function gitHttp(fetcher: typeof fetch = fetch): HttpClient {
5+ return {
6+ async request({ url, method = "GET", headers = {}, body, signal, fetchOptions = {} }) {
7+ const input = body as AsyncIterable<Uint8Array> | Iterable<Uint8Array> | undefined;
8+ const iterator = input
9+ ? Symbol.asyncIterator in input
10+ ? input[Symbol.asyncIterator]()
11+ : input[Symbol.iterator]()
12+ : undefined;
13+ const stream = iterator
14+ ? new ReadableStream<Uint8Array>(
15+ {
16+ async pull(controller) {
17+ try {
18+ const next = await iterator.next();
19+ if (next.done) controller.close();
20+ else controller.enqueue(next.value);
21+ } catch (error) {
22+ controller.error(error);
23+ }
24+ },
25+ async cancel() {
26+ await iterator.return?.();
27+ },
28+ },
29+ { highWaterMark: 0 },
30+ )
31+ : undefined;
32+ let response: Response;
33+ try {
34+ const options: RequestInit & { duplex?: string } = {
35+ ...fetchOptions,
36+ method,
37+ headers,
38+ body: stream,
39+ signal: signal ?? fetchOptions.signal,
40+ ...(stream ? { duplex: "half" } : {}),
41+ };
42+ response = await fetcher(url, options);
43+ } catch (error) {
44+ await iterator?.return?.();
45+ throw error;
46+ }
47+ const responseBody = response.body;
48+ return {
49+ url: response.url,
50+ method,
51+ statusCode: response.status,
52+ statusMessage: response.statusText,
53+ headers: Object.fromEntries(response.headers.entries()),
54+ body: responseBody ? responseBody[Symbol.asyncIterator]() : (async function* () {})(),
55+ };
56+ },
57+ };
58+}
--- /dev/null
+++ b/server/src/git-intake-trees.ts
@@ -0,0 +1,77 @@
1+import { StoredText } from "../../src/engine/stored-text.ts";
2+import type { SqliteStorage } from "./engine-project.ts";
3+import type { PushedCommits } from "./ingest.ts";
4+import { SqliteWriterState } from "./writer-host.ts";
5+
6+type Tree = Pick<PushedCommits["commits"][number], "files" | "modes" | "blobs">;
7+
8+/** Keeps earlier Git trees on disk while later commits are decoded. */
9+export class GitIntakeTrees {
10+ /** Only at a cold Durable Object start, before any intake can be active. */
11+ static recover(storage: SqliteStorage): void {
12+ SqliteWriterState.initialize(storage);
13+ storage.sql.exec("DELETE FROM writer_state WHERE namespace GLOB 'git-intake:*'");
14+ }
15+ readonly namespace = `git-intake:${crypto.randomUUID()}`;
16+ readonly storage: SqliteStorage;
17+ readonly text: StoredText;
18+ private next = 0;
19+ private active = true;
20+ constructor(storage: SqliteStorage) {
21+ this.storage = storage;
22+ SqliteWriterState.initialize(storage);
23+ this.text = new StoredText(new SqliteWriterState(storage, this.namespace), "files");
24+ }
25+ /** Created outside any scope containing decoded file text or a whole tree. */
26+ private getter(key: string): () => string {
27+ return () => {
28+ if (!this.active) throw Error("Git intake trees are closed");
29+ return this.text.read(key);
30+ };
31+ }
32+ retainFile(files: Record<string, string>, path: string, body: string, oid?: string): void {
33+ this.retainChunks(
34+ files,
35+ path,
36+ (function* () {
37+ for (let at = 0; at < body.length; at += StoredText.chunkCharacters)
38+ yield body.slice(at, at + StoredText.chunkCharacters);
39+ })(),
40+ oid,
41+ );
42+ }
43+ retainChunks(files: Record<string, string>, path: string, chunks: Iterable<string>, oid?: string): void {
44+ if (!this.active) throw Error("Git intake trees are closed");
45+ if (oid !== undefined && !/^[0-9a-f]{40}$/.test(oid)) throw Error("Invalid Git blob id");
46+ const key = oid === undefined ? String(this.next++) : `blob:${oid}`;
47+ this.storage.transactionSync(() => {
48+ if (this.text.storage.read(this.text.collection, key) === undefined) this.text.writeChunks(key, chunks);
49+ });
50+ Object.defineProperty(files, path, {
51+ enumerable: true,
52+ get: this.getter(key),
53+ });
54+ }
55+ retain(tree: Tree): Tree {
56+ if (!this.active) throw Error("Git intake trees are closed");
57+ const files: Record<string, string> = Object.create(null);
58+ this.storage.transactionSync(() => {
59+ for (const path of Object.keys(tree.files)) {
60+ const key = String(this.next++);
61+ this.text.write(key, tree.files[path]!);
62+ Object.defineProperty(files, path, {
63+ enumerable: true,
64+ get: this.getter(key),
65+ });
66+ }
67+ });
68+ return { files, modes: tree.modes, blobs: tree.blobs };
69+ }
70+ [Symbol.dispose](): void {
71+ this.dispose();
72+ }
73+ dispose(): void {
74+ this.active = false;
75+ this.storage.sql.exec("DELETE FROM writer_state WHERE namespace = ?", this.namespace);
76+ }
77+}
--- /dev/null
+++ b/server/src/git-object-bytes.ts
@@ -0,0 +1,146 @@
1+import { createHash } from "node:crypto";
2+import type { SqliteStorage } from "./engine-project.ts";
3+import type { GitByteRanges } from "./git-delta-stream.ts";
4+
5+export type StoredGitBytes = GitByteRanges & {
6+ id: string;
7+ oid: string;
8+ type: string;
9+};
11+/** Intake-local object bytes; callers own this store's lifetime. */
12+export class GitObjectBytes {
13+ readonly scope = crypto.randomUUID();
14+ private closed = false;
15+ private readonly storage: SqliteStorage;
16+ private readonly maxDecodedBytes: number;
17+ constructor(storage: SqliteStorage, maxDecodedBytes = Number.MAX_SAFE_INTEGER) {
18+ if (!Number.isSafeInteger(maxDecodedBytes) || maxDecodedBytes < 0) throw Error("invalid decoded byte limit");
19+ this.storage = storage;
20+ this.maxDecodedBytes = maxDecodedBytes;
21+ storage.sql.exec(
22+ "CREATE TABLE IF NOT EXISTS git_object_bytes (scope TEXT, id TEXT, part INTEGER, data BLOB NOT NULL, PRIMARY KEY(scope,id,part))",
23+ );
24+ storage.sql.exec(
25+ "CREATE TABLE IF NOT EXISTS git_object_meta (scope TEXT, id TEXT, type TEXT, bytes INTEGER, oid TEXT, PRIMARY KEY(scope,id))",
26+ );
27+ storage.sql.exec("CREATE TABLE IF NOT EXISTS git_object_budget (scope TEXT PRIMARY KEY, decoded INTEGER NOT NULL)");
28+ storage.sql.exec("INSERT INTO git_object_budget VALUES (?, 0)", this.scope);
29+ }
30+ private active(): void {
31+ if (this.closed) throw Error("Git object store is closed");
32+ }
33+ put(type: string, produce: (write: (bytes: Uint8Array) => void) => void, maxBytes: number): StoredGitBytes {
34+ this.active();
35+ if (!["blob", "tree", "commit", "tag"].includes(type) || !Number.isSafeInteger(maxBytes) || maxBytes < 0)
36+ throw Error("invalid Git object limits or type");
37+ const id = crypto.randomUUID();
38+ this.storage.transactionSync(() => {
39+ const budget = this.storage.sql
40+ .exec("SELECT decoded FROM git_object_budget WHERE scope = ?", this.scope)
41+ .toArray() as { decoded: number }[];
42+ if (budget.length !== 1) throw Error("missing Git decoded budget");
43+ const remaining = this.maxDecodedBytes - budget[0]!.decoded;
44+ let length = 0,
45+ part = 0,
46+ used = 0;
47+ const pending = new Uint8Array(65536);
48+ const flush = () => {
49+ this.storage.sql.exec(
50+ "INSERT INTO git_object_bytes VALUES (?, ?, ?, ?)",
51+ this.scope,
52+ id,
53+ part++,
54+ pending.slice(0, used),
55+ );
56+ used = 0;
57+ };
58+ produce((bytes) => {
59+ if (length + bytes.length > maxBytes) throw Error("Git object exceeds byte limit");
60+ if (length + bytes.length > remaining) throw Error("Git pack exceeds total decoded byte limit");
61+ length += bytes.length;
62+ for (let at = 0; at < bytes.length; ) {
63+ const count = Math.min(pending.length - used, bytes.length - at);
64+ pending.set(bytes.subarray(at, at + count), used);
65+ at += count;
66+ used += count;
67+ if (used === pending.length) flush();
68+ }
69+ });
70+ if (used) flush();
71+ const hash = createHash("sha1").update(`${type} ${length}\0`);
72+ for (let index = 0; index < part; index++) hash.update(this.chunk(id, index));
73+ this.storage.sql.exec(
74+ "INSERT INTO git_object_meta VALUES (?, ?, ?, ?, ?)",
75+ this.scope,
76+ id,
77+ type,
78+ length,
79+ hash.digest("hex"),
80+ );
81+ this.storage.sql.exec("UPDATE git_object_budget SET decoded = decoded + ? WHERE scope = ?", length, this.scope);
82+ });
83+ return this.get(id);
84+ }
85+ private chunk(id: string, part: number): Uint8Array {
86+ this.active();
87+ const rows = this.storage.sql
88+ .exec("SELECT data FROM git_object_bytes WHERE scope = ? AND id = ? AND part = ?", this.scope, id, part)
89+ .toArray() as { data: ArrayBuffer }[];
90+ if (rows.length !== 1) throw Error("missing Git object chunk");
91+ const bytes = new Uint8Array(rows[0]!.data);
92+ if (!bytes.length || bytes.length > 65536) throw Error("invalid Git object chunk");
93+ return bytes;
94+ }
95+ get(id: string): StoredGitBytes {
96+ this.active();
97+ const rows = this.storage.sql
98+ .exec("SELECT type, bytes, oid FROM git_object_meta WHERE scope = ? AND id = ?", this.scope, id)
99+ .toArray() as { type: string; bytes: number; oid: string }[];
100+ if (rows.length !== 1) throw Error("missing Git object");
101+ const meta = rows[0]!;
102+ return {
103+ id,
104+ oid: meta.oid,
105+ type: meta.type,
106+ byteLength: meta.bytes,
107+ read: (start, length) => {
108+ this.active();
109+ if (
110+ !Number.isSafeInteger(start) ||
111+ !Number.isSafeInteger(length) ||
112+ start < 0 ||
113+ length < 0 ||
114+ length > 65536 ||
115+ start + length > meta.bytes
116+ )
117+ throw Error("invalid Git object range");
118+ const result = new Uint8Array(length);
119+ for (let copied = 0; copied < length; ) {
120+ const position = start + copied,
121+ chunk = this.chunk(id, Math.floor(position / 65536));
122+ const offset = position % 65536,
123+ count = Math.min(length - copied, chunk.length - offset);
124+ if (count <= 0) throw Error("truncated Git object chunk");
125+ result.set(chunk.subarray(offset, offset + count), copied);
126+ copied += count;
127+ }
128+ return result;
129+ },
130+ };
131+ }
132+ /** Remove obsolete delta instructions without refunding their decoded-work budget. */
133+ remove(id: string): void {
134+ this.active();
135+ this.storage.sql.exec("DELETE FROM git_object_bytes WHERE scope = ? AND id = ?", this.scope, id);
136+ this.storage.sql.exec("DELETE FROM git_object_meta WHERE scope = ? AND id = ?", this.scope, id);
137+ }
138+ dispose(): void {
139+ this.closed = true;
140+ this.storage.transactionSync(() => {
141+ this.storage.sql.exec("DELETE FROM git_object_bytes WHERE scope = ?", this.scope);
142+ this.storage.sql.exec("DELETE FROM git_object_meta WHERE scope = ?", this.scope);
143+ this.storage.sql.exec("DELETE FROM git_object_budget WHERE scope = ?", this.scope);
144+ });
145+ }
146+}
--- /dev/null
+++ b/server/src/git-pack-decode.ts
@@ -0,0 +1,100 @@
1+import type { GitPackResolver } from "./git-pack-resolver.ts";
2+import type { GitPackSpool } from "./git-pack-spool.ts";
3+
4+/** Structural adapter for the pinned Git dependency's streaming inflater. */
5+export interface PackInflater {
6+ onData: (bytes: Uint8Array) => void;
7+ push(bytes: Uint8Array, final: boolean): unknown;
8+ ended: boolean;
9+ err: number;
10+ msg: string;
11+ strm: { avail_in: number };
12+}
14+/** Decode verified disk bytes without collecting a pack or decoded object in memory. */
15+export function decodeGitPack(
16+ spool: GitPackSpool,
17+ resolver: GitPackResolver,
18+ createInflater: () => PackInflater,
19+): void {
20+ try {
21+ decodeVerifiedPack(spool, resolver, createInflater);
22+ } catch (error) {
23+ // Intake owns this resolver. Never expose earlier objects from a rejected pack.
24+ resolver.dispose();
25+ throw error;
26+ }
27+}
29+function decodeVerifiedPack(spool: GitPackSpool, resolver: GitPackResolver, createInflater: () => PackInflater): void {
30+ const end = spool.byteLength - 20;
31+ const header = spool.read(0, 12);
32+ const count = new DataView(header.buffer, header.byteOffset, header.byteLength).getUint32(8);
33+ let position = 12;
34+ let cached: Uint8Array = new Uint8Array(0),
35+ cachedAt = 0;
36+ const byte = () => {
37+ if (position >= end) throw Error("truncated Git pack header");
38+ if (position < cachedAt || position >= cachedAt + cached.length) {
39+ cachedAt = position;
40+ cached = spool.read(position, Math.min(65536, end - position));
41+ }
42+ return cached[position++ - cachedAt]!;
43+ };
44+ for (let index = 0; index < count; index++) {
45+ const offset = position;
46+ let current = byte();
47+ const kind = (current >> 4) & 7;
48+ let length = current & 15,
49+ factor = 16;
50+ while (current & 128) {
51+ current = byte();
52+ length += (current & 127) * factor;
53+ factor *= 128;
54+ if (!Number.isSafeInteger(length) || !Number.isSafeInteger(factor)) throw Error("invalid Git object size");
55+ }
56+ let base: number | string | undefined;
57+ if (kind === 6) {
58+ current = byte();
59+ let distance = current & 127;
60+ while (current & 128) {
61+ current = byte();
62+ distance = (distance + 1) * 128 + (current & 127);
63+ if (!Number.isSafeInteger(distance)) throw Error("invalid Git delta distance");
64+ }
65+ base = offset - distance;
66+ } else if (kind === 7) {
67+ let reference = "";
68+ for (let i = 0; i < 20; i++) reference += byte().toString(16).padStart(2, "0");
69+ base = reference;
70+ }
71+ const type = ["", "commit", "tree", "blob", "tag", "", "delta", "delta"][kind];
72+ if (!type) throw Error("unsupported Git object type");
73+ resolver.addChunks(
74+ offset,
75+ type,
76+ (write) => {
77+ const inflater = createInflater();
78+ let decoded = 0;
79+ inflater.onData = (bytes) => {
80+ decoded += bytes.length;
81+ if (bytes.length > 65536 || decoded > length) throw Error("invalid inflated Git object size");
82+ write(bytes);
83+ };
84+ while (!inflater.ended) {
85+ if (position >= end) throw Error("truncated compressed Git object");
86+ const chunk = spool.read(position, Math.min(65536, end - position));
87+ inflater.push(chunk, false);
88+ if (inflater.err) throw Error(`Git inflate failed: ${inflater.msg}`);
89+ const consumed = chunk.length - inflater.strm.avail_in;
90+ if (consumed <= 0 || consumed > chunk.length) throw Error("Git inflater made no progress");
91+ position += consumed;
92+ }
93+ if (decoded !== length) throw Error("inflated Git object size mismatch");
94+ },
95+ base,
96+ );
97+ }
98+ if (position !== end) throw Error("unexpected bytes after Git pack objects");
99+ resolver.resolve();
100+}
--- /dev/null
+++ b/server/src/git-pack-resolver.ts
@@ -0,0 +1,133 @@
1+import type { SqliteStorage } from "./engine-project.ts";
2+import { applyGitDeltaChunks } from "./git-delta-stream.ts";
3+import { GitObjectBytes, type StoredGitBytes } from "./git-object-bytes.ts";
4+
5+/** Scratch index and decoded objects for one pack. No in-memory object map. */
6+export class GitPackResolver {
7+ readonly scope = crypto.randomUUID();
8+ readonly objects: GitObjectBytes;
9+ private readonly storage: SqliteStorage;
10+ private readonly maxObjectBytes: number;
11+ private closed = false;
12+ constructor(storage: SqliteStorage, maxObjectBytes: number, maxDecodedBytes = maxObjectBytes) {
13+ if (!Number.isSafeInteger(maxObjectBytes) || maxObjectBytes < 0) throw Error("invalid object limit");
14+ this.storage = storage;
15+ this.maxObjectBytes = maxObjectBytes;
16+ this.objects = new GitObjectBytes(storage, maxDecodedBytes);
17+ storage.sql.exec(
18+ "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))",
19+ );
20+ storage.sql.exec("CREATE INDEX IF NOT EXISTS git_pack_resolve_oid ON git_pack_resolve(scope,oid)");
21+ storage.sql.exec(
22+ "CREATE INDEX IF NOT EXISTS git_pack_unresolved ON git_pack_resolve(scope,offset) WHERE result IS NULL",
23+ );
24+ }
25+ private active(): void {
26+ if (this.closed) throw Error("pack resolver is closed");
27+ }
28+ add(offset: number, type: string, data: Uint8Array, base?: number | string): void {
29+ this.addChunks(offset, type, (write) => write(data), base);
30+ }
31+ /** The inflater writes bounded output directly into the transactional object store. */
32+ addChunks(
33+ offset: number,
34+ type: string,
35+ produce: (write: (bytes: Uint8Array) => void) => void,
36+ base?: number | string,
37+ ): void {
38+ this.active();
39+ if (!Number.isSafeInteger(offset) || offset < 12) throw Error("invalid pack offset");
40+ if (type === "delta") {
41+ if (
42+ typeof base === "number"
43+ ? !Number.isSafeInteger(base) || base < 12 || base >= offset
44+ : typeof base !== "string" || !/^[0-9a-f]{40}$/.test(base)
45+ )
46+ throw Error("invalid delta base reference");
47+ } else if (base !== undefined) throw Error("ordinary object has delta base");
48+ this.storage.transactionSync(() => {
49+ const stored = this.objects.put(type === "delta" ? "blob" : type, produce, this.maxObjectBytes);
50+ this.storage.sql.exec(
51+ "INSERT INTO git_pack_resolve VALUES (?, ?, ?, ?, ?, ?, ?, ?)",
52+ this.scope,
53+ offset,
54+ stored.id,
55+ typeof base === "number" ? base : null,
56+ typeof base === "string" ? base : null,
57+ type === "delta" ? null : stored.id,
58+ type === "delta" ? null : stored.oid,
59+ type === "delta" ? null : 0,
60+ );
61+ });
62+ }
63+ resolve(): void {
64+ this.active();
65+ this.storage.transactionSync(() => {
66+ for (;;) {
67+ const rows = this.storage.sql
68+ .exec(
69+ `SELECT p.offset, p.raw, COALESCE(b.result, r.result) AS base, COALESCE(b.depth, r.depth) AS depth
70+FROM git_pack_resolve p
71+LEFT JOIN git_pack_resolve b ON b.scope = p.scope AND b.offset = p.base_offset
72+LEFT JOIN git_pack_resolve r ON r.scope = p.scope AND r.oid = p.base_oid
73+WHERE p.scope = ? AND p.result IS NULL AND (b.result IS NOT NULL OR r.result IS NOT NULL)
74+ORDER BY p.offset LIMIT 1`,
75+ this.scope,
76+ )
77+ .toArray() as {
78+ offset: number;
79+ raw: string;
80+ base: string;
81+ depth: number;
82+ }[];
83+ if (!rows.length) break;
84+ const row = rows[0]!;
85+ if (row.depth >= 64) throw Error("Git delta chain exceeds depth limit");
86+ const base = this.objects.get(row.base),
87+ delta = this.objects.get(row.raw);
88+ const result = this.objects.put(
89+ base.type,
90+ (write) => {
91+ applyGitDeltaChunks(delta, base, write, this.maxObjectBytes);
92+ },
93+ this.maxObjectBytes,
94+ );
95+ this.storage.sql.exec(
96+ "UPDATE git_pack_resolve SET result = ?, oid = ?, depth = ? WHERE scope = ? AND offset = ?",
97+ result.id,
98+ result.oid,
99+ row.depth + 1,
100+ this.scope,
101+ row.offset,
102+ );
103+ this.objects.remove(row.raw);
104+ }
105+ if (
106+ this.storage.sql
107+ .exec("SELECT offset FROM git_pack_resolve WHERE scope = ? AND result IS NULL LIMIT 1", this.scope)
108+ .toArray().length
109+ )
110+ throw Error("unresolved or cyclic Git delta base");
111+ });
112+ }
113+ get(oid: string): StoredGitBytes {
114+ const value = this.find(oid);
115+ if (!value) throw Error("missing packed Git object");
116+ return value;
117+ }
118+ find(oid: string): StoredGitBytes | undefined {
119+ this.active();
120+ const rows = this.storage.sql
121+ .exec("SELECT result FROM git_pack_resolve WHERE scope = ? AND oid = ? LIMIT 1", this.scope, oid)
122+ .toArray() as { result: string }[];
123+ if (!rows.length) return undefined;
124+ return this.objects.get(rows[0]!.result);
125+ }
126+ dispose(): void {
127+ this.closed = true;
128+ this.storage.transactionSync(() => {
129+ this.storage.sql.exec("DELETE FROM git_pack_resolve WHERE scope = ?", this.scope);
130+ this.objects.dispose();
131+ });
132+ }
133+}
--- /dev/null
+++ b/server/src/git-pack-spool.ts
@@ -0,0 +1,119 @@
1+import { createHash } from "node:crypto";
2+import type { SqliteStorage } from "./engine-project.ts";
3+
4+/** Temporary verified pack bytes. No whole-pack read API is exposed. */
5+export class GitPackSpool {
6+ static readonly chunkBytes = 65536;
7+ /** Cold Durable Object construction only, before any intake starts. */
8+ static recover(storage: SqliteStorage): void {
9+ GitPackSpool.initialize(storage);
10+ storage.sql.exec("DELETE FROM git_pack_spool");
11+ }
12+ private static initialize(storage: SqliteStorage): void {
13+ storage.sql.exec(
14+ "CREATE TABLE IF NOT EXISTS git_pack_spool (id TEXT NOT NULL, part INTEGER NOT NULL, data BLOB NOT NULL, PRIMARY KEY (id, part))",
15+ );
16+ }
17+ readonly id = crypto.randomUUID();
18+ private size = 0;
19+ private sealed = false;
20+ private closed = false;
21+ private readonly storage: SqliteStorage;
22+ constructor(storage: SqliteStorage) {
23+ this.storage = storage;
24+ GitPackSpool.initialize(storage);
25+ }
26+ get byteLength(): number {
27+ this.assertReadable();
28+ return this.size;
29+ }
30+ private assertReadable(): void {
31+ if (!this.sealed || this.closed) throw Error("pack spool is not readable");
32+ }
33+ async ingest(chunks: AsyncIterable<Uint8Array> | Iterable<Uint8Array>, maxBytes: number): Promise<string> {
34+ if (this.size || this.sealed || this.closed) throw Error("pack spool already used");
35+ if (!Number.isSafeInteger(maxBytes) || maxBytes < 32) throw Error("invalid pack byte limit");
36+ const hash = createHash("sha1");
37+ let tail = new Uint8Array(0);
38+ let pending = new Uint8Array(GitPackSpool.chunkBytes),
39+ used = 0,
40+ part = 0;
41+ const save = () => {
42+ if (this.closed) throw Error("pack spool is closed");
43+ this.storage.sql.exec("INSERT INTO git_pack_spool VALUES (?, ?, ?)", this.id, part++, pending.slice(0, used));
44+ used = 0;
45+ };
46+ try {
47+ for await (const chunk of chunks) {
48+ if (this.closed) throw Error("pack spool is closed");
49+ if (!(chunk instanceof Uint8Array)) throw Error("invalid pack chunk");
50+ for (let at = 0; at < chunk.length; ) {
51+ const count = Math.min(GitPackSpool.chunkBytes - used, chunk.length - at);
52+ if (this.size + count > maxBytes) throw Error("pack exceeds byte limit");
53+ const piece = chunk.subarray(at, at + count);
54+ const joined = new Uint8Array(tail.length + piece.length);
55+ joined.set(tail);
56+ joined.set(piece, tail.length);
57+ const end = Math.max(0, joined.length - 20);
58+ hash.update(joined.subarray(0, end));
59+ tail = joined.slice(end);
60+ pending.set(piece, used);
61+ used += count;
62+ at += count;
63+ this.size += count;
64+ if (used === pending.length) save();
65+ }
66+ }
67+ if (used) save();
68+ if (this.size < 32 || tail.length !== 20) throw Error("truncated pack");
69+ const digest = hash.digest("hex");
70+ if (digest !== Buffer.from(tail).toString("hex")) throw Error("pack checksum mismatch");
71+ this.sealed = true;
72+ const header = this.read(0, 12);
73+ if (new TextDecoder().decode(header.subarray(0, 4)) !== "PACK" || new DataView(header.buffer).getUint32(4) !== 2)
74+ throw Error("unsupported pack header");
75+ return digest;
76+ } catch (error) {
77+ this.dispose();
78+ throw error;
79+ }
80+ }
81+ read(start: number, length: number): Uint8Array {
82+ this.assertReadable();
83+ if (
84+ !Number.isSafeInteger(start) ||
85+ !Number.isSafeInteger(length) ||
86+ start < 0 ||
87+ length < 0 ||
88+ length > GitPackSpool.chunkBytes ||
89+ start + length > this.size
90+ )
91+ throw Error("invalid pack byte range");
92+ const result = new Uint8Array(length);
93+ let copied = 0;
94+ while (copied < length) {
95+ const position = start + copied,
96+ part = Math.floor(position / GitPackSpool.chunkBytes);
97+ const rows = this.storage.sql
98+ .exec("SELECT data FROM git_pack_spool WHERE id = ? AND part = ?", this.id, part)
99+ .toArray() as { data: ArrayBuffer }[];
100+ if (rows.length !== 1) throw Error("missing pack chunk");
101+ const data = new Uint8Array(rows[0]!.data),
102+ offset = position % GitPackSpool.chunkBytes;
103+ const count = Math.min(length - copied, data.length - offset);
104+ if (count <= 0 || data.length > GitPackSpool.chunkBytes) throw Error("invalid pack chunk");
105+ result.set(data.subarray(offset, offset + count), copied);
106+ copied += count;
107+ }
108+ return result;
109+ }
110+ *chunks(): IterableIterator<Uint8Array> {
111+ this.assertReadable();
112+ for (let start = 0; start < this.size; start += GitPackSpool.chunkBytes)
113+ yield this.read(start, Math.min(GitPackSpool.chunkBytes, this.size - start));
114+ }
115+ dispose(): void {
116+ this.closed = true;
117+ this.storage.sql.exec("DELETE FROM git_pack_spool WHERE id = ?", this.id);
118+ }
119+}
--- a/server/src/ingest.ts
+++ b/server/src/ingest.ts
@@ -2,12 +2,17 @@
22// project's Artifacts repo, read back for project.ingest. Every commit the
33// Worker pushes ends "abso-version: N" ("avcs-version: N" before the rename); the commits above the newest such
44// commit that haven't been taken in yet are the person's, and N is their base.
5−import git from "isomorphic-git";
6−import http from "isomorphic-git/http/web";
5+import git, { type HttpClient } from "isomorphic-git";
76import type { FileModes } from "../../worker/project/project-api.ts";
7+import type { SqliteStorage } from "./engine-project.ts";
8+import { gitBlobText, InvalidGitUtf8 } from "./git-blob-text.ts";
9+import { GitDiskIntake } from "./git-disk-intake.ts";
10+import { gitHttp } from "./git-http.ts";
811import { MemoryFS } from "./memory-fs.ts";
912import { repoName } from "./push.ts";
1013
14+const http = gitHttp();
1116const EXEC = 0o100755;
1217const LINK = 0o120000;
1318
@@ -40,7 +45,10 @@
4045async function readAccess(
4146 artifacts: Artifacts,
4247 project: string,
43−): Promise<{ url: string; onAuth: () => { username: string; password: string } } | null> {
48+): Promise<{
49+ url: string;
50+ onAuth: () => { username: string; password: string };
51+} | null> {
4452 let repo: Awaited<ReturnType<Artifacts["get"]>>;
4553 try {
4654 repo = await artifacts.get(repoName(project));
@@ -57,7 +65,12 @@
5765export async function remoteHead(artifacts: Artifacts, project: string): Promise<string | null> {
5866 const access = await readAccess(artifacts, project);
5967 if (!access) return null;
60− const refs = await git.listServerRefs({ http, url: access.url, onAuth: access.onAuth, prefix: "refs/heads/main" });
68+ const refs = await git.listServerRefs({
69+ http,
70+ url: access.url,
71+ onAuth: access.onAuth,
72+ prefix: "refs/heads/main",
73+ });
6174 return refs.find((r) => r.ref === "refs/heads/main")?.oid ?? null;
6275}
6376
@@ -67,6 +80,12 @@
6780 */
6881/** Stores a binary file's bytes and answers their SHA-256, or null when they're over the limit. */
6982export type StoreBlob = (bytes: Uint8Array) => Promise<string | null>;
83+export type RetainFileChunks = (
84+ files: Record<string, string>,
85+ path: string,
86+ chunks: Iterable<string>,
87+ oid: string,
88+) => void;
7089
7190/**
7291 * `oldBlob` gives shared's blob for a path: a binary file over the limit
@@ -78,14 +97,35 @@
7897 seen: string | undefined,
7998 storeBlob?: StoreBlob,
8099 oldBlob: (path: string) => string | undefined = () => undefined,
100+ retainFile: (files: Record<string, string>, path: string, body: string, oid?: string) => void = (
101+ files,
102+ path,
103+ body,
104+ ) => {
105+ files[path] = body;
106+ },
107+ disk?: {
108+ storage: SqliteStorage;
109+ maxPackBytes: number;
110+ maxObjectBytes: number;
111+ maxDecodedBytes?: number;
112+ http?: HttpClient;
113+ retainFileChunks?: RetainFileChunks;
114+ },
81115): Promise<PushedCommits | null> {
82116 const access = await readAccess(artifacts, project);
83117 if (!access) return null;
84118 const fs = new MemoryFS();
85119 const dir = "/repo";
120+ using intake = disk
121+ ? new GitDiskIntake(disk.storage, disk.maxPackBytes, disk.maxObjectBytes, disk.maxDecodedBytes)
122+ : undefined;
123+ const cache = disk ? {} : undefined;
124+ if (intake && cache) intake.attach(cache);
86125 await git.clone({
87126 fs,
88− http,
127+ cache,
128+ http: disk?.http ?? http,
89129 dir,
90130 url: access.url,
91131 onAuth: access.onAuth,
@@ -94,7 +134,8 @@
94134 depth: DEPTH,
95135 noCheckout: true,
96136 });
97− const log = await git.log({ fs, dir, ref: "main", depth: DEPTH });
137+ intake?.assertReady();
138+ const log = await git.log({ fs, dir, cache, ref: "main", depth: DEPTH });
98139 if (log.length === 0) return null;
99140 const head = log[0]!.oid;
100141 const fresh: typeof log = [];
@@ -113,9 +154,26 @@
113154 commits.push({
114155 sha: c.oid,
115156 message: c.commit.message.trim(),
116− ...(await treeText(fs, dir, c.oid, storeBlob, tooBig, oldBlob)),
157+ ...(await treeText(
158+ fs,
159+ dir,
160+ c.oid,
161+ storeBlob,
162+ tooBig,
163+ oldBlob,
164+ retainFile,
165+ cache,
166+ intake,
167+ disk?.retainFileChunks,
168+ )),
117169 });
118− return { head, author: fresh.at(-1)?.commit.author.name ?? "git", base, commits, tooBig: [...tooBig] };
170+ return {
171+ head,
172+ author: fresh.at(-1)?.commit.author.name ?? "git",
173+ base,
174+ commits,
175+ tooBig: [...tooBig],
176+ };
119177}
120178
121179/**
@@ -123,24 +181,59 @@
123181 * a link (120000) is "" with its target in modes. Files that aren't UTF-8
124182 * are left out.
125183 */
126−async function treeText(
184+export async function treeText(
127185 fs: MemoryFS,
128186 dir: string,
129187 oid: string,
130188 storeBlob: StoreBlob | undefined,
131189 tooBig: Set<string>,
132190 oldBlob: (path: string) => string | undefined,
133−): Promise<{ files: Record<string, string>; modes: FileModes; blobs: Record<string, string> }> {
191+ retainFile: (files: Record<string, string>, path: string, body: string, oid?: string) => void,
192+ cache: object = {},
193+ intake?: GitDiskIntake,
194+ retainFileChunks?: RetainFileChunks,
195+): Promise<{
196+ files: Record<string, string>;
197+ modes: FileModes;
198+ blobs: Record<string, string>;
199+}> {
134200 const files: Record<string, string> = {};
135201 const modes: FileModes = {};
136202 const blobs: Record<string, string> = {};
137203 await git.walk({
138204 fs,
205+ cache,
139206 dir,
140207 trees: [git.TREE({ ref: oid })],
208+ iterate: async (walk, children) => {
209+ for (const child of children) await walk(child);
210+ return [];
211+ },
212+ reduce: async () => undefined,
141213 map: async (path, [entry]) => {
142214 if (!entry || path === ".") return true;
143215 if ((await entry.type()) !== "blob") return true;
216+ const mode = await entry.mode();
217+ const blobOid = await entry.oid();
218+ if (intake && retainFileChunks && mode !== LINK) {
219+ const stored = intake.bytes(blobOid);
220+ if (stored?.type !== "blob") throw Error("Git intake blob is missing");
221+ let valid = true;
222+ try {
223+ // Validate before retaining: a late invalid byte must take the binary path.
224+ for (const _ of gitBlobText(stored)) {
225+ /* Retain no decoded text. */
226+ }
227+ } catch (error) {
228+ if (!(error instanceof InvalidGitUtf8)) throw error;
229+ valid = false;
230+ }
231+ if (valid) {
232+ retainFileChunks(files, path, gitBlobText(stored), blobOid);
233+ modes[path] = { exec: mode === EXEC, link: null };
234+ return true;
235+ }
236+ }
144237 const bytes = await entry.content();
145238 if (!bytes) return true;
146239 let body: string;
@@ -151,7 +244,7 @@
151244 const sha = storeBlob ? await storeBlob(bytes) : null;
152245 if (sha) {
153246 blobs[path] = sha;
154− modes[path] = { exec: (await entry.mode()) === EXEC, link: null };
247+ modes[path] = { exec: mode === EXEC, link: null };
155248 } else if (storeBlob) {
156249 tooBig.add(path);
157250 const kept = oldBlob(path);
@@ -159,12 +252,11 @@
159252 }
160253 return true;
161254 }
162− const mode = await entry.mode();
163255 if (mode === LINK) {
164− files[path] = "";
256+ retainFile(files, path, "");
165257 modes[path] = { exec: false, link: body };
166258 } else {
167− files[path] = body;
259+ retainFile(files, path, body, blobOid);
168260 modes[path] = { exec: mode === EXEC, link: null };
169261 }
170262 return true;
--- a/server/src/project-object.ts
+++ b/server/src/project-object.ts
@@ -12,6 +12,8 @@
1212import { DiskFirstRuntime } from "./disk-first-runtime.ts";
1313import { EngineProject, SqliteLog } from "./engine-project.ts";
1414import { artifactsOf, type Env } from "./env.ts";
15+import { GitDiskIntake } from "./git-disk-intake.ts";
16+import { GitIntakeTrees } from "./git-intake-trees.ts";
1517import { pushedSince, remoteHead } from "./ingest.ts";
1618import {
1719 checkKey,
@@ -59,6 +61,10 @@
5961export const PUSH_EVERY_MS = 60_000;
6062/** While agents are working, how often a call looks for plain-git pushes to the repo. */
6163const GIT_CHECK_MS = 15_000;
64+// Disk scratch admission limits, independent of the Worker's resident memory.
65+const GIT_PACK_MAX_BYTES = 128 * 1024 * 1024;
66+const GIT_OBJECT_MAX_BYTES = 64 * 1024 * 1024;
67+const GIT_DECODED_MAX_BYTES = 256 * 1024 * 1024;
6268
6369/**
6470 * The load guard (platform issue 46): an estimate of a loaded project's memory from its log entries, lines and claim
@@ -119,6 +125,10 @@
119125 constructor(ctx: DurableObjectState, env: Env) {
120126 super(ctx, env);
121127 this.blobs = new BlobStore(ctx.storage);
128+ if (env.ABSO_DISK_FIRST === "on") {
129+ GitDiskIntake.recover(ctx.storage);
130+ GitIntakeTrees.recover(ctx.storage);
131+ }
122132 }
123133
124134 /** Where files kept whole go: the project's blob store. */
@@ -533,12 +543,23 @@
533543 const head = await remoteHead(artifacts, name);
534544 if (!head || head === seen || head === pushed?.commit) return null;
535545 const sharedBlobs = this.useProject((p) => p.shared().blobs ?? {});
546+ using trees = this.diskRuntime() ? new GitIntakeTrees(this.ctx.storage) : undefined;
536547 const found = await pushedSince(
537548 artifacts,
538549 name,
539550 seen,
540551 async (bytes) => (bytes.byteLength > BLOB_MAX ? null : this.blobs.putBytes(bytes)),
541552 (path) => sharedBlobs[path],
553+ trees ? (files, path, body, oid) => trees.retainFile(files, path, body, oid) : undefined,
554+ trees
555+ ? {
556+ storage: this.ctx.storage,
557+ maxPackBytes: GIT_PACK_MAX_BYTES,
558+ maxObjectBytes: GIT_OBJECT_MAX_BYTES,
559+ maxDecodedBytes: GIT_DECODED_MAX_BYTES,
560+ retainFileChunks: (files, path, chunks, oid) => trees.retainChunks(files, path, chunks, oid),
561+ }
562+ : undefined,
542563 );
543564 if (!found || found.commits.length === 0) {
544565 if (found) await this.ctx.storage.put("git:head", found.head);
--- /dev/null
+++ b/server/test/git-blob-text.test.ts
@@ -0,0 +1,58 @@
1+import assert from "node:assert/strict";
2+import { test } from "node:test";
3+import { gitBlobText, InvalidGitUtf8 } from "../src/git-blob-text.ts";
4+import { GitIntakeTrees } from "../src/git-intake-trees.ts";
5+import { memoryStorage } from "./helpers.ts";
6+
7+function source(bytes: Uint8Array) {
8+ return {
9+ byteLength: bytes.length,
10+ read(start: number, length: number) {
11+ assert.ok(length <= 16384);
12+ return bytes.slice(start, start + length);
13+ },
14+ };
15+}
17+test("Git text chunks preserve BOM and split UTF-8 semantics with bounded pieces", () => {
18+ for (const text of ["", "\ufefftext", "x".repeat(16383) + "🚀é中".repeat(20000), "nul\0text"]) {
19+ const bytes = new TextEncoder().encode(text);
20+ const chunks = [...gitBlobText(source(bytes))];
21+ assert.ok(chunks.every((chunk) => chunk.length <= 16384));
22+ assert.equal(chunks.join(""), new TextDecoder("utf-8", { fatal: true, ignoreBOM: false }).decode(bytes));
23+ }
24+});
26+test("late invalid UTF-8 rolls back retained chunks without publishing a file", (t) => {
27+ const storage = memoryStorage();
28+ t.after(() => storage.db.close());
29+ const trees = new GitIntakeTrees(storage);
30+ const files: Record<string, string> = {};
31+ const bytes = new Uint8Array(100000).fill(97);
32+ bytes[bytes.length - 1] = 0xf0;
33+ assert.throws(() => trees.retainChunks(files, "bad", gitBlobText(source(bytes)), "a".repeat(40)), InvalidGitUtf8);
34+ assert.deepEqual(Object.keys(files), []);
35+ assert.equal(
36+ storage.db.prepare("SELECT COUNT(*) AS n FROM writer_state WHERE namespace = ?").get(trees.namespace)!.n,
37+ 0,
38+ );
39+ bytes[bytes.length - 1] = 98;
40+ trees.retainChunks(files, "good", gitBlobText(source(bytes)), "a".repeat(40));
41+ assert.equal(files.good, new TextDecoder().decode(bytes));
42+ trees.dispose();
43+});
45+test("Git text reading preserves storage errors instead of classifying them as binary", () => {
46+ const failure = new TypeError("storage failure");
47+ assert.throws(
48+ () => [
49+ ...gitBlobText({
50+ byteLength: 1,
51+ read: () => {
52+ throw failure;
53+ },
54+ }),
55+ ],
56+ (error) => error === failure,
57+ );
58+});
--- /dev/null
+++ b/server/test/git-budget-recovery.test.ts
@@ -0,0 +1,31 @@
1+import assert from "node:assert/strict";
2+import { test } from "node:test";
3+import { GitDiskIntake } from "../src/git-disk-intake.ts";
4+import { GitPackResolver } from "../src/git-pack-resolver.ts";
5+import { memoryStorage } from "./helpers.ts";
6+
7+test("cold Git recovery removes abandoned byte budgets without touching canonical data", (t) => {
8+ const storage = memoryStorage();
9+ t.after(() => storage.db.close());
10+ storage.sql.exec("CREATE TABLE canonical_budget_fixture (value TEXT)");
11+ storage.sql.exec("INSERT INTO canonical_budget_fixture VALUES ('preserved')");
12+ const abandoned = new GitPackResolver(storage, 100, 100);
13+ abandoned.add(12, "blob", new TextEncoder().encode("abandoned"));
14+ assert.equal(storage.db.prepare("SELECT decoded FROM git_object_budget").get()!.decoded, 9);
15+ GitDiskIntake.recover(storage);
16+ GitDiskIntake.recover(storage);
17+ for (const table of [
18+ "git_pack_spool",
19+ "git_pack_resolve",
20+ "git_object_bytes",
21+ "git_object_meta",
22+ "git_object_budget",
23+ ])
24+ assert.equal(storage.db.prepare(`SELECT COUNT(*) AS n FROM ${table}`).get()!.n, 0);
25+ assert.equal(storage.db.prepare("SELECT value FROM canonical_budget_fixture").get()!.value, "preserved");
26+ const retry = new GitPackResolver(storage, 3, 3);
27+ retry.add(12, "blob", new TextEncoder().encode("new"));
28+ assert.equal(storage.db.prepare("SELECT decoded FROM git_object_budget").get()!.decoded, 3);
29+ retry.dispose();
30+ assert.equal(storage.db.prepare("SELECT COUNT(*) AS n FROM git_object_budget").get()!.n, 0);
31+});
--- /dev/null
+++ b/server/test/git-delta-stream.test.ts
@@ -0,0 +1,64 @@
1+import assert from "node:assert/strict";
2+import { test } from "node:test";
3+import { applyGitDeltaChunks, type GitByteRanges } from "../src/git-delta-stream.ts";
4+
5+const ranges = (bytes: Uint8Array): GitByteRanges => ({
6+ byteLength: bytes.length,
7+ read(start, length) {
8+ assert.ok(length <= 65536);
9+ return bytes.slice(start, start + length);
10+ },
11+});
12+const integer = (value: number) => {
13+ const bytes = [];
14+ do {
15+ const next = value % 128;
16+ value = Math.floor(value / 128);
17+ bytes.push(next | (value ? 128 : 0));
18+ } while (value);
19+ return bytes;
20+};
21+test("delta copy and literal instructions use bounded base reads and output", () => {
22+ const base = Uint8Array.from({ length: 200000 }, (_, i) => i % 251);
23+ // Copy 131072 bytes from offset zero, then append three literal bytes.
24+ const delta = Uint8Array.from([...integer(base.length), ...integer(131075), 0xc0, 2, 3, 4, 5, 6]);
25+ const output: Uint8Array[] = [];
26+ assert.equal(
27+ applyGitDeltaChunks(
28+ ranges(delta),
29+ ranges(base),
30+ (chunk) => {
31+ assert.ok(chunk.length <= 65536);
32+ output.push(chunk);
33+ },
34+ 200000,
35+ ),
36+ 131075,
37+ );
38+ assert.deepEqual(Buffer.concat(output), Buffer.concat([base.subarray(0, 131072), new Uint8Array([4, 5, 6])]));
39+});
40+test("delta refuses malformed instructions, bounds and truncated input", () => {
41+ for (const bytes of [
42+ [1, 0],
43+ [0, 1, 0],
44+ [0, 1, 1],
45+ [0, 1, 0x80],
46+ [0, 2, 1, 7],
47+ [0, 0, 1, 7],
48+ ])
49+ assert.throws(() => applyGitDeltaChunks(ranges(Uint8Array.from(bytes)), ranges(new Uint8Array()), () => {}, 10));
50+ let writes = 0;
51+ assert.throws(
52+ () =>
53+ applyGitDeltaChunks(
54+ ranges(new Uint8Array([0, 11])),
55+ ranges(new Uint8Array()),
56+ () => {
57+ writes++;
58+ },
59+ 10,
60+ ),
61+ /exceeds bound/,
62+ );
63+ assert.equal(writes, 0);
64+});
--- /dev/null
+++ b/server/test/git-disk-clone.test.ts
@@ -0,0 +1,213 @@
1+import assert from "node:assert/strict";
2+import { randomBytes } from "node:crypto";
3+import { test } from "node:test";
4+import git, { type HttpClient } from "isomorphic-git";
5+import { GitDiskIntake } from "../src/git-disk-intake.ts";
6+import { GitIntakeTrees } from "../src/git-intake-trees.ts";
7+import { pushedSince } from "../src/ingest.ts";
8+import { MemoryFS } from "../src/memory-fs.ts";
9+import { memoryStorage } from "./helpers.ts";
11+const packet = (text: string | Uint8Array) => {
12+ const body = Buffer.from(text);
13+ return Buffer.concat([Buffer.from((body.length + 4).toString(16).padStart(4, "0")), body]);
14+};
16+for (const mode of ["success", "limit", "fatal", "server-intake", "text-intake"])
17+ test(`actual disk clone handles ${mode}`, async (t) => {
18+ const rejectPack = mode === "limit";
19+ const source = new MemoryFS(),
20+ dir = "/repo";
21+ await git.init({ fs: source, dir, defaultBranch: "main" });
22+ const blob = mode === "text-intake" ? Buffer.from("x".repeat(16383) + "🚀é中".repeat(20000)) : randomBytes(400000);
23+ const blobOid = await git.writeBlob({ fs: source, dir, blob });
24+ const tree = await git.writeTree({
25+ fs: source,
26+ dir,
27+ tree: [{ mode: "100644", path: "large.bin", oid: blobOid, type: "blob" }],
28+ });
29+ const author = {
30+ name: "Capacity fixture",
31+ email: "fixture@example.invalid",
32+ timestamp: 1,
33+ timezoneOffset: 0,
34+ };
35+ const base = await git.writeCommit({
36+ fs: source,
37+ dir,
38+ commit: {
39+ tree,
40+ parent: [],
41+ author,
42+ committer: author,
43+ message: "Base\n\nabso-version: 0\n",
44+ },
45+ });
46+ const head = await git.writeCommit({
47+ fs: source,
48+ dir,
49+ commit: {
50+ tree,
51+ parent: [base],
52+ author,
53+ committer: author,
54+ message: "Fixture\n",
55+ },
56+ });
57+ const packed = (
58+ await git.packObjects({
59+ fs: source,
60+ dir,
61+ oids: [head, base, tree, blobOid],
62+ write: false,
63+ })
64+ ).packfile!;
65+ const advertisement = Buffer.concat([
66+ packet("# service=git-upload-pack\n"),
67+ Buffer.from("0000"),
68+ packet(`${head} HEAD\0symref=HEAD:refs/heads/main side-band-64k shallow\n`),
69+ packet(`${head} refs/heads/main\n`),
70+ Buffer.from("0000"),
71+ ]);
72+ let uploads = 0;
73+ let uploadChunksRead = 0;
74+ let uploadClosed = false;
75+ const uploadParts = [packet("NAK\n")];
76+ for (let at = 0; at < packed.length; at += 16000) {
77+ uploadParts.push(packet(Buffer.concat([Buffer.from([1]), packed.subarray(at, at + 16000)])));
78+ uploadParts.push(
79+ packet(Buffer.concat([Buffer.from([2]), Buffer.from("Counting objects: 50% (1/2)\n".repeat(200))])),
80+ );
81+ if (mode === "fatal" && at === 16000) {
82+ uploadParts.push(packet(Buffer.concat([Buffer.from([3]), Buffer.from("fixture remote failure")])));
83+ break;
84+ }
85+ }
86+ uploadParts.push(Buffer.from("0000"));
87+ const http: HttpClient = {
88+ request: async ({ url, method }) => {
89+ const body = method === "POST" ? Buffer.concat(uploadParts) : advertisement;
90+ if (method === "POST") uploads++;
91+ return {
92+ url,
93+ method: method ?? "GET",
94+ statusCode: 200,
95+ statusMessage: "OK",
96+ headers: {},
97+ body: (async function* () {
98+ try {
99+ for (let at = 0; at < body.length; at += 997) {
100+ if (method === "POST") uploadChunksRead++;
101+ yield body.subarray(at, at + 997);
102+ }
103+ } finally {
104+ if (method === "POST") uploadClosed = true;
105+ }
106+ })(),
107+ };
108+ },
109+ };
110+ const storage = memoryStorage();
111+ const intake = new GitDiskIntake(storage, rejectPack ? 70000 : 2000000, 1000000);
112+ const ingest = intake.ingest.bind(intake);
113+ intake.ingest = async (...args) => {
114+ await new Promise((resolve) => setTimeout(resolve, 25));
115+ assert.ok(uploadChunksRead < 64, `pack source read ahead ${uploadChunksRead} chunks before disk consumption`);
116+ return ingest(...args);
117+ };
118+ const cache = {};
119+ intake.attach(cache);
120+ const fs = new MemoryFS();
121+ const write = fs.promises.writeFile;
122+ fs.promises.writeFile = async (path, ...args) => {
123+ assert.ok(!/\.(pack|idx)$/.test(path), "clone must not persist a collected pack or index");
124+ return write(path, ...args);
125+ };
126+ try {
127+ if (mode === "server-intake" || mode === "text-intake") {
128+ const trees = new GitIntakeTrees(storage);
129+ if (mode === "text-intake") {
130+ const original = GitDiskIntake.prototype.read;
131+ t.mock.method(GitDiskIntake.prototype, "read", function (this: GitDiskIntake, oid: string) {
132+ if (oid === blobOid) throw Error("whole text blob read forbidden");
133+ return original.call(this, oid);
134+ });
135+ }
136+ const artifacts = {
137+ get: async () => ({
138+ info: async () => ({ remote: "https://fixture.invalid/repo" }),
139+ createToken: async () => ({ plaintext: "invented-test-token" }),
140+ [Symbol.dispose]() {},
141+ }),
142+ };
143+ const found = await pushedSince(
144+ artifacts as never,
145+ "fixture",
146+ undefined,
147+ async (bytes) => {
148+ assert.deepEqual(Buffer.from(bytes), blob);
149+ return "fixture-blob";
150+ },
151+ undefined,
152+ undefined,
153+ {
154+ storage,
155+ maxPackBytes: 2000000,
156+ maxObjectBytes: 1000000,
157+ http,
158+ retainFileChunks: (files, path, chunks, oid) => trees.retainChunks(files, path, chunks, oid),
159+ },
160+ );
161+ assert.equal(found!.base, 0);
162+ assert.equal(found!.commits.length, 1);
163+ if (mode === "text-intake") assert.equal(found!.commits[0]!.files["large.bin"], blob.toString("utf8"));
164+ else assert.equal(found!.commits[0]!.blobs["large.bin"], "fixture-blob");
165+ trees.dispose();
166+ for (const table of ["git_pack_spool", "git_pack_resolve", "git_object_meta", "git_object_bytes"])
167+ assert.equal(storage.db.prepare(`SELECT COUNT(*) AS n FROM ${table}`).get()!.n, 0);
168+ return;
169+ }
170+ const clone = git.clone({
171+ fs,
172+ dir,
173+ http,
174+ cache,
175+ url: "https://fixture.invalid/repo",
176+ ref: "main",
177+ singleBranch: true,
178+ noCheckout: true,
179+ });
180+ if (mode !== "success") {
181+ await assert.rejects(clone, rejectPack ? /pack exceeds byte limit/ : /fixture remote failure/);
182+ assert.equal(uploadClosed, true);
183+ for (const table of ["git_pack_spool", "git_pack_resolve", "git_object_meta", "git_object_bytes"])
184+ assert.equal(storage.db.prepare(`SELECT COUNT(*) AS n FROM ${table}`).get()!.n, 0);
185+ return;
186+ }
187+ await clone;
188+ intake.assertReady();
189+ assert.equal((await git.log({ fs, dir, cache, ref: "main" })).length, 2);
190+ let walked = 0;
191+ await git.walk({
192+ fs,
193+ dir,
194+ cache,
195+ trees: [git.TREE({ ref: head })],
196+ map: async (path, [entry]) => {
197+ if (path === "large.bin") {
198+ assert.deepEqual(Buffer.from((await entry!.content())!), blob);
199+ walked++;
200+ }
201+ return true;
202+ },
203+ });
204+ assert.equal(walked, 1);
205+ assert.equal(uploads, 1);
206+ assert.equal(await git.resolveRef({ fs, dir, ref: "main" }), head);
207+ assert.equal((await git.readCommit({ fs, dir, cache, oid: head })).commit.tree, tree);
208+ assert.deepEqual(Buffer.from((await git.readBlob({ fs, dir, cache, oid: blobOid })).blob), blob);
209+ } finally {
210+ intake.dispose();
211+ storage.db.close();
212+ }
213+ });
--- /dev/null
+++ b/server/test/git-intake-trees.test.ts
@@ -0,0 +1,118 @@
1+import assert from "node:assert/strict";
2+import { test } from "node:test";
3+import { GitIntakeTrees } from "../src/git-intake-trees.ts";
4+import { SqliteWriterState } from "../src/writer-host.ts";
5+import { memoryStorage } from "./helpers.ts";
6+
7+test("unchanged Git blobs share stored text across paths and commits", (t) => {
8+ const storage = memoryStorage();
9+ t.after(() => storage.db.close());
10+ const trees = new GitIntakeTrees(storage);
11+ const body = "unchanged\n".repeat(10000);
12+ const oid = "a".repeat(40);
13+ const count = () =>
14+ storage.db.prepare("SELECT COUNT(*) AS n FROM writer_state WHERE namespace = ?").get(trees.namespace)!.n;
15+ const first: Record<string, string> = {};
16+ trees.retainFile(first, "original", body, oid);
17+ const initialRows = count();
18+ for (let i = 0; i < 100; i++) {
19+ const files: Record<string, string> = {};
20+ trees.retainFile(files, `renamed-${i}`, body, oid);
21+ assert.equal(files[`renamed-${i}`], body);
22+ }
23+ assert.equal(count(), initialRows);
24+ trees.retainFile(first, "changed", "new text", "b".repeat(40));
25+ assert.equal(first.original, body);
26+ assert.equal(first.changed, "new text");
27+ assert.ok(Number(count()) > Number(initialRows));
28+ assert.throws(() => trees.retainFile(first, "bad", "text", "bad-id"), /Invalid Git blob id/);
29+ trees.dispose();
30+ assert.equal(count(), 0);
31+});
33+test("Git intake stores each decoded file before the next file arrives", (t) => {
34+ const storage = memoryStorage();
35+ t.after(() => storage.db.close());
36+ const trees = new GitIntakeTrees(storage);
37+ const files: Record<string, string> = Object.create(null);
38+ for (let i = 0; i < 20; i++) {
39+ trees.retainFile(files, `file-${i}`, `${i}:${"x".repeat(50000)}`);
40+ assert.equal(Object.getOwnPropertyDescriptor(files, `file-${i}`)?.value, undefined);
41+ assert.equal(files[`file-${i}`], `${i}:${"x".repeat(50000)}`);
42+ }
43+ assert.equal(Object.keys(files).length, 20);
44+ trees.dispose();
45+ assert.throws(() => files["file-0"], /closed/);
46+ assert.throws(() => trees.retainFile(files, "later", "text"), /closed/);
47+});
49+test("Git intake retains independent trees on disk and releases their text rows", (t) => {
50+ const storage = memoryStorage();
51+ t.after(() => storage.db.close());
52+ const trees = new GitIntakeTrees(storage);
53+ const retained: ReturnType<GitIntakeTrees["retain"]>[] = [];
54+ for (let i = 0; i < 50; i++) {
55+ const files = {
56+ "a.txt": `${i}:${"\ud83d\ude80".repeat(20000)}\n`,
57+ "empty.txt": "",
58+ };
59+ retained.push(
60+ trees.retain({
61+ files,
62+ modes: { "a.txt": { exec: true, link: null } },
63+ blobs: {},
64+ }),
65+ );
66+ files["a.txt"] = "changed after retention";
67+ }
68+ for (let i = 0; i < retained.length; i++) {
69+ const tree = retained[i]!;
70+ assert.deepEqual(Object.keys(tree.files), ["a.txt", "empty.txt"]);
71+ assert.equal(Object.getOwnPropertyDescriptor(tree.files, "a.txt")?.value, undefined);
72+ assert.equal(tree.files["a.txt"], `${i}:${"\ud83d\ude80".repeat(20000)}\n`);
73+ assert.equal(tree.files["empty.txt"], "");
74+ assert.equal(tree.modes["a.txt"]?.exec, true);
75+ }
76+ const count = () =>
77+ storage.db.prepare("SELECT COUNT(*) AS n FROM writer_state WHERE namespace = ?").get(trees.namespace)!.n;
78+ assert.ok(Number(count()) > 0);
79+ trees.dispose();
80+ assert.equal(count(), 0);
81+ assert.throws(() => retained[0]!.files["a.txt"], /closed/);
82+ assert.throws(() => trees.retain({ files: {}, modes: {}, blobs: {} }), /closed/);
83+ trees.dispose();
84+});
86+test("disposing one intake does not delete another concurrent intake", (t) => {
87+ const storage = memoryStorage();
88+ t.after(() => storage.db.close());
89+ const first = new GitIntakeTrees(storage);
90+ const second = new GitIntakeTrees(storage);
91+ first.retain({ files: { a: "first" }, modes: {}, blobs: {} });
92+ const retained = second.retain({
93+ files: { a: "second" },
94+ modes: {},
95+ blobs: {},
96+ });
97+ first.dispose();
98+ assert.equal(retained.files.a, "second");
99+ second.dispose();
100+});
102+test("cold recovery removes abandoned intake text and preserves canonical writer state", (t) => {
103+ const storage = memoryStorage();
104+ t.after(() => storage.db.close());
105+ const abandoned = new GitIntakeTrees(storage);
106+ abandoned.retain({ files: { a: "abandoned text" }, modes: {}, blobs: {} });
107+ const canonical = new SqliteWriterState(storage, "server-disk-v1");
108+ canonical.write("receipt", "operation", { committed: true });
109+ GitIntakeTrees.recover(storage);
110+ assert.deepEqual(canonical.read("receipt", "operation"), { committed: true });
111+ assert.equal(
112+ storage.db.prepare("SELECT COUNT(*) AS n FROM writer_state WHERE namespace = ?").get(abandoned.namespace)!.n,
113+ 0,
114+ );
115+ const retry = new GitIntakeTrees(storage);
116+ assert.equal(retry.retain({ files: { a: "retry" }, modes: {}, blobs: {} }).files.a, "retry");
117+ retry.dispose();
118+});
--- /dev/null
+++ b/server/test/git-object-bytes.test.ts
@@ -0,0 +1,74 @@
1+import assert from "node:assert/strict";
2+import { createHash } from "node:crypto";
3+import { test } from "node:test";
4+import { applyGitDeltaChunks } from "../src/git-delta-stream.ts";
5+import { GitObjectBytes } from "../src/git-object-bytes.ts";
6+import { memoryStorage } from "./helpers.ts";
7+
8+const integer = (value: number) => {
9+ const bytes = [];
10+ do {
11+ const part = value % 128;
12+ value = Math.floor(value / 128);
13+ bytes.push(part | (value ? 128 : 0));
14+ } while (value);
15+ return bytes;
16+};
17+test("disk delta output has exact Git identity and partial failures roll back", (t) => {
18+ const storage = memoryStorage();
19+ t.after(() => storage.db.close());
20+ const objects = new GitObjectBytes(storage);
21+ const bytes = Uint8Array.from({ length: 200000 }, (_, i) => i % 251);
22+ const base = objects.put("blob", (write) => write(bytes), 200000);
23+ const instructions = Uint8Array.from([...integer(bytes.length), ...integer(131075), 0xc0, 2, 3, 4, 5, 6]);
24+ const delta = objects.put("blob", (write) => write(instructions), 100);
25+ const result = objects.put(
26+ "blob",
27+ (write) => {
28+ applyGitDeltaChunks(delta, base, write, 200000);
29+ },
30+ 200000,
31+ );
32+ const expected = Buffer.concat([bytes.subarray(0, 131072), new Uint8Array([4, 5, 6])]);
33+ assert.equal(result.oid, createHash("sha1").update(`blob ${expected.length}\0`).update(expected).digest("hex"));
34+ assert.deepEqual(result.read(65530, 100), new Uint8Array(expected.subarray(65530, 65630)));
35+ assert.equal(result.byteLength, expected.length);
36+ const counts = () => [
37+ storage.db.prepare("SELECT COUNT(*) AS n FROM git_object_bytes").get()!.n,
38+ storage.db.prepare("SELECT COUNT(*) AS n FROM git_object_meta").get()!.n,
39+ ];
40+ const bad = objects.put("blob", (write) => write(Uint8Array.from([...instructions, 0])), 101);
41+ const before = counts();
42+ assert.throws(
43+ () =>
44+ objects.put(
45+ "blob",
46+ (write) => {
47+ applyGitDeltaChunks(bad, base, write, 200000);
48+ },
49+ 200000,
50+ ),
51+ /invalid Git delta instruction/,
52+ );
53+ assert.deepEqual(counts(), before);
54+ assert.throws(
55+ () =>
56+ objects.put(
57+ "blob",
58+ (write) => {
59+ write(bytes);
60+ throw Error("injected producer failure");
61+ },
62+ 200000,
63+ ),
64+ /injected producer failure/,
65+ );
66+ assert.deepEqual(counts(), before);
67+ assert.throws(() => objects.put("blob", (write) => write(bytes), 100000), /exceeds byte limit/);
68+ assert.deepEqual(counts(), before);
69+ assert.deepEqual(base.read(0, 100), bytes.slice(0, 100));
70+ assert.equal(objects.put("blob", () => {}, 0).oid, "e69de29bb2d1d6434b8b29ae775ad8c2e48c5391");
71+ objects.dispose();
72+ assert.deepEqual(counts(), [0, 0]);
73+ assert.throws(() => base.read(0, 1), /closed/);
74+});
--- /dev/null
+++ b/server/test/git-pack-decode.test.ts
@@ -0,0 +1,183 @@
1+import assert from "node:assert/strict";
2+import { createHash, randomBytes } from "node:crypto";
3+import { createRequire } from "node:module";
4+import { test } from "node:test";
5+import { deflateSync } from "node:zlib";
6+import { GitDiskIntake } from "../src/git-disk-intake.ts";
7+import { decodeGitPack, type PackInflater } from "../src/git-pack-decode.ts";
8+import { GitPackResolver } from "../src/git-pack-resolver.ts";
9+import { GitPackSpool } from "../src/git-pack-spool.ts";
10+import { memoryStorage } from "./helpers.ts";
12+const require = createRequire(import.meta.url);
13+const { Inflate } = require("pako") as {
14+ Inflate: new (options: { chunkSize: number }) => PackInflater;
15+};
17+test("cold intake recovery removes abandoned scratch and preserves project rows", () => {
18+ const storage = memoryStorage();
19+ try {
20+ GitDiskIntake.recover(storage);
21+ storage.sql.exec("CREATE TABLE canonical_fixture (value TEXT)");
22+ storage.sql.exec("INSERT INTO canonical_fixture VALUES (?)", "preserved");
23+ const resolver = new GitPackResolver(storage, 1000);
24+ resolver.add(12, "blob", new TextEncoder().encode("abc"));
25+ storage.sql.exec("INSERT INTO git_pack_spool VALUES (?, ?, ?)", "abandoned", 0, new Uint8Array([1]));
26+ GitDiskIntake.recover(storage);
27+ GitDiskIntake.recover(storage);
28+ for (const table of ["git_pack_spool", "git_pack_resolve", "git_object_meta", "git_object_bytes"])
29+ assert.equal(storage.db.prepare(`SELECT COUNT(*) AS n FROM ${table}`).get()!.n, 0);
30+ assert.equal(storage.db.prepare("SELECT value FROM canonical_fixture").get()!.value, "preserved");
31+ } finally {
32+ storage.db.close();
33+ }
34+});
36+test("disk intake exposes only verified objects and disposes all scratch", async () => {
37+ const storage = memoryStorage();
38+ try {
39+ for (const corrupt of [false, true]) {
40+ const intake = new GitDiskIntake(storage, 1000000, 1000000);
41+ const cache = {};
42+ intake.attach(cache);
43+ assert.equal(Reflect.get(cache, Symbol.for("abso.git.disk-pack")), intake);
44+ assert.throws(() => intake.attach(cache), /already attached/);
45+ assert.equal(intake.read("0".repeat(40)), undefined);
46+ const bytes = pack([Buffer.concat([objectHeader(3, 3), deflateSync(Buffer.from("abc"))])]);
47+ if (corrupt) bytes[bytes.length - 1]! ^= 1;
48+ try {
49+ if (corrupt) {
50+ await assert.rejects(
51+ intake.ingest([bytes], () => new Inflate({ chunkSize: 16384 })),
52+ /checksum/,
53+ );
54+ assert.throws(() => intake.read("0".repeat(40)), /closed/);
55+ } else {
56+ await intake.ingest([bytes], () => new Inflate({ chunkSize: 16384 }));
57+ const oid = createHash("sha1").update("blob 3\0abc").digest("hex");
58+ assert.equal(intake.read(oid)!.object.toString(), "abc");
59+ assert.equal(intake.read("0".repeat(40)), undefined);
60+ assert.equal(storage.db.prepare("SELECT COUNT(*) AS n FROM git_pack_spool").get()!.n, 0);
61+ }
62+ } finally {
63+ intake.dispose();
64+ }
65+ for (const table of ["git_pack_spool", "git_pack_resolve", "git_object_meta", "git_object_bytes"])
66+ assert.equal(storage.db.prepare(`SELECT COUNT(*) AS n FROM ${table}`).get()!.n, 0);
67+ }
68+ } finally {
69+ storage.db.close();
70+ }
71+});
72+test("late input cannot recreate scratch after intake disposal", async () => {
73+ const storage = memoryStorage();
74+ const intake = new GitDiskIntake(storage, 1000000, 1000000);
75+ let sourceClosed = false;
76+ async function* source() {
77+ try {
78+ yield new Uint8Array(65536);
79+ intake.dispose();
80+ yield new Uint8Array(65536);
81+ } finally {
82+ sourceClosed = true;
83+ }
84+ }
85+ try {
86+ await assert.rejects(
87+ intake.ingest(source(), () => new Inflate({ chunkSize: 16384 })),
88+ /closed/,
89+ );
90+ assert.equal(sourceClosed, true);
91+ for (const table of ["git_pack_spool", "git_pack_resolve", "git_object_meta", "git_object_bytes"])
92+ assert.equal(storage.db.prepare(`SELECT COUNT(*) AS n FROM ${table}`).get()!.n, 0);
93+ } finally {
94+ intake.dispose();
95+ storage.db.close();
96+ }
97+});
99+function objectHeader(kind: number, size: number): Uint8Array {
100+ const bytes = [(kind << 4) | (size & 15)];
101+ size = Math.floor(size / 16);
102+ while (size) {
103+ bytes[bytes.length - 1]! |= 128;
104+ bytes.push(size & 127);
105+ size = Math.floor(size / 128);
106+ }
107+ return Uint8Array.from(bytes);
108+}
109+function pack(entries: Uint8Array[]): Uint8Array {
110+ const header = Buffer.alloc(12);
111+ header.write("PACK");
112+ header.writeUInt32BE(2, 4);
113+ header.writeUInt32BE(entries.length, 8);
114+ const body = Buffer.concat([header, ...entries]);
115+ return Buffer.concat([body, createHash("sha1").update(body).digest()]);
116+}
118+test("verified disk pack inflates large objects and forward deltas without collected output", async () => {
119+ const storage = memoryStorage();
120+ const spool = new GitPackSpool(storage);
121+ const resolver = new GitPackResolver(storage, 2000000);
122+ try {
123+ const large = randomBytes(800000);
124+ const base = Buffer.from("abc");
125+ const baseId = createHash("sha1").update("blob 3\0").update(base).digest();
126+ const delta = Uint8Array.from([3, 4, 0x90, 3, 1, 100]);
127+ const bytes = pack([
128+ Buffer.concat([objectHeader(7, delta.length), baseId, deflateSync(delta)]),
129+ Buffer.concat([objectHeader(3, large.length), deflateSync(large)]),
130+ Buffer.concat([objectHeader(3, base.length), deflateSync(base)]),
131+ ]);
132+ await spool.ingest([bytes], 2000000);
133+ decodeGitPack(spool, resolver, () => {
134+ const inflater = new Inflate({ chunkSize: 16384 });
135+ Object.defineProperty(inflater, "result", {
136+ set(value: Uint8Array) {
137+ assert.equal(value.length, 0, "inflater must not collect decoded bytes");
138+ },
139+ });
140+ return inflater;
141+ });
142+ const largeId = createHash("sha1").update(`blob ${large.length}\0`).update(large).digest("hex");
143+ const stored = resolver.get(largeId);
144+ for (let at = 0; at < large.length; at += 65536) {
145+ const n = Math.min(65536, large.length - at);
146+ assert.deepEqual(stored.read(at, n), new Uint8Array(large.subarray(at, at + n)));
147+ }
148+ const deltaId = createHash("sha1").update("blob 4\0abcd").digest("hex");
149+ assert.equal(new TextDecoder().decode(resolver.get(deltaId).read(0, 4)), "abcd");
150+ } finally {
151+ resolver.dispose();
152+ spool.dispose();
153+ storage.db.close();
154+ }
155+});
157+test("invalid later pack entries clear earlier decoded objects and close the resolver", async () => {
158+ const valid = Buffer.concat([objectHeader(3, 3), deflateSync(Buffer.from("abc"))]);
159+ const cases = [
160+ Buffer.concat([objectHeader(3, 4), deflateSync(Buffer.from("abc"))]),
161+ Buffer.concat([objectHeader(3, 2), deflateSync(Buffer.from("abc"))]),
162+ Buffer.concat([objectHeader(3, 3), deflateSync(Buffer.from("abc")).subarray(0, 3)]),
163+ Uint8Array.from([0]),
164+ Buffer.concat([objectHeader(6, 0), Uint8Array.from([0]), deflateSync(new Uint8Array())]),
165+ Buffer.concat([objectHeader(7, 2), Buffer.alloc(20, 255), deflateSync(Uint8Array.from([0, 0]))]),
166+ ];
167+ for (const invalid of cases) {
168+ const storage = memoryStorage();
169+ const spool = new GitPackSpool(storage);
170+ const resolver = new GitPackResolver(storage, 1000000);
171+ try {
172+ await spool.ingest([pack([valid, invalid])], 1000000);
173+ assert.throws(() => decodeGitPack(spool, resolver, () => new Inflate({ chunkSize: 16384 })));
174+ assert.throws(() => resolver.get("0".repeat(40)), /closed/);
175+ for (const table of ["git_pack_resolve", "git_object_meta", "git_object_bytes"])
176+ assert.equal(storage.db.prepare(`SELECT COUNT(*) AS n FROM ${table}`).get()!.n, 0);
177+ } finally {
178+ resolver.dispose();
179+ spool.dispose();
180+ storage.db.close();
181+ }
182+ }
183+});
--- /dev/null
+++ b/server/test/git-pack-resolver.test.ts
@@ -0,0 +1,117 @@
1+import assert from "node:assert/strict";
2+import { createHash } from "node:crypto";
3+import { test } from "node:test";
4+import { GitPackResolver } from "../src/git-pack-resolver.ts";
5+import { memoryStorage } from "./helpers.ts";
6+
7+const oid = (text: string) => createHash("sha1").update(`blob ${text.length}\0${text}`).digest("hex");
8+const text = (value: ReturnType<GitPackResolver["get"]>) => new TextDecoder().decode(value.read(0, value.byteLength));
9+
10+test("decoded budget spans objects and rolls back failed additions", (t) => {
11+ const storage = memoryStorage();
12+ t.after(() => storage.db.close());
13+ const resolver = new GitPackResolver(storage, 10, 8);
14+ resolver.add(12, "blob", new TextEncoder().encode("abc"));
15+ assert.throws(() => resolver.add(12, "blob", new Uint8Array(4)), /UNIQUE/);
16+ resolver.add(30, "blob", new TextEncoder().encode("defgh"));
17+ assert.throws(() => resolver.add(50, "blob", new Uint8Array(1)), /total decoded byte limit/);
18+ assert.equal(text(resolver.get(oid("defgh"))), "defgh");
19+ assert.equal(storage.db.prepare("SELECT decoded FROM git_object_budget").get()!.decoded, 8);
20+ resolver.dispose();
21+ assert.equal(storage.db.prepare("SELECT COUNT(*) AS n FROM git_object_budget").get()!.n, 0);
22+});
24+test("delta results consume budget and failed resolution rolls back all accounting", (t) => {
25+ const storage = memoryStorage();
26+ t.after(() => storage.db.close());
27+ const resolver = new GitPackResolver(storage, 100, 12);
28+ resolver.add(12, "blob", new TextEncoder().encode("abc"));
29+ resolver.add(30, "delta", new Uint8Array([3, 4, 0x90, 3, 1, 100]), 12);
30+ assert.throws(() => resolver.resolve(), /total decoded byte limit/);
31+ assert.equal(storage.db.prepare("SELECT decoded FROM git_object_budget").get()!.decoded, 9);
32+ assert.equal(storage.db.prepare("SELECT COUNT(*) AS n FROM git_object_meta").get()!.n, 2);
33+ assert.throws(() => resolver.get(oid("abcd")), /missing/);
34+ resolver.dispose();
35+});
37+test("resolved delta instructions are deleted without refunding decoded work", (t) => {
38+ const storage = memoryStorage();
39+ t.after(() => storage.db.close());
40+ const resolver = new GitPackResolver(storage, 100, 13);
41+ resolver.add(12, "blob", new TextEncoder().encode("abc"));
42+ resolver.add(30, "delta", new Uint8Array([3, 4, 0x90, 3, 1, 100]), 12);
43+ resolver.resolve();
44+ assert.equal(text(resolver.get(oid("abcd"))), "abcd");
45+ assert.equal(storage.db.prepare("SELECT SUM(bytes) AS n FROM git_object_meta").get()!.n, 7);
46+ assert.equal(storage.db.prepare("SELECT decoded FROM git_object_budget").get()!.decoded, 13);
47+ assert.throws(() => resolver.add(50, "blob", new Uint8Array(1)), /total decoded byte limit/);
48+ resolver.resolve();
49+ resolver.dispose();
50+});
52+test("disk pack resolver handles forward ID bases and offset delta chains", (t) => {
53+ const storage = memoryStorage();
54+ t.after(() => storage.db.close());
55+ const resolver = new GitPackResolver(storage, 1000);
56+ resolver.add(12, "delta", new Uint8Array([3, 4, 0x90, 3, 1, 100]), oid("abc"));
57+ resolver.add(40, "blob", new TextEncoder().encode("abc"));
58+ resolver.add(80, "delta", new Uint8Array([4, 5, 0x90, 4, 1, 101]), 12);
59+ resolver.resolve();
60+ for (const expected of ["abc", "abcd", "abcde"]) assert.equal(text(resolver.get(oid(expected))), expected);
61+ resolver.resolve();
62+ resolver.dispose();
63+ assert.throws(() => resolver.get(oid("abc")), /closed/);
64+ for (const table of ["git_pack_resolve", "git_object_meta", "git_object_bytes"])
65+ assert.equal(storage.db.prepare(`SELECT COUNT(*) AS n FROM ${table}`).get()!.n, 0);
66+});
68+test("unresolved references roll back earlier resolutions in the same pass", (t) => {
69+ const storage = memoryStorage();
70+ t.after(() => storage.db.close());
71+ const resolver = new GitPackResolver(storage, 1000);
72+ resolver.add(12, "blob", new TextEncoder().encode("abc"));
73+ resolver.add(40, "delta", new Uint8Array([3, 4, 0x90, 3, 1, 100]), 12);
74+ resolver.add(80, "delta", new Uint8Array([0, 0]), "f".repeat(40));
75+ const before = storage.db.prepare("SELECT COUNT(*) AS n FROM git_object_meta").get()!.n;
76+ assert.throws(() => resolver.resolve(), /unresolved or cyclic/);
77+ assert.equal(storage.db.prepare("SELECT COUNT(*) AS n FROM git_object_meta").get()!.n, before);
78+ assert.throws(() => resolver.get(oid("abcd")), /missing/);
79+ assert.equal(text(resolver.get(oid("abc"))), "abc");
80+ resolver.dispose();
81+});
83+test("decoded objects stream into the resolver and producer failures roll back", (t) => {
84+ const storage = memoryStorage();
85+ const resolver = new GitPackResolver(storage, 1000000);
86+ t.after(() => {
87+ try {
88+ resolver.dispose();
89+ } finally {
90+ storage.db.close();
91+ }
92+ });
93+ const expected = createHash("sha1").update("blob 800000\0");
94+ resolver.addChunks(12, "blob", (write) => {
95+ for (let i = 0; i < 100; i++) {
96+ const chunk = new Uint8Array(8000).fill(i);
97+ expected.update(chunk);
98+ write(chunk);
99+ }
100+ });
101+ resolver.resolve();
102+ const object = resolver.get(expected.digest("hex"));
103+ assert.equal(object.byteLength, 800000);
104+ assert.deepEqual(object.read(799990, 10), new Uint8Array(10).fill(99));
105+ assert.ok(Number(storage.db.prepare("SELECT MAX(length(data)) AS n FROM git_object_bytes").get()!.n) <= 65536);
106+ const before = storage.db.prepare("SELECT COUNT(*) AS n FROM git_object_meta").get()!.n;
107+ assert.throws(
108+ () =>
109+ resolver.addChunks(40, "blob", (write) => {
110+ write(new Uint8Array(70000));
111+ throw Error("inflate failed");
112+ }),
113+ /inflate failed/,
114+ );
115+ assert.equal(storage.db.prepare("SELECT COUNT(*) AS n FROM git_object_meta").get()!.n, before);
116+ assert.equal(storage.db.prepare("SELECT COUNT(*) AS n FROM git_pack_resolve WHERE offset = 40").get()!.n, 0);
117+});
--- /dev/null
+++ b/server/test/git-pack-spool.test.ts
@@ -0,0 +1,70 @@
1+import assert from "node:assert/strict";
2+import { randomBytes } from "node:crypto";
3+import { test } from "node:test";
4+import git from "isomorphic-git";
5+import { GitPackSpool } from "../src/git-pack-spool.ts";
6+import { MemoryFS } from "../src/memory-fs.ts";
7+import { memoryStorage } from "./helpers.ts";
8+
9+test("cold pack recovery clears abandoned scratch without changing canonical tables", (t) => {
10+ const storage = memoryStorage();
11+ t.after(() => storage.db.close());
12+ GitPackSpool.recover(storage);
13+ storage.sql.exec("CREATE TABLE canonical_test (value TEXT)");
14+ storage.sql.exec("INSERT INTO canonical_test VALUES (?)", "preserved");
15+ storage.sql.exec("INSERT INTO git_pack_spool VALUES (?, ?, ?)", "abandoned", 0, new Uint8Array([1, 2]));
16+ GitPackSpool.recover(storage);
17+ assert.equal(storage.db.prepare("SELECT COUNT(*) AS n FROM git_pack_spool").get()!.n, 0);
18+ assert.equal(storage.db.prepare("SELECT value FROM canonical_test").get()!.value, "preserved");
19+ GitPackSpool.recover(storage);
20+});
22+test("pack spool verifies real pack bytes and serves bounded ranges across chunk boundaries", async (t) => {
23+ const storage = memoryStorage();
24+ t.after(() => storage.db.close());
25+ const fs = new MemoryFS(),
26+ dir = "/repo";
27+ await git.init({ fs, dir });
28+ const oids = [];
29+ for (let i = 0; i < 4; i++) oids.push(await git.writeBlob({ fs, dir, blob: randomBytes(180000) }));
30+ const packed = await git.packObjects({ fs, dir, oids, write: false });
31+ const bytes = packed.packfile!;
32+ const spool = new GitPackSpool(storage);
33+ assert.throws(() => spool.read(0, 0), /not readable/);
34+ async function* source() {
35+ for (let at = 0; at < bytes.length; at += 997) yield bytes.subarray(at, at + 997);
36+ }
37+ assert.equal(await spool.ingest(source(), 1000000), Buffer.from(bytes.subarray(-20)).toString("hex"));
38+ assert.equal(spool.byteLength, bytes.length);
39+ for (const start of [0, 65530, 65536, 131070, bytes.length - 101]) {
40+ const length = Math.min(101, bytes.length - start);
41+ assert.deepEqual(spool.read(start, length), new Uint8Array(bytes.subarray(start, start + length)));
42+ }
43+ assert.deepEqual(Buffer.concat([...spool.chunks()]), Buffer.from(bytes));
44+ assert.throws(() => spool.read(0, 65537), /invalid pack byte range/);
45+ assert.throws(() => spool.read(bytes.length, 1), /invalid pack byte range/);
46+ const max = storage.db.prepare("SELECT MAX(length(data)) AS n FROM git_pack_spool").get()!.n;
47+ assert.ok(Number(max) <= 65536);
48+ spool.dispose();
49+ assert.throws(() => spool.read(0, 0), /not readable/);
50+ assert.equal(storage.db.prepare("SELECT COUNT(*) AS n FROM git_pack_spool").get()!.n, 0);
51+ for (const mode of ["corrupt", "limit", "source-error"]) {
52+ const bad = new GitPackSpool(storage);
53+ let closed = false;
54+ async function* broken() {
55+ try {
56+ const data = Uint8Array.from(bytes);
57+ if (mode === "corrupt") data[20]! ^= 1;
58+ yield data.subarray(0, 100000);
59+ if (mode === "source-error") throw Error("injected source failure");
60+ yield data.subarray(100000);
61+ } finally {
62+ closed = true;
63+ }
64+ }
65+ await assert.rejects(bad.ingest(broken(), mode === "limit" ? 70000 : 1000000));
66+ assert.equal(closed, true);
67+ assert.throws(() => bad.read(0, 0), /not readable/);
68+ assert.equal(storage.db.prepare("SELECT COUNT(*) AS n FROM git_pack_spool").get()!.n, 0);
69+ }
70+});
--- a/server/test/project-object-disk-first.test.ts
+++ b/server/test/project-object-disk-first.test.ts
@@ -1,9 +1,10 @@
11import assert from "node:assert/strict";
2−import { registerHooks } from "node:module";
2+import { createRequire, registerHooks } from "node:module";
33import { test } from "node:test";
44import git from "isomorphic-git";
55import { Project } from "../../worker/project/project.ts";
66import { EngineProject } from "../src/engine-project.ts";
7+import { GitDiskIntake } from "../src/git-disk-intake.ts";
78import { MemoryFS } from "../src/memory-fs.ts";
89import { memoryStorage } from "./helpers.ts";
@@ -20,6 +21,40 @@
2021const { ProjectObject } = await import("../src/project-object.ts");
2122hooks.deregister();
2223
24+function assertGitScratchEmpty(storage: ReturnType<typeof memoryStorage>) {
25+ for (const table of [
26+ "git_pack_spool",
27+ "git_pack_resolve",
28+ "git_object_meta",
29+ "git_object_bytes",
30+ "git_object_budget",
31+ ])
32+ assert.equal(storage.db.prepare(`SELECT COUNT(*) AS n FROM ${table}`).get()!.n, 0, table);
33+}
35+/** Keep transport synthetic while exercising the real disk pack decoder and cache. */
36+async function cloneFixture(remote: MemoryFS, options: Parameters<typeof git.clone>[0]) {
37+ const intake = (options.cache as Record<symbol, GitDiskIntake> | undefined)?.[Symbol.for("abso.git.disk-pack")];
38+ if (!intake) {
39+ (options.fs as MemoryFS).entries = structuredClone(remote.entries);
40+ return;
41+ }
42+ const oids = [...remote.entries.keys()].flatMap((path) => {
43+ const match = /\/objects\/([0-9a-f]{2})\/([0-9a-f]{38})$/.exec(path);
44+ return match ? [match[1]! + match[2]!] : [];
45+ });
46+ const pack = (await git.packObjects({ fs: remote, dir: "/repo", oids, write: false })).packfile!;
47+ const { Inflate } = createRequire(import.meta.url)("pako");
48+ await intake.ingest([pack], () => new Inflate({ chunkSize: 16384 }));
49+ await git.init({ fs: options.fs, dir: options.dir, defaultBranch: "main" });
50+ await git.writeRef({
51+ fs: options.fs,
52+ dir: options.dir,
53+ ref: "main",
54+ value: await git.resolveRef({ fs: remote, dir: "/repo", ref: "main" }),
55+ });
56+}
2358test("empty disk projects and unloadable legacy projects preserve lookup fallbacks", async (t) => {
2459 const storage = memoryStorage();
2560 t.after(() => storage.db.close());
@@ -344,9 +379,14 @@
344379 await git.writeRef({ fs: remote, dir: "/repo", ref: "main", value: incoming, force: true });
345380 t.mock.method(git, "listServerRefs", async () => [{ ref: "refs/heads/main", oid: incoming }]);
346381 t.mock.method(git, "clone", async (options: Parameters<typeof git.clone>[0]) => {
347− (options.fs as MemoryFS).entries = structuredClone(remote.entries);
382+ await cloneFixture(remote, options);
348383 });
349384 const beforeIntake = rows();
385+ const originalRead = GitDiskIntake.prototype.read;
386+ t.mock.method(GitDiskIntake.prototype, "read", function (this: GitDiskIntake, oid: string) {
387+ if (oid === blob) throw Error("whole intake text blob forbidden");
388+ return originalRead.call(this, oid);
389+ });
350390 const originalIngest = EngineProject.prototype.ingest;
351391 const failedIngest = t.mock.method(
352392 EngineProject.prototype,
@@ -357,15 +397,18 @@
357397 },
358398 );
359399 await assert.rejects(() => bound().gitSync(), /injected after Git intake/);
400+ assertGitScratchEmpty(storage);
360401 assert.deepEqual(rows(), beforeIntake);
361402 assert.equal((await bound().out()).git.head, parent, "failed intake must not acknowledge the remote head");
362403 failedIngest.mock.restore();
363404 failGitAcknowledgement = true;
364405 await assert.rejects(() => bound().gitSync(), /Git cursor persistence failure/);
406+ assertGitScratchEmpty(storage);
365407 const committedIntake = rows();
366408 assert.equal((await bound().out()).version, 3);
367409 assert.equal((await bound().out()).git.head, parent);
368410 const intake = await bound().gitSync();
411+ assertGitScratchEmpty(storage);
369412 assert.deepEqual(rows(), committedIntake, "retry after cursor failure returns the atomic intake receipt");
370413 assert.ok(intake);
371414 assert.equal(intake?.head, incoming);
@@ -443,7 +486,7 @@
443486 let head = await commit({ "A.TXT": "clash\n", "a.txt": "original\n" }, "Refused", [base]);
444487 t.mock.method(git, "listServerRefs", async () => [{ ref: "refs/heads/main", oid: head }]);
445488 t.mock.method(git, "clone", async (options: Parameters<typeof git.clone>[0]) => {
446− (options.fs as MemoryFS).entries = structuredClone(remote.entries);
489+ await cloneFixture(remote, options);
447490 });
448491 const refused = await object().gitSync();
449492 assert.ok(refused);