peppa/packages/testkit/test/autonomy-levels.test.ts
Асель 4c001ba5f6 PEP-23: inAutonomyQuietHours (PEP-29 owns inQuietHours for user notification prefs)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-14 05:25:52 +05:00

376 lines
20 KiB
TypeScript

// PEP-23/24/25, spec project-autonomy: levels, dispatcher (no idle without a push),
// auto-merge and closing, working copy after the merge — mock-claude runners, mock Gitea.
import assert from "node:assert/strict";
import { execFileSync } from "node:child_process";
import { mkdtempSync, writeFileSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { after, before, describe, test } from "node:test";
import { core, db, project, runner, teardown, waitFor, type TestProject } from "./helpers.ts";
import { MockGitea } from "../src/mock-gitea.ts";
import { projects } from "@peppa/db";
import { eq } from "drizzle-orm";
process.env.PEPPA_SECRET = "mock-secret-for-tests";
const gitea = new MockGitea(join(mkdtempSync(join(tmpdir(), "peppa-auto-")), "gitea"));
const BOT = { id: 71, login: "peppa-bot", token: "mock-token-bot" };
const CHECKS = { typecheck: "pnpm typecheck", test: "pnpm test" };
before(async () => {
await gitea.start();
process.env.GITEA_URL = gitea.url;
process.env.GITEA_TOKEN = BOT.token;
gitea.addUser(BOT);
});
after(async () => {
await gitea.stop();
await teardown();
});
const projectOf = (p: TestProject) => core.getProject(db, p.key);
const taskOf = async (key: string) => (await core.resolveTask(db, key)).task;
const openQuestions = async (projectId: number) => core.pendingQuestions(db, projectId);
const activeOf = async (projectId: number) => (await core.listSessions(db, { active: true })).filter((s) => s.projectId === projectId);
const autonomy = (now = new Date()) => runner.autonomyTick(db, { now });
/** Settings without quiet hours: tests run at any time of day. */
const NO_QUIET = { quietFrom: null, quietTo: null } as const;
describe("autonomy settings", () => {
test("a project without settings is manual; presets and custom combinations; validation", async () => {
const p = await projectOf(await project({ turns: [] }));
const s = await core.getAutonomy(db, p.id);
assert.equal(core.autonomyLevel(s), "manual");
assert.deepEqual({ pick: s.pick, merge: s.merge, close: s.close, idlePush: s.idlePush }, { pick: "pm", merge: "manual", close: "pm", idlePush: false });
const auto = await core.setAutonomy(db, p.id, { level: "auto" });
assert.equal(core.autonomyLevel(auto), "auto");
assert.deepEqual({ pick: auto.pick, merge: auto.merge, close: auto.close }, { pick: "auto", merge: "auto", close: "after_merge" });
const custom = await core.setAutonomy(db, p.id, { proposal: "pm", close: "after_hours", closeAfterHours: 6 });
assert.equal(core.autonomyLevel(custom), "custom");
assert.equal(custom.pick, "auto", "fields override the current settings");
assert.match(core.describeAutonomy(custom), /каждый одобряет PM[\s\S]*через 6 ч/);
await assert.rejects(core.setAutonomy(db, p.id, { wipLimit: 0 }), /wipLimit/);
await assert.rejects(core.setAutonomy(db, p.id, { merge: "yolo" as never }), /merge/);
await core.setAutonomy(db, p.id, { level: "manual" });
assert.equal(await core.getSetting(db, `project.autonomy:${p.id}`), null, "manual = no row, as before PEP-23");
});
test("quiet hours wrap over midnight", () => {
const q = { quietFrom: 22, quietTo: 9 };
assert.equal(core.inAutonomyQuietHours(q, new Date(2026, 10, 14, 23, 30)), true);
assert.equal(core.inAutonomyQuietHours(q, new Date(2026, 10, 14, 8, 59)), true);
assert.equal(core.inAutonomyQuietHours(q, new Date(2026, 10, 14, 12, 0)), false);
assert.equal(core.inAutonomyQuietHours({ quietFrom: null, quietTo: null }, new Date(2026, 10, 14, 23)), false);
});
});
describe("dispatcher", () => {
test("manual (default): nothing starts by itself and the PM gets no push", async () => {
const tp = await project({ turns: [] });
const p = await projectOf(tp);
await runner.tick(db, { intervalMs: 0, stallMs: 60_000 });
assert.equal((await activeOf(p.id)).length, 0);
assert.equal((await openQuestions(p.id)).length, 0);
assert.equal((await taskOf(tp.taskKey)).status, "backlog");
});
test("auto: backlog → work → review → merged → done → next story, without a human; then 'backlog empty' once", async () => {
const tp = await project({ turns: [[{ mcp: "update_task", args: { task: "$TASK", status: "review" } }, { say: "Готово, PR открыт." }]] });
const p = await projectOf(tp);
const second = await core.createTask(db, { projectId: p.id, title: "вторая стори" });
await core.setAutonomy(db, p.id, { level: "auto", ...NO_QUIET });
// The watchdog tick runs the dispatcher: the lowest number first, WIP 1.
await runner.tick(db, { intervalMs: 0, stallMs: 600_000 });
let active = await activeOf(p.id);
assert.equal(active.length, 1);
assert.equal(active[0]!.taskKey, tp.taskKey);
assert.equal((await taskOf(second.key)).status, "backlog", "WIP limit 1: the second story waits");
await waitFor("first story in review", async () => (await taskOf(tp.taskKey)).status === "review");
await waitFor("agent finished its turn", async () => (await core.getSession(db, active[0]!.id)).status === "waiting_input");
assert.equal((await openQuestions(p.id)).length, 0, "merge=auto: no 'ready for review' for the PM");
await autonomy();
assert.equal((await taskOf(tp.taskKey)).status, "done", "no PR → nothing to merge → closed after merge");
assert.equal((await core.getSession(db, active[0]!.id)).status, "done", "its agent stopped");
active = await activeOf(p.id);
assert.equal(active[0]?.taskKey, second.key, "the next story was taken in the same tick");
await waitFor("second story in review", async () => (await taskOf(second.key)).status === "review");
await waitFor("second agent idle", async () => (await core.getSession(db, active[0]!.id)).status === "waiting_input");
await autonomy();
assert.equal((await taskOf(second.key)).status, "done");
const empty = (await openQuestions(p.id)).filter((q) => q.text.includes("бэклог пуст"));
assert.equal(empty.length, 1);
await autonomy();
assert.equal((await openQuestions(p.id)).filter((q) => q.text.includes("бэклог пуст")).length, 1, "told once");
});
test("auto: nothing starts while a runner of the project is rate-limited or its pool is exhausted", async () => {
const tp = await project({ turns: [] });
const p = await projectOf(tp);
const other = await core.createTask(db, { projectId: p.id, title: "другая" });
await core.setAutonomy(db, p.id, { level: "auto", ...NO_QUIET });
// A rate-limited runner on another story of the project.
const s = await core.createSession(db, { projectId: p.id, taskId: other.task.id });
await core.updateSession(db, s.id, { status: "rate_limited", resumeAt: new Date(Date.now() + 3_600_000) });
await autonomy();
assert.equal((await taskOf(tp.taskKey)).status, "backlog");
await core.updateSession(db, s.id, { status: "done" });
const sub = await core.createSubscription(db, { provider: "claude", name: `mock-sub-${p.key}`, authKind: "oauth", secret: "mock-token" });
await core.updateSubscription(db, sub.id, { status: "limited", limitedUntil: new Date(Date.now() + 3_600_000) });
const pool = await core.createPool(db, { name: `mock-pool-${p.key}`, subscriptionIds: [sub.id] });
await core.setProjectPool(db, p.id, pool.id);
assert.equal(await core.projectPoolExhausted(db, p.id), true);
await autonomy();
assert.equal((await taskOf(tp.taskKey)).status, "backlog");
assert.equal((await openQuestions(p.id)).length, 0, "no push during a limit either");
});
test("auto: a failed start puts the story back, tells the PM once and backs off", async () => {
const tp = await project({ turns: [] });
const p = await projectOf(tp);
await db.update(projects).set({ workspacePath: "/nonexistent/mock-ws" }).where(eq(projects.id, p.id));
await core.setAutonomy(db, p.id, { level: "auto", ...NO_QUIET });
const now = new Date();
await autonomy(now);
assert.equal((await taskOf(tp.taskKey)).status, "backlog");
const qs = await openQuestions(p.id);
assert.equal(qs.length, 1);
assert.match(qs[0]!.text, /не смог запустить агента/);
await autonomy(new Date(now.getTime() + 60_000));
assert.equal((await openQuestions(p.id)).length, 1, "no retry storm within the back-off");
});
test("assisted: idle push with buttons — no duplicates; Next offers the next story; Not now snoozes; Take starts", async () => {
const tp = await project({ turns: [[{ say: "работаю" }]] });
const p = await projectOf(tp);
const second = await core.createTask(db, { projectId: p.id, title: "вторая" });
await core.setAutonomy(db, p.id, { level: "assisted", ...NO_QUIET });
await autonomy();
let [q] = await openQuestions(p.id);
assert.ok(q, "pushed");
assert.match(q.text, /агенты простаивают/);
assert.match(q.text, new RegExp(`Взять в работу ${tp.taskKey}`));
assert.equal(q.options?.length, 3);
await autonomy();
assert.equal((await openQuestions(p.id)).length, 1, "one open push at a time");
await runner.answerAndDeliver(db, q.id, runner.IDLE_NEXT, "telegram");
[q] = await openQuestions(p.id);
assert.match(q!.text, new RegExp(`Взять в работу ${second.key}`), "Next → the next story right away");
await runner.answerAndDeliver(db, q!.id, q!.options![2]!, "telegram");
assert.equal((await openQuestions(p.id)).length, 0);
await autonomy();
assert.equal((await openQuestions(p.id)).length, 0, "Not now → quiet for idlePushHours");
await autonomy(new Date(Date.now() + 5 * 3_600_000));
[q] = await openQuestions(p.id);
assert.ok(q, "pushed again after the snooze");
await runner.answerAndDeliver(db, q.id, q.options![0]!, "web");
assert.equal((await taskOf(tp.taskKey)).status, "in_progress", "Take → the story is in work");
const active = await activeOf(p.id);
assert.equal(active.length, 1);
await autonomy();
assert.equal((await openQuestions(p.id)).filter((x) => x.text.includes("простаивают")).length, 0, "an agent works: no push");
await runner.stopSession(db, active[0]!.id);
});
test("assisted: no push in quiet hours, nor more often than idlePushHours; a manual move closes the push", async () => {
const tp = await project({ turns: [[{ say: "работаю" }]] });
const p = await projectOf(tp);
await core.setAutonomy(db, p.id, { level: "assisted", quietFrom: 22, quietTo: 9, idlePushHours: 4 });
await autonomy(new Date(2026, 10, 14, 23, 0));
assert.equal((await openQuestions(p.id)).length, 0, "quiet hours");
await autonomy(new Date(2026, 10, 14, 10, 0));
const [q] = await openQuestions(p.id);
assert.ok(q);
// The PM starts the story from the board instead: the push is moot.
const { started } = await runner.moveTask(db, await core.resolveTask(db, tp.taskKey), "in_progress");
await autonomy(new Date(2026, 10, 14, 10, 1));
assert.equal((await core.getQuestion(db, q.id)).answeredVia, "system");
await runner.stopSession(db, started!);
await runner.moveTask(db, await core.resolveTask(db, tp.taskKey), "backlog");
await autonomy(new Date(2026, 10, 14, 11, 0));
assert.equal((await openQuestions(p.id)).length, 0, "not more often than every 4 h");
await autonomy(new Date(2026, 10, 14, 14, 1));
assert.equal((await openQuestions(p.id)).length, 1);
});
});
interface PrTask {
tp: TestProject;
proj: Awaited<ReturnType<typeof core.getProject>>;
pr: { number: number };
push(files?: Record<string, string>): string;
green(sha: string): void;
}
/** A story in review with an open PR (task/<KEY>-1) in mock Gitea. */
async function prTask(level: Parameters<typeof core.setAutonomy>[2]): Promise<PrTask> {
const tp = await project({ turns: [] });
const proj = await projectOf(tp);
const pj = JSON.stringify({ slug: proj.slug, key: tp.key, name: tp.key, peppaUrl: "http://test", checks: CHECKS });
writeFileSync(join(tp.dir, ".peppa/project.json"), pj);
gitea.addRepo(proj.giteaOwner, proj.giteaRepo, { files: { "README.md": "x\n", ".peppa/project.json": pj } });
gitea.repo(proj.giteaOwner, proj.giteaRepo).collaborators[BOT.login] = "write";
let n = 0;
const push = (files: Record<string, string> = {}) => gitea.commit(proj.giteaOwner, proj.giteaRepo, `task/${tp.taskKey}`, { [`f${n++}.txt`]: String(n), ...files });
const sha = push();
const pr = gitea.openPull(proj.giteaOwner, proj.giteaRepo, `task/${tp.taskKey}`);
const green = (s: string) => {
for (const c of Object.keys(CHECKS)) gitea.setStatus(proj.giteaOwner, proj.giteaRepo, s, `peppa/${c}`, "success");
};
green(sha);
await core.updateTask(db, await core.resolveTask(db, tp.taskKey), { status: "review", prUrl: `${gitea.url}/${proj.giteaOwner}/${proj.giteaRepo}/pulls/${pr.number}` });
await core.setAutonomy(db, proj.id, { ...level, ...NO_QUIET });
return { tp, proj, pr, push, green };
}
const pull = (t: PrTask) => gitea.repo(t.proj.giteaOwner, t.proj.giteaRepo).pulls[t.pr.number - 1]!;
describe("auto-merge and closing", () => {
test("merge=auto, close=after_merge: a green PR is merged and the story closed", async () => {
const t = await prTask({ merge: "auto", close: "after_merge" });
await autonomy();
assert.equal(pull(t).merged, true);
assert.equal((await taskOf(t.tp.taskKey)).status, "done");
});
test("merge=auto, close=pm: merged, then 'ready for review' with Accept → done", async () => {
const t = await prTask({ merge: "auto", close: "pm" });
await autonomy();
assert.equal(pull(t).merged, true);
assert.equal((await taskOf(t.tp.taskKey)).status, "review");
const [q] = await openQuestions(t.proj.id);
assert.match(q!.text, /PR смержен автоматически/);
assert.ok(await runner.isReviewQuestion(db, q!));
await autonomy();
assert.equal((await openQuestions(t.proj.id)).length, 1, "asked once");
await runner.acceptTask(db, q!.id, "telegram");
assert.equal((await taskOf(t.tp.taskKey)).status, "done");
});
test("pending checks: nothing merged yet", async () => {
const t = await prTask({ merge: "auto", close: "after_merge" });
t.push(); // new head without statuses
await autonomy();
assert.equal(pull(t).merged, false);
assert.equal((await taskOf(t.tp.taskKey)).status, "review");
});
test("conflicts: the agent is asked to rebase (once per head commit)", async () => {
const t = await prTask({ merge: "auto", close: "after_merge" });
pull(t).mergeable = false;
await autonomy();
assert.equal(pull(t).merged, false);
assert.equal((await taskOf(t.tp.taskKey)).status, "in_progress", "back to work");
const [s] = await activeOf(t.proj.id);
assert.ok(s, "an agent was started for the rebase");
const ev = await t.tp.waitLog("rebase prompt", (e) => e.ev === "prompt" && String(e.prompt).includes("rebase"));
assert.match(String(ev.prompt), /force-with-lease/);
await runner.stopSession(db, s!.id);
});
test("pipeline change: not merged, the PM gets one review message with Accept", async () => {
const t = await prTask({ merge: "auto", close: "after_merge" });
t.green(t.push({ ".gitea/workflows/ci.yml": "on: push\n" }));
await autonomy();
await autonomy();
assert.equal(pull(t).merged, false);
const qs = (await openQuestions(t.proj.id)).filter((q) => q.text.includes("меняет конвейер"));
assert.equal(qs.length, 1, "asked once per head commit");
assert.ok(await runner.isReviewQuestion(db, qs[0]!), "with «Принять»");
await runner.acceptTask(db, qs[0]!.id, "web");
assert.equal(pull(t).merged, true, "the PM's Accept merges it");
});
test("close=after_hours: 'ready for review' without comments for N hours → accepted (PR merged)", async () => {
const t = await prTask({ close: "after_hours", closeAfterHours: 2 });
const q = await core.askPm(db, await core.resolveTask(db, t.tp.taskKey), { kind: "attention", text: "✅ Стори готова к ревью" });
await autonomy(new Date(Date.now() + 3_600_000));
assert.equal((await taskOf(t.tp.taskKey)).status, "review", "not yet");
await autonomy(new Date(Date.now() + 2 * 3_600_000 + 60_000));
assert.equal((await taskOf(t.tp.taskKey)).status, "done");
assert.equal(pull(t).merged, true);
assert.match((await core.getQuestion(db, q.id)).answer ?? "", /автоматически/);
});
test("close=after_hours never accepts a pipeline change by itself", async () => {
const t = await prTask({ close: "after_hours", closeAfterHours: 1 });
t.green(t.push({ ".gitea/peppa-check.sh": "exit 0\n" }));
await core.askPm(db, await core.resolveTask(db, t.tp.taskKey), { kind: "attention", text: "✅ Стори готова к ревью" });
await autonomy(new Date(Date.now() + 2 * 3_600_000));
assert.equal((await taskOf(t.tp.taskKey)).status, "review");
assert.equal(pull(t).merged, false);
assert.ok((await openQuestions(t.proj.id)).some((q) => q.text.includes("меняет конвейер")));
});
});
describe("proposal approval and the working copy", () => {
test("proposal=pm: the agent can't start Apply itself; the prompt says to request approval", async () => {
const tp = await project({
turns: [
[
{ mcp: "update_task", args: { task: "$TASK", status: "proposing", openspec_change: "x-1" } },
{ mcp: "update_task", args: { task: "$TASK", status: "in_progress" } },
{ mcp: "request_approval", args: { task: "$TASK", summary: "Proposal: сделать X без новых зависимостей" } },
],
],
});
const p = await projectOf(tp);
await core.setAutonomy(db, p.id, { proposal: "pm" });
const sid = await tp.start();
const refused = await tp.waitLog("refused apply", (e) => e.ev === "mcp" && e.tool === "update_task" && e.isError === true);
assert.match(String(refused.text), /approves every proposal/);
assert.ok(tp.log().some((e) => e.ev === "prompt" && String(e.prompt).includes("PM одобряет каждый proposal")));
const q = await tp.waitQuestion(sid, "approval");
assert.equal((await taskOf(tp.taskKey)).status, "awaiting_approval");
await runner.answerAndDeliver(db, q.id, "ок", "web");
assert.equal((await taskOf(tp.taskKey)).status, "in_progress", "the PM's approval starts Apply");
await runner.stopSession(db, sid);
});
test("syncWorkspace: the working copy on the story branch goes to the merged main; the local branch is deleted", async () => {
const root = mkdtempSync(join(tmpdir(), "peppa-sync-"));
const g = (cwd: string, ...a: string[]) => execFileSync("git", ["-c", "user.email=t@t", "-c", "user.name=t", ...a], { cwd, encoding: "utf8", stdio: ["ignore", "pipe", "ignore"] }).trim();
const origin = join(root, "origin.git");
execFileSync("git", ["init", "--bare", "-b", "main", origin], { stdio: "ignore" });
const ws = join(root, "ws");
execFileSync("git", ["clone", origin, ws], { stdio: "ignore" });
g(ws, "checkout", "-b", "main");
writeFileSync(join(ws, "a.txt"), "1");
g(ws, "add", ".");
g(ws, "commit", "-m", "init");
g(ws, "push", "-u", "origin", "main");
const tp = await project({ turns: [] });
const p = await projectOf(tp);
await db.update(projects).set({ workspacePath: ws }).where(eq(projects.id, p.id));
g(ws, "checkout", "-b", `task/${tp.taskKey}`);
writeFileSync(join(ws, "b.txt"), "2");
g(ws, "add", "b.txt");
g(ws, "commit", "-m", "story");
g(ws, "push", "origin", `task/${tp.taskKey}`);
// The PR is merged on the server: main gets the story's commit.
g(ws, "push", "origin", `task/${tp.taskKey}:main`);
const ref = await core.resolveTask(db, tp.taskKey);
assert.equal(await runner.syncWorkspace(db, ref), "synced");
assert.equal(g(ws, "rev-parse", "--abbrev-ref", "HEAD"), "main");
assert.equal(g(ws, "rev-parse", "HEAD"), g(ws, "rev-parse", "origin/main"));
assert.equal(g(ws, "branch", "--list", `task/${tp.taskKey}`), "", "merged local branch deleted");
// Another branch or uncommitted changes: left alone.
g(ws, "checkout", "-b", "feature/other");
assert.equal(await runner.syncWorkspace(db, ref), "other_branch");
g(ws, "checkout", "main");
writeFileSync(join(ws, "a.txt"), "dirty");
assert.equal(await runner.syncWorkspace(db, ref), "dirty");
});
});