// PEP-84: runs «продакт» and «аналитик» over new backlog stories (see core/intake.ts). The // watchdog calls `intakeTick`; each story moves through product → analyst → (waiting for the // PM's answers | done). LLM calls run in the background of the tick (one story at a time per // process), so a slow model never holds the watchdog. The dispatcher skips stories the roles // have not finished with (`readyBacklog`), a PM who drags the card to work overrides them. import { addIntakeNote, analystMessage, analystPrompt, answerQuestion, askPm, createTask, getAutonomy, getIntakeSettings, getIntakeState, inAutonomyQuietHours, intakeContext, intakeDescription, intakePending, listTasks, parseAnalystNote, parseProductNote, productMessage, productPrompt, questionsText, setIntakeState, updateTask, type IntakeState, type Project, type Question, type TaskRef, } from "@peppa/core"; import type { Db } from "@peppa/db"; import { projects } from "@peppa/db"; import { claudePrint } from "./claude-print.ts"; import { onAnswer, resolveTaskById } from "./sessions.ts"; const MAX_ATTEMPTS = 2; const inFlight = new Set(); const ask = (db: Db, project: Project, prompt: string, who: string) => claudePrint(db, project, { bin: process.env.PEPPA_INTAKE_BIN ?? "claude", model: process.env.PEPPA_INTAKE_MODEL ?? "sonnet", timeoutMs: Number(process.env.PEPPA_INTAKE_TIMEOUT_MS ?? 180_000), prompt, who, }); /** When the analyst stops waiting: `waitMin` from now, moved past the project's quiet hours. */ function deadline(now: Date, waitMin: number, quiet: { quietFrom: number | null; quietTo: number | null }): number { const at = new Date(now.getTime() + waitMin * 60_000); if (quiet.quietTo != null && inAutonomyQuietHours(quiet, at)) { const morning = new Date(at); morning.setHours(quiet.quietTo, 0, 0, 0); if (morning <= at) morning.setDate(morning.getDate() + 1); return morning.getTime(); } return at.getTime(); } /** One step of a story; returns the new state. Throws on a model failure (the caller counts attempts). */ async function step(db: Db, ref: TaskRef, state: IntakeState, now: Date): Promise { const { project, task } = ref; const context = await intakeContext(db, project, task); if (state.stage === "product") { const out = await ask(db, project, productPrompt(context, state.original), "продакт"); if (!out.ok) throw new Error(out.error); const note = parseProductNote(out.text, state.original.title); if (!note) throw new Error("продакт ответил не по формату"); const splitKeys: string[] = []; for (const s of note.split) { const extra = await createTask(db, { projectId: project.id, goalId: task.goalId ?? undefined, title: s.title, description: s.description }); // A split story is already cut by the product manager: the analyst takes it from here. await setIntakeState(db, extra.task.id, { stage: "analyst", original: { title: s.title, description: s.description }, product: { ...note, title: s.title, split: [] }, attempts: 0 }); splitKeys.push(extra.key); } if (note.title !== task.title) await updateTask(db, ref, { title: note.title }); await addIntakeNote(db, task, "product", productMessage(note, splitKeys)); return { ...state, stage: "analyst", product: note, attempts: 0 }; } if (state.stage === "analyst" || state.stage === "finalize") { const answers = state.stage === "finalize" && state.analyst ? { questions: state.analyst.questions, answer: state.answer ?? "" } : undefined; const out = await ask(db, project, analystPrompt(context, { title: task.title, description: state.original.description }, state.product, answers), "аналитик"); if (!out.ok) throw new Error(out.error); const note = parseAnalystNote(out.text); if (!note) throw new Error("аналитик ответил не по формату"); if (answers) note.questions = []; await updateTask(db, ref, { description: intakeDescription(state.original, note) }); await addIntakeNote(db, task, "analyst", answers ? `Учёл ответ. ${analystMessage(note)}` : analystMessage(note)); if (!note.questions.length) return { ...state, stage: "done", analyst: note, attempts: 0 }; const settings = await getIntakeSettings(db, project.id); const q = await askPm(db, ref, { kind: "question", text: questionsText(ref.key, note.questions, settings.waitMin) }); return { ...state, stage: "waiting", analyst: note, questionId: q.id, deadline: deadline(now, settings.waitMin, await getAutonomy(db, project.id)), attempts: 0 }; } return state; } /** Nobody answered in time: the analyst's defaults become decisions, the story is ready. */ async function goByDefaults(db: Db, ref: TaskRef, state: IntakeState): Promise { const a = state.analyst!; const decided = a.questions.map((q) => `${q.q} — ${q.default} (ответа не было, взят вариант по умолчанию)`); await updateTask(db, ref, { description: intakeDescription(state.original, a, decided) }); if (state.questionId) await answerQuestion(db, state.questionId, "(ответа не было — аналитик взял варианты по умолчанию)", "system").catch(() => {}); await addIntakeNote(db, ref.task, "analyst", `Ответа не было — иду по вариантам по умолчанию:\n${a.questions.map((q) => `• ${q.q} → ${q.default}`).join("\n")}\nСтори готова к работе.`); await setIntakeState(db, ref.task.id, { ...state, stage: "done" }); } async function advance(db: Db, taskId: number, now: Date, log: (m: string) => void): Promise { const ref = await resolveTaskById(db, taskId).catch(() => null); if (!ref) return; const settings = await getIntakeSettings(db, ref.project.id); let state = await getIntakeState(db, taskId); if (!intakePending(settings, ref.task, state)) return; state ??= { stage: "product", original: { title: ref.task.title, description: ref.task.description ?? "" }, attempts: 0 }; if (state.stage === "waiting") { if ((state.deadline ?? 0) <= now.getTime()) { await goByDefaults(db, ref, state); log(`${ref.key}: intake — no answer, defaults taken`); } return; } try { // Several steps in a row: product → analyst without waiting for the next tick. for (let i = 0; i < 3 && state.stage !== "waiting" && state.stage !== "done"; i++) { state = await step(db, ref, state, now); await setIntakeState(db, taskId, state); log(`${ref.key}: intake → ${state.stage}`); } } catch (e) { const attempts = state.attempts + 1; // The roles must never hold a story for ever: after a couple of failures it goes on as written. if (attempts >= MAX_ATTEMPTS) { await setIntakeState(db, taskId, { ...state, stage: "done", attempts, note: (e as Error).message }); await addIntakeNote(db, ref.task, state.stage === "product" ? "product" : "analyst", `Не смог разобрать задачу (${(e as Error).message}) — стори идёт в работу как написана.`); } else await setIntakeState(db, taskId, { ...state, attempts }); log(`${ref.key}: intake failed (${attempts}): ${(e as Error).message}`); } } export interface IntakeTickOptions { now?: Date; log?: (m: string) => void; /** Tests: wait for the model calls instead of leaving them in the background. */ wait?: boolean; } export async function intakeTick(db: Db, opts: IntakeTickOptions = {}): Promise { const now = opts.now ?? new Date(); const log = opts.log ?? (() => {}); const jobs: Promise[] = []; for (const { id } of await db.select({ id: projects.id }).from(projects)) { const settings = await getIntakeSettings(db, id); if (!settings.enabled) continue; for (const t of await listTasks(db, { projectId: id, statuses: ["backlog"] })) { if (inFlight.has(t.id) || !intakePending(settings, t, await getIntakeState(db, t.id))) continue; inFlight.add(t.id); jobs.push(advance(db, t.id, now, log).catch((e) => log(`intake ${t.id}: ${(e as Error).message}`)).finally(() => inFlight.delete(t.id))); } } if (opts.wait) await Promise.all(jobs); } /** The PM answered the analyst's questions: the analyst finishes the story with the answer. */ export async function onIntakeAnswer(db: Db, q: Question, answer: string): Promise { if (!q.taskId) return false; const state = await getIntakeState(db, q.taskId); if (!state || state.stage !== "waiting" || state.questionId !== q.id) return false; await setIntakeState(db, q.taskId, { ...state, stage: "finalize", answer, attempts: 0 }); return true; } onAnswer(onIntakeAnswer); /** The PM dragged the card to work (or the story left the backlog): the roles let it go. */ export async function releaseIntake(db: Db, taskId: number): Promise { const state = await getIntakeState(db, taskId); if (!state || state.stage === "done") return; if (state.questionId) await answerQuestion(db, state.questionId, "(стори взята в работу без ответа)", "system").catch(() => {}); await setIntakeState(db, taskId, { ...state, stage: "done", note: "взята в работу вручную" }); }