import assert from "node:assert/strict"; import { test } from "node:test"; import { agentActor } from "../identity.ts"; import { Policy } from "../policy.ts"; import { agentSessions, type Answer } from "../sessions.ts"; import { d1, migrated } from "./d1.ts"; const ORIGIN = "https://refs.test"; function sessions(clientSession: string) { return sessionsWithDb(clientSession).agent; } function sessionsWithDb(clientSession: string) { 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@refs.test', 'Aman', '', 0); INSERT INTO memberships (namespace_id, user_id, role, created_at) VALUES ('ns', 'u1', 'owner', 0)"); sqlite.exec("INSERT INTO repos (id, namespace_id, name, visibility, artifacts_name, creator_id, created_at) VALUES ('r1', 'ns', 'demo', 'private', 'demo', 'u1', 0)"); sqlite.exec("INSERT INTO tasks (id, repo_id, number, title, author_id, created_at, updated_at) VALUES (1, 'r1', 7, 'Do it', 'u1', 0, 0)"); return { sqlite, agent: agentSessions({ DB: d1(sqlite) } as Env, { waitUntil() {} }, "u1", "mcp-1", "claude-code", ORIGIN, clientSession) }; } test("connect and take keep the token out of the text for the credential helper, and in it for clients without one", async () => { for (const credentials of ["helper", undefined]) { const agent = sessions(`client-${credentials}`); const connected = (await agent.connect({ repo: "refs/demo", credentials })) as Answer; const taken = await agent.take({ branch: "fix-login" }, credentials); const released = await agent.release(); for (const answer of [connected, taken]) { assert.match(answer.refs!.token!, /^refs_agent_/); assert.equal(answer.refs!.remote, `${ORIGIN}/refs/demo.git`); assert.equal(answer.text.includes(answer.refs!.token!), credentials === undefined); } assert.notEqual(taken.refs!.token, connected.refs!.token); assert.match(released, /still pushes as this session/); assert.equal(/refs_agent_|extraHeader/.test(connected.text + taken.text + released), credentials === undefined); } }); test("refs_take hands a session a named branch or a pull request's branch, and never the default branch", async () => { const agent = sessions("client-take"); await agent.connect({ repo: "refs/demo", credentials: "helper" }); assert.match((await agent.take({ branch: "agent/fix-login" }, "helper")).text, /^You took branch agent\/fix-login\. You may push only agent\/fix-login\./); assert.match(await agent.status(), /on branch agent\/fix-login\.$/); assert.match(await agent.release(), /^Released branch agent\/fix-login\./); assert.match(await agent.status(), /, idle\.$/); for (const [target, problem] of [ [{ branch: "main" }, /default branch/], [{ branch: "a..b" }, /not a valid branch name/], [{ pull: 1, branch: "x" }, /exactly one/], [{}, /exactly one/], [{ pull: 9 }, /No pull request #9/], ] as const) await assert.rejects(agent.take(target, "helper"), problem); }); test("refs_take on a pull request takes its head branch", async () => { for (const head of ["fix-login", "tasks/7"]) { const { agent, sqlite } = sessionsWithDb(`client-pull-${head}`); sqlite.prepare("INSERT INTO pulls (id, repo_id, number, title, author_id, base_ref, head_ref, created_at, updated_at) VALUES (1, 'r1', 1, 'Fix login', 'u1', 'main', ?, 0, 0)").run(head); await agent.connect({ repo: "refs/demo", credentials: "helper" }); assert.equal((await agent.take({ pull: 1 }, "helper")).text.split("\n")[0], `You took pull request #1: Fix login, on branch ${head}. You may push only ${head}.`); assert.deepEqual({ ...sqlite.prepare("SELECT branch FROM agent_sessions").get() }, { branch: head }); } }); test("an agent sees the pull requests of its branch, and no others, and reads tasks like its human", () => { const row = { id: "s1", runtime: "claude-code", expires_at: 2 ** 31, repo_id: "r1", repo_name: "refs/demo", user_id: "u1", email: "a@refs.test", name: "Aman" }; const onBranch = new Policy(agentActor({ ...row, branch: "fix-login" }), "owner"); const idle = new Policy(agentActor({ ...row, branch: null }), "owner"); assert.equal(onBranch.canOpenPull("refs/demo", { head: "fix-login" }), true); assert.equal(onBranch.canOpenPull("refs/demo", { head: "other" }), false); assert.equal(onBranch.canOpenPull("refs/other", { head: "fix-login" }), false); assert.equal(idle.canOpenPull("refs/demo", { head: "fix-login" }), false); assert.equal(idle.canOpenTask("refs/demo"), true); assert.equal(idle.canOpenTask("refs/other"), false); }); test("refs_open_pull needs a held branch", async () => { const agent = sessions("client-pull"); await agent.connect({ repo: "refs/demo" }); await assert.rejects(agent.openPull("Fix it", "", undefined), /Take a branch/); await agent.take({ branch: "fix-login" }); await assert.rejects(agent.openPull("", "", undefined), /title must be/); }); test("refs_view_pull needs a held branch with an open pull request", async () => { const agent = sessions("client-view"); await agent.connect({ repo: "refs/demo" }); await assert.rejects(agent.viewPull(), /Take a branch/); }); test("two refs_events calls at the same time hand an update to only one of them", async () => { const { sqlite, agent } = sessionsWithDb("racing"); await agent.connect({ repo: "refs/demo" }); const session = (sqlite.prepare("SELECT id FROM agent_sessions").get() as { id: string }).id; sqlite.prepare("INSERT INTO events (stream, kind, data, actor_kind, actor_id, created_at) VALUES ('repo:r1', 'session.instructed', ?, 'human', 'u1', 0)").run(JSON.stringify({ session, body: "Stop and write tests." })); const answers = await Promise.all([agent.events(), agent.events()]); assert.equal(answers.filter((answer) => answer.includes("Stop and write tests.")).length, 1); assert.doesNotMatch(await agent.events(), /Stop and write tests\./); }); test("refs_connect names the session outside the text, both for a new session and for a reconnect", async () => { const agent = sessions("reconnecting"); const first = (await agent.connect({ repo: "refs/demo" })) as Answer; const again = (await agent.connect({ repo: "refs/demo" })) as Answer; assert.match(first.session!, /^[0-9a-f-]{36}$/); assert.equal(again.session, first.session); assert.equal(again.refs, undefined); });