import assert from "node:assert/strict"; import { mock, test } from "node:test"; import { consumePushes, reconcilePushes, type PushMessage } from "../pushes.ts"; import { d1, migrated } from "./d1.ts"; const base = "b".repeat(40); const recorded = "1".repeat(40); const broken = "2".repeat(40); const merge = "3".repeat(40); const decisionId = "DEC-01JB7Q3M8Z4K2N6V9XWRT5HYCE"; const commits = new Map([ [base, { hash: base, parents: [], message: "Start" }], [recorded, { hash: recorded, parents: [base], message: `Decide\n\n\`\`\`decision\ndecision_id: ${decisionId}\ntask: 7\ndecision: "Queue pushes."\nreason:\n - waitUntil drops work\n\`\`\`\n` }], [broken, { hash: broken, parents: [recorded], message: "Break\n\n```decision\ndecision: x\n" }], [merge, { hash: merge, parents: [base, broken], message: "Merge" }], ]); function log(tip: string) { const seen: { hash: string; message: string }[] = []; for (let hash: string | undefined = tip; hash; hash = commits.get(hash)!.parents.at(-1)) seen.push(commits.get(hash)!); return seen; } function pkt(line: string): string { return (line.length + 4).toString(16).padStart(4, "0") + line; } function setup() { const sqlite = migrated(); sqlite.exec(` INSERT INTO namespaces (id, slug, name, kind, created_at) VALUES ('ns', 'refs', 'refs', 'org', 0); INSERT INTO users (id, email, name, password_hash, created_at) VALUES ('u1', 'a@x', 'Aman', 'h', 0); INSERT INTO memberships (namespace_id, user_id, role, created_at) VALUES ('ns', 'u1', 'owner', 0); INSERT INTO repos (id, namespace_id, name, visibility, artifacts_name, creator_id, created_at) VALUES ('repo', 'ns', 'refs', 'private', 'refs-art', 'u1', 0); INSERT INTO tasks (id, repo_id, number, title, author_id, created_at, updated_at) VALUES (1, 'repo', 7, 't', 'u1', 0, 0); INSERT INTO agent_sessions (id, token_hash, user_id, repo_id, runtime, created_at, expires_at, ended_at) VALUES ('s1', 'th', 'u1', 'repo', 'claude-code', 0, 1, 1); INSERT INTO pulls (id, repo_id, number, title, author_id, base_ref, head_ref, created_at, updated_at) VALUES (1, 'repo', 1, 't', 'u1', 'main', 'tasks/7', 0, 0); `); let failures = 0; const ci = { reads: [] as unknown[], down: false }; const handle = { readFile: async (query: unknown) => { if (ci.down) throw new Error("ci down"); ci.reads.push(query); return null; }, log: async ({ ref }: { ref: string }) => log(ref === "main" ? merge : ref), readCommit: async (hash: string) => commits.get(hash) ?? null, info: async () => ({ remote: "https://artifacts.test/refs-art" }), createToken: async () => ({ plaintext: "t" }), [Symbol.dispose]() {}, }; const env = { DB: d1(sqlite), ARTIFACTS: { get: async () => { if (failures-- > 0) throw new Error("Artifacts unavailable"); return handle; }, }, } as unknown as Env; return { sqlite, env, ci, failNext: (count: number) => (failures = count) }; } async function deliver(env: Env, body: PushMessage, attempts = 1, ctx: Pick = { waitUntil() {} }): Promise<"ack" | "retry"> { let outcome: "ack" | "retry" | undefined; const message = { body, attempts, ack: () => (outcome = "ack"), retry: () => (outcome = "retry") }; await consumePushes({ queue: "refs-pushes", messages: [message] } as unknown as MessageBatch, env, ctx); return outcome!; } const push: PushMessage = { repoId: "repo", actor: { kind: "agent", person: "u1", session: "s1" }, updates: [{ ref: "refs/heads/main", from: base, to: merge }], at: 100 }; mock.method(globalThis, "fetch", async () => new Response(pkt(`${merge} refs/heads/main\n`) + pkt(`${broken} refs/heads/tasks/7\n`) + "0000")); function outcome(sqlite: ReturnType) { const count = (sql: string) => (sqlite.prepare(sql).get() as { n: number }).n; return { pushed: count("SELECT count(*) AS n FROM events WHERE kind = 'repo.pushed' AND session_id = 's1'"), merged: count("SELECT count(*) AS n FROM pulls WHERE status = 'merged'"), mergedEvents: count("SELECT count(*) AS n FROM events WHERE kind = 'pull.merged'"), decisions: count(`SELECT count(*) AS n FROM decisions WHERE id = '${decisionId}' AND commit_sha = '${recorded}'`), problems: count("SELECT count(*) AS n FROM events WHERE kind = 'session.problem'"), }; } const once = { pushed: 1, merged: 1, mergedEvents: 1, decisions: 1, problems: 0 }; test("a push delivered twice, by a session that has since ended, has its consequences once", async () => { const { sqlite, env } = setup(); assert.equal(await deliver(env, push), "ack"); assert.equal(await deliver(env, push), "ack"); assert.deepEqual(outcome(sqlite), once); }); test("a push asks CI for the pipeline at its branch tip, and a CI failure does not fail the push", async () => { const { sqlite, env, ci } = setup(); assert.equal(await deliver(env, push), "ack"); assert.deepEqual(ci.reads, [{ ref: merge, path: ".refs/ci.yml" }]); ci.down = true; const original = console.error; console.error = () => undefined; try { assert.equal(await deliver(env, { ...push, at: 200 }), "ack"); } finally { console.error = original; } assert.equal(outcome(sqlite).merged, 1); }); test("a push whose processing fails is retried until the pull request is merged and its decisions indexed", async () => { const { sqlite, env, failNext } = setup(); failNext(1); assert.equal(await deliver(env, push), "retry"); assert.equal(await deliver(env, push, 2), "ack"); assert.deepEqual(outcome(sqlite), once); }); test("a push is indexed under the session that pushed it, even after the session ended", async () => { const { sqlite, env } = setup(); assert.equal(await deliver(env, push), "ack"); assert.deepEqual({ ...sqlite.prepare("SELECT session_id FROM decisions").get() }, { session_id: "s1" }); assert.deepEqual(outcome(sqlite), once); }); test("a human push to any branch indexes its decisions, with no session", async () => { const { sqlite, env } = setup(); const human: PushMessage = { repoId: "repo", actor: { kind: "human", person: "u1", via: "session" }, updates: [{ ref: "refs/heads/fix-queue", from: base, to: broken }], at: 100 }; assert.equal(await deliver(env, human), "ack"); assert.deepEqual({ ...sqlite.prepare("SELECT session_id FROM decisions").get() }, { session_id: null }); }); test("a merge into the default branch changes no task, even when the pull request names one with a closing keyword", async () => { const { sqlite, env } = setup(); sqlite.exec("UPDATE pulls SET body = 'Closes #7'"); assert.equal(await deliver(env, push), "ack"); assert.equal(count(sqlite, "SELECT count(*) AS n FROM pulls WHERE status = 'merged'"), 1); assert.equal(count(sqlite, "SELECT count(*) AS n FROM tasks WHERE status = 'closed'"), 0); assert.equal(count(sqlite, "SELECT count(*) AS n FROM events WHERE kind = 'task.closed'"), 0); }); function sweepable(seeded: boolean) { const { sqlite, env } = setup(); const sent: PushMessage[] = []; Object.assign(env, { PUSHES: { sendBatch: async (messages: { body: PushMessage }[]) => sent.push(...messages.map((message) => message.body)) } }); if (seeded) sqlite.exec(`UPDATE repos SET tips_checked_at = 0; INSERT INTO ref_tips (repo_id, ref, sha, seen_at) VALUES ('repo', 'refs/heads/main', '${base}', 0), ('repo', 'refs/heads/tasks/7', '${base}', 0)`); return { sqlite, env, sent }; } const count = (sqlite: ReturnType, sql: string) => (sqlite.prepare(sql).get() as { n: number }).n; test("pushes whose messages were lost are found by the sweep and processed once, as refs", async () => { const { sqlite, env, sent } = sweepable(true); await reconcilePushes(env); assert.deepEqual( sent.map((message) => [message.actor, message.updates]), [ [{ kind: "system" }, [{ ref: "refs/heads/main", from: base, to: merge }]], [{ kind: "system" }, [{ ref: "refs/heads/tasks/7", from: base, to: broken }]], ], ); for (const message of sent) assert.equal(await deliver(env, message), "ack"); assert.equal(await deliver(env, push), "ack"); assert.equal(count(sqlite, "SELECT count(*) AS n FROM events WHERE kind = 'repo.pushed' AND actor_id = 'refs'"), 2); assert.equal(count(sqlite, "SELECT count(*) AS n FROM events WHERE kind = 'repo.pushed'"), 2); assert.deepEqual({ ...outcome(sqlite), pushed: 1 }, once); assert.equal(count(sqlite, `SELECT count(*) AS n FROM decisions WHERE id = '${decisionId}' AND session_id IS NULL`), 1); sent.length = 0; await reconcilePushes(env); assert.deepEqual(sent, []); }); test("the first sweep of a repository records its tips without replaying them", async () => { const { sqlite, env, sent } = sweepable(false); await reconcilePushes(env); assert.deepEqual(sent, []); assert.deepEqual( sqlite.prepare("SELECT ref, sha FROM ref_tips ORDER BY ref").all().map((row) => ({ ...row })), [ { ref: "refs/heads/main", sha: merge }, { ref: "refs/heads/tasks/7", sha: broken }, ], ); assert.equal(count(sqlite, "SELECT count(*) AS n FROM events"), 0); await reconcilePushes(env); assert.deepEqual(sent, []); }); test("a push processed after a later one does not move its ref back", async () => { const { sqlite, env } = sweepable(true); assert.equal(await deliver(env, { ...push, at: 200 }), "ack"); assert.equal(await deliver(env, { ...push, actor: { kind: "system" }, updates: [{ ref: "refs/heads/main", from: null, to: base }], at: 150 }), "ack"); assert.deepEqual({ ...sqlite.prepare("SELECT sha FROM ref_tips WHERE ref = 'refs/heads/main'").get() }, { sha: merge }); });