peppa/packages/testkit/test/stuck-heal.test.ts
2026-11-18 16:54:55 +05:00

205 lines
13 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

// PEP-209, spec platform-delays: a stuck story — in work, no agent working on it — is healed by
// the platform: green checks → review without a turn of the agent, merged result → done, a
// conflict → the agent is relaunched with the reason; retries 5 min / 15 min / 1 h / 2 h; the 4th
// failure — one message to the superadmin; stale cards go; the owner sees when the next attempt is.
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, waitFor } from "./helpers.ts";
import { MockGitea } from "../src/mock-gitea.ts";
import { events, questions, sessions, telegramOutbox, users } from "@peppa/db";
import { and, eq, inArray, sql } from "drizzle-orm";
import { stripAsIs } from "@peppa/shared/i18n";
process.env.PEPPA_SECRET = "mock-secret-for-tests";
const gitea = new MockGitea(join(mkdtempSync(join(tmpdir(), "peppa-stuck-")), "gitea"));
const BOT = { id: 72, login: "peppa-bot", token: "mock-token-bot" };
const CHECKS = { test: "pnpm test" };
const MIN = 60_000;
const ADMIN_CHAT = 9202;
before(async () => {
await gitea.start();
process.env.GITEA_URL = gitea.url;
process.env.GITEA_TOKEN = BOT.token;
process.env.PEPPA_STUCK_TASKS = "on";
gitea.addUser(BOT);
const owner = await core.upsertUserFromGitea(db, { id: 9201, login: "mock-owner-stuck" }, { access_token: "x" });
const admin = await core.upsertUserFromGitea(db, { id: 9202, login: "mock-admin-stuck" }, { access_token: "x" });
await db.update(users).set({ telegramChatId: 9201, telegramUserId: 9201 }).where(eq(users.id, owner.id));
await db.update(users).set({ telegramChatId: ADMIN_CHAT, telegramUserId: ADMIN_CHAT }).where(eq(users.id, admin.id));
await core.setPlatformAdmins(db, ["mock-admin-stuck"]);
setDefaultOwner(owner.id);
});
after(async () => {
delete process.env.PEPPA_STUCK_TASKS;
await gitea.stop();
await teardown();
});
const toAdmin = async (key: string) =>
(await db.select().from(telegramOutbox).where(eq(sql`json_extract(${telegramOutbox.params}, '$.chat_id')`, ADMIN_CHAT))).map((r) => stripAsIs(String(r.params.text))).filter((t) => t.includes(key));
/** A story in work whose agent went idle 40 minutes ago, with a result (PR) in Gitea. */
async function stuck(o: { checks?: "success" | "failure" | null; prUrl?: boolean } = {}) {
const tp = 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";
const sha = gitea.commit(proj.giteaOwner, proj.giteaRepo, `task/${tp.taskKey}`, { "f.txt": "1" });
const pr = gitea.openPull(proj.giteaOwner, proj.giteaRepo, `task/${tp.taskKey}`);
const ref = await core.resolveTask(db, tp.taskKey);
await core.updateTask(db, ref, { status: "in_progress", ...(o.prUrl === false ? {} : { prUrl: `${gitea.url}/${proj.giteaOwner}/${proj.giteaRepo}/pulls/${pr.number}` }) });
if (o.checks !== null) gitea.setStatus(proj.giteaOwner, proj.giteaRepo, sha, "peppa/test", o.checks ?? "success");
const s = await core.createSession(db, { projectId: proj.id, taskId: ref.task.id });
await db.update(sessions).set({ status: "idle", lastActivityAt: new Date(Date.now() - 40 * MIN) }).where(eq(sessions.id, s.id));
const pull = () => gitea.repo(proj.giteaOwner, proj.giteaRepo).pulls[pr.number - 1]!;
return { tp, proj, ref, sid: s.id, pull, scope: { projectId: proj.id, taskId: ref.task.id } };
}
/** Only this story's tick: other suites' stories are not touched by the assertions. */
const tick = (now: number) => runner.stuckTaskTick(db, { now: new Date(now) });
describe("Застрявшая задача доходит сама", () => {
test("Scenario: Проверки зелёные, статус не «ревью» — платформа переводит сама", async () => {
const t = await stuck();
await tick(Date.now());
assert.equal((await t.tp.task()).status, "review", "moved to review without a turn of the agent");
const cards = await db.select().from(questions).where(and(eq(questions.taskId, t.ref.task.id), eq(questions.msgType, "done")));
assert.equal(cards.length, 1, "the owner gets the «готово» card");
assert.equal(await core.getPlatformDelay(db, t.scope, "stuck"), null);
const [e] = await db.select().from(events).where(and(eq(events.taskId, t.ref.task.id), eq(events.type, "stuck_to_review")));
assert.ok(e);
});
test("Scenario: Результат смержен, вебхук не дошёл — задача «Готово» (адреса результата нет, найден по ветке)", async () => {
const t = await stuck({ prUrl: false });
Object.assign(t.pull(), { merged: true, state: "closed" });
await tick(Date.now());
assert.equal((await t.tp.task()).status, "done");
});
test("Scenario: Агент свободен меньше 30 минут — не трогаем", async () => {
const t = await stuck();
await db.update(sessions).set({ lastActivityAt: new Date(Date.now() - 10 * MIN) }).where(eq(sessions.id, t.sid));
await tick(Date.now());
assert.equal((await t.tp.task()).status, "in_progress");
});
});
describe("Повторы по расписанию", () => {
test("Scenario: Четыре неудачи — до них суперадмин молчит, потом одно сообщение; рано — не перезапускаем", async () => {
const t = await stuck();
t.pull().mergeable = false;
const T = Date.now();
const relaunches = async () => (await db.select().from(events).where(and(eq(events.sessionId, t.sid), inArray(events.type, ["started", "resumed"])))).length;
const settle = async () => {
// The relaunched agent finishes its (empty) turn; the story stays where it was.
await waitFor("relaunched", async () => ((await core.getSession(db, t.sid)).status !== "starting" ? true : null));
await runner.stopSession(db, t.sid).catch(() => {});
};
await tick(T);
await settle();
let d = await core.getPlatformDelay(db, t.scope, "stuck");
assert.equal(d?.attempts, 1);
assert.equal(d?.retryAt, T + 5 * MIN, "next attempt in 5 min");
assert.equal(await relaunches(), 1, "the agent was relaunched as a new process");
assert.match((await runner.getStuckHeal(db, t.ref.task.id))!.action, /конфликтуют/);
await tick(T + 3 * MIN);
assert.equal(await relaunches(), 1, "too early — no relaunch");
assert.equal((await core.getPlatformDelay(db, t.scope, "stuck"))?.attempts, 1);
for (const [at, n] of [[5, 2], [20, 3], [80, 4]] as const) {
await tick(T + at * MIN);
await settle();
assert.equal((await runner.getStuckHeal(db, t.ref.task.id))?.attempts, n, `attempt ${n} at +${at} min`);
}
assert.equal((await runner.getStuckHeal(db, t.ref.task.id))?.nextAt, T + 200 * MIN, "then every 2 h");
assert.equal((await toAdmin(t.tp.taskKey)).length, 0, "nothing to the superadmin before the attempts run out");
await tick(T + 200 * MIN);
d = await core.getPlatformDelay(db, t.scope, "stuck");
assert.equal(d?.exhausted, true, "the card says «нужен администратор»");
assert.equal(await relaunches(), 4, "no fifth relaunch");
const msgs = await toAdmin(t.tp.taskKey);
assert.equal(msgs.length, 1, "one message to the superadmin");
assert.match(msgs[0]!, /конфликтуют с основной версией кода/);
const [row] = await db.select().from(telegramOutbox).where(eq(sql`json_extract(${telegramOutbox.params}, '$.chat_id')`, ADMIN_CHAT));
assert.match(JSON.stringify(row?.params.reply_markup), /pd:t\d+:stuck:v/, "with the superadmin's buttons");
await tick(T + 400 * MIN);
assert.equal((await toAdmin(t.tp.taskKey)).length, 1, "still one");
assert.match(stripAsIs((await core.taskDelayLine(db, t.ref.task.id))!), /Нужен администратор, мы ему сообщили/);
});
});
describe("Устаревшие карточки закрываются", () => {
test("Scenario: Задача снова движется — карточки нет", async () => {
const t = await stuck({ checks: "failure" });
await tick(Date.now());
await waitFor("relaunched", async () => ((await core.getSession(db, t.sid)).status !== "starting" ? true : null));
assert.ok(await core.getPlatformDelay(db, t.scope, "stuck"));
await db.update(sessions).set({ status: "running" }).where(eq(sessions.id, t.sid));
await runner.platformDelayTick(db);
assert.equal(await core.getPlatformDelay(db, t.scope, "stuck"), null);
await runner.stopSession(db, t.sid).catch(() => {});
});
test("Scenario: Ошибка исправленной версии — карточка снята, счётчик перезапусков пуст, агент перезапущен", async () => {
const t = await stuck();
await db.update(sessions).set({ status: "failed", watchState: { restarts: [1, 2, 3] } }).where(eq(sessions.id, t.sid));
await core.platformDelay(db, { ...t.scope, sessionId: t.sid }, { reason: "agent", state: "stopped", exhausted: true, details: "codex: unexpected argument 'danger-full-access'" });
await runner.platformDelayTick(db, { commit: (await core.getPlatformDelay(db, t.scope, "agent"))!.commit ?? "same" });
assert.ok(await core.getPlatformDelay(db, t.scope, "agent"), "the same version — the card stays");
await runner.platformDelayTick(db, { commit: "newer-version" });
assert.equal(await core.getPlatformDelay(db, t.scope, "agent"), null);
const s = await core.getSession(db, t.sid);
assert.deepEqual(s.watchState?.restarts ?? [], [], "restart count reset");
const [e] = await db.select().from(events).where(and(eq(events.taskId, t.ref.task.id), eq(events.type, "delay_stale_restarted")));
assert.ok(e, "the story is tried again");
await waitFor("relaunched", async () => ((await core.getSession(db, t.sid)).status !== "starting" ? true : null));
await runner.stopSession(db, t.sid).catch(() => {});
});
});
describe("Кнопки суперадмина", () => {
test("Scenario: «Перевести на ревью» при зелёных проверках; при красных — причина", async () => {
const t = await stuck();
await core.platformDelay(db, t.scope, { reason: "stuck", state: "admin", exhausted: true, details: "x" });
assert.match(stripAsIs(await runner.delayAction(db, t.scope, "stuck", "review")), /на ревью/);
assert.equal((await t.tp.task()).status, "review");
assert.equal(await core.getPlatformDelay(db, t.scope, "stuck"), null);
const r = await stuck({ checks: "failure" });
await assert.rejects(runner.delayAction(db, r.scope, "stuck", "review"), /Перевести на ревью нельзя: проверки не пройдены/);
assert.equal((await r.tp.task()).status, "in_progress");
await core.platformDelay(db, r.scope, { reason: "stuck", state: "admin", exhausted: true, details: "x" });
await runner.delayAction(db, r.scope, "stuck", "close");
assert.equal(await core.getPlatformDelay(db, r.scope, "stuck"), null, "«Закрыть»");
});
test("Кнопка Telegram разбирается", () => {
assert.deepEqual(core.parseDelayCallback("pd:t12:stuck:v"), { scope: { taskId: 12, projectId: null }, reason: "stuck", action: "review" });
assert.equal(core.parseDelayCallback("pd:t12:nope:v"), null);
});
});
describe("Владелец видит время следующей попытки", () => {
test("Scenario: Попытка запланирована — строка со временем, без текста терминала", async () => {
const t = await stuck({ checks: null });
const now = new Date("2026-11-18T08:00:00Z");
process.env.PEPPA_TZ = "Asia/Almaty";
await core.platformDelay(db, t.scope, { reason: "stuck", state: "retrying", quiet: true, details: "$ codex exec … error: unexpected argument", retryAt: new Date("2026-11-18T09:00:00Z").getTime(), now });
const line = stripAsIs((await core.taskDelayLine(db, t.ref.task.id, { now }))!);
assert.equal(line, "Задерживается на нашей стороне. Следующая попытка в 14:00");
const view = core.storyProductView({ status: "in_progress", agentWorking: false, openQuestions: 0, delayed: true, delayLine: line } as Parameters<typeof core.storyProductView>[0]);
assert.equal(stripAsIs(view.now), line);
assert.doesNotMatch(JSON.stringify(view), /codex|unexpected/, "no terminal text");
delete process.env.PEPPA_TZ;
});
});