Files
crosscode-platform/apps/agent/tests/loop.test.ts
T
joshuaandClaude Opus 5.5 1eeaf4d94f Agent 1.0.0: polls the Hub for signed jobs, runs crosscode, sends reports and stats
apps/agent (docs/AGENT-1.0-PLAN.md §3-4, §10): listens on nothing; checks
every job (pinned Hub key, server, time window, replays for 90 days,
type per mode, strict arguments) before running crosscode with an
argument array; opens the sealed config into a root-only file only for
the job; redacts log lines; keeps unsent reports in an outbox; encrypts
exports before upload; check-ports on the central server (read-only);
self-update with automatic revert. One bundled dist/cli.js, a systemd
unit and the install script that joins a server with a one-time token.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-17 12:58:08 +02:00

113 lines
5.1 KiB
TypeScript

import fs from "node:fs";
import path from "node:path";
import { agent } from "@crosscode/contracts";
import { decryptExport } from "@crosscode/contracts/signing";
import { HubRequestError, type HubClient } from "../src/hub";
import { Agent } from "../src/loop";
import type { RunResult } from "../src/runner";
import { SeenJobs } from "../src/verify";
import { config, job, NOW, serverKeys, tempState } from "./helpers";
const state = tempState();
function fakeHub(jobs: unknown[]) {
const posts: { path: string; body: unknown }[] = [];
const puts: { path: string; body: Uint8Array }[] = [];
let down = false;
const hub: HubClient = {
async post(p, body) {
if (down) throw new HubRequestError("down", 0, "HUB_UNREACHABLE");
posts.push({ path: p, body });
if (p === "/api/agent/v1/poll") return { jobs: jobs.splice(0), pollSeconds: 30 };
return null;
},
async put(p, body) {
puts.push({ path: p, body });
return null;
},
};
return { hub, posts, puts, setDown: (v: boolean) => { down = v; } };
}
const ok = (over: Partial<RunResult> = {}): RunResult => ({ status: "succeeded", steps: [{ name: "x", startedAt: NOW.toISOString(), finishedAt: NOW.toISOString(), outcome: "ok" }], result: {}, log: ["==> done"], startedAt: NOW.toISOString(), finishedAt: NOW.toISOString(), ...over });
type Run = (args: string[], job: agent.AgentJob) => Promise<RunResult>;
function make(jobs: unknown[], run: jest.Mock<ReturnType<Run>, Parameters<Run>> = jest.fn<ReturnType<Run>, Parameters<Run>>(async () => ok())) {
const h = fakeHub(jobs);
const a = new Agent({ config, keys: { ed25519Pem: serverKeys.ed25519.privateKeyPem, x25519Pem: serverKeys.x25519.privateKeyPem }, hub: h.hub, seen: new SeenJobs(path.join(state, `seen-${Math.random()}.json`)), run, now: () => NOW });
return { a, run, ...h };
}
const reports = (posts: { path: string; body: unknown }[]) => posts.filter((p) => p.path === "/api/agent/v1/report").map((p) => p.body as agent.AgentReport);
describe("the agent loop", () => {
it("runs a valid job once and reports it", async () => {
const j = job();
const { a, run, posts } = make([j, j]);
await a.pollOnce();
expect(run).toHaveBeenCalledTimes(1);
expect(run.mock.calls[0]).toEqual([["deploy", "hope", "events", "--version", "events@2.4.1"], expect.objectContaining({ id: j.id })]);
// The second copy is a replay: refused quietly (the first one's report already went).
const rs = reports(posts);
expect(rs.map((r) => [r.jobId, r.status])).toEqual([[j.id, "succeeded"]]);
expect(agent.agentReportSchema.safeParse(rs[0]).success).toBe(true);
});
it("reports refused and expired jobs without running them", async () => {
const forged = { ...job(), signature: "A".repeat(86) };
const late = job({ expiresAt: "2026-11-20T12:01:00.000Z", notBefore: "2026-11-20T11:00:00.000Z" });
const { a, run, posts } = make([forged, late]);
await a.pollOnce();
expect(run).not.toHaveBeenCalled();
expect(reports(posts).map((r) => r.status)).toEqual(["refused", "expired"]);
});
it("keeps a report it can't send and sends it on the next poll", async () => {
const j = job();
let setDownLater: (v: boolean) => void = () => {};
const { a, posts, setDown } = make([j], jest.fn<ReturnType<Run>, Parameters<Run>>(async () => { setDownLater(true); return ok(); }));
setDownLater = setDown;
await a.pollOnce();
expect(reports(posts)).toEqual([]);
expect(fs.readdirSync(path.join(state, "outbox"))).toContain(`${j.id}.json`);
setDown(false);
await a.pollOnce();
expect(reports(posts).map((r) => r.jobId)).toEqual([j.id]);
expect(fs.readdirSync(path.join(state, "outbox"))).toEqual([]);
});
it("backs off while the Hub is unreachable", async () => {
const { a, setDown } = make([]);
setDown(true);
expect(await a.pollOnce()).toBe(60);
expect(await a.pollOnce()).toBe(120);
setDown(false);
expect(await a.pollOnce()).toBe(30);
});
it("export: encrypts the ZIP, uploads it, and only the report carries the key", async () => {
const j = job({ type: "export", args: { church: "hope", exportId: "exp_abcdefgh" } });
const run = jest.fn<ReturnType<Run>, Parameters<Run>>(async (args: string[]) => {
fs.writeFileSync(args[3]!, "PK zip bytes");
return ok({ result: { file: args[3], bytes: 12 } });
});
const { a, puts, posts } = make([j], run);
await a.pollOnce();
expect(puts).toHaveLength(1);
expect(puts[0]!.path).toBe("/api/agent/v1/exports/exp_abcdefgh");
const r = reports(posts)[0]!;
expect(r.status).toBe("succeeded");
const key = r.result.key as string;
expect(decryptExport(puts[0]!.body, key).toString()).toBe("PK zip bytes");
expect(Buffer.from(puts[0]!.body).includes(Buffer.from("PK zip"))).toBe(false);
expect(fs.readdirSync(path.join(state, "exports"))).toEqual([]);
});
it("a job that throws is reported as failed", async () => {
const { a, posts } = make([job()], jest.fn<ReturnType<Run>, Parameters<Run>>(async () => { throw new Error("boom"); }));
await a.pollOnce();
expect(reports(posts)[0]).toMatchObject({ status: "failed", message: "boom" });
});
});