mirror of
https://github.com/Louis-CFM/coucou.git
synced 2026-12-07 07:32:35 +09:00
The Cloud ran only PR Reviewer. It now runs what each Mochi needs: - GitHub events: new PR (PR Reviewer), new issue (Issue Triage), an issue labelled for an unscheduled Night Shift, a failed run on the default branch (CI Fixer, its failed logs in the prompt); - schedules in the user's time zone, once per slot (Night Shift takes the oldest labelled issue it hasn't worked on, Deps & Security, Ship Log from the week's commits); - a click on the Mac (POST /v1/mochis/:id/run: Release Prep, or any of them now); - Prod Watch every 15 minutes, no AI, a run only when an address changes. A Mochi that changes files is asked, once its report is written, to run a pack script mounted in the sandbox: the changed files go to the session's outputs and the Worker keeps them until the click, which makes the draft PR with GitHub's API (blobs, tree, commit, a mochi/ branch, the PR). Nothing is pushed from the sandbox, which keeps read-only tokens; each GitHub token asks only what its step needs. Issue Triage's reply is posted on the issue. Mac: brain 0.9.1 sends kind, tools, schedule, label, addresses, runs a day and the time zone; a Cloud Mochi no longer runs on the Mac's schedule, Run now goes to the Cloud, turning one on or off reaches the Cloud, and Cloud runs keep their link and what started them. The Cloud page lists Prod Watch and says why a Mochi stays on the Mac. Claude-Session: https://claude.ai/code/session_01LJm3SRL9k3gBPaVtfPhwcT Co-authored-by: Claude <noreply@anthropic.com>
253 lines
18 KiB
TypeScript
253 lines
18 KiB
TypeScript
import { describe, it, expect, beforeEach, afterEach } from "vitest";
|
|
import fs from "node:fs";
|
|
import os from "node:os";
|
|
import path from "node:path";
|
|
import type { BrainConfig } from "../src/config.js";
|
|
import { addPreset, loadMochi, mochiStatuses, readRuns, runDue, setEnabled } from "../src/mochis.js";
|
|
import type { Sh } from "../src/agents.js";
|
|
import { cloudBilling, cloudDecide, cloudRunNow, cloudKey, cloudLogin, cloudLoginFinish, cloudLoginStart, cloudMove, cloudRuns, cloudStatus, decideCloudRun, pullCloudRuns, readCloudConfig, type TokenStore } from "../src/cloud-client.js";
|
|
|
|
let dir: string;
|
|
let repo: string;
|
|
let config: BrainConfig;
|
|
let token: string | null;
|
|
let calls: { url: string; method: string; body?: any; headers: Record<string, string> }[];
|
|
let answers: [RegExp, (body: any) => { status?: number; json: unknown }][];
|
|
|
|
const store: TokenStore = { read: () => token, write: (t) => { token = t; } };
|
|
const sh: Sh = (cmd, args) => cmd === "git" && args[0] === "remote"
|
|
? { status: 0, stdout: "origin\tgit@github.com:Louis-CFM/coucou.git (fetch)\n", stderr: "" }
|
|
: { status: 0, stdout: "", stderr: "" };
|
|
const fakeFetch = (async (input: RequestInfo | URL, init?: RequestInit) => {
|
|
const url = String(input);
|
|
const method = init?.method ?? "GET";
|
|
const raw = init?.body ? String(init.body) : undefined;
|
|
const body = raw ? (() => { try { return JSON.parse(raw); } catch { return Object.fromEntries(new URLSearchParams(raw)); } })() : undefined;
|
|
calls.push({ url, method, body, headers: (init?.headers ?? {}) as Record<string, string> });
|
|
const hit = answers.find(([re]) => re.test(`${method} ${url}`));
|
|
const a = hit ? hit[1](body) : { status: 404, json: { error: "no route" } };
|
|
return new Response(JSON.stringify(a.json), { status: a.status ?? 200 });
|
|
}) as typeof fetch;
|
|
const deps = () => ({ fetch: fakeFetch, store, sh, sleep: async () => {}, say: () => {} });
|
|
|
|
beforeEach(() => {
|
|
dir = fs.mkdtempSync(path.join(os.tmpdir(), "cloud-client"));
|
|
repo = path.join(dir, "repo");
|
|
fs.mkdirSync(path.join(repo, ".git"), { recursive: true });
|
|
config = {
|
|
brainPath: path.join(dir, "brain"), claudeProjectsPath: path.join(dir, "none"), repoPaths: [],
|
|
chunkModel: "sonnet", mergeModel: "opus", maxChunkTokens: 100000, language: "fr", repoAliases: {},
|
|
};
|
|
token = null;
|
|
calls = [];
|
|
let polls = 0;
|
|
answers = [
|
|
[/POST https:\/\/github\.com\/login\/device\/code/, () => ({ json: { device_code: "dc", user_code: "ABCD-1234", verification_uri: "https://github.com/login/device", interval: 5, expires_in: 900 } })],
|
|
[/POST https:\/\/github\.com\/login\/oauth\/access_token/, () => (++polls < 2 ? { json: { error: "authorization_pending" } } : { json: { access_token: "ghu_x" } })],
|
|
[/POST https:\/\/cloud\.test\/v1\/login/, () => ({ json: { token: "f".repeat(64), login: "Louis-CFM", installations: ["Louis-CFM"] } })],
|
|
[/PUT https:\/\/cloud\.test\/v1\/anthropic-key/, () => ({ json: { ok: true } })],
|
|
[/PUT https:\/\/cloud\.test\/v1\/mochis/, (b) => ({ json: { ok: true, mochis: b.mochis.length } })],
|
|
[/GET https:\/\/cloud\.test\/v1\/runs/, () => ({ json: { runs: [{ id: "r1", mochi_id: "pr-reviewer", repo: "Louis-CFM/coucou", item_number: 1148, status: "done", cost_usd: 0.17, proposal_state: "waiting" }] } })],
|
|
[/POST https:\/\/cloud\.test\/v1\/runs\/r1\/apply/, () => ({ json: { url: "https://github.com/x#review" } })],
|
|
];
|
|
});
|
|
afterEach(() => fs.rmSync(dir, { recursive: true, force: true }));
|
|
|
|
describe("brain cloud", () => {
|
|
it("signs in with GitHub's device flow, keeps the Cloud token in the store and only the address on disk", async () => {
|
|
const r = await cloudLogin(config, { url: "https://cloud.test/", clientId: "Iv1.abc" }, deps());
|
|
expect(r).toEqual({ login: "Louis-CFM", installations: ["Louis-CFM"] });
|
|
expect(token).toBe("f".repeat(64));
|
|
expect(readCloudConfig(config)).toEqual({ url: "https://cloud.test", clientId: "Iv1.abc", login: "Louis-CFM" });
|
|
expect(fs.readFileSync(path.join(config.brainPath, ".state", "cloud", "config.json"), "utf8")).not.toContain("ffff");
|
|
expect(calls.find(c => c.url.endsWith("/v1/login"))!.body).toEqual({ github_token: "ghu_x" });
|
|
expect(calls.filter(c => c.url.includes("access_token"))).toHaveLength(2);
|
|
});
|
|
|
|
it("refuses to talk to the Cloud before signing in", async () => {
|
|
await expect(cloudRuns(config, deps())).rejects.toThrow(/brain cloud login/);
|
|
});
|
|
|
|
it("sends the key with the brain's language, with the Cloud token", async () => {
|
|
await cloudLogin(config, { url: "https://cloud.test", clientId: "Iv1.abc" }, deps());
|
|
await cloudKey(config, deps(), "sk-ant-test");
|
|
const put = calls.find(c => c.url.endsWith("/v1/anthropic-key"))!;
|
|
expect(put.body).toEqual({ key: "sk-ant-test", language: "fr" });
|
|
expect(put.headers.authorization).toBe(`Bearer ${"f".repeat(64)}`);
|
|
await expect(cloudKey(config, deps(), null)).rejects.toThrow(/brain mochi key/);
|
|
});
|
|
|
|
it("moves a PR Mochi to the Cloud: the file says so, the Cloud gets the list, the Mac stops watching", async () => {
|
|
await cloudLogin(config, { url: "https://cloud.test", clientId: "Iv1.abc" }, deps());
|
|
const m = addPreset(config, "pr-reviewer", { repo });
|
|
setEnabled(config, m.id, true);
|
|
expect(await cloudMove(config, m.id, true, deps())).toBe(1);
|
|
expect(loadMochi(config, m.id)!.cloud).toBe(true);
|
|
const sent = calls.filter(c => c.url.endsWith("/v1/mochis")).at(-1)!.body.mochis;
|
|
expect(sent).toEqual([expect.objectContaining({ id: m.id, repo: "Louis-CFM/coucou", trigger: "pr-opened", enabled: true, budget_cents: 100 })]);
|
|
|
|
// the Mac no longer polls GitHub for it
|
|
let ran = false;
|
|
runDue(config, { sh, repoRun: () => { ran = true; return { summary: "", proposal: null }; }, onNote: () => { ran = true; } });
|
|
expect(ran).toBe(false);
|
|
|
|
// back on the Mac
|
|
expect(await cloudMove(config, m.id, false, deps())).toBe(0);
|
|
expect(loadMochi(config, m.id)!.cloud).toBe(false);
|
|
expect(fs.readFileSync(loadMochi(config, m.id)!.file, "utf8")).not.toMatch(/^cloud:/m);
|
|
});
|
|
|
|
it("only takes Mochis the Cloud can run, and keeps the Mac watching when the Cloud says no", async () => {
|
|
await cloudLogin(config, { url: "https://cloud.test", clientId: "Iv1.abc" }, deps());
|
|
// your memory stays on your Mac: a Mochi that writes from it stays there too
|
|
const gardener = addPreset(config, "memory-gardener", {});
|
|
await expect(cloudMove(config, gardener.id, true, deps())).rejects.toThrow(/mémoire/);
|
|
const pr = addPreset(config, "pr-reviewer", { repo });
|
|
answers.unshift([/PUT https:\/\/cloud\.test\/v1\/mochis/, () => ({ status: 401, json: { error: "sign in from Coucou first" } })]);
|
|
await expect(cloudMove(config, pr.id, true, deps())).rejects.toThrow(/sign in/);
|
|
expect(loadMochi(config, pr.id)!.cloud).toBe(false);
|
|
// the app isn't installed for the repo's owner: the Cloud refuses it, the Mac keeps watching
|
|
answers.unshift([/PUT https:\/\/cloud\.test\/v1\/mochis/, () => ({ json: { ok: true, mochis: 0, refused: ["Louis-CFM/coucou"] } })]);
|
|
await expect(cloudMove(config, pr.id, true, deps())).rejects.toThrow(/pas installée pour Louis-CFM\/coucou/);
|
|
expect(loadMochi(config, pr.id)!.cloud).toBe(false);
|
|
});
|
|
|
|
it("every ready-made Mochi but the Memory Gardener goes: what starts it, its schedule and where you live go with it", async () => {
|
|
await cloudLogin(config, { url: "https://cloud.test", clientId: "Iv1.abc" }, deps());
|
|
const night = addPreset(config, "night-shift", { repo });
|
|
const watch = addPreset(config, "prod-watch", { urls: ["https://louisraille.fr"] });
|
|
const ship = addPreset(config, "ship-log", { repo });
|
|
setEnabled(config, night.id, true); setEnabled(config, ship.id, true);
|
|
await cloudMove(config, night.id, true, deps());
|
|
await cloudMove(config, watch.id, true, deps());
|
|
expect(await cloudMove(config, ship.id, true, deps())).toBe(3);
|
|
const body = calls.filter(c => c.url.endsWith("/v1/mochis")).at(-1)!.body;
|
|
expect(body.tz).toBe(Intl.DateTimeFormat().resolvedOptions().timeZone);
|
|
expect(body.mochis.find((m: any) => m.id === night.id)).toMatchObject({ repo: "Louis-CFM/coucou", trigger: "issue-label", kind: "repo", tools: "write", schedule: "daily 01:30", label: "mochi", budget_cents: 300, per_day: 1 });
|
|
expect(body.mochis.find((m: any) => m.id === watch.id)).toMatchObject({ repo: "", kind: "watch", urls: ["https://louisraille.fr"] });
|
|
expect(body.mochis.find((m: any) => m.id === ship.id)).toMatchObject({ kind: "brief", trigger: "schedule", schedule: "weekly fri 17:00" });
|
|
|
|
// the Mac no longer runs them on their schedule
|
|
let ran = 0;
|
|
runDue(config, { now: new Date("2026-12-04T18:00:00"), sh, llm: () => { ran++; return "x"; }, repoRun: () => { ran++; return { summary: "", proposal: null }; } });
|
|
expect(ran).toBe(0);
|
|
|
|
// a click runs it in the Cloud
|
|
answers.unshift([/POST https:\/\/cloud\.test\/v1\/mochis\/night-shift\/run/, () => ({ json: { nothing: true } })]);
|
|
expect(await cloudRunNow(config, night.id, deps())).toEqual({ started: false });
|
|
});
|
|
|
|
it("an issue run from the Cloud keeps its link and what started it", async () => {
|
|
await cloudLogin(config, { url: "https://cloud.test", clientId: "Iv1.abc" }, deps());
|
|
const m = addPreset(config, "night-shift", { repo });
|
|
answers.unshift([/GET https:\/\/cloud\.test\/v1\/runs/, () => ({ json: { runs: [{
|
|
id: "r7", mochi_id: m.id, repo: "Louis-CFM/coucou", item_type: "issue", item_number: 20, item_title: "Typo", status: "done", trigger: "schedule",
|
|
started_at: "2026-12-01T00:40:00.000Z", finished_at: "2026-12-01T00:52:00.000Z", cost_usd: 0.4, turns: 12, text: "## What I did\nFixed.",
|
|
proposal: JSON.stringify({ type: "pr", branch: "mochi/night-shift/20261201005200", base: "main", title: "Typo", body: "Fixed.\n\nCloses #20", files: 1 }),
|
|
proposal_state: "waiting", proposal_url: null, error: null,
|
|
}] } })]);
|
|
await pullCloudRuns(config, deps());
|
|
expect(readRuns(config, m.id).at(-1)).toMatchObject({ trigger: "schedule", item: { type: "issue", number: 20, url: "https://github.com/Louis-CFM/coucou/issues/20" }, proposal: { type: "pr", title: "Typo" } });
|
|
});
|
|
|
|
it("lists the runs and posts one on the click", async () => {
|
|
await cloudLogin(config, { url: "https://cloud.test", clientId: "Iv1.abc" }, deps());
|
|
expect((await cloudRuns(config, deps()))[0]).toMatchObject({ id: "r1", proposal_state: "waiting" });
|
|
expect(await cloudDecide(config, "r1", true, deps())).toEqual({ url: "https://github.com/x#review" });
|
|
});
|
|
|
|
it("brings the Cloud's runs to the Mac like its own: the notch, Results and the click work as for a local run", async () => {
|
|
await cloudLogin(config, { url: "https://cloud.test", clientId: "Iv1.abc" }, deps());
|
|
const m = addPreset(config, "pr-reviewer", { repo });
|
|
let remote = [{
|
|
id: "r1", mochi_id: m.id, repo: "Louis-CFM/coucou", item_type: "pr", item_number: 1198, item_title: "cloud: deploy notes",
|
|
status: "done", started_at: "2026-11-30T02:12:00.000Z", finished_at: "2026-11-30T02:13:10.000Z", cost_usd: 0.11, turns: 5, active_seconds: 48,
|
|
text: "## Summary\nGood.", proposal: JSON.stringify({ type: "review", pr: 1198, body: "## Summary\nGood." }), proposal_state: "waiting", proposal_url: null, error: null,
|
|
}, {
|
|
id: "r0", mochi_id: m.id, repo: "Louis-CFM/coucou", item_type: "pr", item_number: 1199, item_title: "x", status: "running",
|
|
started_at: "2026-11-30T02:13:00.000Z", cost_usd: null, turns: null, text: null, proposal: null, proposal_state: null, proposal_url: null, error: null,
|
|
}];
|
|
answers.unshift([/GET https:\/\/cloud\.test\/v1\/runs/, () => ({ json: { runs: remote } })]);
|
|
|
|
expect(await pullCloudRuns(config, deps())).toEqual({ added: 1, updated: 0 });
|
|
const run = readRuns(config, m.id).at(-1)!;
|
|
expect(run).toMatchObject({ t: "2026-11-30T02:13:10.000Z", trigger: "github", status: "ok", cloud: "r1", ms: 48000,
|
|
item: { type: "pr", number: 1198 }, proposal: { type: "review", pr: 1198 }, usage: { costUsd: 0.11, turns: 5 } });
|
|
expect(fs.readFileSync(run.file!, "utf8")).toContain("## Summary");
|
|
expect(mochiStatuses(config).find(x => x.id === m.id)!.waiting).toHaveLength(1);
|
|
|
|
// pulled once only
|
|
expect(await pullCloudRuns(config, deps())).toEqual({ added: 0, updated: 0 });
|
|
|
|
// the click from the notch goes through the Cloud
|
|
answers.unshift([/POST https:\/\/cloud\.test\/v1\/runs\/r1\/apply/, () => ({ json: { url: "https://github.com/Louis-CFM/coucou/pull/1198#review" } })]);
|
|
expect(await decideCloudRun(config, m.id, run.t, true, deps())).toMatchObject({ state: "applied", url: "https://github.com/Louis-CFM/coucou/pull/1198#review" });
|
|
expect(mochiStatuses(config).find(x => x.id === m.id)!.waiting).toHaveLength(0);
|
|
// a local run isn't the Cloud's business
|
|
expect(await decideCloudRun(config, m.id, "2026-01-01T00:00:00.000Z", true, deps())).toBeNull();
|
|
});
|
|
|
|
it("what an autonomous Mochi posted in the Cloud reaches the Mac as done on its own", async () => {
|
|
await cloudLogin(config, { url: "https://cloud.test", clientId: "Iv1.abc" }, deps());
|
|
const m = addPreset(config, "pr-reviewer", { repo });
|
|
answers.unshift([/GET https:\/\/cloud\.test\/v1\/runs/, () => ({ json: { runs: [{
|
|
id: "r5", mochi_id: m.id, repo: "Louis-CFM/coucou", item_type: "pr", item_number: 9, item_title: "t", status: "done",
|
|
started_at: "2026-11-30T04:00:00.000Z", finished_at: "2026-11-30T04:01:00.000Z", cost_usd: 0.1, turns: 3, text: "## Summary\nok",
|
|
proposal: JSON.stringify({ type: "review", pr: 9, body: "## Summary\nok" }), proposal_state: "applied",
|
|
proposal_url: "https://github.com/Louis-CFM/coucou/pull/9#review", error: null, auto: 1,
|
|
}] } })]);
|
|
await pullCloudRuns(config, deps());
|
|
expect(readRuns(config, m.id).at(-1)).toMatchObject({ cloud: "r5", proposal: { type: "review", pr: 9 }, auto: { state: "applied", url: "https://github.com/Louis-CFM/coucou/pull/9#review" } });
|
|
expect(mochiStatuses(config).find(x => x.id === m.id)!.waiting).toHaveLength(0);
|
|
});
|
|
|
|
it("a click made elsewhere (brain cloud discard) reaches the Mac at the next pull", async () => {
|
|
await cloudLogin(config, { url: "https://cloud.test", clientId: "Iv1.abc" }, deps());
|
|
const m = addPreset(config, "pr-reviewer", { repo });
|
|
const base = { id: "r2", mochi_id: m.id, repo: "Louis-CFM/coucou", item_type: "pr", item_number: 7, item_title: "t", status: "done",
|
|
started_at: "2026-11-30T03:00:00.000Z", finished_at: "2026-11-30T03:01:00.000Z", cost_usd: 0.1, turns: 3, text: "## Summary\nok",
|
|
proposal: JSON.stringify({ type: "review", pr: 7, body: "## Summary\nok" }), proposal_url: null, error: null };
|
|
let state = "waiting";
|
|
answers.unshift([/GET https:\/\/cloud\.test\/v1\/runs/, () => ({ json: { runs: [{ ...base, proposal_state: state }] } })]);
|
|
await pullCloudRuns(config, deps());
|
|
expect(mochiStatuses(config).find(x => x.id === m.id)!.waiting).toHaveLength(1);
|
|
state = "discarded";
|
|
expect(await pullCloudRuns(config, deps())).toEqual({ added: 0, updated: 1 });
|
|
expect(mochiStatuses(config).find(x => x.id === m.id)!.waiting).toHaveLength(0);
|
|
});
|
|
|
|
it("the app's way: the code first, then the wait; the status the Cloud page reads", async () => {
|
|
config.cloudUrl = "https://cloud.test";
|
|
config.cloudClientId = "Iv1.abc";
|
|
// not signed in: nothing to ask the Cloud, the Mochis still listed
|
|
const m = addPreset(config, "pr-reviewer", { repo });
|
|
const night = addPreset(config, "night-shift", { repo });
|
|
let st = await cloudStatus(config, deps());
|
|
expect(st).toMatchObject({ signedIn: false, reachable: false, url: "https://cloud.test", keyInCloud: false });
|
|
expect(st.mochis.find(x => x.id === m.id)).toMatchObject({ ready: true, cloud: false });
|
|
expect(st.mochis.find(x => x.id === night.id)).toMatchObject({ ready: true });
|
|
const gardener = addPreset(config, "memory-gardener", {});
|
|
expect((await cloudStatus(config, deps())).mochis.find(x => x.id === gardener.id)).toMatchObject({ ready: false, reason: expect.stringContaining("mémoire") });
|
|
|
|
const code = await cloudLoginStart(config, {}, deps());
|
|
expect(code).toEqual({ deviceCode: "dc", userCode: "ABCD-1234", verificationUri: "https://github.com/login/device", interval: 5, expiresIn: 900 });
|
|
expect(await cloudLoginFinish(config, code, {}, deps())).toEqual({ login: "Louis-CFM", installations: ["Louis-CFM"] });
|
|
|
|
answers.unshift([/GET https:\/\/cloud\.test\/v1\/me/, () => ({ json: { login: "Louis-CFM", has_key: true, installations: ["Louis-CFM"], mochis: 1,
|
|
plan: "byok", status: "active", renews_at: "2026-12-30T00:00:00.000Z", cancels: false, entitled: true, billing: true } })]);
|
|
answers.unshift([/GET https:\/\/cloud\.test\/v1\/plans/, () => ({ json: { plans: [{ id: "free", monthly: 0, credits: null, mochis: 0, available: true, currency: "eur" }, { id: "byok", monthly: 900, credits: null, mochis: 9, available: true, currency: "eur" }] } })]);
|
|
answers.unshift([/POST https:\/\/cloud\.test\/v1\/billing\/checkout/, (b: any) => ({ json: { url: `https://checkout.stripe.com/c/${b.plan}` } })]);
|
|
answers.unshift([/GET https:\/\/cloud\.test\/v1\/runs/, () => ({ json: { runs: [{
|
|
id: "r9", mochi_id: m.id, repo: "Louis-CFM/coucou", item_type: "pr", item_number: 12, item_title: "Fix", status: "done",
|
|
started_at: new Date().toISOString(), finished_at: new Date().toISOString(), cost_usd: 0.12, turns: 4, text: "## Summary\nok",
|
|
proposal: JSON.stringify({ type: "review", pr: 12, body: "## Summary\nok" }), proposal_state: "waiting", proposal_url: null, error: null }] } })]);
|
|
await pullCloudRuns(config, deps());
|
|
st = await cloudStatus(config, deps());
|
|
expect(st).toMatchObject({ signedIn: true, reachable: true, keyInCloud: true, installations: ["Louis-CFM"], month: { runs: 1, costUsd: 0.12, waiting: 1 } });
|
|
expect(st.recent[0]).toMatchObject({ mochi: m.id, number: 12, title: "Fix", costUsd: 0.12, state: "waiting" });
|
|
expect(st.plan).toEqual({ plan: "byok", status: "active", renews_at: "2026-12-30T00:00:00.000Z", cancels: false, entitled: true, billing: true });
|
|
expect(st.plans.map(p => p.id)).toEqual(["free", "byok"]);
|
|
expect(await cloudBilling(config, "checkout", "byok", deps())).toBe("https://checkout.stripe.com/c/byok");
|
|
});
|
|
});
|