// PEP-127, spec task-autonomy «"Принять" при конфликте доводится до конца без PM»: // mock-claude runners, mock Gitea. import assert from "node:assert/strict"; 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, superadmin, teardown, waitFor, type TestProject } from "./helpers.ts"; import { MockGitea } from "../src/mock-gitea.ts"; import { events } from "@peppa/db"; import { and, eq } from "drizzle-orm"; process.env.PEPPA_SECRET = "mock-secret-for-tests"; const gitea = new MockGitea(join(mkdtempSync(join(tmpdir(), "peppa-accept-")), "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(); }); type Turns = Parameters[0]["turns"]; /** A story with an open green PR (task/-1) in mock Gitea; `review` puts it in review right away. */ async function prTask(turns: Turns, review = true) { const tp: TestProject = await project({ turns }); const proj = await core.getProject(db, tp.key); 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 = () => gitea.commit(proj.giteaOwner, proj.giteaRepo, `task/${tp.taskKey}`, { [`f${n++}.txt`]: String(n) }); const green = (s: string) => { for (const c of Object.keys(CHECKS)) gitea.setStatus(proj.giteaOwner, proj.giteaRepo, s, `peppa/${c}`, "success"); }; green(push()); const pr = gitea.openPull(proj.giteaOwner, proj.giteaRepo, `task/${tp.taskKey}`); const prUrl = `${gitea.url}/${proj.giteaOwner}/${proj.giteaRepo}/pulls/${pr.number}`; const ref = () => core.resolveTask(db, tp.taskKey); if (review) await core.updateTask(db, await ref(), { status: "review", prUrl }); const pull = () => gitea.repo(proj.giteaOwner, proj.giteaRepo).pulls[pr.number - 1]!; const status = async () => (await ref()).task.status; const toReview = async () => core.updateTask(db, await ref(), { status: "review" }); const stopAll = async () => { for (const s of (await core.listSessions(db, { active: true })).filter((s) => s.projectId === proj.id)) await runner.stopSession(db, s.id); }; /** Someone else's story lands in main: the PR branch is behind now (no conflict). */ const mainMoves = () => gitea.commit(proj.giteaOwner, proj.giteaRepo, "main", { [`main${n++}.txt`]: "m" }); const head = () => gitea.sha(proj.giteaOwner, proj.giteaRepo, `task/${tp.taskKey}`); const contains = (sha: string) => gitea.ahead(gitea.repo(proj.giteaOwner, proj.giteaRepo), `task/${tp.taskKey}`, sha) === 0; const taskEvents = async (type: string) => db.select().from(events).where(and(eq(events.taskId, (await ref()).task.id), eq(events.type, type))); return { tp, proj, prUrl, push, green, ref, pull, status, toReview, stopAll, taskEvents, mainMoves, head, contains }; } const tick = (now = new Date()) => runner.pendingAcceptTick(db, { now }); const failures = async (projectId: number) => (await core.pendingQuestions(db, projectId)).filter((q) => q.text.includes("не получилось довести приёмку")); describe("accept over a conflict", () => { test("Конфликт при «Принять» — закрывается само", async () => { const t = await prTask( [ [{ mcp: "update_task", args: { task: "1", status: "review" } }, { say: "PR открыт." }], [{ mcp: "update_task", args: { task: "1", status: "review" } }, { say: "Rebase сделан." }], ], false, ); // The agent's first turn hands the story to review with the PR. await core.updateTask(db, await t.ref(), { prUrl: t.prUrl }); const sid = await t.tp.start(); const review = await t.tp.waitQuestion(sid, "attention"); assert.match(review.text, /готова к ревью/); t.pull().mergeable = false; const r = await runner.acceptTask(db, review.id, "telegram"); t.pull().mergeable = true; // the agent "rebases" before its turn reaches update_task assert.equal(r.pending, true, "accepted, carried through by Peppa"); assert.equal((await core.getQuestion(db, review.id)).answer, core.PENDING_ACCEPT_ANSWER); assert.ok(await core.getPendingAccept(db, (await t.ref()).task.id)); 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/); // Back in review: no new «готова к ревью» for the PM. await waitFor("stop hook saw the accept", async () => (await t.taskEvents("awaiting_accept_merge")).length || undefined); assert.equal(await t.status(), "review"); assert.equal((await core.pendingQuestions(db, t.proj.id)).length, 0, "nothing new to answer"); assert.equal(t.pull().merged, false); await tick(); assert.equal(t.pull().merged, true); assert.equal(await t.status(), "done"); assert.equal(await core.getPendingAccept(db, (await t.ref()).task.id), null); assert.equal((await t.taskEvents("accept_completed")).length, 1); await t.tp.waitStatus(sid, "done"); }); test("Проверки после rebase ещё идут", async () => { const t = await prTask([]); t.pull().mergeable = false; const r = await runner.acceptStory(db, await t.ref(), "web"); assert.equal(r.pending, true); assert.equal(await t.status(), "in_progress", "the agent is rebasing"); await tick(); assert.equal(t.pull().merged, false, "not merged while the agent works"); const sha = t.push(); // the rebased head, checks not reported yet t.pull().mergeable = true; await t.toReview(); await tick(); assert.equal(t.pull().merged, false); assert.equal(await t.status(), "review"); assert.equal((await failures(t.proj.id)).length, 0); t.green(sha); await tick(); assert.equal(t.pull().merged, true); assert.equal(await t.status(), "done"); }); test("Три конфликта подряд", async () => { const sent = await superadmin(); const t = await prTask([]); t.pull().mergeable = false; await runner.acceptStory(db, await t.ref(), "web"); for (let i = 2; i <= runner.ACCEPT_MAX_REBASES; i++) { await t.toReview(); await tick(); assert.equal(await t.status(), "in_progress", `rebase ${i} requested`); assert.equal((await core.getPendingAccept(db, (await t.ref()).task.id))?.rebases, i); } await t.toReview(); await tick(); await tick(); // PEP-150: the owner is not told; the superadmin gets one message. assert.equal((await failures(t.proj.id)).length, 0, "nothing for the owner"); const told = (await sent()).filter((x) => x.includes("не получилось довести приёмку")); assert.equal(told.length, 1, "one message"); assert.match(told[0]!, /несколько раз подряд разошлись/); assert.equal(await core.getPendingAccept(db, (await t.ref()).task.id), null); assert.equal(await t.status(), "review"); // Nothing merges by itself any more, even when the conflict is gone… t.pull().mergeable = true; await tick(); assert.equal(t.pull().merged, false); // …the story goes back to the owner the usual way: «готова к ревью» once it can be accepted. assert.ok(await core.getReviewHold(db, (await t.ref()).task.id), "a held ready-for-review message"); // (An open message on a story in review is its «Принять» — whichever text it carries.) The held // card goes out on a review tick once the gate opens; the mock's checks settle within a few ticks. const id = (await t.ref()).task.id; const open = async () => (await core.pendingQuestions(db, t.proj.id)).filter((q) => q.taskId === id && (q.kind === "attention" || q.msgType === "done")); for (let i = 0; i < 10 && !(await open()).length; i++) { await runner.reviewCardTick(db, {}); await new Promise((r) => setTimeout(r, 200)); } const cards = await open(); assert.ok(cards.length >= 1, "the owner gets «Принять» again"); await t.stopAll(); }); test("Срок вышел: одно сообщение суперадмину", async () => { const sent = await superadmin(); const t = await prTask([]); t.pull().mergeable = false; await runner.acceptStory(db, await t.ref(), "web"); await tick(new Date(Date.now() + 25 * 3_600_000)); await tick(new Date(Date.now() + 26 * 3_600_000)); assert.equal((await failures(t.proj.id)).length, 0, "nothing for the owner"); const told = (await sent()).filter((x) => x.includes("не получилось довести приёмку")); assert.equal(told.length, 1); assert.match(told[0]!, /за 24 ч/); await t.stopAll(); }); test("PM забрал стори", async () => { const t = await prTask([]); t.pull().mergeable = false; await runner.acceptStory(db, await t.ref(), "web"); await runner.moveTask(db, await t.ref(), "backlog"); await tick(); assert.equal(await core.getPendingAccept(db, (await t.ref()).task.id), null); t.pull().mergeable = true; await tick(); assert.equal(t.pull().merged, false); assert.equal(await t.status(), "backlog"); }); test("без конфликта «Принять» работает как раньше", async () => { const t = await prTask([]); const r = await runner.acceptStory(db, await t.ref(), "web"); assert.ok(!r.pending); assert.equal(t.pull().merged, true); assert.equal(await t.status(), "done"); }); }); // PEP-127 (дополнение PM): «готова к ревью» уходит PM только когда стори можно смержить. const cardTick = () => runner.reviewCardTick(db); const cards = async (projectId: number) => (await core.pendingQuestions(db, projectId)).filter((q) => q.kind === "attention" && q.text.includes("готова к ревью")); const CARD = "✅ Стори готова к ревью"; /** The rebasing mock agent is done: stopped, and what it asked meanwhile is answered. */ async function agentDone(t: Awaited>) { await t.stopAll(); for (const q of await core.pendingQuestions(db, t.proj.id)) await core.answerQuestion(db, q.id, "ок", "system").catch(() => {}); } describe("ready-for-review only when mergeable", () => { test("Зелёные проверки и нет конфликта — сообщение уходит сразу", async () => { const t = await prTask([]); const q = await core.sendReviewCard(db, await t.ref(), CARD); assert.ok(q, "sent"); assert.equal((await cards(t.proj.id)).length, 1); assert.equal(await core.getReviewHold(db, (await t.ref()).task.id), null); }); test("Ошибка Gitea — гейт закрыт: в ревью нельзя, сообщение ждёт", async () => { const t = await prTask([], false); await core.updateTask(db, await t.ref(), { status: "in_progress", prUrl: t.prUrl }); gitea.down = true; try { await assert.rejects(runner.moveTask(db, await t.ref(), "review"), /не удалось проверить состояние проверок/); assert.equal(await t.status(), "in_progress"); await t.toReview(); assert.equal(await core.sendReviewCard(db, await t.ref(), CARD), null); await cardTick(); assert.equal((await cards(t.proj.id)).length, 0, "still closed while Gitea is down"); } finally { gitea.down = false; } assert.equal((await t.taskEvents("awaiting_checks")).length, 1); await cardTick(); assert.equal((await cards(t.proj.id)).length, 1, "sent once Gitea answers and the PR is green"); }); test("Проверки ещё идут — Stop-хук не шлёт сообщение, вачдог шлёт после зелёного", async () => { const t = await prTask([[{ say: "Готово." }]]); const sha = t.push(); // head without statuses const sid = await t.tp.start(); await waitFor("held by the stop hook", async () => (await t.taskEvents("awaiting_checks")).length || undefined); assert.equal((await cards(t.proj.id)).length, 0); await cardTick(); assert.equal((await cards(t.proj.id)).length, 0, "checks still running"); t.green(sha); await cardTick(); const [q] = await cards(t.proj.id); assert.ok(q, "sent after green"); assert.equal(q!.sessionId, sid); assert.ok(await runner.isReviewQuestion(db, q!), "with «Принять»"); await cardTick(); assert.equal((await cards(t.proj.id)).length, 1, "once"); await t.stopAll(); }); test("Конфликт — агенту rebase один раз на коммит, после — сообщение", async () => { const t = await prTask([]); t.pull().mergeable = false; assert.equal(await core.sendReviewCard(db, await t.ref(), CARD), null); await cardTick(); assert.equal(await t.status(), "in_progress", "the agent rebases"); await t.tp.waitLog("rebase prompt", (e) => e.ev === "prompt" && String(e.prompt).includes("rebase")); assert.equal((await cards(t.proj.id)).length, 0); await agentDone(t); // Back in review with the same head and the conflict still there: no second request. await t.toReview(); await cardTick(); assert.equal(await t.status(), "review"); t.pull().mergeable = true; await cardTick(); assert.equal((await cards(t.proj.id)).length, 1); await t.stopAll(); }); test("Сообщение уже у PM, а PR стал в конфликте — отзывается, после rebase приходит новое", async () => { const t = await prTask([]); const q = await core.sendReviewCard(db, await t.ref(), CARD); await cardTick(); assert.equal((await core.getQuestion(db, q!.id)).answeredAt, null, "mergeable: stays"); t.pull().mergeable = false; await cardTick(); const taken = await core.getQuestion(db, q!.id); assert.equal(taken.answer, core.REVIEW_REVOKED_ANSWER); assert.equal(taken.answeredVia, "system"); assert.equal(await t.status(), "in_progress"); await t.tp.waitLog("rebase prompt", (e) => e.ev === "prompt" && String(e.prompt).includes("rebase")); await agentDone(t); t.green(t.push()); t.pull().mergeable = true; await t.toReview(); await cardTick(); const fresh = await cards(t.proj.id); assert.equal(fresh.length, 1, "a new message"); assert.notEqual(fresh[0]!.id, q!.id); await t.stopAll(); }); }); // PEP-127 (дополнение координатора): зелёные проверки головы PR без свежего main ничего не // гарантируют — перед «Принять» и автомержем ветка должна содержать текущую голову main. describe("merge only with the current main inside", () => { test("Main ушёл вперёд — «Принять» запоминается, ветка обновляется, мерж после проверок нового коммита", async () => { const t = await prTask([]); const before = t.head(); const main = t.mainMoves(); const r = await runner.acceptStory(db, await t.ref(), "web"); assert.equal(r.pending, true, "not merged on stale checks"); assert.equal(t.pull().merged, false); assert.notEqual(t.head(), before, "Peppa updated the PR branch itself"); assert.ok(t.contains(main), "the branch has the current main"); assert.equal(await t.status(), "review", "no agent needed"); await tick(); assert.equal(t.pull().merged, false, "checks of the new head are not there yet"); t.green(t.head()); await tick(); assert.equal(t.pull().merged, true); assert.equal(await t.status(), "done"); }); test("Два зелёных PR подряд: второй не мержится, если вместе с main проверки красные", async () => { const t = await prTask([]); t.mainMoves(); await runner.acceptStory(db, await t.ref(), "web"); gitea.setStatus(t.proj.giteaOwner, t.proj.giteaRepo, t.head(), "peppa/typecheck", "success"); gitea.setStatus(t.proj.giteaOwner, t.proj.giteaRepo, t.head(), "peppa/test", "failure"); await tick(); assert.equal(t.pull().merged, false, "main stays green"); assert.notEqual(await t.status(), "done"); await t.stopAll(); }); test("Проверки ещё идут при «Принять» — запоминается и закрывается само", async () => { const t = await prTask([]); const sha = t.push(); const r = await runner.acceptStory(db, await t.ref(), "web"); assert.equal(r.pending, true); await tick(); assert.equal(t.pull().merged, false); t.green(sha); await tick(); assert.equal(t.pull().merged, true); assert.equal(await t.status(), "done"); }); test("Сообщение PM не уходит, пока ветка отстаёт от main", async () => { const t = await prTask([]); const main = t.mainMoves(); assert.equal(await core.sendReviewCard(db, await t.ref(), CARD), null, "held"); await cardTick(); assert.ok(t.contains(main), "branch updated by Peppa"); await cardTick(); assert.equal((await cards(t.proj.id)).length, 0, "waiting for the checks of the new head"); t.green(t.head()); await cardTick(); assert.equal((await cards(t.proj.id)).length, 1); }); test("Агент отдаёт в ревью отставшую ветку — можно: обновит Peppa", async () => { const t = await prTask([], false); await core.updateTask(db, await t.ref(), { status: "in_progress", prUrl: t.prUrl }); t.mainMoves(); await runner.moveTask(db, await t.ref(), "review"); assert.equal(await t.status(), "review"); }); test("Автомерж: отставшая ветка сначала обновляется", async () => { const t = await prTask([]); await core.setAutonomy(db, t.proj.id, { merge: "auto", close: "after_merge", quietFrom: null, quietTo: null }); const main = t.mainMoves(); await runner.autonomyTick(db, {}); assert.equal(t.pull().merged, false); assert.ok(t.contains(main)); await runner.autonomyTick(db, {}); assert.equal(t.pull().merged, false, "checks of the new head pending"); t.green(t.head()); await runner.autonomyTick(db, {}); assert.equal(t.pull().merged, true); assert.equal(await t.status(), "done"); }); });