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 <noreply@anthropic.com>
136 lines
8.7 KiB
TypeScript
136 lines
8.7 KiB
TypeScript
// 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");
|
||
});
|
||
});
|