// PEP-182: at most N live runners per subscription (9 by default, a superadmin changes it per // set); no room → the story waits «В очереди» and starts by itself in board order; rotation // never moves onto a full subscription; the team grows only within the capacity. import assert from "node:assert/strict"; import { after, before, describe, test } from "node:test"; import { agents } 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: 182, login: "mock-pm-182" }, { access_token: "x" }); admin = await core.upsertUserFromGitea(db, { id: 1182, login: "mock-admin-182" }, { 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[]) => { const pool = await core.createPool(db, { name: `Пул C${++seq}`, subscriptionIds: ids }); await core.setProjectPool(db, (await core.getProject(db, key)).id, pool.id); return pool; }; /** A live runner on the subscription without a process (counts like a real one). */ const fakeRunner = async (projectKey: string, subscriptionId: number) => (await core.createSession(db, { projectId: (await core.getProject(db, projectKey)).id, subscriptionId, provider: "claude" })).id; const fill = async (projectKey: string, subscriptionId: number, n: number) => { const ids: number[] = []; for (let i = 0; i < n; i++) ids.push(await fakeRunner(projectKey, subscriptionId)); return ids; }; const finish = (id: number) => core.updateSession(db, id, { status: "done", endedAt: new Date() }); const LONG = { turns: [[{ work: 60_000 }, { say: "Готово." }]] }; describe("Команда растёт в пределах ёмкости", () => { // First in the file: the team rule looks at all subscriptions of all sets. test("Все заняты, место есть — новый агент; ёмкость заполнена — не создаётся", async () => { for (const a of await core.listAgents(db)) await core.updateAgent(db, a.id, { disabled: true }); const a = await claudeSub("Team A", "teamA"); const p = await project({ turns: [] }); const pool = await poolFor(p.key, [a.id]); await core.setPoolCapacity(db, admin, pool.id, 2); const [s1, s2] = await fill(p.key, a.id, 2); const g1 = await core.ensureSessionAgent(db, s1!); const g2 = await core.ensureSessionAgent(db, s2!); assert.ok(g1 && g2 && g1.id !== g2.id, "both runners got a persona while there was room"); const before = (await db.select().from(agents)).length; // A third runner past the capacity (as if started before the rules): no new persona. const s3 = await fakeRunner(p.key, a.id); assert.equal(await core.ensureSessionAgent(db, s3), null); assert.equal((await db.select().from(agents)).length, before, "the team did not grow"); await assert.rejects(core.assertAgentAvailable(db, a.id), (e) => core.isNoCapacity(e)); // The manual «Добавить» works as before. const manual = await core.createAgent(db, {}); assert.ok(manual.id); for (const id of [s1!, s2!, s3]) await finish(id); await core.updateAgent(db, manual.id, { disabled: true }); }); }); describe("Ёмкость подписки при запуске", () => { test("На подписке 9 живых — раннер на другой подписке набора; других нет — задача в очереди", async () => { const [a, b] = [await claudeSub("Cap A", "capA"), await claudeSub("Cap B", "capB")]; const p = await project(LONG); await poolFor(p.key, [a.id, b.id]); const busy = await fill(p.key, a.id, 9); const r = await runner.moveTask(db, await core.resolveTask(db, p.taskKey), "in_progress"); assert.ok(r.started, "a runner started"); assert.equal((await core.getSession(db, r.started!)).subscriptionId, b.id, "on the subscription with room"); await runner.stopSession(db, r.started!); // The other subscription is full too: the story waits. const busyB = await fill(p.key, b.id, 9); const ref = await core.createTask(db, { projectId: (await core.getProject(db, p.key)).id, title: "Ждёт места" }); const w = await runner.moveTask(db, ref, "in_progress"); assert.equal(w.waiting, true); assert.equal(w.started, undefined); assert.equal((await core.resolveTask(db, ref.key)).task.status, "in_progress", "stays in work"); assert.equal((await core.listSessions(db, { active: true, taskId: ref.task.id })).length, 0, "no runner"); const q = await core.capacityQueue(db, { projectIds: [ref.project.id] }); assert.deepEqual(q.map((x) => [x.key, x.position]), [[ref.key, 1]]); // Moving it to «В работу» again keeps its place and starts nothing. assert.equal((await runner.moveTask(db, ref, "in_progress")).started, undefined); // Back to the backlog: out of the queue. await runner.moveTask(db, ref, "backlog"); assert.equal((await core.capacityQueue(db, { projectIds: [ref.project.id] })).length, 0); for (const id of [...busy, ...busyB]) await finish(id); }); test("Уже работающие сверх ёмкости не останавливаются, новые не стартуют, пока их не станет меньше", async () => { const a = await claudeSub("Over A", "overA"); const p = await project(LONG); await poolFor(p.key, [a.id]); const over = await fill(p.key, a.id, 12); const w = await runner.moveTask(db, await core.resolveTask(db, p.taskKey), "in_progress"); assert.equal(w.waiting, true); for (const id of over) assert.notEqual((await core.getSession(db, id)).status, "done", "nobody was stopped"); // 12 → 9: still full. for (const id of over.slice(0, 3)) await finish(id); assert.equal(await runner.capacityQueueTick(db), 0); for (const id of over.slice(3)) await finish(id); await runner.moveTask(db, await core.resolveTask(db, p.taskKey), "backlog"); }); }); describe("Очередь задач по ёмкости", () => { test("Место освободилось — задача из очереди запускается сама, по порядку на доске", async () => { const a = await claudeSub("Queue A", "queueA"); const p = await project(LONG); const projectId = (await core.getProject(db, p.key)).id; const pool = await poolFor(p.key, [a.id]); await core.setPoolCapacity(db, admin, pool.id, 1); const [holder] = await fill(p.key, a.id, 1); const first = await core.resolveTask(db, p.taskKey); // higher on the board const second = await core.createTask(db, { projectId, title: "Вторая на доске" }); // Queued in the opposite order: the board decides, not who came first. assert.equal((await runner.moveTask(db, second, "in_progress")).waiting, true); assert.equal((await runner.moveTask(db, first, "in_progress")).waiting, true); const q = await core.capacityQueue(db, { projectIds: [projectId] }); assert.deepEqual(q.map((x) => [x.key, x.position]), [[first.key, 1], [second.key, 2]]); assert.deepEqual(await core.workLine(db, [projectId]), { doing: 0, queued: 2 }); // PEP-216: the indexed form (one pass for many projects) gives the same line. assert.deepEqual((await core.workLineIndex(db, [projectId]))([projectId]), { doing: 0, queued: 2 }); // Still full — nothing starts. assert.equal(await runner.capacityQueueTick(db), 0); await finish(holder!); assert.equal(await runner.capacityQueueTick(db), 1); const live = await core.listSessions(db, { active: true, taskId: first.task.id }); assert.equal(live.length, 1, "the story higher on the board started"); assert.equal(live[0]!.subscriptionId, a.id); const left = await core.capacityQueue(db, { projectIds: [projectId] }); assert.deepEqual(left.map((x) => [x.key, x.position]), [[second.key, 1]]); assert.deepEqual(await core.workLine(db, [projectId]), { doing: 1, queued: 1 }); assert.deepEqual((await core.workLineIndex(db, [projectId]))([projectId]), { doing: 1, queued: 1 }); await runner.stopSession(db, live[0]!.id); await waitFor("runner stopped", async () => (await core.getSession(db, live[0]!.id)).status === "done" || (await core.getSession(db, live[0]!.id)).status === "failed"); await runner.moveTask(db, second, "backlog"); }); test("Диспетчер не берёт задачи из бэклога, пока у набора нет места", async () => { const a = await claudeSub("Disp A", "dispA"); const p = await project(LONG); const projectId = (await core.getProject(db, p.key)).id; const pool = await poolFor(p.key, [a.id]); await core.setPoolCapacity(db, admin, pool.id, 1); const [holder] = await fill(p.key, a.id, 1); assert.equal(await core.poolHasRoom(db, projectId), false); await core.setAutonomy(db, projectId, { level: "auto" }); await runner.autonomyTick(db, {}); assert.equal((await core.resolveTask(db, p.taskKey)).task.status, "backlog", "stays in the backlog"); await finish(holder!); assert.equal(await core.poolHasRoom(db, projectId), true); }); }); describe("Ротация уважает ёмкость", () => { test("Запасная подписка заполнена — переключения нет", async () => { const [a, b] = [await claudeSub("Rot A", "rotA"), await claudeSub("Rot B", "rotB")]; const p = await project({ turns: [] }); const projectId = (await core.getProject(db, p.key)).id; await poolFor(p.key, [a.id, b.id]); const busyB = await fill(p.key, b.id, 9); assert.equal(await core.rotationCandidate(db, { projectId, provider: "claude", subscriptionId: a.id }), null); await finish(busyB[0]!); assert.equal((await core.rotationCandidate(db, { projectId, provider: "claude", subscriptionId: a.id }))?.id, b.id, "room again — moves there"); for (const id of busyB) await finish(id); }); test("Ручной перевод на заполненную подписку — агенты остаются на месте", async () => { const [a, b] = [await claudeSub("Sw A", "swA"), await claudeSub("Sw B", "swB")]; const p = await project({ turns: [] }); await poolFor(p.key, [a.id, b.id]); const onA = await fill(p.key, a.id, 1); const busyB = await fill(p.key, b.id, 9); assert.deepEqual(await runner.switchAgents(db, { fromId: a.id, toId: b.id }), { moved: 0, skipped: 1 }); assert.equal((await core.getSession(db, onA[0]!)).subscriptionId, a.id); for (const id of [...onA, ...busyB]) await finish(id); }); }); describe("Суперадмин меняет ёмкость", () => { test("Новое значение действует сразу; вне 1–20 и не суперадмину — отказ; «агентов: N из M»", async () => { const a = await claudeSub("Set A", "setA"); const p = await project({ turns: [] }); const projectId = (await core.getProject(db, p.key)).id; const pool = await poolFor(p.key, [a.id]); const busy = await fill(p.key, a.id, 3); assert.equal(await core.poolHasRoom(db, projectId), true); let o = (await core.poolOverview(db, pool.id))!; assert.equal(o.capacity, 9); assert.equal(o.subscriptions[0]!.capacity, 9); assert.equal(o.subscriptions[0]!.load, "агентов: 3 из 9"); assert.equal(await core.setPoolCapacity(db, admin, pool.id, 3), 3); assert.equal(await core.poolHasRoom(db, projectId), false, "works at once"); o = (await core.poolOverview(db, pool.id))!; assert.equal(o.subscriptions[0]!.load, "агентов: 3 из 3"); assert.deepEqual({ live: o.live, total: o.total }, { live: 3, total: 3 }); await assert.rejects(core.setPoolCapacity(db, admin, pool.id, 25), /от 1 до 20/); await assert.rejects(core.setPoolCapacity(db, admin, pool.id, 0), /от 1 до 20/); await assert.rejects(core.setPoolCapacity(db, pm, pool.id, 5)); for (const id of busy) await finish(id); }); }); describe("Очередь на виду у продакта", () => { test("Страница задачи в очереди: место в очереди и что дальше — без подписок", () => { const v = core.storyProductView({ status: "in_progress", agentWorking: false, openQuestions: 0, queued: 2 }); assert.equal(stripAsIs(v.now), "В очереди: 2-я, начнётся, когда освободится агент"); assert.doesNotMatch(`${v.now} ${v.next}`, /подписк|раннер|ёмкост/i); const paused = core.storyProductView({ status: "in_progress", agentWorking: false, openQuestions: 0 }); assert.equal(paused.now, core.STORY_PRODUCT_TEXT.paused.now, "without a queue — as before"); }); });