- 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?version=170&format=json
463 linescodex-capacity-chair 100%Last change codex-capacity-chair in version 163, 3 versions changed it
You're reading version 170. The newest is 318, and 2 versions since then changed this file.
1import assert from "node:assert/strict";
2import { 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 { MemoryFS } from "../src/memory-fs.ts";
8import { memoryStorage } from "./helpers.ts";
10const hooks = registerHooks({
11 resolve(specifier, context, next) {
12 if (specifier === "cloudflare:workers")
13 return {
14 url: `data:text/javascript,${encodeURIComponent("export class DurableObject { constructor(ctx, env) { this.ctx = ctx; this.env = env; } }")}`,
15 shortCircuit: true,
16 };
17 return next(specifier, context);
18 },
19});
20const { ProjectObject } = await import("../src/project-object.ts");
21hooks.deregister();
23test("empty disk projects and unloadable legacy projects preserve lookup fallbacks", async (t) => {
24 const storage = memoryStorage();
25 t.after(() => storage.db.close());
26 const context = { id: { toString: () => "empty" }, storage: { ...storage, get: async () => undefined } };
27 const disk = new ProjectObject(context as never, { ABSO_DISK_FIRST: "on" } as never);
28 assert.deepEqual(await disk.call("empty", "status", undefined, {}), {
29 status: 404,
30 body: { error: "no such project; run init first" },
31 });
32 assert.deepEqual(await disk.agents("empty"), []);
33 assert.deepEqual(await disk.news("empty", [{ from: "alice", issue: null, text: "Hello" }]), [{ to: [] }]);
34 await disk.alarm();
35 t.mock.method(EngineProject, "open", () => {
36 throw Error("unloadable legacy log");
37 });
38 const legacy = new ProjectObject(context as never, {} as never);
39 assert.deepEqual(await legacy.agents("empty"), []);
40 assert.deepEqual(await legacy.news("empty", [{ from: "alice", issue: null, text: "Hello" }]), [{ to: [] }]);
41 await legacy.alarm();
42});
44test("ProjectObject disk-first calls survive cold objects without replay", async (t) => {
45 const storage = memoryStorage();
46 t.after(() => storage.db.close());
47 const values = new Map<string, unknown>();
48 let alarm: number | null = null;
49 let onReaders: (() => Promise<void>) | undefined;
50 let failGitAcknowledgement = false;
51 let failNamePersistence = false;
52 const context = {
53 id: { toString: () => "project-1" },
54 storage: {
55 ...storage,
56 get: async (key: string) => {
57 if (key === "readers" && onReaders) {
58 const action = onReaders;
59 onReaders = undefined;
60 await action();
61 }
62 return values.get(key);
63 },
64 put: async (key: string | Record<string, unknown>, value?: unknown) => {
65 if (key === "name" && failNamePersistence) {
66 failNamePersistence = false;
67 throw Error("injected name persistence failure");
68 }
69 if (failGitAcknowledgement && typeof key === "object" && "git:head" in key) {
70 failGitAcknowledgement = false;
71 throw Error("injected Git cursor persistence failure");
72 }
73 if (typeof key === "string") values.set(key, value);
74 else for (const [name, v] of Object.entries(key)) values.set(name, v);
75 },
76 delete: async (key: string) => values.delete(key),
77 getAlarm: async () => alarm,
78 setAlarm: async (value: number) => {
79 alarm = value;
80 },
81 },
82 };
83 const object = () =>
84 new ProjectObject(
85 context as never,
86 { ABSO_DISK_FIRST: "on", ABSO_ARTIFACTS: "off", KEY_HMAC_SECRET: "invented-test-secret" } as never,
87 );
88 t.mock.method(Project, "load", () => {
89 throw Error("full history replay forbidden");
90 });
91 const call = async (op: string, agent: string | undefined, body: unknown, requestId?: string) => {
92 for (let page = 0; page < 100; page++) {
93 const result = await object().call("project", op, agent, body, false, undefined, undefined, requestId);
94 if (result.status !== 503) {
95 assert.notEqual(result.status, 500, JSON.stringify({ op, result }));
96 return result;
97 }
98 assert.notEqual(alarm, null);
99 await object().alarm();
100 }
101 throw Error("adoption did not finish");
102 };
103 const initId = "00000000-0000-4000-8000-000000000008";
104 const initBody = { files: { "a.txt": "one\ntwo\n" } };
105 failNamePersistence = true;
106 await assert.rejects(
107 () => object().call("project", "init", undefined, initBody, false, undefined, undefined, initId),
108 /name persistence failure/,
109 );
110 const initializedLog = storage.db.prepare("SELECT * FROM log ORDER BY seq,part").all();
111 assert.equal((await call("init", undefined, initBody, initId)).status, 200);
112 assert.deepEqual(storage.db.prepare("SELECT * FROM log ORDER BY seq,part").all(), initializedLog);
113 assert.equal((await call("sync", "alice", {})).status, 200);
114 const requestId = "00000000-0000-4000-8000-000000000007";
115 const recordBody = { files: { "a.txt": "changed\n" } };
116 failNamePersistence = true;
117 await assert.rejects(
118 () => object().call("project", "record", "alice", recordBody, false, undefined, undefined, requestId),
119 /name persistence failure/,
120 );
121 const recordedLog = storage.db.prepare("SELECT * FROM log ORDER BY seq,part").all();
122 assert.equal(
123 (await object().call("project", "record", "alice", recordBody, false, undefined, undefined, requestId)).status,
124 200,
125 );
126 assert.deepEqual(storage.db.prepare("SELECT * FROM log ORDER BY seq,part").all(), recordedLog);
127 assert.equal(
128 (
129 await object().call(
130 "project",
131 "record",
132 "alice",
133 { files: { "a.txt": "different\n" } },
134 false,
135 undefined,
136 undefined,
137 requestId,
138 )
139 ).status,
140 409,
141 );
142 const published = await call("publish", "alice", { message: "Disk first" });
143 assert.equal(published.status, 200);
144 assert.equal((published.body as { ok: boolean }).ok, true);
145 const issued = await object().issueAgentKey("alice", "test-address", null, "writer");
146 assert.ok("key" in issued);
147 const keyCall = { presented: issued.key, address: "test-address", write: true, route: "record" };
148 const crossPrincipal = await object().call(
149 "project",
150 "record",
151 "alice",
152 recordBody,
153 false,
154 undefined,
155 keyCall,
156 requestId,
157 );
158 assert.equal(crossPrincipal.status, 200, "each checked principal owns its own request ID namespace");
159 const principalReceipts = storage.db
160 .prepare("SELECT DISTINCT key FROM writer_state WHERE collection = 'runtime:receipts' AND key LIKE ?")
161 .all(`http:%:${requestId}`);
162 assert.equal(principalReceipts.length, 2);
163 const beforeSharedReplay = storage.db.prepare("SELECT * FROM log ORDER BY seq,part").all();
164 assert.equal((await call("record", "alice", recordBody, requestId)).status, 200);
165 assert.deepEqual(storage.db.prepare("SELECT * FROM log ORDER BY seq,part").all(), beforeSharedReplay);
166 const keyRequestId = "00000000-0000-4000-8000-000000000010";
167 assert.equal(
168 (await object().call("project", "record", "alice", recordBody, false, undefined, keyCall, keyRequestId)).status,
169 200,
170 );
171 await object().revokeAgentKey(issued.id, "test-address");
172 const beforeRevokedRetry = storage.db.prepare("SELECT * FROM log ORDER BY seq,part").all();
173 const revokedRetry = await object().call(
174 "project",
175 "record",
176 "alice",
177 recordBody,
178 false,
179 undefined,
180 keyCall,
181 keyRequestId,
182 );
183 assert.equal(revokedRetry.status, 403);
184 assert.deepEqual(storage.db.prepare("SELECT * FROM log ORDER BY seq,part").all(), beforeRevokedRetry);
185 const readerId = "00000000-0000-4000-8000-000000000009";
186 failNamePersistence = true;
187 await assert.rejects(
188 () => object().call("project", "reader", "alice", { reader: true }, false, undefined, undefined, readerId),
189 /name persistence failure/,
190 );
191 const nowRefused = await object().call(
192 "project",
193 "record",
194 "alice",
195 recordBody,
196 false,
197 undefined,
198 undefined,
199 requestId,
200 );
201 assert.equal(
202 (nowRefused.body as { ok: boolean }).ok,
203 false,
204 "current reader authority overrides an earlier successful receipt",
205 );
206 assert.equal(
207 (await object().call("project", "reader", "alice", { reader: true }, false, undefined, undefined, readerId)).status,
208 200,
209 );
210 assert.equal((await call("reader", "alice", { reader: false })).status, 200);
211 const file = await call("file", undefined, { path: "a.txt", version: "1" });
212 assert.equal(file.status, 200);
213 assert.match(JSON.stringify(file.body), /changed/);
214 const feed = await call("feed", undefined, { from: "0", limit: "2" });
215 assert.equal(feed.status, 200);
216 assert.ok((feed.body as { next: number }).next > 0);
217 assert.deepEqual(await object().agents("project"), ["alice"]);
218 assert.equal((await object().out()).version, 1);
219 assert.deepEqual(await object().news("project", [{ from: "bob", issue: null, text: "Hello", to: ["alice"] }]), [
220 { to: ["alice"] },
221 ]);
222 assert.equal((await call("status", undefined, {})).status, 200);
223 for (const agent of ["alice", "bob"]) assert.equal((await call("sync", agent, {})).status, 200);
224 assert.equal((await call("record", "alice", { files: { "a.txt": "Alice's change\n" } })).status, 200);
225 assert.equal((await call("record", "bob", { files: { "a.txt": "Bob's change\n" } })).status, 200);
226 assert.equal((await call("publish", "alice", { message: "Alice wins first" })).status, 200);
227 const collision = await call("publish", "bob", { message: "Bob conflicts" });
228 assert.equal((collision.body as { ok: boolean }).ok, false);
229 assert.equal((collision.body as { collisions: unknown[] }).collisions.length, 1);
230 const historical = await call("file", undefined, { path: "a.txt", version: "1" });
231 assert.equal(historical.status, 200);
232 assert.match(JSON.stringify(historical.body), /changed/);
233 const rows = () => ({
234 log: storage.db.prepare("SELECT * FROM log ORDER BY seq,part").all(),
235 state: storage.db.prepare("SELECT * FROM writer_state ORDER BY namespace,collection,key,part").all(),
236 });
237 const stable = rows();
238 const disabled = new ProjectObject(context as never, { ABSO_DISK_FIRST: "off" } as never);
239 const held = await disabled.call("project", "record", "alice", { files: { "a.txt": "legacy write\n" } });
240 assert.equal(held.status, 409);
241 assert.match(JSON.stringify(held.body), /enable ABSO_DISK_FIRST/);
242 assert.equal(await disabled.gitSync(), null);
243 assert.deepEqual(rows(), stable);
244 assert.equal((await call("status", undefined, {})).status, 200, "re-enabling disk mode preserves the valid root");
245 const originalAnnounce = EngineProject.prototype.announce;
246 const failingAnnounce = t.mock.method(
247 EngineProject.prototype,
248 "announce",
249 function (this: EngineProject, ...args: Parameters<EngineProject["announce"]>) {
250 originalAnnounce.apply(this, args);
251 throw Error("injected after announce");
252 },
253 );
254 await assert.rejects(
255 () => object().news("project", [{ from: "bob", issue: null, text: "Must roll back", to: ["alice"] }]),
256 /injected after announce/,
257 );
258 assert.deepEqual(rows(), stable);
259 failingAnnounce.mock.restore();
260 const current = object();
261 onReaders = async () => {
262 await current.revokeAgentKey("missing-test-key", "127.0.0.1");
263 };
264 const revoked = await current.call("project", "record", "alice", { files: { "a.txt": "unauthorized\n" } });
265 assert.equal(revoked.status, 409);
266 assert.equal((revoked.body as { retryable: boolean }).retryable, true);
267 assert.deepEqual(rows(), stable);
268 const original = EngineProject.prototype.record;
269 t.mock.method(
270 EngineProject.prototype,
271 "record",
272 function (this: EngineProject, ...args: Parameters<EngineProject["record"]>) {
273 original.apply(this, args);
274 throw Error("injected after record");
275 },
276 );
277 await assert.rejects(
278 () => object().call("project", "record", "alice", { files: { "a.txt": "failed\n" } }),
279 /injected after record/,
280 );
281 assert.deepEqual(rows(), stable);
282 // Exercise the real alarm and commit builder; only remote transport is mocked.
283 t.mock.method(git, "listServerRefs", async () => []);
284 t.mock.method(git, "clone", async () => {
285 throw Error("empty test repository");
286 });
287 let pushed = 0;
288 let failPush = true;
289 let remoteFiles: MemoryFS | undefined;
290 t.mock.method(git, "push", async (options: Parameters<typeof git.push>[0]) => {
291 if (failPush) {
292 failPush = false;
293 throw Error("injected Artifacts transport failure");
294 }
295 const oid = await git.resolveRef({ fs: options.fs, dir: options.dir, ref: "main" });
296 const commit = await git.readCommit({ fs: options.fs, dir: options.dir, oid });
297 assert.match(commit.commit.message, /abso-version: 2/);
298 const blob = await git.readBlob({ fs: options.fs, dir: options.dir, oid, filepath: "a.txt" });
299 assert.equal(new TextDecoder().decode(blob.blob), "Alice's change\n");
300 pushed++;
301 remoteFiles = options.fs as MemoryFS;
302 return { ok: true };
303 });
304 const artifacts = {
305 get: async () => ({
306 info: async () => ({ remote: "https://artifacts.invalid/test" }),
307 createToken: async () => ({ plaintext: "invented-test-token" }),
308 [Symbol.dispose]() {},
309 }),
310 };
311 const bound = () => new ProjectObject(context as never, { ABSO_DISK_FIRST: "on", ARTIFACTS: artifacts } as never);
312 // Deliver the pending alarm: the fake storage must clear it as the host does.
313 alarm = null;
314 await bound().alarm();
315 assert.equal(pushed, 0);
316 assert.equal(values.get("pushed"), undefined, "failed transport must not acknowledge a push");
317 assert.match(JSON.stringify(values.get("pushError")), /injected Artifacts transport failure/);
318 assert.deepEqual(rows(), stable, "failed remote transport leaves canonical state unchanged");
319 assert.ok(alarm !== null && alarm > Date.now(), "failed transport schedules a retry");
320 await bound().alarm();
321 assert.equal(pushed, 1);
322 assert.equal(values.get("pushError"), undefined, "cold retry clears the transport error");
323 assert.equal((await bound().out()).pushed?.version, 2);
324 assert.deepEqual(rows(), stable, "pushing shared does not mutate canonical project state");
325 await bound().alarm();
326 assert.equal(pushed, 1, "a cold alarm does not push the same version again");
327 assert.ok(remoteFiles);
328 const remote = remoteFiles;
329 const parent = await git.resolveRef({ fs: remote, dir: "/repo", ref: "main" });
330 const blob = await git.writeBlob({ fs: remote, dir: "/repo", blob: new TextEncoder().encode("From Git\n") });
331 const tree = await git.writeTree({
332 fs: remote,
333 dir: "/repo",
334 tree: [{ mode: "100644", path: "a.txt", oid: blob, type: "blob" }],
335 });
336 const incoming = await git.commit({
337 fs: remote,
338 dir: "/repo",
339 tree,
340 parent: [parent],
341 message: "Plain Git edit",
342 author: { name: "Git writer", email: "test@example.invalid" },
343 });
344 await git.writeRef({ fs: remote, dir: "/repo", ref: "main", value: incoming, force: true });
345 t.mock.method(git, "listServerRefs", async () => [{ ref: "refs/heads/main", oid: incoming }]);
346 t.mock.method(git, "clone", async (options: Parameters<typeof git.clone>[0]) => {
347 (options.fs as MemoryFS).entries = structuredClone(remote.entries);
348 });
349 const beforeIntake = rows();
350 const originalIngest = EngineProject.prototype.ingest;
351 const failedIngest = t.mock.method(
352 EngineProject.prototype,
353 "ingest",
354 function (this: EngineProject, ...args: Parameters<EngineProject["ingest"]>) {
355 originalIngest.apply(this, args);
356 throw Error("injected after Git intake");
357 },
358 );
359 await assert.rejects(() => bound().gitSync(), /injected after Git intake/);
360 assert.deepEqual(rows(), beforeIntake);
361 assert.equal((await bound().out()).git.head, parent, "failed intake must not acknowledge the remote head");
362 failedIngest.mock.restore();
363 failGitAcknowledgement = true;
364 await assert.rejects(() => bound().gitSync(), /Git cursor persistence failure/);
365 const committedIntake = rows();
366 assert.equal((await bound().out()).version, 3);
367 assert.equal((await bound().out()).git.head, parent);
368 const intake = await bound().gitSync();
369 assert.deepEqual(rows(), committedIntake, "retry after cursor failure returns the atomic intake receipt");
370 assert.ok(intake);
371 assert.equal(intake?.head, incoming);
372 assert.equal(intake?.commits, 1);
373 assert.equal((intake.answer as { landed: boolean }).landed, true, JSON.stringify(intake));
374 const imported = await call("file", undefined, { path: "a.txt", version: "3" });
375 assert.equal(imported.status, 200);
376 assert.match(JSON.stringify(imported.body), /From Git/);
377 const afterIntake = rows();
378 assert.equal(await bound().gitSync(), null);
379 assert.deepEqual(rows(), afterIntake, "cold intake does not apply the same commit twice");
380});
382for (const disk of [false, true]) {
383 test(`Git refusal permits a later fixing commit with disk mode ${disk}`, async (t) => {
384 const storage = memoryStorage();
385 t.after(() => storage.db.close());
386 const values = new Map<string, unknown>();
387 const context = {
388 id: { toString: () => "refusal" },
389 storage: {
390 ...storage,
391 get: async (key: string) => values.get(key),
392 put: async (key: string | Record<string, unknown>, value?: unknown) => {
393 if (typeof key === "string") values.set(key, value);
394 else for (const [k, v] of Object.entries(key)) values.set(k, v);
395 },
396 getAlarm: async () => null,
397 setAlarm: async () => {},
398 },
399 };
400 const artifacts = {
401 get: async () => ({
402 info: async () => ({ remote: "https://artifacts.invalid/refusal" }),
403 createToken: async () => ({ plaintext: "invented-test-token" }),
404 [Symbol.dispose]() {},
405 }),
406 };
407 const object = () =>
408 new ProjectObject(context as never, { ABSO_DISK_FIRST: disk ? "on" : "off", ARTIFACTS: artifacts } as never);
409 const call = async (op: string, body: unknown) => {
410 for (let page = 0; page < 100; page++) {
411 const result = await object().call("refusal", op, undefined, body);
412 if (result.status !== 503) return result;
413 }
414 throw Error("preparation did not finish");
415 };
416 assert.equal((await call("init", { files: { "a.txt": "original\n" } })).status, 200);
417 assert.equal((await call("status", {})).status, 200);
418 const remote = new MemoryFS();
419 await git.init({ fs: remote, dir: "/repo", defaultBranch: "main" });
420 const commit = async (files: Record<string, string>, message: string, parent: string[]) => {
421 const entries = [];
422 for (const [path, text] of Object.entries(files))
423 entries.push({
424 mode: "100644",
425 path,
426 type: "blob" as const,
427 oid: await git.writeBlob({ fs: remote, dir: "/repo", blob: new TextEncoder().encode(text) }),
428 });
429 const tree = await git.writeTree({ fs: remote, dir: "/repo", tree: entries });
430 const oid = await git.commit({
431 fs: remote,
432 dir: "/repo",
433 tree,
434 parent,
435 message,
436 author: { name: "Git writer", email: "test@example.invalid" },
437 });
438 await git.writeRef({ fs: remote, dir: "/repo", ref: "main", value: oid, force: true });
439 return oid;
440 };
441 const base = await commit({ "a.txt": "original\n" }, "Initial\n\nabso-version: 0", []);
442 values.set("git:head", base);
443 let head = await commit({ "A.TXT": "clash\n", "a.txt": "original\n" }, "Refused", [base]);
444 t.mock.method(git, "listServerRefs", async () => [{ ref: "refs/heads/main", oid: head }]);
445 t.mock.method(git, "clone", async (options: Parameters<typeof git.clone>[0]) => {
446 (options.fs as MemoryFS).entries = structuredClone(remote.entries);
447 });
448 const refused = await object().gitSync();
449 assert.ok(refused);
450 assert.match(JSON.stringify(refused.answer), /one file|clash/i);
451 assert.equal(values.get("git:head"), head);
452 assert.equal(await object().gitSync(), null);
453 head = await commit({ "a.txt": "fixed\n" }, "Fixed", [head]);
454 const fixed = await object().gitSync();
455 assert.ok(fixed);
456 assert.equal((fixed.answer as { landed: boolean }).landed, true, JSON.stringify(fixed));
457 assert.equal(values.get("git:head"), head);
458 assert.match(
459 JSON.stringify((await call("file", { path: "a.txt", version: String((await object().out()).version) })).body),
460 /fixed/,
461 );
462 });
463}