From 3d35bbf2b69635c21b8e2db871babd0bec5a2650 Mon Sep 17 00:00:00 2001 From: peppa-bot Date: Fri, 27 Nov 2026 00:55:50 +0500 Subject: [PATCH] =?UTF-8?q?PEP-308:=20=D0=BF=D1=80=D0=BE=D0=B2=D0=B5=D1=80?= =?UTF-8?q?=D0=BA=D0=B0,=20=D0=BA=D0=BE=D1=82=D0=BE=D1=80=D0=B0=D1=8F=20?= =?UTF-8?q?=D0=BD=D0=B5=20=D0=BE=D1=82=D1=87=D0=B8=D1=82=D0=B0=D0=BB=D0=B0?= =?UTF-8?q?=D1=81=D1=8C,=20=D0=BD=D0=B5=20=D0=B4=D0=B5=D1=80=D0=B6=D0=B8?= =?UTF-8?q?=D1=82=20=D0=B7=D0=B0=D0=B4=D0=B0=D1=87=D1=83=20=E2=80=94=20?= =?UTF-8?q?=C2=AB=D0=BF=D1=80=D0=BE=D0=B2=D0=B5=D1=80=D0=BA=D0=B8=20=D0=B5?= =?UTF-8?q?=D1=89=D1=91=20=D0=B8=D0=B4=D1=83=D1=82=C2=BB=20=D1=82=D0=BE?= =?UTF-8?q?=D0=BB=D1=8C=D0=BA=D0=BE=20=D0=BF=D0=BE=D0=BA=D0=B0=20=D1=81?= =?UTF-8?q?=D1=82=D0=B0=D1=82=D1=83=D1=81=D1=8B=20=D0=BC=D0=B5=D0=BD=D1=8F?= =?UTF-8?q?=D1=8E=D1=82=D1=81=D1=8F?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit PEP-217 стояла шесть дней: ветка в конфликте с main, три проверки из четырёх зелёные, статуса peppa/test нет — задание пропало. Гейт отвечал «проверки ещё идут (3 из 4)»: просьба обновить ветку была придержана «до конца проверок» навсегда, агент на update_task(status: review) получал «подожди проверок». - core/ci.ts: `lostChecks` — нужные проверки без результата на голове, чьи статусы peppa/* молчат дольше PEPPA_CHECKS_LOST_HOURS (3 ч); `prGate` для такой головы не говорит «ещё идут», а идёт дальше: конфликт, отставание (обновление ветки запустит проверки), иначе «проверки не завершились». - runner/flow.ts: `requestRebase` потерянных проверок не ждёт. - mcp/agent.ts: отказ агенту называет конфликт и молчащую проверку и что сделать; такую передачу на ревью не запоминаем (`review.wanted`). - runner/review-wanted.ts, stuck-tasks.ts: отметка снимается; сторож застрявших задач просит агента запустить проверки новым коммитом. - Мок Gitea: у статуса время (`updated_at`). Спека platform-delays, переводы en/kk. - Тесты lost-checks.test.ts: 5 из 6 падали до исправления. Co-Authored-By: Claude Fable 5.2 --- openspec/specs/platform-delays/spec.md | 17 +++ packages/core/src/ci.ts | 41 ++++++- packages/mcp/src/agent.ts | 13 ++- packages/runner/src/flow.ts | 3 +- packages/runner/src/review-wanted.ts | 3 +- packages/runner/src/stuck-tasks.ts | 11 ++ packages/shared/src/i18n/en/bot.ts | 2 + packages/shared/src/i18n/kk/bot.ts | 2 + packages/testkit/src/mock-gitea.ts | 7 +- packages/testkit/test/lost-checks.test.ts | 135 ++++++++++++++++++++++ 10 files changed, 223 insertions(+), 11 deletions(-) create mode 100644 packages/testkit/test/lost-checks.test.ts diff --git a/openspec/specs/platform-delays/spec.md b/openspec/specs/platform-delays/spec.md index a32a2057..89c4b86a 100644 --- a/openspec/specs/platform-delays/spec.md +++ b/openspec/specs/platform-delays/spec.md @@ -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** стоит очередь проверок проекта diff --git a/packages/core/src/ci.ts b/packages/core/src/ci.ts index 6af16917..b2fa0c34 100644 --- a/packages/core/src/ci.ts +++ b/packages/core/src/ci.ts @@ -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 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 }; } diff --git a/packages/mcp/src/agent.ts b/packages/mcp/src/agent.ts index bf8fe33e..3f28a273 100644 --- a/packages/mcp/src/agent.ts +++ b/packages/mcp/src/agent.ts @@ -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.`); } } diff --git a/packages/runner/src/flow.ts b/packages/runner/src/flow.ts index 97e68fd8..18020d69 100644 --- a/packages/runner/src/flow.ts +++ b/packages/runner/src/flow.ts @@ -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) { diff --git a/packages/runner/src/review-wanted.ts b/packages/runner/src/review-wanted.ts index 82b75626..6cada7e3 100644 --- a/packages/runner/src/review-wanted.ts +++ b/packages/runner/src/review-wanted.ts @@ -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; } diff --git a/packages/runner/src/stuck-tasks.ts b/packages/runner/src/stuck-tasks.ts index d816de32..841151a5 100644 --- a/packages/runner/src/stuck-tasks.ts +++ b/packages/runner/src/stuck-tasks.ts @@ -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" }; } diff --git a/packages/shared/src/i18n/en/bot.ts b/packages/shared/src/i18n/en/bot.ts index 0d65ea4e..f28dffe9 100644 --- a/packages/shared/src/i18n/en/bot.ts +++ b/packages/shared/src/i18n/en/bot.ts @@ -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", diff --git a/packages/shared/src/i18n/kk/bot.ts b/packages/shared/src/i18n/kk/bot.ts index 7aa12ea2..8f73263b 100644 --- a/packages/shared/src/i18n/kk/bot.ts +++ b/packages/shared/src/i18n/kk/bot.ts @@ -261,6 +261,8 @@ export const bot: Dict = { "Проверки ещё не запускались": "Тексерістер әлі іске қосылмаған", "Проверки идут: {passed} из {total}": "Тексерістер жүріп жатыр: {passed} / {total}", "проверки не пройдены ({list})": "тексерістерден өтпеді ({list})", + "проверки не завершились: {list} — отчёта нет больше {hours} ч, нужна новая версия изменений": "тексерістер аяқталмады: {list} — {hours} сағаттан астам есеп жоқ, өзгерістердің жаңа нұсқасы қажет", + "проверки не завершились ({list})": "тексерістер аяқталмады ({list})", "проверки ещё идут ({passed} из {total})": "тексерістер әлі жүріп жатыр ({passed} / {total})", "изменения конфликтуют с основной версией кода": "өзгерістер кодтың негізгі нұсқасымен қайшы келеді", "ссылка на результат ведёт не в код проекта": "нәтижеге сілтеме жоба кодына апармайды", diff --git a/packages/testkit/src/mock-gitea.ts b/packages/testkit/src/mock-gitea.ts index 9255a27a..e50080a2 100644 --- a/packages/testkit/src/mock-gitea.ts +++ b/packages/testkit/src/mock-gitea.ts @@ -31,7 +31,7 @@ interface MockRepo { admins: Set; private: boolean; pulls: MockPull[]; - statuses: Map>; + statuses: Map>; secrets: Record; 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); } diff --git a/packages/testkit/test/lost-checks.test.ts b/packages/testkit/test/lost-checks.test.ts new file mode 100644 index 00000000..13eaca15 --- /dev/null +++ b/packages/testkit/test/lost-checks.test.ts @@ -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[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"); + }); +});