Merge pull request 'PEP-196: агент не засыпает при зелёных проверках и конфликте PR' (#188) from task/pep-196 into main

This commit is contained in:
peppa-bot 2026-11-17 16:46:17 +05:00
commit 32c6179b86
3 changed files with 69 additions and 4 deletions

View File

@ -66,14 +66,56 @@ export async function wakeOnGreen(db: Db, ref: TaskRef, r: Pick<CheckReport, "sh
const n = taskPrNumber(ref.project, ref.task.prUrl) ?? r.prNumber ?? (r.branch ? (await gitea.openPullForBranch(o, repo, r.branch))?.number : null);
if (!n) return false;
const gate = await prGate({ ...ref, task: { ...ref.task, prUrl: `/${o}/${repo}/pulls/${n}` } }, gitea);
if (!gate.summary || gate.pull?.head.sha !== r.sha) return false;
// PEP-196: green checks but the PR conflicts with main — nobody else would wake the agent, and it
// would wait forever. Tell it to bring the branch up to date (once per commit).
const conflict = !gate.ok && !gate.behind && gate.summary.state === "success" && gate.pull?.mergeable === false;
// Only the commit the PR stands on now; a branch behind the base is updated by Peppa itself.
if (!(gate.ok || gate.behind) || !gate.summary || gate.pull?.head.sha !== r.sha) return false;
if (!(gate.ok || gate.behind || conflict)) return false;
await setSetting(db, wokeKey(ref.task.id), r.sha);
await logEvent(db, { projectId: ref.project.id, taskId: ref.task.id, sessionId: s.id, type: "checks_passed_wake", payload: { sha: r.sha, pr: n } });
await sendToSession(db, s.id, `✅ Проверки PR ${ref.key} прошли (коммит ${r.sha.slice(0, 7)}). Если работа закончена — update_task(status: review${ref.task.prUrl ? "" : ", pr_url"}); если нет — продолжай.`);
await logEvent(db, { projectId: ref.project.id, taskId: ref.task.id, sessionId: s.id, type: "checks_passed_wake", payload: { sha: r.sha, pr: n, ...(conflict ? { conflict: true } : {}) } });
const prArg = ref.task.prUrl ? "" : `, pr_url: ${gate.pull?.html_url ?? `PR #${n}`}`;
await sendToSession(
db,
s.id,
conflict
? `✅ Проверки PR ${ref.key} прошли (коммит ${r.sha.slice(0, 7)}), но PR конфликтует с основной веткой — смержить его нельзя. Обнови ветку: git fetch origin && git rebase origin/main (или merge), разреши конфликты, сохранив и свою работу, и то, что уже в main; запушь (git push --force-with-lease) и закончи ход — после зелёных проверок Пеппа разбудит тебя снова.`
: `✅ Проверки PR ${ref.key} прошли (коммит ${r.sha.slice(0, 7)}). Если работа закончена — update_task(status: review${prArg}); если нет — продолжай.`,
);
return true;
}
/**
* PEP-196: the safety net for {@link wakeOnGreen}. A check report arrives once; if the agent was busy
* then, or its PR is not written on the task yet, it would sleep forever. Once a minute: every task in
* work whose agent is idle, with an open PR (from the task or its branch `task/<key>`) and all `peppa/*`
* checks of the head green, is woken (once per commit).
*/
export async function wakeIdleOnGreen(db: Db, gitea: GiteaClient = giteaForBot()): Promise<number> {
let woke = 0;
for (const t of await listTasks(db, { statuses: ["proposing", "in_progress"] })) {
const [s] = await listSessions(db, { active: true, taskId: t.id });
if (!s || (s.status !== "idle" && s.status !== "waiting_input")) continue;
const [p] = await db.select().from(projects).where(eq(projects.id, t.projectId));
if (!p || (await isProjectPaused(db, p.id))) continue;
try {
const n = taskPrNumber(p, t.prUrl);
const key = `${p.key}-${t.number}`;
const pull = n
? await gitea.getPullRequest(p.giteaOwner, p.giteaRepo, n)
: ((await gitea.openPullForBranch(p.giteaOwner, p.giteaRepo, `task/${key.toLowerCase()}`)) ?? (await gitea.openPullForBranch(p.giteaOwner, p.giteaRepo, `task/${key}`)));
if (!pull || pull.state !== "open") continue;
if ((await getSetting<string>(db, wokeKey(t.id))) === pull.head.sha) continue;
const st = await gitea.combinedStatus(p.giteaOwner, p.giteaRepo, pull.head.sha);
const ours = (st.statuses ?? []).filter((x) => x.context.startsWith("peppa/"));
if (!ours.length || ours.some((x) => x.status !== "success")) continue;
const ref = await taskForCheck(db, p, pull.head.ref, pull.number);
if (ref && ref.task.id === t.id && (await wakeOnGreen(db, ref, { sha: pull.head.sha, branch: pull.head.ref, prNumber: pull.number }, gitea))) woke++;
} catch {}
}
return woke;
}
export interface CheckOutcome {
task: string | null;
/** What Peppa did: nothing, told the agent, restarted it, stopped it and told the superadmin, reset the counter. */

View File

@ -41,7 +41,7 @@ import { earlyRotationEnabled, planRotation, rotationEnabled, tryRotate, usageWa
import { monitorTick } from "./monitor.ts";
import { platformBuildTick } from "./platform-build.ts";
import { incidentTick } from "./incidents.ts";
import { pollChecks } from "./ci-feedback.ts";
import { pollChecks, wakeIdleOnGreen } from "./ci-feedback.ts";
import { reviewTick } from "./reviewer.ts";
import { autonomyTick } from "./autonomy.ts";
import { capacityQueueTick } from "./capacity-queue.ts";
@ -333,6 +333,7 @@ export async function runWatchdog(db: Db, opts: WatchdogOptions, signal?: AbortS
if (Date.now() - lastCiPoll >= 60_000) {
lastCiPoll = Date.now();
await pollChecks(db).catch(failed(db, log, "ci poll failed"));
await wakeIdleOnGreen(db).catch(failed(db, log, "wake on green failed"));
// Reviews whose MCP process died before running them (PEP-26).
await reviewTick(db, log).catch(failed(db, log, "review tick failed"));
// PEP-127: held or stale ready-for-review messages — send when mergeable, rebase on a conflict.

View File

@ -222,6 +222,28 @@ describe("Платформа будит агента, когда проверк
});
});
describe("Зелёные проверки, но PR конфликтует (PEP-196)", () => {
test("агент, ждущий проверок, получает просьбу обновить ветку; страховка находит PR по ветке", async () => {
const t = await prTask([[{ say: "PR открыт." }], [{ say: "Жду проверок" }], [{ say: "Обновляю ветку." }], [{ say: "Ок." }]]);
await core.updateTask(db, await t.ref(), { status: "in_progress" });
const sid = await t.tp.start();
await t.tp.waitStatus(sid, "idle");
const woke = () => t.tp.log().filter((e) => e.ev === "prompt" && String(e.prompt).includes("Проверки PR"));
t.set("typecheck", "success");
t.set("test", "success");
gitea.repo(t.proj.giteaOwner, t.proj.giteaRepo).pulls.at(-1)!.mergeable = false;
// The report came while nobody listened: the minute sweep finds the PR by the branch (no pr_url on the task).
assert.equal((await core.resolveTask(db, t.tp.taskKey)).task.prUrl, null);
assert.equal(await runner.wakeIdleOnGreen(db), 1);
await waitFor("the agent is told to update its branch", async () => woke().length || undefined);
assert.match(String(woke()[0]!.prompt), /конфликтует.*rebase origin\/main/s);
assert.deepEqual(await projectQuestions(t.proj.id), [], "the person is not involved");
await t.tp.waitStatus(sid, "idle");
assert.equal(await runner.wakeIdleOnGreen(db), 0, "once per commit");
await runner.stopSession(db, sid);
});
});
describe("Вопрос агента — с вариантами и вариантом по умолчанию", () => {
test("Вопрос с вариантами принят", async () => {
const tp = await project({ turns: [] });