peppa/packages/testkit/test/stuck-no-agent.test.ts

128 lines
7.0 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-247, spec platform-delays: a story «В работе» that never had an agent (no session, no
// runner queue, no capacity wait) is not forgotten — after 30 minutes the stuck-story watchdog
// starts an agent and keeps a `stuck` delay; a lawful reason (pause, no subscription, budget) is
// no delay, the card says why.
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 { projects, sessions, tasks } from "@peppa/db";
import { eq } from "drizzle-orm";
process.env.PEPPA_SECRET = "mock-secret-for-tests";
const gitea = new MockGitea(join(mkdtempSync(join(tmpdir(), "peppa-noagent-")), "gitea"));
const BOT = { id: 72, login: "peppa-bot", token: "mock-token-bot" };
const MIN = 60_000;
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: 9301, login: "mock-owner-noagent" }, { access_token: "x" });
setDefaultOwner(owner.id);
});
after(async () => {
delete process.env.PEPPA_STUCK_TASKS;
await gitea.stop();
await teardown();
});
/** A story moved to «В работе» `ageMin` minutes ago; no agent was ever started on it. */
async function noAgent(ageMin = 40) {
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" });
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 ref = await core.resolveTask(db, tp.taskKey);
await core.updateTask(db, ref, { status: "in_progress" });
await db.update(tasks).set({ updatedAt: new Date(Date.now() - ageMin * MIN) }).where(eq(tasks.id, ref.task.id));
return { tp, proj, ref, scope: { projectId: proj.id, taskId: ref.task.id } };
}
const tick = () => runner.stuckTaskTick(db, { now: new Date() });
const taskSessions = (taskId: number) => db.select().from(sessions).where(eq(sessions.taskId, taskId));
describe("Задача «В работе» без агента не теряется", () => {
test("Scenario: Задача без агента получает агента", async () => {
const t = await noAgent();
assert.equal(await tick(), 1);
const [s] = await taskSessions(t.ref.task.id);
assert.ok(s, "an agent is started on the story");
const d = await core.getPlatformDelay(db, t.scope, "stuck");
assert.equal(d?.state, "retrying");
assert.ok(d?.retryAt && d.retryAt > Date.now(), "the owner sees when the next attempt comes");
assert.match(String(d?.action), /ни разу не запускался/);
assert.equal((await runner.getStuckHeal(db, t.ref.task.id))?.attempts, 1);
await waitFor("settled", async () => ((await core.getSession(db, s.id)).status !== "starting" ? true : null));
await runner.stopSession(db, s.id).catch(() => {});
});
test("Scenario: Задача без агента меньше 30 минут — не трогаем", async () => {
const t = await noAgent(10);
await tick();
assert.equal((await taskSessions(t.ref.task.id)).length, 0);
assert.equal(await core.getPlatformDelay(db, t.scope, "stuck"), null);
});
test("Задача ждёт свободного агента — не застряла", async () => {
const t = await noAgent();
await core.waitForCapacity(db, t.ref.task.id);
await tick();
assert.equal((await taskSessions(t.ref.task.id)).length, 0);
assert.equal(await core.getPlatformDelay(db, t.scope, "stuck"), null);
await core.clearCapacityWait(db, t.ref.task.id);
});
test("Scenario: Задача встала в очередь свободного агента — задержка снимается", async () => {
const t = await noAgent();
await core.platformDelay(db, t.scope, { reason: "stuck", state: "retrying", quiet: true, details: "x" });
await core.waitForCapacity(db, t.ref.task.id);
await runner.platformDelayTick(db, { commit: null });
assert.equal(await core.getPlatformDelay(db, t.scope, "stuck"), null);
await core.clearCapacityWait(db, t.ref.task.id);
});
});
describe("Законная причина без агента — не задержка", () => {
test("Scenario Outline: проект на паузе", async () => {
const t = await noAgent();
await core.setProjectPause(db, t.proj.id, { since: Date.now(), by: null, sessions: [] });
await tick();
assert.equal((await taskSessions(t.ref.task.id)).length, 0);
assert.equal(await core.getPlatformDelay(db, t.scope, "stuck"), null);
assert.equal((await core.taskHoldReason(db, t.proj.id, t.ref.task.id))?.text, "Проект на паузе — агент продолжит, когда вы снимете паузу");
await core.clearProjectPause(db, t.proj.id);
});
test("Scenario Outline: у проекта нет рабочей подписки (прежняя задержка снимается)", async () => {
const t = await noAgent();
const pool = await core.createPool(db, { name: `mock-empty-${t.proj.key}`, subscriptionIds: [] });
await db.update(projects).set({ subscriptionPoolId: pool.id }).where(eq(projects.id, t.proj.id));
await core.platformDelay(db, t.scope, { reason: "stuck", state: "retrying", quiet: true, details: "x" });
await tick();
assert.equal((await taskSessions(t.ref.task.id)).length, 0);
assert.equal(await core.getPlatformDelay(db, t.scope, "stuck"), null, "no false delay");
assert.equal((await core.taskHoldReason(db, t.proj.id, t.ref.task.id))?.text, "Агент не запущен: у проекта нет рабочей подписки");
const holds = await core.taskHoldReasons(db, t.proj.id, [t.ref.task.id]);
assert.equal(holds.get(t.ref.task.id)?.kind, "subscription");
const view = core.storyProductView({ status: "in_progress", agentWorking: false, openQuestions: 0, hold: "subscription" });
assert.equal(view.now, "Агент не запущен: у проекта нет рабочей подписки");
assert.ok(view.need, "the owner is told what to do");
});
test("Scenario Outline: бюджет задачи исчерпан", async () => {
const t = await noAgent();
await core.setBudgetState(db, t.ref.task.id, { pausedAt: Date.now(), over: ["minutes"] });
await tick();
assert.equal((await taskSessions(t.ref.task.id)).length, 0);
assert.equal(await core.getPlatformDelay(db, t.scope, "stuck"), null);
assert.equal((await core.taskHoldReason(db, t.proj.id, t.ref.task.id))?.kind, "budget");
});
});