- MCP
- code on this site's /mcp
- CLI
- none: the JSON below is the answer
- JSON
- /christopher/abso-core/files/server/test/project-object-disk-first.test.ts?format=json
670 linescodex-capacity-chair 100%Last change codex-capacity-chair in version 180, 5 versions changed it
1import assert from "node:assert/strict";
2import { createRequire, registerHooks } from "node:module";
3import { test } from "node:test";
4import git from "isomorphic-git";
5import { Project } from "../../worker/project/project.ts";
6import { EngineProject } from "../src/engine-project.ts";
7import { GitDiskIntake } from "../src/git-disk-intake.ts";
8import { GitIntakeLimitError } from "../src/git-intake-limit.ts";
9import { MemoryFS } from "../src/memory-fs.ts";
10import { memoryStorage } from "./helpers.ts";
12const hooks = registerHooks({
13 resolve(specifier, context, next) {
14 if (specifier === "cloudflare:workers")
15 return {
16 url: `data:text/javascript,${encodeURIComponent("export class DurableObject { constructor(ctx, env) { this.ctx = ctx; this.env = env; } }")}`,
17 shortCircuit: true,
18 };
19 return next(specifier, context);
20 },
21});
22const { ProjectObject } = await import("../src/project-object.ts");
23hooks.deregister();
25for (const disk of [false, true])
26 test(`failed intake retries across cold objects with disk mode ${disk}`, async (t) => {
27 const storage = memoryStorage();
28 t.after(() => storage.db.close());
29 const values = new Map<string, unknown>();
30 let alarm: number | null = null;
31 const context = {
32 id: { toString: () => "retry" },
33 storage: {
34 ...storage,
35 get: async (key: string) => values.get(key),
36 put: async (key: string | Record<string, unknown>, value?: unknown) => {
37 if (typeof key === "string") values.set(key, value);
38 else for (const [name, item] of Object.entries(key)) values.set(name, item);
39 },
40 delete: async (key: string) => values.delete(key),
41 getAlarm: async () => alarm,
42 setAlarm: async (value: number) => {
43 alarm = value;
44 },
45 },
46 };
47 const object = (enabled: boolean) =>
48 new ProjectObject(
49 context as never,
50 {
51 ABSO_DISK_FIRST: disk ? "on" : "off",
52 ABSO_ARTIFACTS: enabled ? "on" : "off",
53 ARTIFACTS: {},
54 } as never,
55 );
56 assert.equal((await object(false).call("retry", "init", undefined, { files: { "a.txt": "first\n" } })).status, 200);
57 let ready = false;
58 for (let page = 0; page < 100; page++) {
59 if ((await object(false).call("retry", "status", undefined, {})).status === 200) {
60 ready = true;
61 break;
62 }
63 }
64 assert.equal(ready, true);
65 let fails = true;
66 t.mock.method(ProjectObject.prototype, "gitSync", async () => {
67 if (fails) throw Error("transient intake failure");
68 return null;
69 });
70 for (const [index, minutes] of [1, 5, 15, 15].entries()) {
71 alarm = null;
72 const before = Date.now();
73 await object(true).alarm();
74 assert.equal(values.get("git:retry-attempts"), index + 1);
75 assert.ok(alarm !== null && alarm >= before + minutes * 60000 && alarm <= Date.now() + minutes * 60000);
76 assert.equal(values.get("pushed"), undefined);
77 }
78 fails = false;
79 values.set("pushed", { version: Number.MAX_SAFE_INTEGER });
80 alarm = null;
81 await object(true).alarm();
82 assert.equal(values.has("git:retry-attempts"), false);
83 assert.equal(values.has("git:error"), false);
84 });
86test("size refusals survive cold objects, retry changed heads or policy, and prevent outgoing pushes", async (t) => {
87 let scheduled = 0;
88 const storage = memoryStorage();
89 t.after(() => storage.db.close());
90 const values = new Map<string, unknown>();
91 const context = {
92 id: { toString: () => "size-refusal" },
93 storage: {
94 ...storage,
95 get: async (key: string) => values.get(key),
96 put: async (key: string | Record<string, unknown>, value?: unknown) => {
97 if (typeof key === "string") values.set(key, value);
98 else for (const [name, item] of Object.entries(key)) values.set(name, item);
99 },
100 delete: async (key: string) => values.delete(key),
101 getAlarm: async () => null,
102 setAlarm: async (value: number) => {
103 scheduled = value;
104 },
105 },
106 };
107 const artifacts = {
108 get: async () => ({
109 info: async () => ({ remote: "https://artifacts.invalid/size" }),
110 createToken: async () => ({ plaintext: "invented-test-token" }),
111 [Symbol.dispose]() {},
112 }),
113 };
114 const object = (enabled = true) =>
115 new ProjectObject(
116 context as never,
117 {
118 ABSO_DISK_FIRST: "on",
119 ABSO_ARTIFACTS: enabled ? "on" : "off",
120 ARTIFACTS: artifacts,
121 } as never,
122 );
123 assert.equal(
124 (await object(false).call("size-refusal", "init", undefined, { files: { "a.txt": "original\n" } })).status,
125 200,
126 );
127 let ready = false;
128 for (let page = 0; page < 100; page++) {
129 const result = await object(false).call("size-refusal", "status", undefined, {});
130 if (result.status === 200) {
131 ready = true;
132 break;
133 }
134 assert.equal(result.status, 503);
135 }
136 assert.equal(ready, true, "project indexing must finish before testing intake refusals");
137 let head = "a".repeat(40),
138 downloads = 0,
139 pushes = 0,
140 transient = false;
141 t.mock.method(git, "listServerRefs", async () => [{ ref: "refs/heads/main", oid: head }]);
142 t.mock.method(git, "clone", async () => {
143 downloads++;
144 if (transient) throw Error("temporary network failure");
145 throw new GitIntakeLimitError("decoded", "Git pack exceeds total decoded byte limit");
146 });
147 t.mock.method(git, "push", async () => {
148 pushes++;
149 return { ok: true };
150 });
151 await assert.rejects(() => object().gitSync(), /decoded byte limit/);
152 await assert.rejects(() => object().gitSync(), /decoded byte limit/);
153 assert.equal(downloads, 1);
154 assert.equal(values.get("git:head"), undefined);
155 assert.equal((await object().out()).version, 0);
156 assert.match(JSON.stringify((await object().out()).git.error), /decoded byte limit/);
157 await object().alarm();
158 assert.ok(scheduled >= Date.now() + 59_000);
159 assert.equal(values.get("git:retry-attempts"), 1);
160 assert.equal(downloads, 1);
161 assert.equal(pushes, 0);
162 head = "b".repeat(40);
163 await assert.rejects(() => object().gitSync(), /decoded byte limit/);
164 assert.equal(downloads, 2);
165 values.set("git:size-refusal", { ...(values.get("git:size-refusal") as object), policy: "old-policy" });
166 await assert.rejects(() => object().gitSync(), /decoded byte limit/);
167 assert.equal(downloads, 3);
168 head = "c".repeat(40);
169 transient = true;
170 await assert.rejects(() => object().gitSync(), /temporary network failure/);
171 await assert.rejects(() => object().gitSync(), /temporary network failure/);
172 assert.equal(downloads, 5);
173 assert.equal(values.has("git:size-refusal"), false);
174 await object().alarm();
175 assert.equal(pushes, 0);
176 assertGitScratchEmpty(storage);
177});
179function assertGitScratchEmpty(storage: ReturnType<typeof memoryStorage>) {
180 for (const table of [
181 "git_pack_spool",
182 "git_pack_resolve",
183 "git_object_meta",
184 "git_object_bytes",
185 "git_object_budget",
186 ])
187 assert.equal(storage.db.prepare(`SELECT COUNT(*) AS n FROM ${table}`).get()!.n, 0, table);
188}
190/** Keep transport synthetic while exercising the real disk pack decoder and cache. */
191async function cloneFixture(remote: MemoryFS, options: Parameters<typeof git.clone>[0]) {
192 const intake = (options.cache as Record<symbol, GitDiskIntake> | undefined)?.[Symbol.for("abso.git.disk-pack")];
193 if (!intake) {
194 (options.fs as MemoryFS).entries = structuredClone(remote.entries);
195 return;
196 }
197 const oids = [...remote.entries.keys()].flatMap((path) => {
198 const match = /\/objects\/([0-9a-f]{2})\/([0-9a-f]{38})$/.exec(path);
199 return match ? [match[1]! + match[2]!] : [];
200 });
201 const pack = (await git.packObjects({ fs: remote, dir: "/repo", oids, write: false })).packfile!;
202 const { Inflate } = createRequire(import.meta.url)("pako");
203 await intake.ingest([pack], () => new Inflate({ chunkSize: 16384 }));
204 await git.init({ fs: options.fs, dir: options.dir, defaultBranch: "main" });
205 await git.writeRef({
206 fs: options.fs,
207 dir: options.dir,
208 ref: "main",
209 value: await git.resolveRef({ fs: remote, dir: "/repo", ref: "main" }),
210 });
211}
213test("empty disk projects and unloadable legacy projects preserve lookup fallbacks", async (t) => {
214 const storage = memoryStorage();
215 t.after(() => storage.db.close());
216 const context = { id: { toString: () => "empty" }, storage: { ...storage, get: async () => undefined } };
217 const disk = new ProjectObject(context as never, { ABSO_DISK_FIRST: "on" } as never);
218 assert.deepEqual(await disk.call("empty", "status", undefined, {}), {
219 status: 404,
220 body: { error: "no such project; run init first" },
221 });
222 assert.deepEqual(await disk.agents("empty"), []);
223 assert.deepEqual(await disk.news("empty", [{ from: "alice", issue: null, text: "Hello" }]), [{ to: [] }]);
224 await disk.alarm();
225 t.mock.method(EngineProject, "open", () => {
226 throw Error("unloadable legacy log");
227 });
228 const legacy = new ProjectObject(context as never, {} as never);
229 assert.deepEqual(await legacy.agents("empty"), []);
230 assert.deepEqual(await legacy.news("empty", [{ from: "alice", issue: null, text: "Hello" }]), [{ to: [] }]);
231 await legacy.alarm();
232});
234test("ProjectObject disk-first calls survive cold objects without replay", async (t) => {
235 const storage = memoryStorage();
236 t.after(() => storage.db.close());
237 const values = new Map<string, unknown>();
238 let alarm: number | null = null;
239 let onReaders: (() => Promise<void>) | undefined;
240 let failGitAcknowledgement = false;
241 let failNamePersistence = false;
242 const context = {
243 id: { toString: () => "project-1" },
244 storage: {
245 ...storage,
246 get: async (key: string) => {
247 if (key === "readers" && onReaders) {
248 const action = onReaders;
249 onReaders = undefined;
250 await action();
251 }
252 return values.get(key);
253 },
254 put: async (key: string | Record<string, unknown>, value?: unknown) => {
255 if (key === "name" && failNamePersistence) {
256 failNamePersistence = false;
257 throw Error("injected name persistence failure");
258 }
259 if (failGitAcknowledgement && typeof key === "object" && "git:head" in key) {
260 failGitAcknowledgement = false;
261 throw Error("injected Git cursor persistence failure");
262 }
263 if (typeof key === "string") values.set(key, value);
264 else for (const [name, v] of Object.entries(key)) values.set(name, v);
265 },
266 delete: async (key: string) => values.delete(key),
267 getAlarm: async () => alarm,
268 setAlarm: async (value: number) => {
269 alarm = value;
270 },
271 },
272 };
273 const object = () =>
274 new ProjectObject(
275 context as never,
276 { ABSO_DISK_FIRST: "on", ABSO_ARTIFACTS: "off", KEY_HMAC_SECRET: "invented-test-secret" } as never,
277 );
278 t.mock.method(Project, "load", () => {
279 throw Error("full history replay forbidden");
280 });
281 const call = async (op: string, agent: string | undefined, body: unknown, requestId?: string) => {
282 for (let page = 0; page < 100; page++) {
283 const result = await object().call("project", op, agent, body, false, undefined, undefined, requestId);
284 if (result.status !== 503) {
285 assert.notEqual(result.status, 500, JSON.stringify({ op, result }));
286 return result;
287 }
288 assert.notEqual(alarm, null);
289 await object().alarm();
290 }
291 throw Error("adoption did not finish");
292 };
293 const initId = "00000000-0000-4000-8000-000000000008";
294 const initBody = { files: { "a.txt": "one\ntwo\n" } };
295 failNamePersistence = true;
296 await assert.rejects(
297 () => object().call("project", "init", undefined, initBody, false, undefined, undefined, initId),
298 /name persistence failure/,
299 );
300 const initializedLog = storage.db.prepare("SELECT * FROM log ORDER BY seq,part").all();
301 assert.equal((await call("init", undefined, initBody, initId)).status, 200);
302 assert.deepEqual(storage.db.prepare("SELECT * FROM log ORDER BY seq,part").all(), initializedLog);
303 assert.equal((await call("sync", "alice", {})).status, 200);
304 const requestId = "00000000-0000-4000-8000-000000000007";
305 const recordBody = { files: { "a.txt": "changed\n" } };
306 failNamePersistence = true;
307 await assert.rejects(
308 () => object().call("project", "record", "alice", recordBody, false, undefined, undefined, requestId),
309 /name persistence failure/,
310 );
311 const recordedLog = storage.db.prepare("SELECT * FROM log ORDER BY seq,part").all();
312 assert.equal(
313 (await object().call("project", "record", "alice", recordBody, false, undefined, undefined, requestId)).status,
314 200,
315 );
316 assert.deepEqual(storage.db.prepare("SELECT * FROM log ORDER BY seq,part").all(), recordedLog);
317 assert.equal(
318 (
319 await object().call(
320 "project",
321 "record",
322 "alice",
323 { files: { "a.txt": "different\n" } },
324 false,
325 undefined,
326 undefined,
327 requestId,
328 )
329 ).status,
330 409,
331 );
332 const published = await call("publish", "alice", { message: "Disk first" });
333 assert.equal(published.status, 200);
334 assert.equal((published.body as { ok: boolean }).ok, true);
335 const issued = await object().issueAgentKey("alice", "test-address", null, "writer");
336 assert.ok("key" in issued);
337 const keyCall = { presented: issued.key, address: "test-address", write: true, route: "record" };
338 const crossPrincipal = await object().call(
339 "project",
340 "record",
341 "alice",
342 recordBody,
343 false,
344 undefined,
345 keyCall,
346 requestId,
347 );
348 assert.equal(crossPrincipal.status, 200, "each checked principal owns its own request ID namespace");
349 const principalReceipts = storage.db
350 .prepare("SELECT DISTINCT key FROM writer_state WHERE collection = 'runtime:receipts' AND key LIKE ?")
351 .all(`http:%:${requestId}`);
352 assert.equal(principalReceipts.length, 2);
353 const beforeSharedReplay = storage.db.prepare("SELECT * FROM log ORDER BY seq,part").all();
354 assert.equal((await call("record", "alice", recordBody, requestId)).status, 200);
355 assert.deepEqual(storage.db.prepare("SELECT * FROM log ORDER BY seq,part").all(), beforeSharedReplay);
356 const keyRequestId = "00000000-0000-4000-8000-000000000010";
357 assert.equal(
358 (await object().call("project", "record", "alice", recordBody, false, undefined, keyCall, keyRequestId)).status,
359 200,
360 );
361 await object().revokeAgentKey(issued.id, "test-address");
362 const beforeRevokedRetry = storage.db.prepare("SELECT * FROM log ORDER BY seq,part").all();
363 const revokedRetry = await object().call(
364 "project",
365 "record",
366 "alice",
367 recordBody,
368 false,
369 undefined,
370 keyCall,
371 keyRequestId,
372 );
373 assert.equal(revokedRetry.status, 403);
374 assert.deepEqual(storage.db.prepare("SELECT * FROM log ORDER BY seq,part").all(), beforeRevokedRetry);
375 const readerId = "00000000-0000-4000-8000-000000000009";
376 failNamePersistence = true;
377 await assert.rejects(
378 () => object().call("project", "reader", "alice", { reader: true }, false, undefined, undefined, readerId),
379 /name persistence failure/,
380 );
381 const nowRefused = await object().call(
382 "project",
383 "record",
384 "alice",
385 recordBody,
386 false,
387 undefined,
388 undefined,
389 requestId,
390 );
391 assert.equal(
392 (nowRefused.body as { ok: boolean }).ok,
393 false,
394 "current reader authority overrides an earlier successful receipt",
395 );
396 assert.equal(
397 (await object().call("project", "reader", "alice", { reader: true }, false, undefined, undefined, readerId)).status,
398 200,
399 );
400 assert.equal((await call("reader", "alice", { reader: false })).status, 200);
401 const file = await call("file", undefined, { path: "a.txt", version: "1" });
402 assert.equal(file.status, 200);
403 assert.match(JSON.stringify(file.body), /changed/);
404 const feed = await call("feed", undefined, { from: "0", limit: "2" });
405 assert.equal(feed.status, 200);
406 assert.ok((feed.body as { next: number }).next > 0);
407 assert.deepEqual(await object().agents("project"), ["alice"]);
408 assert.equal((await object().out()).version, 1);
409 assert.deepEqual(await object().news("project", [{ from: "bob", issue: null, text: "Hello", to: ["alice"] }]), [
410 { to: ["alice"] },
411 ]);
412 assert.equal((await call("status", undefined, {})).status, 200);
413 for (const agent of ["alice", "bob"]) assert.equal((await call("sync", agent, {})).status, 200);
414 assert.equal((await call("record", "alice", { files: { "a.txt": "Alice's change\n" } })).status, 200);
415 assert.equal((await call("record", "bob", { files: { "a.txt": "Bob's change\n" } })).status, 200);
416 assert.equal((await call("publish", "alice", { message: "Alice wins first" })).status, 200);
417 const collision = await call("publish", "bob", { message: "Bob conflicts" });
418 assert.equal((collision.body as { ok: boolean }).ok, false);
419 assert.equal((collision.body as { collisions: unknown[] }).collisions.length, 1);
420 const historical = await call("file", undefined, { path: "a.txt", version: "1" });
421 assert.equal(historical.status, 200);
422 assert.match(JSON.stringify(historical.body), /changed/);
423 const rows = () => ({
424 log: storage.db.prepare("SELECT * FROM log ORDER BY seq,part").all(),
425 state: storage.db.prepare("SELECT * FROM writer_state ORDER BY namespace,collection,key,part").all(),
426 });
427 const stable = rows();
428 const disabled = new ProjectObject(context as never, { ABSO_DISK_FIRST: "off" } as never);
429 const held = await disabled.call("project", "record", "alice", { files: { "a.txt": "legacy write\n" } });
430 assert.equal(held.status, 409);
431 assert.match(JSON.stringify(held.body), /enable ABSO_DISK_FIRST/);
432 assert.equal(await disabled.gitSync(), null);
433 assert.deepEqual(rows(), stable);
434 assert.equal((await call("status", undefined, {})).status, 200, "re-enabling disk mode preserves the valid root");
435 const originalAnnounce = EngineProject.prototype.announce;
436 const failingAnnounce = t.mock.method(
437 EngineProject.prototype,
438 "announce",
439 function (this: EngineProject, ...args: Parameters<EngineProject["announce"]>) {
440 originalAnnounce.apply(this, args);
441 throw Error("injected after announce");
442 },
443 );
444 await assert.rejects(
445 () => object().news("project", [{ from: "bob", issue: null, text: "Must roll back", to: ["alice"] }]),
446 /injected after announce/,
447 );
448 assert.deepEqual(rows(), stable);
449 failingAnnounce.mock.restore();
450 const current = object();
451 onReaders = async () => {
452 await current.revokeAgentKey("missing-test-key", "127.0.0.1");
453 };
454 const revoked = await current.call("project", "record", "alice", { files: { "a.txt": "unauthorized\n" } });
455 assert.equal(revoked.status, 409);
456 assert.equal((revoked.body as { retryable: boolean }).retryable, true);
457 assert.deepEqual(rows(), stable);
458 const original = EngineProject.prototype.record;
459 t.mock.method(
460 EngineProject.prototype,
461 "record",
462 function (this: EngineProject, ...args: Parameters<EngineProject["record"]>) {
463 original.apply(this, args);
464 throw Error("injected after record");
465 },
466 );
467 await assert.rejects(
468 () => object().call("project", "record", "alice", { files: { "a.txt": "failed\n" } }),
469 /injected after record/,
470 );
471 assert.deepEqual(rows(), stable);
472 // Exercise the real alarm and commit builder; only remote transport is mocked.
473 t.mock.method(git, "listServerRefs", async () => []);
474 t.mock.method(git, "clone", async () => {
475 throw Error("empty test repository");
476 });
477 let pushed = 0;
478 let failPush = true;
479 let remoteFiles: MemoryFS | undefined;
480 t.mock.method(git, "push", async (options: Parameters<typeof git.push>[0]) => {
481 if (failPush) {
482 failPush = false;
483 throw Error("injected Artifacts transport failure");
484 }
485 const oid = await git.resolveRef({ fs: options.fs, dir: options.dir, ref: "main" });
486 const commit = await git.readCommit({ fs: options.fs, dir: options.dir, oid });
487 assert.match(commit.commit.message, /abso-version: 2/);
488 const blob = await git.readBlob({ fs: options.fs, dir: options.dir, oid, filepath: "a.txt" });
489 assert.equal(new TextDecoder().decode(blob.blob), "Alice's change\n");
490 pushed++;
491 // The remote owns its copy; the export's scratch files expire when push returns.
492 remoteFiles = new MemoryFS();
493 for (const [path, entry] of (options.fs as MemoryFS).entries) {
494 remoteFiles.entries.set(
495 path,
496 entry.kind === "file"
497 ? { ...entry, data: new Uint8Array((await (options.fs as MemoryFS).readFile(path)) as Uint8Array) }
498 : { ...entry },
499 );
500 }
501 return { ok: true };
502 });
503 const artifacts = {
504 get: async () => ({
505 info: async () => ({ remote: "https://artifacts.invalid/test" }),
506 createToken: async () => ({ plaintext: "invented-test-token" }),
507 [Symbol.dispose]() {},
508 }),
509 };
510 const bound = () => new ProjectObject(context as never, { ABSO_DISK_FIRST: "on", ARTIFACTS: artifacts } as never);
511 // Deliver the pending alarm: the fake storage must clear it as the host does.
512 alarm = null;
513 await bound().alarm();
514 assert.equal(pushed, 0);
515 assert.equal(values.get("pushed"), undefined, "failed transport must not acknowledge a push");
516 assert.match(JSON.stringify(values.get("pushError")), /injected Artifacts transport failure/);
517 assert.deepEqual(rows(), stable, "failed remote transport leaves canonical state unchanged");
518 assert.ok(alarm !== null && alarm > Date.now(), "failed transport schedules a retry");
519 await bound().alarm();
520 assert.equal(pushed, 1);
521 assert.equal(values.get("pushError"), undefined, "cold retry clears the transport error");
522 assert.equal((await bound().out()).pushed?.version, 2);
523 assert.deepEqual(rows(), stable, "pushing shared does not mutate canonical project state");
524 await bound().alarm();
525 assert.equal(pushed, 1, "a cold alarm does not push the same version again");
526 assert.ok(remoteFiles);
527 const remote = remoteFiles;
528 const parent = await git.resolveRef({ fs: remote, dir: "/repo", ref: "main" });
529 const blob = await git.writeBlob({ fs: remote, dir: "/repo", blob: new TextEncoder().encode("From Git\n") });
530 const tree = await git.writeTree({
531 fs: remote,
532 dir: "/repo",
533 tree: [{ mode: "100644", path: "a.txt", oid: blob, type: "blob" }],
534 });
535 const incoming = await git.commit({
536 fs: remote,
537 dir: "/repo",
538 tree,
539 parent: [parent],
540 message: "Plain Git edit",
541 author: { name: "Git writer", email: "test@example.invalid" },
542 });
543 await git.writeRef({ fs: remote, dir: "/repo", ref: "main", value: incoming, force: true });
544 t.mock.method(git, "listServerRefs", async () => [{ ref: "refs/heads/main", oid: incoming }]);
545 t.mock.method(git, "clone", async (options: Parameters<typeof git.clone>[0]) => {
546 await cloneFixture(remote, options);
547 });
548 const beforeIntake = rows();
549 const originalRead = GitDiskIntake.prototype.read;
550 t.mock.method(GitDiskIntake.prototype, "read", function (this: GitDiskIntake, oid: string) {
551 if (oid === blob) throw Error("whole intake text blob forbidden");
552 return originalRead.call(this, oid);
553 });
554 const originalIngest = EngineProject.prototype.ingest;
555 const failedIngest = t.mock.method(
556 EngineProject.prototype,
557 "ingest",
558 function (this: EngineProject, ...args: Parameters<EngineProject["ingest"]>) {
559 originalIngest.apply(this, args);
560 throw Error("injected after Git intake");
561 },
562 );
563 await assert.rejects(() => bound().gitSync(), /injected after Git intake/);
564 assertGitScratchEmpty(storage);
565 assert.deepEqual(rows(), beforeIntake);
566 assert.equal((await bound().out()).git.head, parent, "failed intake must not acknowledge the remote head");
567 failedIngest.mock.restore();
568 failGitAcknowledgement = true;
569 await assert.rejects(() => bound().gitSync(), /Git cursor persistence failure/);
570 assertGitScratchEmpty(storage);
571 const committedIntake = rows();
572 assert.equal((await bound().out()).version, 3);
573 assert.equal((await bound().out()).git.head, parent);
574 const intake = await bound().gitSync();
575 assertGitScratchEmpty(storage);
576 assert.deepEqual(rows(), committedIntake, "retry after cursor failure returns the atomic intake receipt");
577 assert.ok(intake);
578 assert.equal(intake?.head, incoming);
579 assert.equal(intake?.commits, 1);
580 assert.equal((intake.answer as { landed: boolean }).landed, true, JSON.stringify(intake));
581 const imported = await call("file", undefined, { path: "a.txt", version: "3" });
582 assert.equal(imported.status, 200);
583 assert.match(JSON.stringify(imported.body), /From Git/);
584 const afterIntake = rows();
585 assert.equal(await bound().gitSync(), null);
586 assert.deepEqual(rows(), afterIntake, "cold intake does not apply the same commit twice");
587});
589for (const disk of [false, true]) {
590 test(`Git refusal permits a later fixing commit with disk mode ${disk}`, async (t) => {
591 const storage = memoryStorage();
592 t.after(() => storage.db.close());
593 const values = new Map<string, unknown>();
594 const context = {
595 id: { toString: () => "refusal" },
596 storage: {
597 ...storage,
598 get: async (key: string) => values.get(key),
599 put: async (key: string | Record<string, unknown>, value?: unknown) => {
600 if (typeof key === "string") values.set(key, value);
601 else for (const [k, v] of Object.entries(key)) values.set(k, v);
602 },
603 getAlarm: async () => null,
604 setAlarm: async () => {},
605 },
606 };
607 const artifacts = {
608 get: async () => ({
609 info: async () => ({ remote: "https://artifacts.invalid/refusal" }),
610 createToken: async () => ({ plaintext: "invented-test-token" }),
611 [Symbol.dispose]() {},
612 }),
613 };
614 const object = () =>
615 new ProjectObject(context as never, { ABSO_DISK_FIRST: disk ? "on" : "off", ARTIFACTS: artifacts } as never);
616 const call = async (op: string, body: unknown) => {
617 for (let page = 0; page < 100; page++) {
618 const result = await object().call("refusal", op, undefined, body);
619 if (result.status !== 503) return result;
620 }
621 throw Error("preparation did not finish");
622 };
623 assert.equal((await call("init", { files: { "a.txt": "original\n" } })).status, 200);
624 assert.equal((await call("status", {})).status, 200);
625 const remote = new MemoryFS();
626 await git.init({ fs: remote, dir: "/repo", defaultBranch: "main" });
627 const commit = async (files: Record<string, string>, message: string, parent: string[]) => {
628 const entries = [];
629 for (const [path, text] of Object.entries(files))
630 entries.push({
631 mode: "100644",
632 path,
633 type: "blob" as const,
634 oid: await git.writeBlob({ fs: remote, dir: "/repo", blob: new TextEncoder().encode(text) }),
635 });
636 const tree = await git.writeTree({ fs: remote, dir: "/repo", tree: entries });
637 const oid = await git.commit({
638 fs: remote,
639 dir: "/repo",
640 tree,
641 parent,
642 message,
643 author: { name: "Git writer", email: "test@example.invalid" },
644 });
645 await git.writeRef({ fs: remote, dir: "/repo", ref: "main", value: oid, force: true });
646 return oid;
647 };
648 const base = await commit({ "a.txt": "original\n" }, "Initial\n\nabso-version: 0", []);
649 values.set("git:head", base);
650 let head = await commit({ "A.TXT": "clash\n", "a.txt": "original\n" }, "Refused", [base]);
651 t.mock.method(git, "listServerRefs", async () => [{ ref: "refs/heads/main", oid: head }]);
652 t.mock.method(git, "clone", async (options: Parameters<typeof git.clone>[0]) => {
653 await cloneFixture(remote, options);
654 });
655 const refused = await object().gitSync();
656 assert.ok(refused);
657 assert.match(JSON.stringify(refused.answer), /one file|clash/i);
658 assert.equal(values.get("git:head"), head);
659 assert.equal(await object().gitSync(), null);
660 head = await commit({ "a.txt": "fixed\n" }, "Fixed", [head]);
661 const fixed = await object().gitSync();
662 assert.ok(fixed);
663 assert.equal((fixed.answer as { landed: boolean }).landed, true, JSON.stringify(fixed));
664 assert.equal(values.get("git:head"), head);
665 assert.match(
666 JSON.stringify((await call("file", { path: "a.txt", version: String((await object().out()).version) })).body),
667 /fixed/,
668 );
669 });
670}