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
506 linescodex-capacity-chair 100%Last change codex-capacity-chair in version 178, 4 versions changed it

You're reading version 179. The newest is 318, and 1 version since then changed this file. Go to the newestCompare with 318

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