import assert from "node:assert/strict"; import type { DatabaseSync } from "node:sqlite"; import { test } from "node:test"; import { sha256 } from "../auth.ts"; import type { Actor } from "../contract/actor.ts"; import { resolveActor } from "../identity.ts"; import { deliverMentions, onPull } from "../mentions.ts"; import { endGrantSessions } from "../handles/account.ts"; import { agentSessions } from "../sessions.ts"; import { d1, migrated } from "./d1.ts"; const SESSION = "11111111-2222-3333-4444-555555555555"; function counting(sqlite: DatabaseSync, table: string): () => number { sqlite.exec(`CREATE TABLE writes (n INTEGER); CREATE TRIGGER count_writes AFTER UPDATE ON ${table} BEGIN INSERT INTO writes VALUES (1); END;`); return () => (sqlite.prepare("SELECT count(*) AS n FROM writes").get() as { n: number }).n; } function seeded(): DatabaseSync { const sqlite = migrated(); const at = Math.floor(Date.now() / 1000); 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', 'x', 0); INSERT INTO memberships (namespace_id, user_id, role, created_at) VALUES ('ns', 'u1', 'owner', 0)`); sqlite .prepare("INSERT INTO agent_sessions (id, token_hash, user_id, repo_id, runtime, created_at, expires_at, last_seen_at, mcp_session, machine) VALUES (?, 'h', 'u1', 'repo', 'claude-code', ?, ?, NULL, 'mcp', 'laptop')") .run(SESSION, at, at + 3600); return sqlite; } test("consecutive MCP calls within a minute write last_seen_at once", async () => { const sqlite = seeded(); const writes = counting(sqlite, "agent_sessions"); const sessions = agentSessions({ DB: d1(sqlite) } as Env, { waitUntil() {} }, "u1", "mcp", "claude-code", "https://x"); for (let i = 0; i < 5; i++) await sessions.touch(); assert.equal(writes(), 1); }); test("a PAT used for several git requests within a minute writes last_used_at once", async () => { const sqlite = seeded(); sqlite.prepare("INSERT INTO access_tokens (id, user_id, name, token_hash, created_at) VALUES ('t1', 'u1', 'cli', ?, 0)").run(await sha256("refs_pat")); const writes = counting(sqlite, "access_tokens"); for (let i = 0; i < 5; i++) { const pending: Promise[] = []; const ctx = { waitUntil: (promise: Promise) => pending.push(promise) } as unknown as ExecutionContext; const { actor } = await resolveActor(d1(sqlite), ctx, new Request("https://x/repo.git/info/refs", { headers: { authorization: "Bearer refs_pat" } })); assert.equal(actor.kind, "human"); await Promise.all(pending); } assert.equal(writes(), 1); }); test("the refs CLI sign-in works as the human for git only when its grant has the git scope", async () => { const sqlite = seeded(); const ctx = { waitUntil() {} } as unknown as ExecutionContext; const request = new Request("https://x/repo.git/info/refs", { headers: { authorization: "Bearer u1:g1:secret" } }); const oauth = (scope: string[]) => ({ unwrapToken: async () => ({ grant: { scope, props: { userId: "u1" } } }) }) as never; const withGit = await resolveActor(d1(sqlite), ctx, request, oauth(["agents", "git"])); assert.deepEqual([withGit.actor.kind, withGit.actor.kind === "human" && withGit.actor.via], ["human", "cli"]); assert.equal((await resolveActor(d1(sqlite), ctx, request, oauth(["agents"]))).badCredentials, true); assert.equal((await resolveActor(d1(sqlite), ctx, request)).badCredentials, true); }); test("a mention asks the hub, not the machines projection, whether the machine is connected", async () => { const sqlite = seeded(); sqlite.exec("INSERT INTO machines (user_id, name, runtimes, version, connected, last_seen_at) VALUES ('u1', 'laptop', '[]', '1', 1, 0)"); sqlite.exec("INSERT INTO repos (id, namespace_id, name, visibility, artifacts_name, creator_id, created_at) VALUES ('repo', 'ns', 'refs', 'public', 'refs', 'u1', 0)"); const dispatched: string[] = []; const hub = { connected: async () => [] as string[], dispatch: async (machine: string) => (dispatched.push(machine), true) }; const env = { DB: d1(sqlite), USER_HUB: { idFromName: (name: string) => name, get: () => hub } } as unknown as Env; const actor: Actor = { kind: "human", person: { id: "u1", name: "Aman" }, via: "session" } as never; const pull = onPull({ repo_id: "repo", number: 7, title: "t", head_ref: "fix-login" }); await deliverMentions(env, { waitUntil() {} }, actor, pull, `@agent/${SESSION} look`, null); assert.deepEqual(dispatched, []); const { data } = sqlite.prepare("SELECT data FROM events WHERE kind = 'agent.mentioned'").get() as { data: string }; assert.equal(JSON.parse(data).run, false); hub.connected = async () => ["laptop"]; await deliverMentions(env, { waitUntil() {} }, actor, pull, `@agent/${SESSION} again`, null); assert.deepEqual(dispatched, ["laptop"]); }); test("a hub that fails after the mention is saved does not fail the comment that made it", async () => { const sqlite = seeded(); sqlite.exec("INSERT INTO repos (id, namespace_id, name, visibility, artifacts_name, creator_id, created_at) VALUES ('repo', 'ns', 'refs', 'public', 'refs', 'u1', 0)"); const hub = { connected: async () => ["laptop"], dispatch: async () => Promise.reject(new Error("hub evicted")) }; const env = { DB: d1(sqlite), USER_HUB: { idFromName: (name: string) => name, get: () => hub } } as unknown as Env; const actor: Actor = { kind: "human", person: { id: "u1", name: "Aman" }, via: "session" } as never; const pull = onPull({ repo_id: "repo", number: 7, title: "t", head_ref: "fix-login" }); const logged = console.error; console.error = () => {}; try { await deliverMentions(env, { waitUntil() {} }, actor, pull, `@agent/${SESSION} look`, null); } finally { console.error = logged; } assert.equal((sqlite.prepare("SELECT count(*) AS n FROM events WHERE kind = 'agent.mentioned'").get() as { n: number }).n, 1); }); test("assigning on a pull request hands the agent its branch, never the default branch", async () => { for (const [head, assigned] of [["queue-pushes", true], ["main", false]] as const) { const sqlite = seeded(); sqlite.exec("INSERT INTO repos (id, namespace_id, name, visibility, artifacts_name, creator_id, created_at) VALUES ('repo', 'ns', 'refs', 'public', 'refs', 'u1', 0)"); const env = { DB: d1(sqlite), USER_HUB: { idFromName: (name: string) => name, get: () => ({ connected: async () => [] }) } } as unknown as Env; const actor: Actor = { kind: "human", person: { id: "u1", name: "Aman" }, via: "session" } as never; await deliverMentions(env, { waitUntil() {} }, actor, onPull({ repo_id: "repo", number: 3, title: "Queue pushes", head_ref: head }), `@agent/${SESSION} why?`, 12, { assign: true }); const { data } = sqlite.prepare("SELECT data FROM events WHERE kind = 'agent.mentioned'").get() as { data: string }; assert.deepEqual(JSON.parse(data), { session: SESSION, title: "Queue pushes", comment: 12, body: `@agent/${SESSION} why?`, assigned, run: false, pull: 3 }); assert.deepEqual({ ...sqlite.prepare("SELECT branch FROM agent_sessions WHERE id = ?").get(SESSION) }, { branch: assigned ? head : null }); } }); test("the SessionEnd hook takes the conversation's session offline without ending it", async () => { const sqlite = seeded(); sqlite.exec("INSERT INTO repos (id, namespace_id, name, visibility, artifacts_name, creator_id, created_at) VALUES ('repo', 'ns', 'refs', 'public', 'refs', 'u1', 0)"); sqlite.prepare("UPDATE agent_sessions SET client_session = 'conv' WHERE id = ?").run(SESSION); const sessions = agentSessions({ DB: d1(sqlite) } as Env, { waitUntil() {} }, "u1", "hook", "claude-code", "https://x", "conv"); assert.equal(await sessions.events("SessionEnd"), ""); const row = sqlite.prepare("SELECT mcp_session, ended_at FROM agent_sessions WHERE id = ?").get(SESSION) as { mcp_session: string | null; ended_at: number | null }; assert.deepEqual({ ...row }, { mcp_session: null, ended_at: null }); }); test("revoking one agent grant ends only the sessions that grant started, and sessions with no recorded grant", async () => { const sqlite = seeded(); const at = Math.floor(Date.now() / 1000); const insert = sqlite.prepare("INSERT INTO agent_sessions (id, token_hash, user_id, repo_id, runtime, created_at, expires_at, grant_id) VALUES (?, ?, 'u1', 'repo', 'claude-code', ?, ?, ?)"); insert.run("revoked", "h1", at, at + 3600, "g1"); insert.run("kept", "h2", at, at + 3600, "g2"); await endGrantSessions(d1(sqlite), "u1", "g1", at); const ended = (id: string) => (sqlite.prepare("SELECT ended_at FROM agent_sessions WHERE id = ?").get(id) as { ended_at: number | null }).ended_at !== null; assert.equal(ended("revoked"), true); assert.equal(ended("kept"), false); assert.equal(ended(SESSION), true); });