Files
coucou/brain/tests/agents.test.ts
LouisandClaude f44300a470 Mochi teams with a lead: the Team page by project, who leads whom (#1278)
- The Team page groups the Mochis by team (tiles and list): each team under its title and
  repositories, its lead's card on top, the Mochis it sends below a line in the team's colour.
- A team is made or changed in one sheet (name, colour, its Mochis, a lead at its time);
  right-click a Mochi › Move to team; a team's menu edits, adds a lead or ungroups it.
- The Team Lead (brain `team-lead`, `lead: true`): at each run it reads what its Mochis did,
  what waits for a click and the team's repositories (PRs, issues, CI), sends up to 4 Mochis
  with a precise ask (a PR or an issue for code Mochis), and writes one report. It only sends
  Mochis that are on, awake, local and within budget; nothing is merged, closed or posted
  without the click. The page's mission goes through the team's lead (`team plan|run --team`).
- Telegram and WhatsApp: a Mochi sent by its lead only writes when something waits for a tap.
- Fix: pausing a Mochi (or changing its channels) no longer resets its time to "on demand".
- brain 0.15.0: `brain team set`, `brain team lead`; leads are shared in .mochis.json files.


Claude-Session: https://claude.ai/code/session_01LJm3SRL9k3gBPaVtfPhwcT

Co-authored-by: Claude <noreply@anthropic.com>
2026-12-03 18:56:05 +00:00

412 lines
26 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 { spawnSync } from "node:child_process";
import type { BrainConfig } from "../src/config.js";
import {
addPreset, applyMochiProposal, discardMochiProposal, isDue, loadMochi, mochiStatuses, nextSlot, parseSchedule,
presetList, readRuns, runDue, runMochi, runWatches, saveMochi, setEnabled, slotToday, usageSummary, type RepoRunner,
} from "../src/mochis.js";
import {
applyProposal, checkRepo, githubRepo, prDiff, realSh, turnLimit, looksLikeReport, withoutNotes, nextItem, readSeen, replyPart, repoPrompt, runInRepo, toolFlags, type Sh, type ShResult,
} from "../src/agents.js";
import { PRESETS } from "../src/presets.js";
let dir: string;
let repo: string;
let config: BrainConfig;
const at = (d: string) => new Date(d);
beforeEach(() => {
dir = fs.mkdtempSync(path.join(os.tmpdir(), "agents"));
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: "en", repoAliases: {},
};
});
afterEach(() => fs.rmSync(dir, { recursive: true, force: true }));
/** A fake shell: answers by the first words of the command, records every call. */
function fakeSh(answers: Record<string, string | ShResult>) {
const calls: { cmd: string; args: string[]; input?: string }[] = [];
const sh: Sh = (cmd, args, opts = {}) => {
calls.push({ cmd, args, input: opts.input });
const line = [cmd, ...args].join(" ");
const hit = Object.keys(answers).filter(k => line.startsWith(k)).sort((a, b) => b.length - a.length)[0];
const a = hit !== undefined ? answers[hit]! : "";
return typeof a === "string" ? { status: 0, stdout: a, stderr: "" } : a;
};
return { sh, calls };
}
describe("ready-made Mochis", () => {
it("eleven presets, each with its own outfit and instructions in both languages", () => {
expect(PRESETS).toHaveLength(11);
expect(new Set(PRESETS.map(p => p.outfit)).size).toBe(11);
for (const p of PRESETS) {
expect(p.instructions.fr.length).toBeGreaterThan(60);
expect(p.instructions.en.length).toBeGreaterThan(60);
if (p.schedule !== "manual") expect(parseSchedule(p.schedule)).not.toBeNull();
}
});
it("adds one, off, as an ordinary Mochi file; the gallery knows it's there", () => {
expect(() => addPreset(config, "night-shift")).toThrow(/repository/);
const m = addPreset(config, "night-shift", { repo });
expect(m).toMatchObject({ preset: "night-shift", kind: "repo", on: "issue-label", label: "mochi", tools: "write", outfit: "headlamp", enabled: false, repo });
expect(fs.readFileSync(m.file, "utf8")).toContain("Fix the issue below");
expect(presetList(config).find(p => p.id === "night-shift")!.added).toBe(m.id);
expect(presetList(config).find(p => p.id === "ci-fixer")!.added).toBeNull();
});
it("Prod Watch needs addresses and keeps only http(s) ones", () => {
expect(() => addPreset(config, "prod-watch")).toThrow(/address/);
const m = addPreset(config, "prod-watch", { urls: "https://louisraille.fr, ftp://nope, http://example.com" });
expect(m.urls).toEqual(["https://louisraille.fr", "http://example.com"]);
expect(m.kind).toBe("watch");
});
});
describe("weekly schedules", () => {
it("runs on its day only, after its time", () => {
const s = parseSchedule("weekly fri 17:00")!;
expect(slotToday(s, at("2026-11-27T18:00:00"))).not.toBeNull(); // a Friday
expect(slotToday(s, at("2026-11-27T16:00:00"))).toBeNull();
expect(slotToday(s, at("2026-11-28T18:00:00"))).toBeNull(); // Saturday
expect(nextSlot(s, at("2026-11-28T18:00:00")).getDay()).toBe(5);
expect(parseSchedule("weekly xyz 17:00")).toBeNull();
});
});
describe("repo Mochis", () => {
const runner = (summary: string, proposal: ReturnType<RepoRunner>["proposal"]): RepoRunner => () => ({ summary, proposal });
it("a click runs a scheduled repo Mochi; its proposal waits until it is applied", () => {
const m = addPreset(config, "deps-security", { repo });
const proposal = { type: "pr" as const, branch: "mochi/deps-security/x", base: "main", title: "Deps", body: "## Updated" };
const r = runMochi(config, m.id, { repoRun: runner("## Updated\n- vitest", proposal), now: at("2026-11-30T03:10:00") });
expect(r.status).toBe("ok");
expect(r.proposal).toEqual(proposal);
let st = mochiStatuses(config).find(x => x.id === m.id)!;
expect(st.waiting.map(w => w.t)).toEqual([r.t]);
const { sh, calls } = fakeSh({
"gh pr create": "https://github.com/me/app/pull/7\n",
"git remote -v": "upstream\thttps://github.com/them/app.git (fetch)\norigin\tgit@github.com:me/app.git (fetch)\n",
});
expect(applyMochiProposal(config, m.id, r.t, sh)).toMatchObject({ state: "applied", url: "https://github.com/me/app/pull/7" });
const ghCalls = calls.filter(c => !(c.cmd === "git" && c.args[0] === "remote"));
expect(ghCalls.map(c => `${c.cmd} ${c.args.slice(0, 2).join(" ")}`)).toEqual(["git push -u", "gh pr create"]);
expect(ghCalls[1]!.args).toContain("--draft");
// gh is told which repository: it won't choose between two remotes on its own
expect(ghCalls[1]!.args.slice(-2)).toEqual(["-R", "me/app"]);
expect(ghCalls[1]!.input).toBe("## Updated");
st = mochiStatuses(config).find(x => x.id === m.id)!;
expect(st.waiting).toEqual([]);
// a second click does nothing more
expect(applyMochiProposal(config, m.id, r.t, fakeSh({}).sh).state).toBe("applied");
});
it("a failed push leaves it waiting to try again; discard deletes the branch", () => {
const m = addPreset(config, "release-prep", { repo });
const proposal = { type: "pr" as const, branch: "mochi/release-prep/y", base: "main", title: "Release", body: "x" };
const r = runMochi(config, m.id, { repoRun: runner("## Proposed version\n0.8.0", proposal) });
const fail = fakeSh({ "git push": { status: 1, stdout: "", stderr: "denied" } });
expect(applyMochiProposal(config, m.id, r.t, fail.sh)).toMatchObject({ state: "failed", error: expect.stringContaining("denied") });
const { sh, calls } = fakeSh({});
expect(discardMochiProposal(config, m.id, r.t, sh).state).toBe("discarded");
expect(calls[0]!.args).toEqual(["branch", "-D", "mochi/release-prep/y"]);
});
it("an autonomous Mochi posts on its own and says so; when it can't, the click is still there", () => {
const m = addPreset(config, "issue-triage", { repo });
saveMochi(config, { id: m.id, name: m.name, instructions: "x", level: "autonome" });
expect(loadMochi(config, m.id)!.level).toBe("autonome");
const proposal = { type: "issue-comment" as const, issue: 4, body: "Thanks!" };
const ok = fakeSh({ "gh issue comment": "https://github.com/me/app/issues/4#issuecomment-1\n" });
const r = runMochi(config, m.id, { item: { type: "issue", key: "issue#4", number: 4, title: "Bug" }, repoRun: runner("## Reply to post\nThanks!", proposal), sh: ok.sh, now: at("2026-11-30T10:00:00") });
expect(r.auto).toEqual({ state: "applied", url: "https://github.com/me/app/issues/4#issuecomment-1" });
expect(readRuns(config, m.id).at(-1)!.auto?.state).toBe("applied");
expect(mochiStatuses(config).find(x => x.id === m.id)!.waiting).toEqual([]);
const bad = fakeSh({ "gh issue comment": { status: 1, stdout: "", stderr: "HTTP 403" } });
const r2 = runMochi(config, m.id, { item: { type: "issue", key: "issue#5", number: 5, title: "Other" }, repoRun: runner("## Reply to post\nThanks!", { ...proposal, issue: 5 }), sh: bad.sh, now: at("2026-11-30T11:00:00") });
expect(r2.auto).toMatchObject({ state: "failed", error: expect.stringContaining("403") });
// it waits for the click instead
expect(mochiStatuses(config).find(x => x.id === m.id)!.waiting.map(w => w.t)).toEqual([r2.t]);
expect(applyMochiProposal(config, m.id, r2.t, ok.sh).state).toBe("applied");
});
it("only a repo Mochi can be autonomous; a mail Mochi only drafts", () => {
const brief = saveMochi(config, { name: "Brief", instructions: "x", level: "autonome" });
expect(brief.level).toBe("demander");
const mail = saveMochi(config, { name: "Mail", instructions: "x", kind: "mail", level: "autonome" });
expect(mail.level).toBe("brouillon");
});
it("GitHub Mochis first note what exists, then take only what is new", () => {
const m = addPreset(config, "issue-triage", { repo });
setEnabled(config, m.id, true);
let issues = [{ number: 1, title: "Old bug", body: "b", url: "u1" }];
const sh: Sh = (cmd, args) => ({ status: 0, stderr: "", stdout: cmd === "gh" && args[0] === "issue" ? JSON.stringify(issues) : "" });
const seen: string[] = [];
const repoRun: RepoRunner = (_m, item) => { seen.push(item.key); return { summary: "## Reply to post\nThanks!\n## Notes for me\nbug", proposal: { type: "issue-comment", issue: item.number!, body: "Thanks!" } }; };
expect(runDue(config, { sh, repoRun, now: at("2026-11-30T10:00:00") })).toEqual([]); // primed, nothing run
expect(readSeen(config, m.id)).toEqual({ primed: true, keys: ["issue#1"] });
issues = [...issues, { number: 2, title: "New bug", body: "b", url: "u2" }];
const out = runDue(config, { sh, repoRun, now: at("2026-11-30T10:15:00") });
expect(out).toHaveLength(1);
expect(out[0]!.item).toMatchObject({ type: "issue", number: 2 });
expect(seen).toEqual(["issue#2"]);
expect(runDue(config, { sh, repoRun, now: at("2026-11-30T10:30:00") })).toEqual([]);
});
it("Night Shift picks labelled issues straight away, but only once its night slot has come", () => {
const m = addPreset(config, "night-shift", { repo });
setEnabled(config, m.id, true);
const sh: Sh = (cmd, args) => ({ status: 0, stderr: "", stdout: cmd === "gh" && args[0] === "issue" ? JSON.stringify([{ number: 5, title: "Dark mode", body: "", url: "u" }]) : "" });
const repoRun: RepoRunner = () => ({ summary: "## What I did\nx", proposal: null });
expect(isDue(loadMochi(config, m.id)!, [], at("2026-11-30T00:30:00"))).toBe(false);
expect(runDue(config, { sh, repoRun, now: at("2026-11-30T00:30:00") })).toEqual([]);
const out = runDue(config, { sh, repoRun, now: at("2026-11-30T01:45:00") });
expect(out.map(r => r.item?.number)).toEqual([5]);
});
it("PR Reviewer skips drafts and the Mochis' own PRs; CI Fixer reads the failed log", () => {
const pr = fakeSh({
"gh pr list": JSON.stringify([
{ number: 3, title: "WIP", body: "", url: "", headRefOid: "a", headRefName: "feat", isDraft: true },
{ number: 4, title: "Mochi", body: "", url: "", headRefOid: "b", headRefName: "mochi/night-shift/1", isDraft: false },
{ number: 9, title: "Real", body: "", url: "", headRefOid: "c", headRefName: "fix", isDraft: false },
]),
});
expect(nextItem(config, "rev", "pr-opened", repo, "mochi", pr.sh, false)).toMatchObject({ type: "pr", number: 9, key: "pr#9@c" });
const ci = fakeSh({
"git symbolic-ref": "origin/main\n",
"gh run list": JSON.stringify([{ databaseId: 42, workflowName: "CI", headSha: "abc", url: "u", displayTitle: "Merge" }]),
"gh run view": "error: test failed",
});
const item = nextItem(config, "ci", "ci-failed", repo, "mochi", ci.sh, false)!;
expect(item).toMatchObject({ type: "ci", number: 42, headRef: "abc" });
expect(item.body).toContain("test failed");
expect(ci.calls.find(c => c.args[0] === "run" && c.args[1] === "list")!.args).toContain("main");
});
it("a GitHub Mochi that can't ask GitHub says so once; its first look says what it noted", () => {
const m = addPreset(config, "pr-reviewer", { repo });
setEnabled(config, m.id, true);
const repoRun: RepoRunner = () => ({ summary: "## Review\nok", proposal: null });
let fail = true;
const sh: Sh = (cmd, args) => cmd === "gh"
? (fail ? { status: 1, stdout: "", stderr: "no default repository has been set\nmore" }
: { status: 0, stderr: "", stdout: JSON.stringify([{ number: 1, title: "Old", body: "", url: "", headRefOid: "a", headRefName: "x", isDraft: false }]) })
: { status: 0, stdout: "", stderr: "" };
const notes: string[] = [];
const onNote = (_m: unknown, r: { status: string; error?: string }) => notes.push(`${r.status}: ${r.error ?? ""}`);
expect(runDue(config, { sh, repoRun, onNote, now: at("2026-11-30T10:00:00") }).map(r => r.status)).toEqual(["error"]);
expect(readRuns(config, m.id).at(-1)!.error).toBe("GitHub : no default repository has been set");
expect(readSeen(config, m.id).primed).toBe(false); // nothing noted while GitHub was out of reach
// the same error again isn't logged every 15 minutes
expect(runDue(config, { sh, repoRun, onNote, now: at("2026-11-30T10:15:00") })).toEqual([]);
expect(readRuns(config, m.id)).toHaveLength(1);
fail = false;
expect(runDue(config, { sh, repoRun, onNote, now: at("2026-11-30T10:30:00") })).toEqual([]);
expect(notes.at(-1)).toBe("skipped: first look: 1 open PRs noted, it will take the new ones");
runDue(config, { sh, repoRun, onNote, now: at("2026-11-30T10:45:00") });
expect(notes.at(-1)).toBe("skipped: nothing new for now");
});
it("finds the GitHub repository of a clone, and checks a repository before a Mochi gets it", () => {
const remotes = (out: string): Sh => (cmd, args) => ({ status: 0, stderr: "", stdout: cmd === "git" && args[0] === "remote" ? out : "" });
expect(githubRepo(remotes("origin\thttps://github.com/Louis-CFM/coucou (fetch)\n"), repo)).toBe("Louis-CFM/coucou");
expect(githubRepo(remotes("github\thttps://github.com/a/b.git (fetch)\norigin\thttps://github.com/c/d.git (fetch)\n"), repo)).toBe("c/d");
expect(githubRepo(remotes("origin\thttps://gitlab.com/a/b.git (fetch)\nmirror\tgit@github.com:e/f.git (push)\n"), repo)).toBe("e/f");
expect(githubRepo(remotes("origin\thttps://gitlab.com/a/b.git (fetch)\n"), repo)).toBeNull();
expect(checkRepo(path.join(dir, "ton-repo-test"), true)).toMatch(/dossier introuvable/);
const notGit: Sh = () => ({ status: 128, stdout: "", stderr: "not a git repository" });
expect(checkRepo(repo, false, notGit)).toMatch(/not a git repository/);
expect(checkRepo(repo, false, remotes("origin\thttps://gitlab.com/a/b.git (fetch)\n"))).toMatch(/no GitHub remote/);
expect(checkRepo(repo, false, remotes("origin\thttps://github.com/a/b.git (fetch)\n"))).toBeNull();
});
it("what is posted on GitHub is in the repository's language; only the notes are in the brain's", () => {
const item = { type: "pr" as const, key: "pr#1@a", number: 1, title: "Fix", body: "" };
const fr = repoPrompt({ ...config, language: "fr" }, { instructions: "Relis", item });
expect(fr).toContain("langue du dépôt");
expect(fr).toMatch(/Notes pour moi.*s'écrit en français/);
expect(repoPrompt(config, { instructions: "Review", item })).toMatch(/Notes pour moi.*s'écrit en anglais/);
expect(repoPrompt(config, { instructions: "Review", item })).toMatch(/langue des fichiers modifiés ne compte pas/);
// whatever the language of the reply, the notes are never posted
expect(replyPart("## Reply to post\nThanks, fixed in 0.8.\n\n## Notes pour moi\nbug UI")).toBe("Thanks, fixed in 0.8.");
});
it("a review that isn't one is asked for again, and never proposed as it is", () => {
const item = { type: "pr" as const, key: "pr#1142@a", number: 1142, title: "Dictation language", body: "" };
const run = (answers: string[]) => {
const calls: string[][] = [];
const sh: Sh = (cmd, args) => {
calls.push([cmd, ...args]);
if (cmd !== "claude") return { status: 0, stdout: "", stderr: "" };
const text = answers.shift() ?? "";
return { status: 0, stderr: "", stdout: JSON.stringify({ result: text, session_id: "s1" }) };
};
const input = { config, id: "pr-reviewer", name: "PR Reviewer", repo, instructions: "Review", tools: "read" as const,
model: "sonnet", item, stamp: "2026-11-29_201300", system: "", env: {}, sh };
return { calls, go: () => runInRepo(input) };
};
// the last message was about a test that finished in the background: asked again, it gives the review
const ok = run(["Background test finished — exit 0, already incorporated above.", "## Summary\nLooks right.\n## Problems\nNone."]);
expect(ok.go().proposal).toEqual({ type: "review", pr: 1142, body: "## Summary\nLooks right.\n## Problems\nNone." });
const again = ok.calls.filter(c => c[0] === "claude")[1]!;
expect(again.slice(again.indexOf("--resume"), again.indexOf("--resume") + 2)).toEqual(["--resume", "s1"]);
// a review leaves no branch behind
expect(ok.calls.some(c => c[0] === "git" && c[1] === "branch" && c[2] === "-D")).toBe(true);
// twice nothing: an error, no proposal
const bad = run(["Done.", "See above."]);
expect(() => bad.go()).toThrow(/pas de compte rendu complet/);
expect(looksLikeReport("Background test finished — exit 0, already incorporated above.")).toBe(false);
// and a review like that one, already waiting, is refused at the click
expect(() => applyProposal(repo, { type: "review", pr: 1142, body: "Background test finished." }, fakeSh({}).sh)).toThrow(/abandonne-la/);
});
it("the notes for the user are never posted: not in a PR, not in a review", () => {
const summary = "Outputs 0.7.0.\n\n---\n\n## What I did\nRead it from package.json.\n\n---\n\n## Notes pour moi\nChangement minimal.";
const pr = `${summary}\n\nCloses #1185\n\n---\nPrepared by the Night Shift Mochi in Coucou, reviewed before opening.`;
expect(withoutNotes(pr)).toBe("Outputs 0.7.0.\n\n---\n\n## What I did\nRead it from package.json.\n\nCloses #1185\n\n---\nPrepared by the Night Shift Mochi in Coucou, reviewed before opening.");
expect(withoutNotes("## Summary\nOk.\n## Notes for me\nfine\n## Problems\nNone.")).toBe("## Summary\nOk.\n## Problems\nNone.");
expect(withoutNotes("## Summary\nNothing to say.")).toBe("## Summary\nNothing to say.");
// a proposal made before this is cleaned at the click
const { sh, calls } = fakeSh({ "gh pr create": "https://github.com/me/app/pull/8\n" });
applyProposal(repo, { type: "pr", branch: "mochi/night-shift/x", base: "main", title: "brain: version", body: pr }, sh);
expect(calls.find(c => c.cmd === "gh")!.input).not.toContain("Notes pour moi");
});
it("a PR's diff goes in the prompt, without lockfiles, so the reviewer starts from it", () => {
const g = (cwd: string, ...args: string[]) => realSh("git", args, { cwd });
const origin = fs.mkdtempSync(path.join(os.tmpdir(), "origin"));
g(origin, "init", "-q", "-b", "main");
g(origin, "config", "user.email", "t@t"); g(origin, "config", "user.name", "t");
fs.writeFileSync(path.join(origin, "app.ts"), "export const a = 1;\n");
g(origin, "add", "-A"); g(origin, "commit", "-qm", "base");
const clone = fs.mkdtempSync(path.join(os.tmpdir(), "clone"));
g(clone, "clone", "-q", origin, ".");
g(clone, "config", "user.email", "t@t"); g(clone, "config", "user.name", "t");
g(clone, "checkout", "-qb", "feature");
fs.writeFileSync(path.join(clone, "app.ts"), "export const a = 2;\n");
fs.writeFileSync(path.join(clone, "package-lock.json"), JSON.stringify({ big: "x".repeat(5000) }));
g(clone, "add", "-A"); g(clone, "commit", "-qm", "pr");
const d = prDiff(realSh, clone, "main");
expect(d).toContain("-export const a = 1;");
expect(d).toContain("+export const a = 2;");
expect(d).toContain("package-lock.json"); // in the list of files…
expect(d).not.toContain("x".repeat(100)); // …but not in the diff
expect(prDiff(realSh, origin, "nope")).toBe("");
const item = { type: "pr" as const, key: "pr#3@a", number: 3, title: "Bump", body: "" };
const prompt = repoPrompt(config, { instructions: "Review", item, diff: d });
expect(prompt).toMatch(/# Le diff de la PR[\s\S]*\+export const a = 2;/);
expect(repoPrompt(config, { instructions: "Review", item })).not.toContain("# Le diff de la PR");
});
it("a review stops after 25 turns and still gives its report, with tests limited to what the PR touches", () => {
const item = { type: "pr" as const, key: "pr#1148@a", number: 1148, title: "Android", body: "" };
const calls: string[][] = [];
const answers = [
{ status: 1, stdout: JSON.stringify({ subtype: "error_max_turns", is_error: true, session_id: "s9", total_cost_usd: 0.3, num_turns: 25 }) },
{ status: 0, stdout: JSON.stringify({ result: "## Summary\nNo JDK here, read the code.\n## Problems\nNone.", session_id: "s9", total_cost_usd: 0.02, num_turns: 1 }) },
];
const sh: Sh = (cmd, args) => {
calls.push([cmd, ...args]);
if (cmd !== "claude") return { status: 0, stdout: "", stderr: "" };
return { ...answers.shift()!, stderr: "" };
};
const out = runInRepo({ config, id: "pr-reviewer", name: "PR Reviewer", repo, instructions: "Review", tools: "read", model: "sonnet",
item, stamp: "s", system: "", env: {}, sh });
expect(out.proposal).toEqual({ type: "review", pr: 1148, body: "## Summary\nNo JDK here, read the code.\n## Problems\nNone." });
expect(out.usage!.costUsd).toBeCloseTo(0.32);
const [first, again] = calls.filter(c => c[0] === "claude");
expect(first![first!.indexOf("--max-turns") + 1]).toBe("25");
expect(again![again!.indexOf("--max-turns") + 1]).toBe("3");
expect(again![again!.indexOf("--resume") + 1]).toBe("s9");
expect(turnLimit("write")).toBeGreaterThan(turnLimit("read"));
expect(repoPrompt(config, { instructions: "Review", item })).toMatch(/# Les tests[\s\S]*une seule fois[\s\S]*sans rien installer/);
expect(repoPrompt(config, { instructions: "Fix", item: { type: "issue", key: "issue#1", number: 1, title: "Bug", body: "" } })).not.toContain("# Les tests");
});
it("a run keeps what it cost, summed over its questions to Claude Code", () => {
const item = { type: "pr" as const, key: "pr#7@a", number: 7, title: "Fix", body: "" };
const answers = [
{ result: "Tests finished in the background.", session_id: "s1", total_cost_usd: 0.4, num_turns: 18,
usage: { input_tokens: 900, cache_creation_input_tokens: 60000, cache_read_input_tokens: 700000, output_tokens: 9000 } },
{ result: "## Summary\nGood.", session_id: "s1", total_cost_usd: 0.05, num_turns: 1,
usage: { input_tokens: 100, cache_creation_input_tokens: 2000, cache_read_input_tokens: 80000, output_tokens: 600 } },
];
const sh: Sh = (cmd) => cmd === "claude" ? { status: 0, stderr: "", stdout: JSON.stringify(answers.shift()) } : { status: 0, stdout: "", stderr: "" };
const out = runInRepo({ config, id: "pr-reviewer", name: "PR Reviewer", repo, instructions: "Review", tools: "read", model: "sonnet",
item, stamp: "s", system: "", env: {}, sh });
expect(out.usage).toEqual({ costUsd: 0.45, input: 1000, cacheWrite: 62000, cacheRead: 780000, output: 9600, turns: 19 });
// stored with the run, and summed per Mochi
const m = addPreset(config, "pr-reviewer", { repo });
runMochi(config, m.id, { item, repoRun: () => ({ summary: "## Summary\nok", proposal: null, usage: out.usage }), now: at("2026-11-30T10:00:00") });
expect(readRuns(config, m.id).at(-1)!.usage!.costUsd).toBeCloseTo(0.45);
const sum = usageSummary(config, 30, at("2026-11-30T12:00:00")).find(x => x.id === m.id)!;
expect(sum).toMatchObject({ runs: 1, priced: 1, totalUsd: 0.45 });
expect(sum.avgUsd).toBeCloseTo(0.45);
});
it("works with no network tools at all", () => {
const flags = toolFlags("write").join(" ");
expect(flags).toContain("Bash(git push:*)");
expect(flags).toContain("Bash(gh:*)");
expect(flags).toContain("WebFetch");
expect(toolFlags("read").join(" ")).not.toContain("Edit");
});
it("Issue Triage posts only its reply, not its notes", () => {
expect(replyPart("## Reply to post\nThanks, I can reproduce it.\n\n## Notes for me\nbug, src/x.ts")).toBe("Thanks, I can reproduce it.");
expect(replyPart("no sections")).toBe("no sections");
});
});
describe("Prod Watch", () => {
it("logs a run only when an address goes down or comes back", async () => {
const m = addPreset(config, "prod-watch", { urls: "https://a.test, https://b.test" });
setEnabled(config, m.id, true);
let down = false;
const fetcher = async (url: string) => ({ status: url.includes("b.") && down ? 503 : 200 });
expect(await runWatches(config, { fetcher })).toEqual([]);
down = true;
const out = await runWatches(config, { fetcher });
expect(out).toHaveLength(1);
expect(out[0]!.output).toContain("https://b.test — HTTP 503");
expect(await runWatches(config, { fetcher })).toEqual([]); // still down: said once
down = false;
expect((await runWatches(config, { fetcher }))[0]!.output).toContain("Back up");
expect(readRuns(config, m.id)).toHaveLength(2);
});
});
describe("Ship Log", () => {
it("reads the week's commits from its repository", () => {
fs.rmSync(repo, { recursive: true, force: true });
fs.mkdirSync(repo);
const git = (...a: string[]) => spawnSync("git", a, { cwd: repo, encoding: "utf8" });
git("init", "-q"); git("config", "user.email", "t@t"); git("config", "user.name", "t");
fs.writeFileSync(path.join(repo, "a.txt"), "1"); git("add", "."); git("commit", "-qm", "Add the memory graph");
const m = addPreset(config, "ship-log", { repo });
const prompts: string[] = [];
runMochi(config, m.id, { llm: p => { prompts.push(p); return "Title: x"; } });
expect(prompts[0]).toContain("Add the memory graph");
expect(saveMochi(config, { id: m.id, name: m.name, instructions: "x" }).repo).toBe(repo);
});
});