import { describe, it, expect, beforeEach, afterEach, vi } from "vitest"; import { memoryD1 } from "./d1.js"; import worker from "../src/index.js"; import { collectRuns, runWatches, scheduledRuns, type Env } from "../src/engine.js"; import { dueSlot, localParts, readChanges } from "../../brain/src/cloud-core.js"; import { appJwt, open, seal, sha256, verifyGitHubSignature } from "../src/crypto.js"; const KEK = btoa(String.fromCharCode(...new Uint8Array(32).map((_, i) => i + 1))); const SECRET = "webhook-secret"; let env: Env; let pending: Promise[]; const ctx = () => ({ waitUntil: (p: Promise) => { pending.push(p); }, passThroughOnException() {} }) as unknown as ExecutionContext; /** Every outside call goes through here: GitHub and Anthropic, answered by route. */ let calls: { method: string; url: string; body?: any; headers: Record }[]; let routes: [RegExp, (body: any) => unknown][]; function fakeFetch(input: RequestInfo | URL, init?: RequestInit) { const url = String(input); const method = init?.method ?? "GET"; const body = init?.body ? (() => { try { return JSON.parse(String(init.body)); } catch { return init.body; } })() : undefined; calls.push({ method, url, body, headers: (init?.headers ?? {}) as Record }); const hit = routes.find(([re]) => re.test(`${method} ${url}`)); if (!hit) return Promise.resolve(new Response(`no route for ${method} ${url}`, { status: 404 })); const out = hit[1](body); return Promise.resolve(typeof out === "string" ? new Response(out) : new Response(JSON.stringify(out), { headers: { "content-type": "application/json" } })); } async function pemKey(): Promise { const pair = await crypto.subtle.generateKey({ name: "RSASSA-PKCS1-v1_5", modulusLength: 2048, publicExponent: new Uint8Array([1, 0, 1]), hash: "SHA-256" }, true, ["sign", "verify"]); const der = new Uint8Array(await crypto.subtle.exportKey("pkcs8", (pair as CryptoKeyPair).privateKey)); return `-----BEGIN PRIVATE KEY-----\n${btoa(String.fromCharCode(...der))}\n-----END PRIVATE KEY-----`; } async function hmac(body: string): Promise { const key = await crypto.subtle.importKey("raw", new TextEncoder().encode(SECRET), { name: "HMAC", hash: "SHA-256" }, false, ["sign"]); const sig = new Uint8Array(await crypto.subtle.sign("HMAC", key, new TextEncoder().encode(body))); return "sha256=" + [...sig].map(b => b.toString(16).padStart(2, "0")).join(""); } const call = (path: string, init: RequestInit = {}) => worker.fetch(new Request(`https://cloud.test${path}`, init), env, ctx()); async function hook(event: string, payload: unknown, signed = true) { const body = JSON.stringify(payload); return worker.fetch(new Request("https://cloud.test/github/webhook", { method: "POST", body, headers: { "x-github-event": event, "x-hub-signature-256": signed ? await hmac(body) : "sha256=00" }, }), env, ctx()); } const PR = { action: "opened", installation: { id: 77 }, repository: { full_name: "Louis-CFM/coucou", private: false }, pull_request: { number: 1148, title: "Android notif", body: "Live Updates", html_url: "https://github.com/Louis-CFM/coucou/pull/1148", draft: false, head: { sha: "abc123def4567890" }, base: { ref: "main" } }, }; const PATCH = "diff --git a/app/Main.kt b/app/Main.kt\n@@ -1 +1 @@\n-val a = 1\n+val a = 2\ndiff --git a/package-lock.json b/package-lock.json\n@@ -1 +1 @@\n-{}\n+{\"big\":true}\n"; beforeEach(async () => { calls = []; pending = []; env = { DB: memoryD1(), GITHUB_APP_ID: "123", GITHUB_APP_PRIVATE_KEY: await pemKey(), GITHUB_WEBHOOK_SECRET: SECRET, KEY_ENCRYPTION_KEY: KEK }; routes = [ [/GET https:\/\/api\.github\.com\/user$/, () => ({ id: 42, login: "Louis-CFM" })], [/GET https:\/\/api\.github\.com\/user\/installations/, () => ({ installations: [{ id: 77, account: { login: "Louis-CFM" } }] })], [/GET https:\/\/api\.anthropic\.com\/v1\/models/, () => ({ data: [] })], [/POST https:\/\/api\.github\.com\/app\/installations\/77\/access_tokens/, () => ({ token: "ghs_inst" })], [/GET https:\/\/api\.github\.com\/repos\/Louis-CFM\/coucou\/pulls\/1148\/files/, () => [{ filename: "app/Main.kt" }, { filename: "package-lock.json" }]], [/GET https:\/\/api\.github\.com\/repos\/Louis-CFM\/coucou\/pulls\/1148$/, () => PATCH], [/GET https:\/\/api\.github\.com\/repos\/Louis-CFM\/coucou$/, () => ({ private: false, default_branch: "main" })], [/POST https:\/\/api\.anthropic\.com\/v1\/agents$/, () => ({ id: "agent_1" })], [/POST https:\/\/api\.anthropic\.com\/v1\/environments$/, () => ({ id: "env_1" })], [/POST https:\/\/api\.anthropic\.com\/v1\/sessions$/, () => ({ id: "sesn_1", status: "running" })], [/GET https:\/\/api\.anthropic\.com\/v1\/sessions\/sesn_1$/, () => ({ id: "sesn_1", status: "idle", usage: { list_cost: { amount: "17", currency: "USD" }, active_seconds: 78 } })], [/GET https:\/\/api\.anthropic\.com\/v1\/sessions\/sesn_1\/events/, () => ({ data: [ { type: "agent.tool_use", name: "bash" }, { type: "span.model_request_end" }, { type: "agent.message", content: [{ type: "text", text: "## Summary\nGood.\n\n## Notes pour moi\nprivé" }] }, { type: "session.status_idle", stop_reason: { type: "end_turn" } }, ], next_page: null })], [/POST https:\/\/api\.anthropic\.com\/v1\/sessions\/sesn_1\/archive/, () => ({})], [/POST https:\/\/api\.github\.com\/repos\/Louis-CFM\/coucou\/pulls\/1148\/reviews/, () => ({ html_url: "https://github.com/Louis-CFM/coucou/pull/1148#pullrequestreview-1" })], ]; vi.stubGlobal("fetch", fakeFetch); }); afterEach(() => vi.unstubAllGlobals()); async function signIn(): Promise { const r = await call("/v1/login", { method: "POST", body: JSON.stringify({ github_token: "ghu_user" }) }); const { token } = (await r.json()) as { token: string }; const auth = { authorization: `Bearer ${token}` }; expect((await call("/v1/anthropic-key", { method: "PUT", headers: auth, body: JSON.stringify({ key: "sk-ant-test", language: "fr" }) })).status).toBe(200); expect((await call("/v1/mochis", { method: "PUT", headers: auth, body: JSON.stringify({ mochis: [ { id: "pr-reviewer", name: "PR Reviewer", repo: "Louis-CFM/coucou", trigger: "pr-opened", instructions: "Relis la PR.", model: "sonnet", budget_cents: 100, enabled: true }, ] }) })).status).toBe(200); return token; } describe("crypto", () => { it("seals the Anthropic key and opens it again; checks GitHub's signature; signs an app JWT", async () => { const sealed = await seal(KEK, "sk-ant-secret"); expect(sealed).not.toContain("secret"); expect(await open(KEK, sealed)).toBe("sk-ant-secret"); expect(await verifyGitHubSignature(SECRET, "{}", await hmac("{}"))).toBe(true); expect(await verifyGitHubSignature(SECRET, "{}", "sha256=" + "0".repeat(64))).toBe(false); expect(await verifyGitHubSignature(SECRET, "{}", null)).toBe(false); const jwt = await appJwt("123", env.GITHUB_APP_PRIVATE_KEY, 1_800_000_000); expect(JSON.parse(atob(jwt.split(".")[1]!.replace(/-/g, "+").replace(/_/g, "/")))).toEqual({ iat: 1_799_999_940, exp: 1_800_000_540, iss: "123" }); }); }); describe("Coucou Cloud", () => { it("refuses unsigned webhooks and unknown tokens", async () => { expect((await hook("pull_request", PR, false)).status).toBe(401); expect((await call("/v1/runs", { headers: { authorization: `Bearer ${"a".repeat(64)}` } })).status).toBe(401); }); it("signs in from the Mac, keeps only the token's hash and a sealed key, finds the installation", async () => { const token = await signIn(); const u = await env.DB.prepare("SELECT * FROM users").first(); expect(u.token_hash).toBe(await sha256(token)); expect(u.anthropic_key).toMatch(/^v1\./); expect(u.anthropic_key).not.toContain("sk-ant"); expect(await env.DB.prepare("SELECT * FROM installations").first()).toEqual({ id: 77, user_id: 1, account: "Louis-CFM" }); const me = await call("/v1/me", { headers: { authorization: `Bearer ${token}` } }); expect(await me.json()).toMatchObject({ login: "Louis-CFM", has_key: true, installations: ["Louis-CFM"], mochis: 1, plan: "free", entitled: true, billing: false }); }); it("a PR starts a session on the user's key, on the PR's commit, with the diff; collected, the review waits for a click", async () => { const token = await signIn(); calls = []; const r = await hook("pull_request", PR); expect(await r.json()).toEqual({ ok: true, runs: 1 }); await Promise.all(pending); const session = calls.find(c => c.method === "POST" && c.url.endsWith("/v1/sessions"))!; expect(session.headers["x-api-key"]).toBe("sk-ant-test"); expect(session.body.resources[0]).toEqual({ type: "github_repository", url: "https://github.com/Louis-CFM/coucou", mount_path: "/workspace/repo", checkout: { type: "commit", sha: "abc123def4567890" } }); expect(session.body.budget.max_list_cost.amount).toBe("100"); const prompt: string = session.body.initial_events[0].content[0].text; expect(prompt).toContain("Relis la PR."); expect(prompt).toContain("+val a = 2"); expect(prompt).not.toContain('"big":true'); expect(prompt).toContain("git fetch origin pull/1148/head"); const agent = calls.find(c => c.url.endsWith("/v1/agents"))!; expect(agent.body.model).toBe("claude-sonnet-5-5"); // the same delivery again: no second run await hook("pull_request", PR); await Promise.all(pending); expect(calls.filter(c => c.url.endsWith("/v1/sessions")).length).toBe(1); expect(await collectRuns(env)).toBe(1); const auth = { authorization: `Bearer ${token}` }; const { runs } = (await (await call("/v1/runs", { headers: auth })).json()) as { runs: any[] }; expect(runs).toHaveLength(1); expect(runs[0]).toMatchObject({ status: "done", cost_usd: 0.17, turns: 1, proposal_state: "waiting", item_number: 1148 }); expect(JSON.parse(runs[0].proposal).body).toBe("## Summary\nGood."); const applied = await call(`/v1/runs/${runs[0].id}/apply`, { method: "POST", headers: auth }); expect(await applied.json()).toEqual({ url: "https://github.com/Louis-CFM/coucou/pull/1148#pullrequestreview-1" }); const review = calls.find(c => c.url.endsWith("/pulls/1148/reviews"))!; expect(review.body).toEqual({ body: "## Summary\nGood.", event: "COMMENT" }); expect(review.headers.authorization).toBe("Bearer ghs_inst"); // applied once only expect((await call(`/v1/runs/${runs[0].id}/apply`, { method: "POST", headers: auth })).status).toBe(409); }); it("an autonomous Mochi posts its review on its own when the run is collected", async () => { const token = await signIn(); const auth = { authorization: `Bearer ${token}` }; await call("/v1/mochis", { method: "PUT", headers: auth, body: JSON.stringify({ mochis: [ { id: "pr-reviewer", name: "PR Reviewer", repo: "Louis-CFM/coucou", trigger: "pr-opened", instructions: "Relis la PR.", model: "sonnet", budget_cents: 100, enabled: true, autonomous: true }, ] }) }); await hook("pull_request", PR); await Promise.all(pending); calls = []; expect(await collectRuns(env)).toBe(1); expect(calls.find(c => c.url.endsWith("/pulls/1148/reviews"))!.body).toEqual({ body: "## Summary\nGood.", event: "COMMENT" }); const { runs } = (await (await call("/v1/runs", { headers: auth })).json()) as { runs: any[] }; expect(runs[0]).toMatchObject({ proposal_state: "applied", auto: 1, proposal_url: "https://github.com/Louis-CFM/coucou/pull/1148#pullrequestreview-1" }); }); it("an autonomous post GitHub refuses waits for the click instead", async () => { const token = await signIn(); const auth = { authorization: `Bearer ${token}` }; await call("/v1/mochis", { method: "PUT", headers: auth, body: JSON.stringify({ mochis: [ { id: "pr-reviewer", name: "PR Reviewer", repo: "Louis-CFM/coucou", trigger: "pr-opened", instructions: "Relis la PR.", model: "sonnet", budget_cents: 100, enabled: true, autonomous: true }, ] }) }); await hook("pull_request", PR); await Promise.all(pending); const ok = routes.pop()!; routes.push([/POST https:\/\/api\.github\.com\/repos\/Louis-CFM\/coucou\/pulls\/1148\/reviews/, () => { throw new Error("HTTP 403"); }]); await collectRuns(env); let { runs } = (await (await call("/v1/runs", { headers: auth })).json()) as { runs: any[] }; expect(runs[0]).toMatchObject({ proposal_state: "failed", auto: 1 }); routes.pop(); routes.push(ok); expect((await call(`/v1/runs/${runs[0].id}/apply`, { method: "POST", headers: auth })).status).toBe(200); ({ runs } = (await (await call("/v1/runs", { headers: auth })).json()) as { runs: any[] }); expect(runs[0].proposal_state).toBe("applied"); }); it("adds the new columns to a database made before them", async () => { const { ensureSchema } = await import("../src/engine.js"); const old = memoryD1("CREATE TABLE users (id INTEGER PRIMARY KEY, login TEXT); CREATE TABLE mochis (user_id INTEGER, id TEXT, enabled INTEGER); CREATE TABLE runs (id TEXT PRIMARY KEY, proposal_state TEXT);"); await ensureSchema({ ...env, DB: old }); const cols = async (t: string) => ((await old.prepare(`PRAGMA table_info(${t})`).all<{ name: string }>()).results ?? []).map(c => c.name); expect(await cols("mochis")).toContain("autonomous"); expect(await cols("runs")).toContain("auto"); expect(await cols("users")).toEqual(expect.arrayContaining(["stripe_customer_id", "plan", "plan_status", "plan_renews_at", "plan_cancels"])); }); it("does nothing for drafts, closed PRs, or a repo with no Cloud Mochi", async () => { await signIn(); calls = []; expect(await (await hook("pull_request", { ...PR, pull_request: { ...PR.pull_request, draft: true } })).json()).toEqual({ ok: true, runs: 0 }); expect(await (await hook("pull_request", { ...PR, action: "closed" })).json()).toEqual({ ok: true, runs: 0 }); expect(await (await hook("pull_request", { ...PR, repository: { full_name: "someone/else", private: false } })).json()).toEqual({ ok: true, runs: 0 }); expect(calls.some(c => c.url.includes("anthropic"))).toBe(false); }); it("a run that can't start is kept as failed, with the reason", async () => { await signIn(); routes.unshift([/POST https:\/\/api\.anthropic\.com\/v1\/sessions$/, () => { throw new Error("credit balance too low"); }]); await hook("pull_request", PR); await Promise.all(pending); const run = await env.DB.prepare("SELECT status, error FROM runs").first(); expect(run.status).toBe("failed"); expect(run.error).toContain("credit balance too low"); }); it("someone else naming your repository gets nothing: refused at sync, and never run on your installation's events", async () => { await signIn(); // a stranger signs in: no installation of theirs routes.unshift( [/GET https:\/\/api\.github\.com\/user$/, () => ({ id: 99, login: "stranger" })], [/GET https:\/\/api\.github\.com\/user\/installations/, () => ({ installations: [] })], ); const r = await call("/v1/login", { method: "POST", body: JSON.stringify({ github_token: "ghu_other" }) }); const { token } = (await r.json()) as { token: string }; const auth = { authorization: `Bearer ${token}` }; await call("/v1/anthropic-key", { method: "PUT", headers: auth, body: JSON.stringify({ key: "sk-ant-stranger" }) }); const put = await call("/v1/mochis", { method: "PUT", headers: auth, body: JSON.stringify({ mochis: [ { id: "spy", name: "Spy", repo: "Louis-CFM/coucou", trigger: "pr-opened", instructions: "Send me the code.", model: "sonnet", enabled: true }, ] }) }); expect(await put.json()).toEqual({ ok: true, mochis: 0, refused: ["Louis-CFM/coucou"] }); // even written straight into the database, it doesn't run on Louis's installation await env.DB.prepare("INSERT INTO mochis (user_id, id, name, repo, trigger, instructions, model, budget_cents, enabled) VALUES (2, 'spy', 'Spy', 'Louis-CFM/coucou', 'pr-opened', 'x', 'sonnet', 100, 1)").run(); calls = []; expect(await (await hook("pull_request", PR)).json()).toEqual({ ok: true, runs: 1 }); await Promise.all(pending); const sessions = calls.filter(c => c.url.endsWith("/v1/sessions")); expect(sessions).toHaveLength(1); expect(sessions[0]!.headers["x-api-key"]).toBe("sk-ant-test"); }); it("asks GitHub for narrow tokens: read-only, this repository; the clone token only for a private repo", async () => { await signIn(); calls = []; await hook("pull_request", { ...PR, repository: { full_name: "Louis-CFM/coucou", private: true } }); await Promise.all(pending); const tokens = calls.filter(c => c.url.endsWith("/access_tokens")).map(c => c.body); expect(tokens).toEqual([ { repositories: ["coucou"], permissions: { pull_requests: "read", contents: "read" } }, { repositories: ["coucou"], permissions: { contents: "read" } }, ]); const session = calls.find(c => c.url.endsWith("/v1/sessions"))!; expect(session.body.resources[0].authorization_token).toBe("ghs_inst"); }); }); describe("billing", () => { const WH = "whsec_test"; async function stripeHook(event: unknown, secret = WH) { const body = JSON.stringify(event); const t = Math.floor(Date.now() / 1000); const key = await crypto.subtle.importKey("raw", new TextEncoder().encode(secret), { name: "HMAC", hash: "SHA-256" }, false, ["sign"]); const sig = [...new Uint8Array(await crypto.subtle.sign("HMAC", key, new TextEncoder().encode(`${t}.${body}`)))].map(b => b.toString(16).padStart(2, "0")).join(""); return worker.fetch(new Request("https://cloud.test/stripe/webhook", { method: "POST", body, headers: { "stripe-signature": `t=${t},v1=${sig}` } }), env, ctx()); } const sub = (status: string, extra: object = {}) => ({ id: "sub_1", customer: "cus_1", status, cancel_at_period_end: false, metadata: { plan: "byok" }, items: { data: [{ current_period_end: 1_801_000_000, price: { lookup_key: "coucou_cloud_byok_monthly" } }] }, ...extra }); beforeEach(() => { env = { ...env, STRIPE_SECRET_KEY: "sk_test_x", STRIPE_WEBHOOK_SECRET: WH, INVOICE_FOOTER: "TVA non applicable, article 293 B du CGI" }; routes.push( [/POST https:\/\/api\.stripe\.com\/v1\/customers$/, () => ({ id: "cus_1" })], [/GET https:\/\/api\.stripe\.com\/v1\/prices\?/, () => ({ data: [{ id: "price_byok" }] })], [/POST https:\/\/api\.stripe\.com\/v1\/checkout\/sessions$/, () => ({ url: "https://checkout.stripe.com/c/pay/cs_1" })], [/GET https:\/\/api\.stripe\.com\/v1\/billing_portal\/configurations/, () => ({ data: [{ id: "bpc_1", active: true, metadata: { coucou: "cloud" } }] })], [/POST https:\/\/api\.stripe\.com\/v1\/billing_portal\/sessions$/, () => ({ url: "https://billing.stripe.com/p/session_1" })], [/GET https:\/\/api\.stripe\.com\/v1\/subscriptions\/sub_1$/, () => sub("active")], ); }); it("lists the offers to anyone, the credit ones not yet open", async () => { const { plans } = (await (await call("/v1/plans")).json()) as { plans: any[] }; expect(plans.map(p => `${p.id}:${p.available}`)).toEqual(["free:true", "byok:true", "solo:false", "pro:false", "max:false"]); expect(plans.find(p => p.id === "byok")).toMatchObject({ monthly: 900, currency: "usd", credits: null }); expect(plans[1].lookup).toBeUndefined(); }); it("no subscription, no Cloud; Checkout, Stripe's word, then the Cloud; cancelled, back to the Mac", async () => { const r = await call("/v1/login", { method: "POST", body: JSON.stringify({ github_token: "ghu_user" }) }); const { token } = (await r.json()) as { token: string }; const auth = { authorization: `Bearer ${token}` }; await call("/v1/anthropic-key", { method: "PUT", headers: auth, body: JSON.stringify({ key: "sk-ant-test" }) }); const mochis = JSON.stringify({ mochis: [{ id: "pr-reviewer", name: "PR Reviewer", repo: "Louis-CFM/coucou", trigger: "pr-opened", instructions: "x", model: "sonnet", enabled: true }] }); expect((await call("/v1/mochis", { method: "PUT", headers: auth, body: mochis })).status).toBe(402); expect(await (await call("/v1/me", { headers: auth })).json()).toMatchObject({ plan: "free", entitled: false, billing: true }); const co = await call("/v1/billing/checkout", { method: "POST", headers: auth, body: JSON.stringify({ plan: "byok" }) }); expect(await co.json()).toEqual({ url: "https://checkout.stripe.com/c/pay/cs_1" }); const customer = calls.find(c => c.url.endsWith("/v1/customers"))!; expect(String(customer.body)).toContain(encodeURIComponent("invoice_settings[footer]")); const session = new URLSearchParams(String(calls.find(c => c.url.endsWith("/checkout/sessions"))!.body)); expect(session.get("mode")).toBe("subscription"); expect(session.get("customer")).toBe("cus_1"); expect(session.get("line_items[0][price]")).toBe("price_byok"); expect(session.get("client_reference_id")).toBe("1"); expect(session.get("automatic_tax[enabled]")).toBe("false"); expect(session.get("success_url")).toBe("https://cloud.test/billing/done"); // the credit offers wait expect((await call("/v1/billing/checkout", { method: "POST", headers: auth, body: JSON.stringify({ plan: "max" }) })).status).toBe(400); // a forged event changes nothing expect((await stripeHook({ type: "customer.subscription.created", data: { object: sub("active") } }, "whsec_other")).status).toBe(400); expect(await (await call("/v1/me", { headers: auth })).json()).toMatchObject({ entitled: false }); expect(await (await stripeHook({ type: "checkout.session.completed", data: { object: { mode: "subscription", subscription: "sub_1", customer: "cus_1", client_reference_id: "1" } } })).json()).toEqual({ ok: true, did: "subscribed" }); expect(await (await call("/v1/me", { headers: auth })).json()).toMatchObject({ plan: "byok", status: "active", entitled: true, renews_at: new Date(1_801_000_000_000).toISOString(), cancels: false }); expect((await call("/v1/mochis", { method: "PUT", headers: auth, body: mochis })).status).toBe(200); expect(await (await hook("pull_request", PR)).json()).toEqual({ ok: true, runs: 1 }); await Promise.all(pending); expect(await (await call("/v1/billing/portal", { method: "POST", headers: auth })).json()).toEqual({ url: "https://billing.stripe.com/p/session_1" }); expect(new URLSearchParams(String(calls.find(c => c.url.endsWith("/billing_portal/sessions"))!.body)).get("configuration")).toBe("bpc_1"); await stripeHook({ type: "customer.subscription.deleted", data: { object: sub("canceled") } }); expect(await (await call("/v1/me", { headers: auth })).json()).toMatchObject({ plan: "free", entitled: false }); expect(await (await hook("pull_request", { ...PR, pull_request: { ...PR.pull_request, head: { sha: "fff" } } })).json()).toEqual({ ok: true, runs: 0 }); // bringing them back is always allowed expect((await call("/v1/mochis", { method: "PUT", headers: auth, body: JSON.stringify({ mochis: [] }) })).status).toBe(200); }); it("the logins the Cloud is offered to need no subscription", async () => { env = { ...env, COMP_LOGINS: "someone, louis-cfm" }; const token = await signIn(); expect(await (await call("/v1/me", { headers: { authorization: `Bearer ${token}` } })).json()).toMatchObject({ plan: "comp", entitled: true }); }); it("the page Stripe sends the browser back to", async () => { const r = await call("/billing/done"); expect(r.headers.get("content-type")).toContain("text/html"); expect(await r.text()).toContain("Coucou"); }); }); describe("every kind of Mochi", () => { const putMochis = (auth: Record, mochis: unknown[], tz = "Europe/Paris") => call("/v1/mochis", { method: "PUT", headers: auth, body: JSON.stringify({ tz, mochis }) }); const idleWith = (text: string) => [/GET https:\/\/api\.anthropic\.com\/v1\/sessions\/sesn_1\/events/, () => ({ data: [ { type: "span.model_request_end" }, { type: "agent.message", content: [{ type: "text", text }] }, { type: "session.status_idle", stop_reason: { type: "end_turn" } }, ], next_page: null })] as [RegExp, (b: any) => unknown]; const swap = (re: RegExp, route: [RegExp, (b: any) => unknown]) => { routes = routes.filter(([r]) => String(r) !== String(re)); routes.unshift(route); }; const EVENTS = /GET https:\/\/api\.anthropic\.com\/v1\/sessions\/sesn_1\/events/; it("schedules run where the user lives, once per slot", () => { expect(localParts(new Date("2026-12-01T00:40:00Z"), "Europe/Paris")).toMatchObject({ date: "2026-12-01", h: 1, min: 40, dow: 2 }); expect(dueSlot("daily 01:30", "Europe/Paris", new Date("2026-12-01T00:20:00Z"))).toBeNull(); expect(dueSlot("daily 01:30", "Europe/Paris", new Date("2026-12-01T00:40:00Z"))).toBe("2026-12-01"); expect(dueSlot("weekly mon 03:00", "UTC", new Date("2026-12-01T04:00:00Z"))).toBeNull(); // a Tuesday expect(dueSlot("weekly tue 03:00", "UTC", new Date("2026-12-01T04:00:00Z"))).toBe("2026-12-01"); expect(dueSlot("weekdays 08:00", "UTC", new Date("2026-12-06T09:00:00Z"))).toBeNull(); // a Sunday expect(dueSlot("manual", "UTC", new Date())).toBeNull(); expect(readChanges({ base: "x", files: { "../etc/passwd": null } })).toBeNull(); expect(readChanges({ base: "x", files: { ".git/config": null } })).toBeNull(); expect(readChanges({ base: "x", files: { "src/a.ts": { mode: "100644", b64: "YQ==" }, "old.txt": null } })).toEqual({ base: "x", files: { "src/a.ts": { mode: "100644", b64: "YQ==" }, "old.txt": null } }); }); it("Issue Triage: a new issue gets a reply that waits for the click, posted as a comment", async () => { const token = await signIn(); const auth = { authorization: `Bearer ${token}` }; await putMochis(auth, [{ id: "issue-triage", name: "Issue Triage", repo: "Louis-CFM/coucou", trigger: "issue-opened", instructions: "Trie l'issue.", model: "sonnet", enabled: true, kind: "repo", tools: "read" }]); routes.push([/GET https:\/\/api\.github\.com\/repos\/Louis-CFM\/coucou\/commits\/main/, () => ({ sha: "main0000sha" })]); routes.push([/POST https:\/\/api\.github\.com\/repos\/Louis-CFM\/coucou\/issues\/12\/comments/, () => ({ html_url: "https://github.com/Louis-CFM/coucou/issues/12#issuecomment-1" })]); calls = []; const issue = { action: "opened", installation: { id: 77 }, repository: { full_name: "Louis-CFM/coucou", private: false }, issue: { number: 12, title: "Crash at launch", body: "It crashes on macOS 27", html_url: "https://github.com/Louis-CFM/coucou/issues/12" } }; expect(await (await hook("issues", issue)).json()).toEqual({ ok: true, runs: 1 }); await Promise.all(pending); const session = calls.find(c => c.method === "POST" && c.url.endsWith("/v1/sessions"))!; expect(session.body.resources).toHaveLength(1); // no pack script: it only reads expect(session.body.resources[0].checkout).toEqual({ type: "commit", sha: "main0000sha" }); expect(session.body.initial_events[0].content[0].text).toContain("It crashes on macOS 27"); expect(calls.find(c => c.url.endsWith("/access_tokens"))!.body.permissions).toEqual({ contents: "read", issues: "read" }); swap(EVENTS, idleWith("## Reply to post\nThanks, I can reproduce it.\n\n## Notes for me\nbug, src/x.ts")); expect(await collectRuns(env)).toBe(1); const { runs } = (await (await call("/v1/runs", { headers: auth })).json()) as { runs: any[] }; expect(runs[0]).toMatchObject({ item_type: "issue", item_number: 12, item_url: "https://github.com/Louis-CFM/coucou/issues/12", trigger: "github", proposal_state: "waiting" }); expect(JSON.parse(runs[0].proposal)).toEqual({ type: "issue-comment", issue: 12, body: "Thanks, I can reproduce it." }); calls = []; expect(await (await call(`/v1/runs/${runs[0].id}/apply`, { method: "POST", headers: auth })).json()).toEqual({ url: "https://github.com/Louis-CFM/coucou/issues/12#issuecomment-1" }); expect(calls.find(c => c.url.endsWith("/issues/12/comments"))!.body).toEqual({ body: "Thanks, I can reproduce it." }); expect(calls.find(c => c.url.endsWith("/access_tokens"))!.body.permissions).toEqual({ issues: "write" }); }); it("Night Shift at night: the oldest labelled issue, its changes packed after the report, a draft PR on the click", async () => { const token = await signIn(); const auth = { authorization: `Bearer ${token}` }; await putMochis(auth, [{ id: "night-shift", name: "Night Shift", repo: "Louis-CFM/coucou", trigger: "issue-label", label: "mochi", schedule: "daily 01:30", instructions: "Règle l'issue.", model: "opus", enabled: true, kind: "repo", tools: "write" }]); routes.push( [/GET https:\/\/api\.github\.com\/repos\/Louis-CFM\/coucou\/issues\?state=open&labels=mochi/, () => [ { number: 9, title: "A PR", body: "", html_url: "x", pull_request: {} }, { number: 20, title: "Typo in README", body: "teh → the", html_url: "https://github.com/Louis-CFM/coucou/issues/20" }, ]], [/GET https:\/\/api\.github\.com\/repos\/Louis-CFM\/coucou\/commits\/main/, () => ({ sha: "main0000sha" })], [/POST https:\/\/api\.anthropic\.com\/v1\/files$/, () => ({ id: "file_pack" })], [/GET https:\/\/api\.anthropic\.com\/v1\/files\?scope_id=sesn_1/, () => ({ data: [{ id: "file_out", filename: "changes.json" }] })], [/GET https:\/\/api\.anthropic\.com\/v1\/files\/file_out\/content/, () => ({ base: "main0000sha", files: { "README.md": { mode: "100644", b64: btoa("the\n") }, "old.txt": null } })], [/POST https:\/\/api\.anthropic\.com\/v1\/sessions\/sesn_1\/events/, () => ({})], [/POST https:\/\/api\.github\.com\/repos\/Louis-CFM\/coucou\/git\/blobs/, () => ({ sha: "blob1" })], [/GET https:\/\/api\.github\.com\/repos\/Louis-CFM\/coucou\/git\/commits\/main0000sha/, () => ({ tree: { sha: "tree0" } })], [/POST https:\/\/api\.github\.com\/repos\/Louis-CFM\/coucou\/git\/trees/, () => ({ sha: "tree1" })], [/POST https:\/\/api\.github\.com\/repos\/Louis-CFM\/coucou\/git\/commits/, () => ({ sha: "commit1" })], [/POST https:\/\/api\.github\.com\/repos\/Louis-CFM\/coucou\/git\/refs/, () => ({ ref: "x" })], [/POST https:\/\/api\.github\.com\/repos\/Louis-CFM\/coucou\/pulls$/, () => ({ html_url: "https://github.com/Louis-CFM/coucou/pull/21" })], ); calls = []; expect(await scheduledRuns(env, Date.parse("2026-12-01T00:20:00Z"))).toBe(0); // 01:20 in Paris: not yet expect(await scheduledRuns(env, Date.parse("2026-12-01T00:40:00Z"))).toBe(1); expect(await scheduledRuns(env, Date.parse("2026-12-01T00:41:00Z"))).toBe(0); // once per slot const session = calls.find(c => c.method === "POST" && c.url.endsWith("/v1/sessions"))!; expect(session.body.initial_events[0].content[0].text).toContain("teh → the"); expect(session.body.resources[1]).toEqual({ type: "file", file_id: "file_pack", mount_path: "/coucou-pack.py" }); expect(calls.find(c => c.url.endsWith("/v1/agents"))!.body.model).toBe("claude-opus-5-5"); // the report is written: the Cloud asks it to pack its changes swap(EVENTS, idleWith("## What I did\nFixed the typo.\n\n## How I checked it\nRead it.\n\n## Notes for me\nnothing")); calls = []; expect(await collectRuns(env, Date.parse("2026-12-01T00:50:00Z"))).toBe(0); const ask = calls.find(c => c.url.endsWith("/sesn_1/events") && c.method === "POST")!; expect(ask.body.events[0].content[0].text).toContain("python3 /mnt/session/uploads/coucou-pack.py main0000sha"); // packed ("ok"): the report stays what it wrote before swap(EVENTS, idleWith("ok")); expect(await collectRuns(env, Date.parse("2026-12-01T00:52:00Z"))).toBe(1); const { runs } = (await (await call("/v1/runs", { headers: auth })).json()) as { runs: any[] }; expect(runs[0]).toMatchObject({ status: "done", trigger: "schedule", item_number: 20, proposal_state: "waiting" }); expect(runs[0].text).toContain("Fixed the typo."); const p = JSON.parse(runs[0].proposal); expect(p).toMatchObject({ type: "pr", base: "main", title: "Typo in README", files: 2 }); expect(p.branch).toMatch(/^mochi\/night-shift\//); expect(p.body).toContain("Closes #20"); expect(p.body).not.toContain("Notes for me"); calls = []; expect(await (await call(`/v1/runs/${runs[0].id}/apply`, { method: "POST", headers: auth })).json()).toEqual({ url: "https://github.com/Louis-CFM/coucou/pull/21" }); expect(calls.find(c => c.url.endsWith("/access_tokens"))!.body.permissions).toEqual({ contents: "write", pull_requests: "write" }); expect(calls.find(c => c.url.endsWith("/git/trees"))!.body).toEqual({ base_tree: "tree0", tree: [ { path: "README.md", mode: "100644", type: "blob", sha: "blob1" }, { path: "old.txt", mode: "100644", type: "blob", sha: null }, ] }); expect(calls.find(c => c.url.endsWith("/git/commits"))!.body.parents).toEqual(["main0000sha"]); expect(calls.find(c => c.url.endsWith("/git/refs"))!.body.ref).toBe(`refs/heads/${p.branch}`); expect(calls.find(c => c.url.endsWith("/pulls"))!.body).toMatchObject({ head: p.branch, base: "main", draft: true }); // the changes aren't kept once the PR is open expect((await env.DB.prepare("SELECT changes FROM runs").first()).changes).toBeNull(); // the next night, the same issue isn't taken again calls = []; expect(await scheduledRuns(env, Date.parse("2026-12-02T00:40:00Z"))).toBe(0); }); it("CI Fixer: a failed run on the default branch, its log in the prompt; elsewhere, nothing", async () => { const token = await signIn(); const auth = { authorization: `Bearer ${token}` }; await putMochis(auth, [{ id: "ci-fixer", name: "CI Fixer", repo: "Louis-CFM/coucou", trigger: "ci-failed", instructions: "Répare la CI.", model: "sonnet", enabled: true, kind: "repo", tools: "write" }]); routes.push( [/GET https:\/\/api\.github\.com\/repos\/Louis-CFM\/coucou\/actions\/runs\/555\/jobs/, () => ({ jobs: [{ id: 1, name: "build", conclusion: "failure" }, { id: 2, name: "lint", conclusion: "success" }] })], [/GET https:\/\/api\.github\.com\/repos\/Louis-CFM\/coucou\/actions\/jobs\/1\/logs/, () => "error: cannot find 'Foo' in scope"], [/POST https:\/\/api\.anthropic\.com\/v1\/files$/, () => ({ id: "file_pack" })], ); const run = (branch: string, conclusion = "failure") => ({ action: "completed", installation: { id: 77 }, repository: { full_name: "Louis-CFM/coucou", private: false, default_branch: "main" }, workflow_run: { id: 555, name: "Build", display_title: "Fix things", head_sha: "ci00sha", head_branch: branch, html_url: "https://github.com/Louis-CFM/coucou/actions/runs/555", conclusion } }); expect(await (await hook("workflow_run", run("feature"))).json()).toEqual({ ok: true, runs: 0 }); expect(await (await hook("workflow_run", run("main", "success"))).json()).toEqual({ ok: true, runs: 0 }); calls = []; expect(await (await hook("workflow_run", run("main"))).json()).toEqual({ ok: true, runs: 1 }); await Promise.all(pending); const session = calls.find(c => c.method === "POST" && c.url.endsWith("/v1/sessions"))!; expect(session.body.resources[0].checkout).toEqual({ type: "commit", sha: "ci00sha" }); expect(session.body.initial_events[0].content[0].text).toContain("cannot find 'Foo' in scope"); expect(calls.find(c => c.url.endsWith("/access_tokens"))!.body.permissions).toEqual({ contents: "read", actions: "read" }); }); it("Release Prep runs on a click; a Mochi that waits for GitHub can't", async () => { const token = await signIn(); const auth = { authorization: `Bearer ${token}` }; await putMochis(auth, [ { id: "release-prep", name: "Release Prep", repo: "Louis-CFM/coucou", trigger: "manual", instructions: "Prépare la release.", model: "sonnet", enabled: true, kind: "repo", tools: "write", per_day: 1 }, { id: "pr-reviewer", name: "PR Reviewer", repo: "Louis-CFM/coucou", trigger: "pr-opened", instructions: "Relis.", model: "sonnet", enabled: true }, ]); routes.push([/GET https:\/\/api\.github\.com\/repos\/Louis-CFM\/coucou\/commits\/main/, () => ({ sha: "main0000sha" })], [/POST https:\/\/api\.anthropic\.com\/v1\/files$/, () => ({ id: "file_pack" })]); const r = await call("/v1/mochis/release-prep/run", { method: "POST", headers: auth }); expect(await r.json()).toMatchObject({ status: "running", item_type: "none", trigger: "manual", base_ref: "main" }); // its runs a day expect((await call("/v1/mochis/release-prep/run", { method: "POST", headers: auth })).status).toBe(400); expect((await call("/v1/mochis/pr-reviewer/run", { method: "POST", headers: auth })).status).toBe(400); }); it("Ship Log writes from the week's commits, and proposes nothing to post", async () => { const token = await signIn(); const auth = { authorization: `Bearer ${token}` }; await putMochis(auth, [{ id: "ship-log", name: "Ship Log", repo: "Louis-CFM/coucou", trigger: "schedule", schedule: "weekly fri 17:00", instructions: "Écris l'article.", model: "sonnet", enabled: true, kind: "brief", tools: "read" }], "UTC"); routes.push( [/GET https:\/\/api\.github\.com\/repos\/Louis-CFM\/coucou\/commits\/main/, () => ({ sha: "main0000sha" })], [/GET https:\/\/api\.github\.com\/repos\/Louis-CFM\/coucou\/commits\?since=/, () => [{ sha: "abcdef1234", commit: { message: "Plans: a real plans page\n\nlong", author: { date: "2026-12-01T10:00:00Z" } } }]], ); calls = []; expect(await scheduledRuns(env, Date.parse("2026-12-04T17:05:00Z"))).toBe(1); expect(calls.find(c => c.method === "POST" && c.url.endsWith("/v1/sessions"))!.body.initial_events[0].content[0].text).toContain("- Plans: a real plans page (abcdef1, 2026-12-01)"); swap(EVENTS, idleWith("Title: Plans\n\n## What shipped\nA plans page.")); await collectRuns(env); const { runs } = (await (await call("/v1/runs", { headers: auth })).json()) as { runs: any[] }; expect(runs[0]).toMatchObject({ status: "done", proposal: null }); }); it("Prod Watch: no AI, a run only when an address goes down or comes back; it needs no repository", async () => { const token = await signIn(); const auth = { authorization: `Bearer ${token}` }; const put = await putMochis(auth, [{ id: "prod-watch", name: "Prod Watch", trigger: "watch", instructions: "", model: "sonnet", enabled: true, kind: "watch", urls: ["https://louisraille.fr", "ftp://nope"] }]); expect(await put.json()).toMatchObject({ mochis: 1, refused: [] }); let up = false; routes.push([/GET https:\/\/louisraille\.fr/, () => { if (!up) throw new Error("down"); return "ok"; }]); calls = []; expect(await runWatches(env, Date.parse("2026-12-01T10:00:00Z"))).toBe(1); expect(calls.some(c => c.url.includes("anthropic"))).toBe(false); expect(await runWatches(env, Date.parse("2026-12-01T10:15:00Z"))).toBe(0); up = true; expect(await runWatches(env, Date.parse("2026-12-01T10:30:00Z"))).toBe(1); const { runs } = (await (await call("/v1/runs", { headers: auth })).json()) as { runs: any[] }; expect(runs.map(r => r.text.split("\n")[0])).toEqual(["## Revenu", "## En panne"]); expect(runs[0]).toMatchObject({ status: "done", trigger: "watch", cost_usd: 0 }); }); it("no more Mochis than the offer allows", async () => { const token = await signIn(); const auth = { authorization: `Bearer ${token}` }; const ten = Array.from({ length: 10 }, (_, i) => ({ id: `m${i}`, name: `M${i}`, repo: "Louis-CFM/coucou", trigger: "pr-opened", instructions: "x", model: "sonnet", enabled: true })); expect(await (await putMochis(auth, ten)).json()).toMatchObject({ mochis: 9, over: 1, cap: 9 }); }); });