// PEP-183: does a story fit one of the team's specialists — one short model call (the cheapest // model, the project's pool subscription), the answer kept with the story and never recomputed. // A failed call = «nobody» (the story goes to a generalist) and a line in the journal only. import { agents, goals, sessions, tasks, type Db } from "@peppa/db"; import { getTeamMatch, getTeamSettings, agentIsBusy, isSpecialist, listSpecialists, logEvent, matchPrompt, parseMatch, setTeamMatch, type TeamMatch } from "@peppa/core"; import { and, eq, isNotNull } from "drizzle-orm"; import { claudePrint } from "./claude-print.ts"; /** The story's match; computed on the first call (when it is about to go to an agent for the first time). */ export async function ensureTaskMatch(db: Db, taskId: number): Promise { const known = await getTeamMatch(db, taskId); if (known) return known; const specialists = await listSpecialists(db); if (!specialists.length) return null; // 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, taskId), isNotNull(sessions.agentId))).limit(1); if (prior) return null; const [t] = await db.select().from(tasks).where(eq(tasks.id, taskId)); if (!t) return null; const [epic] = t.goalId ? await db.select({ title: goals.title }).from(goals).where(eq(goals.id, t.goalId)) : []; const fail = async (error: string): Promise => { const v: TeamMatch = { agentId: null, name: null, reason: "", at: Date.now(), failed: true }; await setTeamMatch(db, taskId, v); await logEvent(db, { projectId: t.projectId, taskId, type: "team_match_failed", payload: { error } }).catch(() => {}); return v; }; try { const out = await claudePrint(db, { id: t.projectId }, { bin: process.env.PEPPA_TEAM_BIN ?? process.env.PEPPA_INTAKE_BIN ?? "claude", model: process.env.PEPPA_TEAM_MATCH_MODEL ?? "haiku", timeoutMs: Number(process.env.PEPPA_TEAM_MATCH_TIMEOUT_MS) || 60_000, who: "подборщик специалиста", prompt: matchPrompt({ title: t.title, description: t.description ?? "", epic: epic?.title ?? null, specialists: specialists.map((s) => ({ name: s.name, character: s.character })) }), }); if (!out.ok) return await fail(out.error); const parsed = parseMatch(out.text, specialists); if (!parsed) return await fail("ответ не по форме"); const v: TeamMatch = { ...parsed, at: Date.now() }; await setTeamMatch(db, taskId, v); return v; } catch (e) { return await fail((e as Error).message); } } // PEP-203: the match is a model call of up to a minute; the watchdog's tick must not wait for it. // The tick only reads finished matches; missing ones are computed in the background, one at a // time, and only for the head of the queue (HOLD_SCAN stories) — those wait until it is known. const HOLD_SCAN = 3; const inflight = new Map>(); 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, 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 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(); if (!match.waitSince) await setTeamMatch(db, t.id, { ...match, waitSince: since }); if (now.getTime() - since < waitMin * 60_000) held.add(t.id); } return held; }