diff --git a/packages/runner/src/team-match.ts b/packages/runner/src/team-match.ts index dfe9266d..d9688daf 100644 --- a/packages/runner/src/team-match.ts +++ b/packages/runner/src/team-match.ts @@ -43,17 +43,48 @@ export async function ensureTaskMatch(db: Db, taskId: number): Promise>(); + +function matchInBackground(db: Db, taskId: number): void { + if (inflight.has(taskId) || inflight.size >= 1) return; + const p = ensureTaskMatch(db, taskId) + .catch(() => null) + .finally(() => inflight.delete(taskId)); + inflight.set(taskId, p); +} + +/** Tests: wait for the background matches started so far. */ +export async function teamMatchesSettled(): Promise { + while (inflight.size) await Promise.all([...inflight.values()]); +} + /** * Stories the dispatcher must hold back: they fit a specialist who is busy right now and have - * not waited longer than the platform's threshold. Not a failure — nobody is told. + * not waited longer than the platform's threshold, or their match is still being computed + * (head of the queue only). Not a failure — nobody is told. */ export async function specialistHold(db: Db, list: T[], now = new Date()): Promise> { const held = new Set(); if (!list.length || !(await listSpecialists(db)).length) return held; const { waitMin } = await getTeamSettings(db); + let unknown = 0; for (const t of list) { - const match = await ensureTaskMatch(db, t.id); - if (!match?.agentId) continue; + const match = await getTeamMatch(db, t.id); + if (!match) { + if (unknown >= HOLD_SCAN) continue; + // The story already had an agent: the same one goes on, nothing to decide. + const [prior] = await db.select({ id: sessions.id }).from(sessions).where(and(eq(sessions.taskId, t.id), isNotNull(sessions.agentId))).limit(1); + if (prior) continue; + unknown++; + matchInBackground(db, t.id); + held.add(t.id); + continue; + } + if (!match.agentId) continue; const [a] = await db.select().from(agents).where(eq(agents.id, match.agentId)); if (!a || !isSpecialist(a) || !(await agentIsBusy(db, a.id))) continue; const since = match.waitSince ?? now.getTime(); diff --git a/packages/testkit/src/mock-team.ts b/packages/testkit/src/mock-team.ts index f2fb4ec5..a102ebe5 100644 --- a/packages/testkit/src/mock-team.ts +++ b/packages/testkit/src/mock-team.ts @@ -1,5 +1,5 @@ // mock-team (PEP-183): stands in for `claude -p` as the specialist matcher. The scenario file -// (MOCK_TEAM_SCENARIO, JSON): { "rules": [{ "match": "безопасн", "agent": "Страж ИБ", "reason": "…" }], "fail": false }. +// (MOCK_TEAM_SCENARIO, JSON): { "rules": [{ "match": "безопасн", "agent": "Страж ИБ", "reason": "…" }], "fail": false, "slowMs": 0 }. // The first rule whose regexp matches the story's title ("Задача: …") wins; none → agent null. // Every call is appended to .log.jsonl. import { appendFileSync, existsSync, readFileSync } from "node:fs"; @@ -7,6 +7,8 @@ import { appendFileSync, existsSync, readFileSync } from "node:fs"; interface Scenario { rules?: Array<{ match: string; agent: string | null; reason?: string }>; fail?: boolean; + /** Answer after this many ms (a slow model). */ + slowMs?: number; } const file = process.env.MOCK_TEAM_SCENARIO; const sc: Scenario = file && existsSync(file) ? JSON.parse(readFileSync(file, "utf8")) : {}; @@ -17,6 +19,7 @@ if (!process.argv.includes("-p")) { console.error("mock-team: expected -p (non-interactive print mode)"); process.exit(2); } +if (sc.slowMs) Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, sc.slowMs); if (sc.fail) { console.error("mock-team: API Error: 529 overloaded"); process.exit(1); diff --git a/packages/testkit/test/team-match.test.ts b/packages/testkit/test/team-match.test.ts index eec5b45d..de4357f2 100644 --- a/packages/testkit/test/team-match.test.ts +++ b/packages/testkit/test/team-match.test.ts @@ -53,6 +53,9 @@ describe("Специалисты и задачи по профилю", () => { 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"); @@ -66,6 +69,29 @@ describe("Специалисты и задачи по профилю", () => { 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 });