peppa/packages/testkit/test/team-match.test.ts
peppa-bot c2b5a46ee6 PEP-203: подбор специалиста не держит тик вачдога
specialistHold звал модель по очереди для каждой готовой задачи бэклога прямо в тике:
на живой 125 задач — вачдог не писал heartbeat, выкатка откатывалась. Теперь тик
читает только готовые подборы, недостающие считаются в фоне по одному и только для
первых трёх задач очереди; пока подбор считается, такая задача ждёт.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-17 20:38:45 +05:00

123 lines
7.0 KiB
TypeScript
Raw Permalink 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-183: specialists get stories of their profile.
import assert from "node:assert/strict";
import { writeFileSync } from "node:fs";
import { join } from "node:path";
import { after, describe, test } from "node:test";
import { core, db, project, runner, teardown } from "./helpers.ts";
process.env.PEPPA_SECRET = "mock-secret-for-tests";
process.env.PEPPA_TEAM_BIN = join(import.meta.dirname, "../bin/mock-team");
after(teardown);
const scenario = (s: object) => {
const f = join(process.env.PEPPA_HOME!, `team-${Math.random().toString(36).slice(2)}.json`);
writeFileSync(f, JSON.stringify(s));
process.env.MOCK_TEAM_SCENARIO = f;
return f;
};
const retitle = async (p: { taskKey: string }, title: string) => core.updateTask(db, await core.resolveTask(db, p.taskKey), { title });
const agentOf = async (sid: number) => (await core.getSession(db, sid)).agentName;
describe("Специалисты и задачи по профилю", () => {
let guard: Awaited<ReturnType<typeof core.createAgent>>;
let plain: Awaited<ReturnType<typeof core.createAgent>>;
test("Scenario: задача про безопасность — специалисту, про интерфейс — универсалу", async () => {
scenario({ rules: [{ match: "безопасн", agent: "Страж ИБ", reason: "про безопасность" }] });
guard = await core.createAgent(db, { name: "Страж ИБ", character: "Безопасность: проверяет ввод и секреты." });
plain = await core.createAgent(db, { name: "Универсал" });
const sec = await project({ turns: [[{ say: "ok" }]] });
await retitle(sec, "Проверить безопасность входа");
const ui = await project({ turns: [[{ say: "ok" }]] });
await retitle(ui, "Поправить кнопку интерфейса");
const s1 = await sec.start();
assert.equal(await agentOf(s1), "Страж ИБ");
const s2 = await ui.start();
assert.equal(await agentOf(s2), "Универсал");
const m = await core.getTeamMatch(db, (await sec.task()).id);
assert.equal(m?.agentId, guard.id);
assert.match(core.matchLine(m)!, /Отдана специалисту/);
assert.equal((await core.listAgents(db)).find((a) => a.id === guard.id)!.profileTasks, 1);
await runner.stopSession(db, s1);
await runner.stopSession(db, s2);
});
test("Scenario: специалист занят — задача ждёт его, через порог уходит универсалу", async () => {
const busy = await project({ turns: [[{ say: "ok" }]] });
await retitle(busy, "Безопасность: ключи");
const s0 = await busy.start();
assert.equal(await agentOf(s0), "Страж ИБ");
const next = await project({ turns: [[{ say: "ok" }]] });
await retitle(next, "Ещё про безопасность");
const t = await next.task();
const [proj] = await core.listProjects(db).then((l) => l.filter((x) => x.key === next.key));
const now = new Date();
// PEP-203: the match is computed in the background; until then the head of the queue waits.
assert.deepEqual([...(await runner.specialistHold(db, [t], now))], [t.id], "the match is being computed");
await runner.teamMatchesSettled();
assert.deepEqual([...(await runner.specialistHold(db, [t], now))], [t.id], "waits for the busy specialist");
assert.deepEqual([...(await runner.specialistHold(db, [t], new Date(now.getTime() + 20 * 60_000)))], [t.id], "still within 30 min");
assert.deepEqual([...(await runner.specialistHold(db, [t], new Date(now.getTime() + 31 * 60_000)))], [], "after the threshold it is free to go");
await core.setTeamSettings(db, { waitMin: 5 });
assert.deepEqual([...(await runner.specialistHold(db, [t], new Date(now.getTime() + 6 * 60_000)))], []);
const s1 = await next.start();
assert.equal(await agentOf(s1), "Универсал", "the specialist is busy → a generalist");
assert.ok(proj);
await runner.stopSession(db, s0);
await runner.stopSession(db, s1);
await core.setTeamSettings(db, { waitMin: 30 });
});
test("Scenario: длинный бэклог — тик не ждёт модель, подбор только для головы очереди (PEP-203)", async () => {
scenario({ rules: [{ match: "безопасн", agent: "Страж ИБ", reason: "про безопасность" }], slowMs: 400 });
const list = [];
for (let i = 0; i < 6; i++) {
const p = await project({ turns: [[{ say: "ok" }]] });
await retitle(p, `Задача ${i}`);
list.push(await p.task());
}
const t0 = Date.now();
const held = await runner.specialistHold(db, list);
assert.ok(Date.now() - t0 < 300, "the tick does not wait for the model");
assert.deepEqual([...held], list.slice(0, 3).map((t) => t.id), "only the head of the queue waits");
await runner.teamMatchesSettled();
for (let i = 0; i < 3 && !(await core.getTeamMatch(db, list[2]!.id)); i++) {
await runner.specialistHold(db, list);
await runner.teamMatchesSettled();
}
for (const t of list.slice(0, 3)) assert.ok(await core.getTeamMatch(db, t.id), "head matched");
for (const t of list.slice(3)) assert.equal(await core.getTeamMatch(db, t.id), null, "the rest is not matched yet");
assert.deepEqual([...(await runner.specialistHold(db, list))], list.slice(3, 6).map((t) => t.id), "the next three are now the unknown head");
await runner.teamMatchesSettled();
});
test("Scenario: стёрли специализацию — следующая задача идёт как универсалу", async () => {
await core.updateAgent(db, guard.id, { character: "" });
await core.updateAgent(db, plain.id, { disabled: true });
const p = await project({ turns: [[{ say: "ok" }]] });
await retitle(p, "Безопасность: логи");
const sid = await p.start();
assert.equal(await agentOf(sid), "Страж ИБ");
assert.equal(await core.getTeamMatch(db, (await p.task()).id), null, "no specialists left — nothing to decide");
await runner.stopSession(db, sid);
await core.updateAgent(db, plain.id, { disabled: false });
});
test("Scenario: запрос к модели упал — задача отдана универсалу, ошибки нет", async () => {
await core.updateAgent(db, guard.id, { character: "Безопасность." });
scenario({ fail: true });
const p = await project({ turns: [[{ say: "ok" }]] });
await retitle(p, "Безопасность: пароли");
const sid = await p.start();
assert.equal(await agentOf(sid), "Универсал");
const m = await core.getTeamMatch(db, (await p.task()).id);
assert.equal(m?.failed, true);
assert.equal(core.matchLine(m), "Специалиста не нашлось");
const proj = (await core.listProjects(db)).find((x) => x.key === p.key)!;
const j = await core.listJournal(db, { projectId: proj.id } as never);
assert.ok(j.some((e) => e.type === "team_match_failed"));
await runner.stopSession(db, sid);
});
});