peppa/packages/testkit/test/stuck-heal.test.ts

339 lines
22 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,
// red checks → the agent is relaunched with the reason (a conflict is its own step, PEP-269); 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 { existsSync, mkdtempSync, realpathSync, writeFileSync } from "node:fs";
import { execFileSync } from "node:child_process";
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 { Client } from "@modelcontextprotocol/sdk/client/index.js";
import { InMemoryTransport } from "@modelcontextprotocol/sdk/inMemory.js";
const { createAgentServer } = await import("@peppa/mcp/agent");
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({ checks: "failure" });
// PEP-269: a conflict is its own step now; red checks keep the relaunch schedule.
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;
});
});
describe("Пустой SET и общая рабочая копия (находки на живой системе)", () => {
test("update_task(status: review) при идущих проверках — без ошибки «No values to set»", async () => {
const t = await stuck({ checks: null });
gitea.setStatus(t.proj.giteaOwner, t.proj.giteaRepo, gitea.sha(t.proj.giteaOwner, t.proj.giteaRepo, `task/${t.tp.taskKey}`), "peppa/test", "pending");
const [a, b] = InMemoryTransport.createLinkedPair();
await createAgentServer(db, { defaultKey: t.tp.key }).connect(a);
const client = new Client({ name: "mock-agent", version: "0" });
await client.connect(b);
const r = await client.callTool({ name: "update_task", arguments: { task: t.tp.taskKey, status: "review" } });
const text = (r.content as Array<{ text: string }>)[0]!.text;
assert.equal(!!r.isError, false, text);
assert.match(text, /still running/);
assert.ok(await runner.getReviewWanted(db, t.ref.task.id), "the request is remembered");
// The same at the core: a patch of undefined fields changes nothing and does not throw.
const same = await core.updateTask(db, t.ref, { prUrl: undefined, title: undefined });
assert.equal(same.id, t.ref.task.id);
await client.close();
});
test("Общая рабочая копия: один агент на копию, вторая задача ждёт очереди", async () => {
const t = await stuck({ checks: "failure" });
// A second stuck story of the same project, same shared copy.
const other = await core.createTask(db, { projectId: t.proj.id, title: "Вторая" });
const sha2 = gitea.commit(t.proj.giteaOwner, t.proj.giteaRepo, `task/${other.key}`, { "g.txt": "2" });
const pr2 = gitea.openPull(t.proj.giteaOwner, t.proj.giteaRepo, `task/${other.key}`);
gitea.setStatus(t.proj.giteaOwner, t.proj.giteaRepo, sha2, "peppa/test", "failure");
await core.updateTask(db, other, { status: "in_progress", prUrl: `${gitea.url}/${t.proj.giteaOwner}/${t.proj.giteaRepo}/pulls/${pr2.number}` });
const s2 = await core.createSession(db, { projectId: t.proj.id, taskId: other.task.id });
await db.update(sessions).set({ status: "idle", lastActivityAt: new Date(Date.now() - 40 * MIN) }).where(eq(sessions.id, s2.id));
// Somebody already works in the shared copy.
const busy = await core.createSession(db, { projectId: t.proj.id, taskId: null });
await db.update(sessions).set({ status: "running" }).where(eq(sessions.id, busy.id));
await tick(Date.now());
for (const id of [t.ref.task.id, other.task.id]) {
const d = await core.getPlatformDelay(db, { projectId: t.proj.id, taskId: id }, "stuck");
assert.equal(d?.state, "queued", "waits for the copy");
assert.equal(d?.attempts, 0, "not an attempt");
}
// The copy is free: exactly one agent is relaunched, the other one waits for it.
await db.update(sessions).set({ status: "done" }).where(eq(sessions.id, busy.id));
await tick(Date.now() + 6 * MIN);
const healed = [await runner.getStuckHeal(db, t.ref.task.id), await runner.getStuckHeal(db, other.task.id)].filter((h) => (h?.attempts ?? 0) > 0);
assert.equal(healed.length, 1, "one agent per shared copy");
for (const id of [t.sid, s2.id]) {
await waitFor("settled", async () => ((await core.getSession(db, id)).status !== "starting" ? true : null));
await runner.stopSession(db, id).catch(() => {});
}
});
});
describe("PEP-246: рабочая копия с другой машины", () => {
const FOREIGN = "/Users/asel/.peppa/worktrees/peppa/s783";
const gitInit = (dir: string) => {
for (const a of [["init", "-q", "-b", "main"], ["add", "-A"], ["-c", "user.name=t", "-c", "user.email=t@t", "commit", "-qm", "init"]]) execFileSync("git", a, { cwd: dir });
};
const foreign = async (t: Awaited<ReturnType<typeof stuck>>) => {
// the reason to relaunch: red checks (stuck({ checks: "failure" }))
await db.update(sessions).set({ workspacePath: FOREIGN }).where(eq(sessions.id, t.sid));
};
test("Scenario: Путь рабочей копии с другой машины — агент перезапускается в новой копии", async () => {
const t = await stuck({ checks: "failure" });
gitInit(t.tp.dir);
await foreign(t);
await tick(Date.now());
await waitFor("relaunched", async () => ((await core.getSession(db, t.sid)).status !== "starting" ? true : null));
await runner.stopSession(db, t.sid).catch(() => {});
const s = await core.getSession(db, t.sid);
const want = realpathSync(runner.worktreePath(t.proj, t.sid));
assert.equal(s.workspacePath, want, "the session remembers the new copy");
assert.ok(existsSync(join(want, ".git")));
assert.equal(execFileSync("git", ["branch", "--show-current"], { cwd: want }).toString().trim(), `task/${t.tp.taskKey.toLowerCase()}`);
const heal = await runner.getStuckHeal(db, t.ref.task.id);
assert.equal(heal?.attempts, 1);
assert.doesNotMatch(heal!.action, /не перезапустился/, "the relaunch did not fail");
const [e] = await db.select().from(events).where(and(eq(events.sessionId, t.sid), eq(events.type, "worktree_created")));
assert.equal((e?.payload as { from?: string }).from, FOREIGN);
assert.ok((await db.select().from(events).where(and(eq(events.sessionId, t.sid), inArray(events.type, ["started", "resumed"])))).length >= 1, "the agent was relaunched");
});
test("Scenario: Перезапуск падает каждый раз — попытки считаются до исчерпания", async () => {
const t = await stuck({ checks: "failure" });
await foreign(t); // the project's copy is not a git repository: no new copy can be made
const T = Date.now();
for (const [at, n] of [[0, 1], [5, 2], [20, 3], [80, 4]] as const) {
await tick(T + at * MIN);
const h = await runner.getStuckHeal(db, t.ref.task.id);
assert.equal(h?.attempts, n, `attempt ${n} at +${at} min`);
assert.match(h!.action, /не перезапустился/);
}
assert.equal((await toAdmin(t.tp.taskKey)).length, 0);
await tick(T + 200 * MIN);
assert.equal((await core.getPlatformDelay(db, t.scope, "stuck"))?.exhausted, true);
assert.equal((await toAdmin(t.tp.taskKey)).length, 1, "one message to the superadmin");
});
test("Scenario: Попытку держит очередь проверок — не дольше 2 часов", async () => {
const t = await stuck();
t.pull().mergeable = false;
const T = Date.now();
await core.setSetting(db, `stuck.heal:${t.ref.task.id}`, { attempts: 3, at: T - 60 * MIN, nextAt: T, action: "x" });
await core.setSetting(db, "checks.queue", { since: T - 300 * MIN, win: 0 });
try {
await tick(T + MIN);
assert.equal((await runner.getStuckHeal(db, t.ref.task.id))?.attempts, 3, "the queue holds the attempt");
const d = await core.getPlatformDelay(db, t.scope, "stuck");
assert.equal(d?.state, "waiting");
assert.ok(d!.retryAt! > T + MIN, "the card shows the next check, not a past time");
await tick(T + 121 * MIN);
// PEP-269: the held conflict goes to its own step anyway — one request to the agent, not a relaunch.
assert.equal((await runner.getConflictStep(db, t.ref.task.id))?.attempts, 1, "after 2 h the request goes anyway");
assert.equal(await runner.getStuckHeal(db, t.ref.task.id), null, "the conflict step owns the story now");
} finally {
await core.deleteSetting(db, "checks.queue");
}
});
test("peppa session paths: находит путь с другой машины и переписывает завершённую сессию", async () => {
const t = await stuck();
await db.update(sessions).set({ workspacePath: FOREIGN, status: "done" }).where(eq(sessions.id, t.sid));
const found = await runner.findForeignPaths(db);
const row = found.sessions.find((x) => x.id === t.sid);
assert.equal(row?.fixTo, runner.worktreePath(t.proj, t.sid));
await runner.fixForeignPaths(db, found);
assert.equal((await core.getSession(db, t.sid)).workspacePath, runner.worktreePath(t.proj, t.sid));
assert.equal((await runner.findForeignPaths(db)).sessions.some((x) => x.id === t.sid && x.fixTo), false);
});
});