// PEP-299: agents of stories waiting for «Принять» give their place on the subscription to a // story waiting «В очереди»: one per set per pass, the longest silent first; agents of stories in // work and agents with an open question stay; «Поправить» continues the same conversation. import assert from "node:assert/strict"; import { after, before, describe, test } from "node:test"; import { events } from "@peppa/db"; import { stripAsIs } from "@peppa/shared/i18n"; import { core, db, project, runner, setDefaultOwner, teardown, waitFor } from "./helpers.ts"; process.env.PEPPA_SECRET = "mock-secret-for-tests"; type User = Awaited>; let pm: User; let admin: User; before(async () => { pm = await core.upsertUserFromGitea(db, { id: 299, login: "mock-pm-299" }, { access_token: "x" }); admin = await core.upsertUserFromGitea(db, { id: 1299, login: "mock-admin-299" }, { access_token: "x" }); await core.setSetting(db, "platform.admins", [admin.login]); setDefaultOwner(pm.id); }); after(teardown); const TOKEN = (tag: string) => `sk-ant-oat01-mock${"x".repeat(24)}${tag}`; const claudeSub = (name: string, tag: string) => runner.addSubscription(db, { provider: "claude", name, method: "token", secret: TOKEN(tag), createdBy: pm.id }); let seq = 0; const poolFor = async (key: string, ids: number[], capacity: number) => { const pool = await core.createPool(db, { name: `Пул R${++seq}`, subscriptionIds: ids }); await core.setProjectPool(db, (await core.getProject(db, key)).id, pool.id); await core.setPoolCapacity(db, admin, pool.id, capacity); return pool; }; const cfg = { ...runner.WATCHDOG_DEFAULTS }; const minAgo = (n: number) => new Date(Date.now() - n * 60_000); const LONG = { turns: [[{ work: 60_000 }, { say: "Готово." }]] }; /** A story in `status` with a live runner on the subscription, its turn over `silentMin` ago (no process). */ async function idleAgent(projectKey: string, subscriptionId: number, status: "review" | "in_progress", silentMin: number) { const p = await core.getProject(db, projectKey); const ref = await core.createTask(db, { projectId: p.id, title: `Задача агента ${++seq}` }); await core.updateTask(db, ref, { status }); const s = await core.createSession(db, { projectId: p.id, taskId: ref.task.id, subscriptionId, provider: "claude" }); await core.updateSession(db, s.id, { status: status === "review" ? "waiting_input" : "idle", lastActivityAt: minAgo(silentMin) }); return { ref, sessionId: s.id }; } const statusOf = async (id: number) => (await core.getSession(db, id)).status; const finish = (id: number) => core.updateSession(db, id, { status: "done", endedAt: new Date() }); const stopAll = async (taskId: number) => { for (const s of await core.listSessions(db, { active: true, taskId })) { await runner.stopSession(db, s.id); await waitFor("stopped", async () => ["done", "failed"].includes(await statusOf(s.id))); } }; describe("Агент задачи на проверке уступает место очереди", () => { test("Очередь ждёт — простаивающий агент ревью уступает место", async () => { const a = await claudeSub("Rel A", "relA"); const p = await project(LONG); await poolFor(p.key, [a.id], 2); const older = await idleAgent(p.key, a.id, "review", 120); const newer = await idleAgent(p.key, a.id, "review", 60); // The owner's «готово» card is open on the older one: it must survive the stop. const card = await core.raiseSessionQuestion(db, await core.getSession(db, older.sessionId), "attention", "✅ Задача готова к ревью", undefined, false, { topic: "review", msgType: "done" }); const queued = await core.resolveTask(db, p.taskKey); assert.equal((await runner.moveTask(db, queued, "in_progress")).waiting, true, "the set is full — the story waits"); // Before the threshold: nobody is stopped. assert.equal(await runner.reviewReleaseTick(db, { now: new Date(), cfg: { ...cfg, reviewReleaseMin: 180 } }), 0); assert.equal(await runner.reviewReleaseTick(db, { now: new Date(), cfg }), 1, "one per pass"); assert.equal(await statusOf(older.sessionId), "done", "the longest silent one gave its place"); assert.equal(await statusOf(newer.sessionId), "waiting_input", "the other one is untouched"); assert.equal((await core.resolveTask(db, older.ref.key)).task.status, "review", "the story stays in review"); const q = (await core.pendingQuestions(db, older.ref.project.id)).find((x) => x.id === card!.id); assert.ok(q, "«Принять» is still there"); const [ev] = (await db.select().from(events)).filter((e) => e.type === "review_released" && e.sessionId === older.sessionId); assert.ok(ev, "event in the story's log"); assert.equal(await runner.capacityQueueTick(db), 1, "the queued story starts"); const live = await core.listSessions(db, { active: true, taskId: queued.task.id }); assert.equal(live.length, 1); await stopAll(queued.task.id); await runner.moveTask(db, queued, "backlog"); await finish(newer.sessionId); }); test("Агент с вопросом и агент задачи в работе не останавливаются; без очереди — тоже", async () => { const a = await claudeSub("Keep A", "keepA"); const p = await project(LONG); await poolFor(p.key, [a.id], 2); const asking = await idleAgent(p.key, a.id, "review", 120); await core.raiseSessionQuestion(db, await core.getSession(db, asking.sessionId), "question", "Какой цвет кнопки?", ["Синий", "Зелёный"]); const working = await idleAgent(p.key, a.id, "in_progress", 120); // No queue yet: nothing to free the place for. assert.equal(await runner.reviewReleaseTick(db, { now: new Date(), cfg }), 0); const queued = await core.resolveTask(db, p.taskKey); assert.equal((await runner.moveTask(db, queued, "in_progress")).waiting, true); assert.equal(await runner.reviewReleaseTick(db, { now: new Date(), cfg }), 0); assert.notEqual(await statusOf(asking.sessionId), "done"); assert.notEqual(await statusOf(working.sessionId), "done"); assert.equal(await runner.capacityQueueTick(db), 0, "the story keeps waiting"); // Switched off (0) — nothing either, even with a releasable agent. await core.answerQuestion(db, (await core.pendingSessionQuestions(db, asking.sessionId))[0]!.id, "Синий", "web"); await core.updateSession(db, asking.sessionId, { status: "waiting_input", lastActivityAt: minAgo(120) }); assert.equal(await runner.reviewReleaseTick(db, { now: new Date(), cfg: { ...cfg, reviewReleaseMin: 0 } }), 0); await runner.moveTask(db, queued, "backlog"); await finish(asking.sessionId); await finish(working.sessionId); }); }); describe("Освобождённый агент продолжает тот же разговор", () => { test("«Поправить»: места нет — ждёт; место есть — та же сессия с тем же разговором", async () => { const a = await claudeSub("Resume A", "resA"); const p = await project({ turns: [[{ say: "Готово." }]], resumeTurns: [[{ say: "Поправил." }]] }); const projectId = (await core.getProject(db, p.key)).id; await poolFor(p.key, [a.id], 1); const ref = await core.resolveTask(db, p.taskKey); const r = await runner.moveTask(db, ref, "in_progress"); const sid = r.started!; assert.ok(sid, "the agent started"); const first = await p.waitLog("started", (e) => e.ev === "start"); const conv = await waitFor("conversation id", async () => (await core.getSession(db, sid)).conversationId); await waitFor("turn over", async () => ["waiting_input", "idle"].includes(await statusOf(sid))); // The agent handed the story in for review an hour ago. await core.updateTask(db, await core.resolveTask(db, p.taskKey), { status: "review" }); await core.updateSession(db, sid, { status: "waiting_input", lastActivityAt: minAgo(60) }); const other = await core.createTask(db, { projectId, title: "Ждёт места" }); assert.equal((await runner.moveTask(db, other, "in_progress")).waiting, true); assert.equal(await runner.reviewReleaseTick(db, { now: new Date(), cfg }), 1); assert.equal(await statusOf(sid), "done"); assert.equal(await runner.capacityQueueTick(db), 1); assert.equal((await core.listSessions(db, { active: true, taskId: other.task.id })).length, 1); // «Поправить» while the subscription is full: the story waits, no new agent. const fix = await runner.fixStory(db, await core.resolveTask(db, p.taskKey), pm, "Кнопка синяя"); assert.equal(fix.delivered, true); assert.equal((await core.listSessions(db, { active: true, taskId: ref.task.id })).length, 0, "no agent yet"); assert.deepEqual((await core.capacityQueue(db, { projectIds: [projectId] })).map((x) => x.key), [ref.key]); // The place frees up: the same session continues its conversation with the remark. await stopAll(other.task.id); assert.equal(await runner.capacityQueueTick(db), 1); const live = await core.listSessions(db, { active: true, taskId: ref.task.id }); assert.deepEqual(live.map((s) => s.id), [sid], "the same agent session"); const relaunch = await p.waitLog("resumed", (e) => e.ev === "start" && e.gen === "2"); assert.equal(relaunch.resume, conv, "same conversation"); assert.equal(first.resume ?? null, null); assert.match(stripAsIs(JSON.stringify(relaunch)), /Кнопка синяя/); await stopAll(ref.task.id); await runner.moveTask(db, other, "backlog"); }); });