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
449 linescodex-capacity-chair 100%Last change codex-capacity-chair in version 162, 2 versions changed it

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

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";
9
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 remoteFiles: MemoryFS | undefined;
289 t.mock.method(git, "push", async (options: Parameters<typeof git.push>[0]) => {
290 const oid = await git.resolveRef({ fs: options.fs, dir: options.dir, ref: "main" });
291 const commit = await git.readCommit({ fs: options.fs, dir: options.dir, oid });
292 assert.match(commit.commit.message, /abso-version: 2/);
293 const blob = await git.readBlob({ fs: options.fs, dir: options.dir, oid, filepath: "a.txt" });
294 assert.equal(new TextDecoder().decode(blob.blob), "Alice's change\n");
295 pushed++;
296 remoteFiles = options.fs as MemoryFS;
297 return { ok: true };
298 });
299 const artifacts = {
300 get: async () => ({
301 info: async () => ({ remote: "https://artifacts.invalid/test" }),
302 createToken: async () => ({ plaintext: "invented-test-token" }),
303 [Symbol.dispose]() {},
304 }),
305 };
306 const bound = () => new ProjectObject(context as never, { ABSO_DISK_FIRST: "on", ARTIFACTS: artifacts } as never);
307 await bound().alarm();
308 assert.equal(pushed, 1);
309 assert.equal((await bound().out()).pushed?.version, 2);
310 assert.deepEqual(rows(), stable, "pushing shared does not mutate canonical project state");
311 await bound().alarm();
312 assert.equal(pushed, 1, "a cold alarm does not push the same version again");
313 assert.ok(remoteFiles);
314 const remote = remoteFiles;
315 const parent = await git.resolveRef({ fs: remote, dir: "/repo", ref: "main" });
316 const blob = await git.writeBlob({ fs: remote, dir: "/repo", blob: new TextEncoder().encode("From Git\n") });
317 const tree = await git.writeTree({
318 fs: remote,
319 dir: "/repo",
320 tree: [{ mode: "100644", path: "a.txt", oid: blob, type: "blob" }],
321 });
322 const incoming = await git.commit({
323 fs: remote,
324 dir: "/repo",
325 tree,
326 parent: [parent],
327 message: "Plain Git edit",
328 author: { name: "Git writer", email: "test@example.invalid" },
329 });
330 await git.writeRef({ fs: remote, dir: "/repo", ref: "main", value: incoming, force: true });
331 t.mock.method(git, "listServerRefs", async () => [{ ref: "refs/heads/main", oid: incoming }]);
332 t.mock.method(git, "clone", async (options: Parameters<typeof git.clone>[0]) => {
333 (options.fs as MemoryFS).entries = structuredClone(remote.entries);
334 });
335 const beforeIntake = rows();
336 const originalIngest = EngineProject.prototype.ingest;
337 const failedIngest = t.mock.method(
338 EngineProject.prototype,
339 "ingest",
340 function (this: EngineProject, ...args: Parameters<EngineProject["ingest"]>) {
341 originalIngest.apply(this, args);
342 throw Error("injected after Git intake");
343 },
344 );
345 await assert.rejects(() => bound().gitSync(), /injected after Git intake/);
346 assert.deepEqual(rows(), beforeIntake);
347 assert.equal((await bound().out()).git.head, parent, "failed intake must not acknowledge the remote head");
348 failedIngest.mock.restore();
349 failGitAcknowledgement = true;
350 await assert.rejects(() => bound().gitSync(), /Git cursor persistence failure/);
351 const committedIntake = rows();
352 assert.equal((await bound().out()).version, 3);
353 assert.equal((await bound().out()).git.head, parent);
354 const intake = await bound().gitSync();
355 assert.deepEqual(rows(), committedIntake, "retry after cursor failure returns the atomic intake receipt");
356 assert.ok(intake);
357 assert.equal(intake?.head, incoming);
358 assert.equal(intake?.commits, 1);
359 assert.equal((intake.answer as { landed: boolean }).landed, true, JSON.stringify(intake));
360 const imported = await call("file", undefined, { path: "a.txt", version: "3" });
361 assert.equal(imported.status, 200);
362 assert.match(JSON.stringify(imported.body), /From Git/);
363 const afterIntake = rows();
364 assert.equal(await bound().gitSync(), null);
365 assert.deepEqual(rows(), afterIntake, "cold intake does not apply the same commit twice");
366});
368for (const disk of [false, true]) {
369 test(`Git refusal permits a later fixing commit with disk mode ${disk}`, async (t) => {
370 const storage = memoryStorage();
371 t.after(() => storage.db.close());
372 const values = new Map<string, unknown>();
373 const context = {
374 id: { toString: () => "refusal" },
375 storage: {
376 ...storage,
377 get: async (key: string) => values.get(key),
378 put: async (key: string | Record<string, unknown>, value?: unknown) => {
379 if (typeof key === "string") values.set(key, value);
380 else for (const [k, v] of Object.entries(key)) values.set(k, v);
381 },
382 getAlarm: async () => null,
383 setAlarm: async () => {},
384 },
385 };
386 const artifacts = {
387 get: async () => ({
388 info: async () => ({ remote: "https://artifacts.invalid/refusal" }),
389 createToken: async () => ({ plaintext: "invented-test-token" }),
390 [Symbol.dispose]() {},
391 }),
392 };
393 const object = () =>
394 new ProjectObject(context as never, { ABSO_DISK_FIRST: disk ? "on" : "off", ARTIFACTS: artifacts } as never);
395 const call = async (op: string, body: unknown) => {
396 for (let page = 0; page < 100; page++) {
397 const result = await object().call("refusal", op, undefined, body);
398 if (result.status !== 503) return result;
399 }
400 throw Error("preparation did not finish");
401 };
402 assert.equal((await call("init", { files: { "a.txt": "original\n" } })).status, 200);
403 assert.equal((await call("status", {})).status, 200);
404 const remote = new MemoryFS();
405 await git.init({ fs: remote, dir: "/repo", defaultBranch: "main" });
406 const commit = async (files: Record<string, string>, message: string, parent: string[]) => {
407 const entries = [];
408 for (const [path, text] of Object.entries(files))
409 entries.push({
410 mode: "100644",
411 path,
412 type: "blob" as const,
413 oid: await git.writeBlob({ fs: remote, dir: "/repo", blob: new TextEncoder().encode(text) }),
414 });
415 const tree = await git.writeTree({ fs: remote, dir: "/repo", tree: entries });
416 const oid = await git.commit({
417 fs: remote,
418 dir: "/repo",
419 tree,
420 parent,
421 message,
422 author: { name: "Git writer", email: "test@example.invalid" },
423 });
424 await git.writeRef({ fs: remote, dir: "/repo", ref: "main", value: oid, force: true });
425 return oid;
426 };
427 const base = await commit({ "a.txt": "original\n" }, "Initial\n\nabso-version: 0", []);
428 values.set("git:head", base);
429 let head = await commit({ "A.TXT": "clash\n", "a.txt": "original\n" }, "Refused", [base]);
430 t.mock.method(git, "listServerRefs", async () => [{ ref: "refs/heads/main", oid: head }]);
431 t.mock.method(git, "clone", async (options: Parameters<typeof git.clone>[0]) => {
432 (options.fs as MemoryFS).entries = structuredClone(remote.entries);
433 });
434 const refused = await object().gitSync();
435 assert.ok(refused);
436 assert.match(JSON.stringify(refused.answer), /one file|clash/i);
437 assert.equal(values.get("git:head"), head);
438 assert.equal(await object().gitSync(), null);
439 head = await commit({ "a.txt": "fixed\n" }, "Fixed", [head]);
440 const fixed = await object().gitSync();
441 assert.ok(fixed);
442 assert.equal((fixed.answer as { landed: boolean }).landed, true, JSON.stringify(fixed));
443 assert.equal(values.get("git:head"), head);
444 assert.match(
445 JSON.stringify((await call("file", { path: "a.txt", version: String((await object().out()).version) })).body),
446 /fixed/,
447 );
448 });