// 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>; let plain: Awaited>; 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); }); });