peppa/packages/testkit/test/cjm.test.ts

328 lines
17 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

// Customer journeys of Peppa, end to end: runner → tmux → mock agent CLI → real hooks /
// notify → DB ← PM answers (as the Telegram bot will send them) → back into the session.
import assert from "node:assert/strict";
import { execFileSync } from "node:child_process";
import { after, describe, test } from "node:test";
import { core, db, project, runner, teardown, tick, waitFor } from "./helpers.ts";
after(teardown);
const PM = "telegram" as const;
const isPrompt = (needle: string) => (e: { ev: string; prompt?: unknown }) => e.ev === "prompt" && String(e.prompt).includes(needle);
describe("Claude: task lifecycle", () => {
test("proposal → PM approval → apply → review; agent can't self-accept", async () => {
const p = await project({
turns: [
[
{ mcp: "get_task", args: { task: "1" } },
{ mcp: "update_task", args: { task: "1", status: "proposing", openspec_change: "cjm-1-demo" } },
{ work: 300 },
{ mcp: "request_approval", args: { task: "1", summary: "Сделаем демо-фичу. Риски: нет." } },
{ say: "Proposal готов, жду одобрения." },
],
[
{ mcp: "report_progress", args: { task: "1", text: "реализовал 1/1" } },
{ mcp: "update_task", args: { task: "1", status: "done" } },
{ mcp: "update_task", args: { task: "1", status: "review", pr_url: "https://git.example/pr/1" } },
{ say: "PR открыт." },
],
],
});
// PEP-94: approval is a project setting now (off by default).
await core.setAutonomy(db, (await core.getProject(db, p.key)).id, { proposal: "pm" });
const sid = await p.start();
const approval = await p.waitQuestion(sid, "approval");
await p.waitStatus(sid, "waiting_input");
assert.equal((await p.task()).status, "awaiting_approval");
assert.equal((await p.task()).openspecChange, "cjm-1-demo");
// The agent already asked, so no extra "attention" ping for the same turn.
assert.deepEqual((await p.pending(sid)).map((q) => q.kind), ["approval"]);
const { delivered } = await runner.answerAndDeliver(db, approval.id, "ок, погнали", PM);
assert.ok(delivered);
assert.equal((await p.task()).status, "in_progress");
await p.waitLog("approval message reaches the agent", isPrompt("одобрил proposal"));
await p.waitLog("PR turn finished", (e) => e.ev === "turn_end" && e.gen === "1" && p.log().filter((x) => x.ev === "turn_end").length >= 2);
const t = await p.task();
assert.equal(t.status, "review");
assert.equal(t.prUrl, "https://git.example/pr/1");
const doneAttempt = p.log().find((e) => e.ev === "mcp" && e.tool === "update_task" && (e.args as { status?: string }).status === "done");
assert.equal(doneAttempt?.isError, true, "agent must not be able to mark the task done");
const attention = await p.waitQuestion(sid, "attention");
assert.match(attention.text, /PR открыт/);
await runner.stopSession(db, sid);
});
test("rejected proposal goes back to proposing with the PM's comment", async () => {
const p = await project({
turns: [[{ mcp: "request_approval", args: { task: "1", summary: "План А для проверки отказа." } }, { say: "Жду." }], [{ say: "Переделал." }]],
});
// PEP-94: approval is a project setting now (off by default).
await core.setAutonomy(db, (await core.getProject(db, p.key)).id, { proposal: "pm" });
const sid = await p.start();
const q = await p.waitQuestion(sid, "approval");
await runner.answerAndDeliver(db, q.id, "нет, сделай через очередь", PM);
assert.equal((await p.task()).status, "proposing");
await p.waitLog("rejection reaches the agent", isPrompt("не одобрил"));
assert.ok(p.log().some(isPrompt("сделай через очередь")));
await runner.stopSession(db, sid);
});
});
describe("Claude: questions to the PM", () => {
test("ask_pm question answered from Telegram is typed into the session", async () => {
const p = await project({
turns: [[{ mcp: "ask_pm", args: { task: "1", question: "Какую БД взять?", options: ["Postgres", "SQLite"], default: "Postgres" } }, { say: "Жду ответа." }], [{ say: "Беру Postgres." }]],
});
const sid = await p.start();
const q = await p.waitQuestion(sid, "question");
assert.deepEqual(q.options, ["Postgres", "SQLite"]);
await p.waitStatus(sid, "waiting_input");
await runner.answerAndDeliver(db, q.id, "Postgres", PM);
await p.waitLog("answer reaches the agent", isPrompt(`Ответ PM на вопрос #${q.id}: Postgres`));
await runner.stopSession(db, sid);
});
test("multi-line answer arrives as one prompt (bracketed paste)", async () => {
const p = await project({ turns: [[{ say: "Что дальше?" }], [{ say: "Понял." }]] });
const sid = await p.start();
await p.waitStatus(sid, "idle");
// PEP-149: the end of a turn asks nobody — a message of the factory stands in for the old alert.
const q = await core.raiseSessionQuestion(db, await p.session(sid), "attention", "Что дальше?");
await runner.answerAndDeliver(db, q.id, "строка один\nстрока два", PM);
const e = await p.waitLog("pasted prompt", isPrompt("строка один"));
assert.equal(e.prompt, "строка один\nстрока два");
assert.equal(p.log().filter((x) => x.ev === "prompt").length, 2, "must not be split into two prompts");
await runner.stopSession(db, sid);
});
test("AskUserQuestion answered in time goes back through the hook", async () => {
const p = await project({
turns: [[{ ask: [{ question: "Какая БД?", options: ["Postgres", "SQLite"] }, { question: "Нужен Docker?", options: ["Да", "Нет"] }] }, { say: "Ок." }]],
});
const sid = await p.start();
const qs = await waitFor("two hook questions", async () => {
const list = (await p.pending(sid)).filter((q) => q.kind === "question");
return list.length === 2 && list;
});
assert.ok(qs.every((q) => q.awaitingHook));
await runner.answerAndDeliver(db, qs[0]!.id, "SQLite", PM);
await runner.answerAndDeliver(db, qs[1]!.id, "Нет", PM);
const e = await p.waitLog("answers via hook", (x) => x.ev === "ask" && x.via === "hook");
assert.deepEqual(e.answers, { "Какая БД?": "SQLite", "Нужен Docker?": "Нет" });
await runner.stopSession(db, sid);
});
test("AskUserQuestion timeout: tool denied, late answer typed into the terminal", async () => {
const p = await project({ turns: [[{ ask: [{ question: "Деплоить сегодня?" }] }], [{ say: "Понял, деплою." }]] });
const sid = await p.start();
const q = await p.waitQuestion(sid, "question");
await p.waitLog("hook gives up and denies", (x) => x.ev === "ask" && x.via === "denied", 15000);
assert.equal((await core.getQuestion(db, q.id)).awaitingHook, false);
await runner.answerAndDeliver(db, q.id, "да", PM);
await p.waitLog("late answer typed in", isPrompt(`Ответ PM на вопрос #${q.id}: да`));
await runner.stopSession(db, sid);
});
test("typing in the terminal answers whatever the session was waiting for", async () => {
const p = await project({ turns: [[{ mcp: "ask_pm", args: { task: "1", question: "Название сервиса?", options: ["Да", "Нет"], default: "Да" } }], [{ say: "Ок." }]] });
const sid = await p.start();
const q = await p.waitQuestion(sid, "question");
await runner.sendToSession(db, sid, "назови peppa-api", { person: true });
await waitFor("answered via terminal", async () => (await core.getQuestion(db, q.id)).answeredVia === "terminal");
assert.equal((await core.getQuestion(db, q.id)).answer, "назови peppa-api");
await runner.stopSession(db, sid);
});
});
describe("Claude: permissions", () => {
for (const [answer, behavior] of [
["allow", "allow"],
["always", "allow"],
["deny", "deny"],
] as const) {
test(`PM answers "${answer}" in time → hook returns ${behavior}`, async () => {
const p = await project({ turns: [[{ permission: { tool: "Bash", input: { command: "rm -rf build" } } }, { say: "Готово." }]] });
const sid = await p.start();
const q = await p.waitQuestion(sid, "permission");
assert.match(q.text, /rm -rf build/);
assert.equal((await p.session(sid)).status, "waiting_input");
await runner.answerAndDeliver(db, q.id, answer, PM);
const e = await p.waitLog("decision via hook", (x) => x.ev === "permission");
assert.equal(e.via, "hook");
assert.equal(e.behavior, behavior);
assert.equal(e.updatedPermissions, answer === "always");
await runner.stopSession(db, sid);
});
}
test("no answer in time → Claude's own dialog; late answer presses the key", async () => {
const p = await project({ turns: [[{ permission: { tool: "Write", input: { file_path: "/etc/hosts" } } }, { say: "Записал." }]] });
const sid = await p.start();
const q = await p.waitQuestion(sid, "permission");
await waitFor("hook released", async () => !(await core.getQuestion(db, q.id)).awaitingHook, 15000);
await p.waitLog("dialog drawn", (e) => e.ev === "dialog");
const { delivered } = await runner.answerAndDeliver(db, q.id, "allow", PM);
assert.ok(delivered);
const e = await p.waitLog("decision in terminal", (x) => x.ev === "permission");
assert.equal(e.via, "terminal");
assert.equal(e.key, "1");
await runner.stopSession(db, sid);
});
});
describe("Claude: failures and recovery", () => {
test("usage limit → rate_limited; resume continues the same conversation in a new generation", async () => {
const p = await project({ turns: [[{ work: 200 }, { limit: true }]], resumeTurns: [[{ say: "Продолжаю после лимита." }]] });
const sid = await p.start();
await p.waitStatus(sid, "rate_limited");
const alert = await p.waitQuestion(sid, "attention");
assert.match(alert.text, /лимит/);
const conv = (await p.session(sid)).conversationId;
assert.ok(conv);
await runner.answerAndDeliver(db, alert.id, "ok", PM).catch(() => {});
execFileSync("tmux", ["-L", process.env.PEPPA_TMUX_SOCKET!, "kill-session", "-t", `=${(await p.session(sid)).tmuxName}`]);
const resumed = await runner.resumeSession(db, sid);
assert.equal(resumed.generation, 2);
const start = await p.waitLog("gen 2 started", (e) => e.ev === "start" && e.gen === "2");
assert.equal(start.resume, conv);
await p.waitLog("resume prompt", (e) => e.ev === "prompt" && e.gen === "2" && String(e.prompt).includes("Продолжай работу"));
// A late hook from generation 1 must be ignored.
execFileSync("bash", ["-c", `echo '{}' | PEPPA_SESSION_ID=${sid} PEPPA_GENERATION=1 ${process.env.PEPPA_MOCK_MCP_BIN!.replace("mcp/bin/peppa-mcp", "runner/bin/peppa-hook")} stop`]);
await p.waitLog("gen 2 turn done", (e) => e.ev === "turn_end" && e.gen === "2");
await runner.stopSession(db, sid);
});
test("hang → watchdog marks stalled and alerts; still-running session can't be resumed", async () => {
const p = await project({ turns: [[{ say: "Начинаю." }, { hang: true }]] });
const sid = await p.start();
await p.waitLog("frozen", (e) => e.ev === "hang");
await tick(500);
await new Promise((r) => setTimeout(r, 1200));
await tick(500);
await p.waitStatus(sid, "stalled", 3000);
const alert = await p.waitQuestion(sid, "attention");
assert.match(alert.text, /ничего не происходит/);
await assert.rejects(runner.resumeSession(db, sid), /still running/);
await runner.stopSession(db, sid);
});
test("busy agent with a changing screen is not reported as stalled", async () => {
const p = await project({ turns: [[{ work: 5000 }, { say: "Долгая работа закончена." }]] });
const sid = await p.start();
await p.waitLog("working", (e) => e.ev === "action" && "work" in (e.action as object));
for (let i = 0; i < 4; i++) {
await new Promise((r) => setTimeout(r, 800));
await tick(600);
assert.notEqual((await p.session(sid)).status, "stalled");
}
await runner.stopSession(db, sid);
});
test("crash → failed with exit code and screen tail; resume relaunches", async () => {
const p = await project({ turns: [[{ say: "Сейчас упаду." }, { crash: 3 }]], resumeTurns: [[{ say: "Поднялся." }]] });
const sid = await p.start();
await p.waitLog("crashed", (e) => e.ev === "exit");
await waitFor("pane dead", async () => {
await tick();
return (await p.session(sid)).status === "failed";
});
const alert = await p.waitQuestion(sid, "attention");
assert.match(alert.text, /код 3/);
assert.match(alert.text, /simulated crash/);
await runner.resumeSession(db, sid);
await p.waitLog("relaunched", (e) => e.ev === "turn_end" && e.gen === "2");
await runner.stopSession(db, sid);
});
test("tmux session killed from outside → failed, PM alerted", async () => {
const p = await project({ turns: [[{ say: "Работаю." }]] });
const sid = await p.start();
await p.waitStatus(sid, "idle");
execFileSync("tmux", ["-L", process.env.PEPPA_TMUX_SOCKET!, "kill-session", "-t", `=${(await p.session(sid)).tmuxName}`]);
await tick();
assert.equal((await p.session(sid)).status, "failed");
assert.ok((await p.pending(sid)).some((q) => /перестал работать/.test(q.text)));
});
test("/clear ends the Claude conversation but not the process", async () => {
const p = await project({ turns: [[{ clear: true }, { say: "Контекст очищен." }]] });
const sid = await p.start();
const before = await waitFor("conversation id", async () => (await p.session(sid)).conversationId);
const cleared = await p.waitLog("cleared", (e) => e.ev === "clear");
await waitFor("new conversation id stored", async () => (await p.session(sid)).conversationId === cleared.newConversationId);
assert.notEqual(before, cleared.newConversationId);
await p.waitStatus(sid, "idle");
await runner.stopSession(db, sid);
});
test("shared rules are injected into the system prompt", async () => {
const p = await project({ turns: [[{ say: "Ок." }]] });
const sid = await p.start();
const start = await p.waitLog("started", (e) => e.ev === "start");
assert.equal(start.rulesHead, "# Правила Пеппы для агентов");
assert.ok((start.argv as string[]).includes("--append-system-prompt-file"));
await runner.stopSession(db, sid);
});
});
describe("Codex", () => {
test("turn completion via notify; thread id stored; answer typed in; rules and MCP passed as config", async () => {
const p = await project({ turns: [[{ mcp: "get_task", args: { task: "1" } }, { say: "Codex: изучил задачу, вопрос — какой фреймворк?" }], [{ say: "Беру Fastify." }]] });
const sid = await p.start({ provider: "codex" });
const start = await p.waitLog("started", (e) => e.ev === "start");
assert.equal(start.rulesHead, "# Правила Пеппы для агентов");
assert.ok((start.argv as string[]).some((a) => a.startsWith("mcp_servers.peppa.command=")));
const mcpCall = await p.waitLog("codex reaches peppa MCP", (e) => e.ev === "mcp" && e.tool === "get_task");
assert.equal(mcpCall.isError, false);
// PEP-149: the end of a turn is a progress record, not a question to the PM.
await p.waitStatus(sid, "idle");
assert.deepEqual(await p.pending(sid), []);
const s = await p.session(sid);
assert.equal(s.provider, "codex");
assert.equal(s.conversationId, start.conversationId);
await runner.sendToSession(db, sid, "Fastify");
await p.waitLog("answer typed in", isPrompt("Fastify"));
await runner.stopSession(db, sid);
});
test("usage limit banner (no hook) → watchdog marks rate_limited", async () => {
const p = await project({ turns: [[{ limit: true }]] });
const sid = await p.start({ provider: "codex" });
await p.waitLog("limit shown", (e) => e.ev === "limit");
await waitFor("rate_limited", async () => {
await tick();
return (await p.session(sid)).status === "rate_limited";
});
assert.ok((await p.pending(sid)).some((q) => /лимит/.test(q.text)));
await runner.stopSession(db, sid);
});
test("crash → resume uses `codex resume <thread>`", async () => {
const p = await project({ turns: [[{ say: "Первый ход." }], [{ crash: 2 }]], resumeTurns: [[{ say: "Вернулся." }]] });
const sid = await p.start({ provider: "codex" });
await p.waitStatus(sid, "idle");
const thread = (await p.session(sid)).conversationId;
await runner.sendToSession(db, sid, "продолжай");
await p.waitLog("crashed", (e) => e.ev === "exit");
await waitFor("failed", async () => {
await tick();
return (await p.session(sid)).status === "failed";
});
await runner.resumeSession(db, sid);
const start = await p.waitLog("gen 2", (e) => e.ev === "start" && e.gen === "2");
assert.equal(start.resume, thread);
const argv = start.argv as string[];
assert.equal(argv[argv.indexOf("resume") + 1], thread);
await runner.stopSession(db, sid);
});
});