PEP-308: проверка, которая не отчиталась, не держит задачу — «проверки ещё идут» только пока статусы меняются #277

Merged
peppa-bot merged 1 commits from task/pep-308 into main 2026-11-26 20:23:29 +00:00
10 changed files with 223 additions and 11 deletions

View File

@ -443,6 +443,23 @@ SHALL получить строку задержки и одно сообщен
проверок, SHALL не считаться сделанной: FORGE SHALL повторить её, когда причина прошла и конфликт
ещё есть.
Проверки результата SHALL считаться идущими, только пока статусы его последней версии меняются:
нужная проверка без результата при статусах, молчащих дольше `PEPPA_CHECKS_LOST_HOURS` (3 часа),
SHALL считаться потерянной. Потерянная проверка SHALL NOT задерживать просьбу обновить изменения,
а отказ агенту при передаче задачи на проверку SHALL называть её и что сделать.
#### Scenario: Проверка не отчиталась и уже не отчитается
- **GIVEN** задача «В работе», её результат конфликтует с основной веткой
- **AND** три проверки из четырёх зелёные, четвёртая без результата, статусы не менялись 4 часа
- **WHEN** FORGE видит конфликт
- **THEN** агент получает просьбу обновить изменения сразу, без ожидания проверок
- **AND** на попытку отдать задачу на проверку агент получает отказ «изменения конфликтуют, проверка не завершилась — влей основную ветку и запушь», а не «подожди проверок»
#### Scenario: Статусы свежие
- **GIVEN** тот же результат, но статусы менялись час назад
- **WHEN** FORGE видит конфликт
- **THEN** просьба ждёт конца проверок, как раньше
#### Scenario: Очередь проверок подавила просьбу
- **GIVEN** задача «В работе», её результат конфликтует с основной веткой
- **AND** стоит очередь проверок проекта

View File

@ -6,7 +6,7 @@ import { join } from "node:path";
import { checkRuns, tasks, type Db } from "@peppa/db";
import { CHECK_NAMES, formatTaskKey, loadEnv, type CheckName, type PeppaProjectFile } from "@peppa/shared";
import { and, desc, eq } from "drizzle-orm";
import type { GiteaClient, GiteaPull } from "./gitea.ts";
import type { GiteaClient, GiteaCommitStatus, GiteaPull } from "./gitea.ts";
import { giteaForBot } from "./users.ts";
import { getSetting } from "./settings.ts";
import type { Project } from "./projects.ts";
@ -187,6 +187,27 @@ export interface GateResult {
pull: GiteaPull | null;
/** PEP-127: the only obstacle — the PR branch lacks the current head of the base branch (Peppa updates it itself). */
behind?: boolean;
/** PEP-308: checks of the head that never reported and no longer will (see `lostChecks`): nothing is running. */
lost?: string[];
}
/** PEP-308: statuses of a head silent for longer than this — a check without a result is lost, not running. 0 — never. */
export const checksLostMs = () => Math.max(0, Number(process.env.PEPPA_CHECKS_LOST_HOURS ?? 3)) * 3600_000;
/**
* PEP-308: the configured checks that have no result on a head whose `peppa/*` statuses have all been
* silent for `checksLostMs()` — their job is gone (cut by a restart, never taken by a runner). PEP-217
* stood for six days on «проверки ещё идут (3 из 4)». Empty when a status is fresh, when Gitea gives
* no times, or when there are no statuses at all (that head is the checks queue's business, PEP-205).
*/
export function lostChecks(configured: string[], statuses: GiteaCommitStatus[], now: number = Date.now()): string[] {
const limit = checksLostMs();
const own = statuses.filter((s) => s.context.startsWith("peppa/"));
if (!limit || !own.length) return [];
const times = own.map((s) => Date.parse(s.updated_at ?? ""));
if (times.some((t) => !Number.isFinite(t)) || now - Math.max(...times) < limit) return [];
const done = new Set(own.filter((s) => s.status === "success" || s.status === "failure" || s.status === "error").map((s) => s.context.slice(6)));
return configured.filter((c) => !done.has(c));
}
/** True when the PR branch does not contain the current head of its base branch. */
@ -212,12 +233,22 @@ export async function prGate(ref: TaskRef, client?: GiteaClient): Promise<GateRe
const runs = (status.statuses ?? [])
.filter((s) => s.context.startsWith("peppa/"))
.map((s) => ({ check: s.context.slice(6), state: (s.status === "error" || s.status === "failure" ? "failure" : s.status === "success" ? "success" : "pending") as CheckState, runUrl: s.target_url }));
const summary = summarizeChecks(configuredChecks(projectJson), runs, pull.head.sha);
const configured = configuredChecks(projectJson);
const summary = summarizeChecks(configured, runs, pull.head.sha);
if (summary.state === "failure") return { ok: false, reason: tr("проверки не пройдены ({list})", { list: summary.failed.map((f) => f.check).join(", ") }), summary, pull };
if (summary.state === "pending" || summary.state === "none") return { ok: false, reason: tr("проверки ещё идут ({passed} из {total})", { passed: summary.passed, total: summary.total }), summary, pull };
if (pull.state === "open" && pull.mergeable === false) return { ok: false, reason: tr("изменения конфликтуют с основной версией кода"), summary, pull };
// PEP-308: a check that has been silent for hours is not «still running» — waiting for it holds a
// conflict's rebase and the agent's hand-off for ever. Such a head goes on to the reasons below.
const lostList = summary.state === "pending" ? lostChecks(configured, status.statuses ?? []) : [];
const lost = lostList.length ? { lost: lostList } : {};
if ((summary.state === "pending" && !lostList.length) || summary.state === "none") return { ok: false, reason: tr("проверки ещё идут ({passed} из {total})", { passed: summary.passed, total: summary.total }), summary, pull };
if (pull.state === "open" && pull.mergeable === false) return { ok: false, ...lost, reason: tr("изменения конфликтуют с основной версией кода"), summary, pull };
// PEP-127: green checks of a head that lacks the fresh base prove nothing about the merge result.
if (pullBehind(pull)) return { ok: false, behind: true, reason: tr("изменения отстают от основной версии кода — FORGE обновляет их и ждёт проверок"), summary, pull };
// (A head with lost checks that is only behind: Peppa's update of the branch makes a new head, the checks run again.)
if (pullBehind(pull)) return { ok: false, behind: true, ...lost, reason: tr("изменения отстают от основной версии кода — FORGE обновляет их и ждёт проверок"), summary, pull };
if (lostList.length) {
const hours = Math.round(checksLostMs() / 3600_000);
return { ok: false, ...lost, reason: tr("проверки не завершились: {list} — отчёта нет больше {hours} ч, нужна новая версия изменений", { list: lostList.join(", "), hours }), summary, pull };
}
return { ok: true, summary, pull };
}

View File

@ -231,13 +231,24 @@ export function createAgentServer(db: Db, opts: AgentServerOptions = {}): McpSer
// PEP-205: the checks still run — don't poll them: Peppa moves the story to review when they are green.
if (reason) {
const gate = await prGate(withPr0).catch(() => null);
if (gate?.pull?.state === "open" && gate.summary && (gate.summary.state === "pending" || gate.summary.state === "none") && gate.pull.mergeable !== false) {
if (gate?.pull?.state === "open" && gate.summary && (gate.summary.state === "pending" || gate.summary.state === "none") && gate.pull.mergeable !== false && !gate.lost?.length) {
await wantReview(db, ref, pr_url ?? ref.task.prUrl ?? null);
await updateTask(db, ref, { openspecChange: openspec_change, prUrl: pr_url, title, description }, sessionId);
return `${ref.key}: the checks of the PR are still running. Noted — FORGE moves the story to review by itself as soon as they are green (red ones come back to you with the log). End your turn now: do not poll the checks (curl, gh, API), do not rebase or push empty commits.`;
}
}
if (reason) {
// PEP-308: checks of the last commit never reported and no longer will — «wait» would be for ever
// (PEP-217 stood six days). Say what moves the story: a new commit, and the conflict if there is one.
const gate = await prGate(withPr0).catch(() => null);
const base = ref.project.defaultBranch;
if (gate?.lost?.length) {
const lost = `the checks of the PR's last commit never finished (${gate.lost.join(", ")}: no report for hours — the job is gone, nothing is running)`;
if (gate.pull?.mergeable === false) {
throw new PeppaError(`Not moved to review: the PR conflicts with ${base}, and ${lost}. Merge the fresh ${base} into your branch (git fetch origin && git merge origin/${base}), resolve the conflicts, run the checks locally, push — the new commit runs the checks again. Then set status: review again.`);
}
throw new PeppaError(`Not moved to review: ${lost}. Push a new commit to run them again: merge the fresh ${base} into your branch (git fetch origin && git merge origin/${base}) or, if the branch is up to date, an empty commit. Then set status: review again.`);
}
throw new PeppaError(`Not moved to review: ${reason}. Wait for the CI checks of the PR's last commit to pass (red ones come back to you with the log), then set status: review again.`);
}
}

View File

@ -134,7 +134,8 @@ export async function requestRebase(db: Db, ref: TaskRef, o: { force?: boolean }
// PEP-255: the queue of the project's own lane.
if (!o.force && (await checksQueueStanding(db, ref.project))) return false;
const gate = await prGate(ref).catch(() => null);
if (gate?.summary?.state === "pending") return false;
// PEP-308: checks that never reported and no longer will are not «running» — the rebase makes a new head anyway.
if (gate?.summary?.state === "pending" && !gate.lost?.length) return false;
const text = `FORGE не может смержить PR ${ref.key}: конфликты с основной веткой (${ref.project.defaultBranch}). Сделай rebase ветки на свежую ${ref.project.defaultBranch}, разреши конфликты, прогони проверки локально и force-push (--force-with-lease) в ту же ветку. После зелёных проверок снова update_task(status: review). Это единственная просьба: если конфликт не разрешить — не гадай, вызови report_blocker и перечисли конфликтующие файлы, FORGE передаст задачу человеку.`;
const session = (await activeSessions(db, ref.task.id))[0];
if (session) {

View File

@ -29,7 +29,8 @@ export async function reviewWantedTick(db: Db, o: { log?: (m: string) => void }
const gate = await prGate(withPr).catch(() => null);
if (!gate || !gate.pull || gate.pull.state !== "open") continue;
// Red checks and a conflict reach the agent through the CI feedback; it asks for review again.
if (gate.summary?.state === "failure" || gate.pull.mergeable === false) {
// PEP-308: lost checks will never be green — the mark goes, the stuck-story healing tells the agent to push again.
if (gate.summary?.state === "failure" || gate.pull.mergeable === false || (gate.lost?.length && !gate.behind)) {
await deleteSetting(db, row.key);
continue;
}

View File

@ -151,6 +151,17 @@ export async function diagnose(db: Db, ref: TaskRef, gitea: GiteaClient = giteaF
if (await checksQueueStanding(db, ref.project)) return { kind: "wait", why: "checks queue", held: conflict };
return conflict;
}
// PEP-308: the checks never reported and no longer will — only a new commit runs them again.
if (gate.lost?.length) {
const list = gate.lost.join(", ");
const base = ref.project.defaultBranch;
return {
kind: "agent",
reason: m("проверки не завершились ({list})", { list }),
agent: `Проверки PR #${pull.number} стори ${ref.key} не завершились: ${list} не отчитались несколько часов — задание пропало, ничего не идёт. Запусти их заново новым коммитом: влей свежую ${base} в ветку (git fetch origin && git merge origin/${base}; если ветка свежая — пустой коммит), запушь и вызови update_task(status: review). Статус проверок не опрашивай: FORGE разбудит.`,
pull,
};
}
return { kind: "wait", why: "checks running" };
}

View File

@ -262,6 +262,8 @@ export const bot: Dict = {
"Проверки ещё не запускались": "Checks haven't run yet",
"Проверки идут: {passed} из {total}": "Checks running: {passed} of {total}",
"проверки не пройдены ({list})": "checks failed ({list})",
"проверки не завершились: {list} — отчёта нет больше {hours} ч, нужна новая версия изменений": "checks did not finish: {list} — no report for over {hours} h, a new version of the changes is needed",
"проверки не завершились ({list})": "checks did not finish ({list})",
"проверки ещё идут ({passed} из {total})": "checks still running ({passed} of {total})",
"изменения конфликтуют с основной версией кода": "the changes conflict with the main version of the code",
"ссылка на результат ведёт не в код проекта": "the link to the result does not lead to the project's code",

View File

@ -261,6 +261,8 @@ export const bot: Dict = {
"Проверки ещё не запускались": "Тексерістер әлі іске қосылмаған",
"Проверки идут: {passed} из {total}": "Тексерістер жүріп жатыр: {passed} / {total}",
"проверки не пройдены ({list})": "тексерістерден өтпеді ({list})",
"проверки не завершились: {list} — отчёта нет больше {hours} ч, нужна новая версия изменений": "тексерістер аяқталмады: {list} — {hours} сағаттан астам есеп жоқ, өзгерістердің жаңа нұсқасы қажет",
"проверки не завершились ({list})": "тексерістер аяқталмады ({list})",
"проверки ещё идут ({passed} из {total})": "тексерістер әлі жүріп жатыр ({passed} / {total})",
"изменения конфликтуют с основной версией кода": "өзгерістер кодтың негізгі нұсқасымен қайшы келеді",
"ссылка на результат ведёт не в код проекта": "нәтижеге сілтеме жоба кодына апармайды",

View File

@ -31,7 +31,7 @@ interface MockRepo {
admins: Set<string>;
private: boolean;
pulls: MockPull[];
statuses: Map<string, Array<{ context: string; status: string; target_url?: string; description?: string }>>;
statuses: Map<string, Array<{ context: string; status: string; target_url?: string; description?: string; updated_at?: string }>>;
secrets: Record<string, string>;
hooks: Array<{ id: number; url: string; secret: string; events: string[] }>;
tags: Array<{ name: string; target: string }>;
@ -226,10 +226,11 @@ export class MockGitea {
}
/** Records a commit status, like a CI job does. */
setStatus(owner: string, name: string, sha: string, context: string, status: string, extra: { target_url?: string; description?: string } = {}) {
/** `updated_at` — when the status was set (now by default), as Gitea reports it. */
setStatus(owner: string, name: string, sha: string, context: string, status: string, extra: { target_url?: string; description?: string; updated_at?: string } = {}) {
const r = this.repo(owner, name);
const list = (r.statuses.get(sha) ?? []).filter((s) => s.context !== context);
list.push({ context, status, ...extra });
list.push({ context, status, updated_at: new Date().toISOString(), ...extra });
r.statuses.set(sha, list);
}

View File

@ -0,0 +1,135 @@
// PEP-308: a check that never reported is not «still running».
// PEP-217 (27.11.2026): a branch of 20.11 in conflict with main, three of four checks green and no
// `peppa/test` status for six days — its job was gone. The gate said «проверки ещё идут (3 из 4)»:
// the request to rebase was held «until the checks finish» for ever, and the agent's
// update_task(status: review) was refused with «wait for the checks». 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, setDefaultOwner, teardown } 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-lost-checks-")), "gitea"));
const BOT = { id: 77, login: "peppa-bot", token: "mock-token-bot" };
const CHECKS = { lint: "pnpm lint", typecheck: "pnpm typecheck", build: "pnpm build", test: "pnpm test" };
const HOUR = 3600_000;
before(async () => {
await gitea.start();
process.env.GITEA_URL = gitea.url;
process.env.GITEA_TOKEN = BOT.token;
gitea.addUser(BOT);
const owner = await core.upsertUserFromGitea(db, { id: 9701, login: "mock-owner-lost" }, { access_token: "x" });
setDefaultOwner(owner.id);
runner.setConflictFilesLister(async () => ["a.txt"]);
});
after(async () => {
runner.setConflictFilesLister(null);
delete process.env.PEPPA_CHECKS_LOST_HOURS;
await gitea.stop();
await teardown();
});
type Turns = Parameters<typeof project>[0]["turns"];
/** A story in work with an open result: lint, typecheck and build reported `ageHours` ago, `test` never did. */
async function story(o: { ageHours: number; conflict?: boolean; turns?: Turns }) {
const tp = await project({ turns: o.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";
const branch = `task/${tp.taskKey}`;
const sha = gitea.commit(proj.giteaOwner, proj.giteaRepo, branch, { "f.txt": "1" });
const at = new Date(Date.now() - o.ageHours * HOUR).toISOString();
for (const c of ["lint", "typecheck", "build"]) gitea.setStatus(proj.giteaOwner, proj.giteaRepo, sha, `peppa/${c}`, "success", { updated_at: at });
const pr = gitea.openPull(proj.giteaOwner, proj.giteaRepo, branch);
const prUrl = `${gitea.url}/${proj.giteaOwner}/${proj.giteaRepo}/pulls/${pr.number}`;
await core.updateTask(db, await core.resolveTask(db, tp.taskKey), { status: "in_progress", prUrl });
const ref = () => core.resolveTask(db, tp.taskKey);
const pull = () => gitea.repo(proj.giteaOwner, proj.giteaRepo).pulls[pr.number - 1]!;
if (o.conflict) pull().mergeable = false;
const live = () => core.giteaForBot().getPullRequest(proj.giteaOwner, proj.giteaRepo, pr.number);
const count = async (type: string) => (await db.select().from(events).where(and(eq(events.taskId, (await ref()).task.id), eq(events.type, type)))).length;
return { tp, proj, sha, pr, ref, pull, live, count };
}
describe("PEP-308: проверка, которая не отчиталась, — не «проверки ещё идут»", () => {
test("lostChecks: молчание дольше порога — проверка потеряна; свежий статус — идёт", () => {
const now = Date.now();
const st = (context: string, status: string, hoursAgo: number) => ({ context, status: status as "success", updated_at: new Date(now - hoursAgo * HOUR).toISOString() });
const all = ["lint", "typecheck", "build", "test"];
const three = [st("peppa/lint", "success", 30), st("peppa/typecheck", "success", 30), st("peppa/build", "success", 29)];
assert.deepEqual(core.lostChecks(all, three, now), ["test"], "six days of silence in life; 29 hours here");
assert.deepEqual(core.lostChecks(all, [...three.slice(0, 2), st("peppa/build", "success", 1)], now), [], "a status an hour old — the checks may still run");
assert.deepEqual(core.lostChecks(all, [...three, st("peppa/test", "pending", 5)], now), ["test"], "a «pending» nobody touched for hours is a dead job too");
assert.deepEqual(core.lostChecks(all, [...three, st("peppa/test", "success", 5)], now), [], "everything reported");
assert.deepEqual(core.lostChecks(all, [], now), [], "no statuses at all — the checks queue's business (PEP-205)");
assert.deepEqual(core.lostChecks(all, [{ context: "peppa/lint", status: "success" }], now), [], "Gitea gave no time — unknown, not lost");
process.env.PEPPA_CHECKS_LOST_HOURS = "0";
assert.deepEqual(core.lostChecks(all, three, now), [], "switched off");
delete process.env.PEPPA_CHECKS_LOST_HOURS;
});
test("Гейт: три проверки из четырёх молчат 4 часа — «не завершились»; час — «ещё идут»", async () => {
const old = await story({ ageHours: 4 });
const g1 = await core.prGate(await old.ref());
assert.equal(g1.ok, false);
assert.deepEqual(g1.lost, ["test"]);
assert.match(String(g1.reason), /проверки не завершились: test/);
const fresh = await story({ ageHours: 1 });
const g2 = await core.prGate(await fresh.ref());
assert.equal(g2.lost, undefined);
assert.match(String(g2.reason), /проверки ещё идут \(3 из 4\)/);
});
test("Конфликт и потерянная проверка (PEP-217): просьба обновить изменения уходит, а не ждёт проверок", async () => {
const t = await story({ ageHours: 4, conflict: true });
const gate = await core.prGate(await t.ref());
assert.match(String(gate.reason), /конфликтуют/, "the conflict is the reason, not «checks are running»");
assert.deepEqual(gate.lost, ["test"]);
const out = await runner.conflictStep(db, await t.ref(), await t.live());
assert.equal(out, "requested");
assert.equal(await t.count("conflict_rebase_requested"), 1);
assert.equal(await runner.getConflictHeld(db, (await t.ref()).task.id), null, "nothing is held");
await runner.stopSession(db, (await core.listSessions(db, { taskId: (await t.ref()).task.id }))[0]!.id).catch(() => {});
});
test("Конфликт, а проверки свежие — просьба ждёт их конца, как раньше (PEP-205)", async () => {
const t = await story({ ageHours: 1, conflict: true });
const out = await runner.conflictStep(db, await t.ref(), await t.live());
assert.equal(out, "held");
assert.equal(await t.count("conflict_rebase_requested"), 0);
assert.ok(await runner.getConflictHeld(db, (await t.ref()).task.id));
});
test("Агент отдаёт задачу на ревью: отказ называет конфликт и потерянную проверку, а не «подожди»", async () => {
const t = await story({ ageHours: 4, conflict: true, turns: [[{ mcp: "update_task", args: { task: "1", status: "review" } }, { say: "Готово." }]] });
await t.tp.start();
const call = await t.tp.waitLog("refused", (e) => e.ev === "mcp" && e.tool === "update_task");
assert.equal(call.isError, true);
assert.match(String(call.text), /conflicts with main/);
assert.match(String(call.text), /never finished \(test/);
assert.match(String(call.text), /git merge origin\/main/);
assert.doesNotMatch(String(call.text), /Wait for the CI checks/);
assert.equal((await t.ref()).task.status, "in_progress");
assert.equal(await runner.getReviewWanted(db, (await t.ref()).task.id), null, "a hand-off that can never be green is not remembered");
});
test("Без конфликта: застрявшую задачу сторож отдаёт агенту со словами «запусти проверки заново»", async () => {
const t = await story({ ageHours: 4 });
const d = await runner.diagnose(db, await t.ref());
assert.equal(d.kind, "agent");
assert.match(String((d as { agent: string }).agent), /не завершились: test/);
assert.match(String((d as { agent: string }).agent), /пустой коммит/);
const f = await story({ ageHours: 1 });
assert.equal((await runner.diagnose(db, await f.ref())).kind, "wait", "fresh statuses — the healer waits as before");
});
});