// PEP-115: the analyst reworks a backlog story after a person's comment (see core/story-refine.ts). // The watchdog calls `storyRefineTick`; the model call runs in the background of the tick, on the // project's subscription, like the intake roles. A failure is said once and never retried — the // comment stays where the developer agent reads it. import { m } from "@peppa/shared/i18n"; import { addIntakeNote, attachmentsForModel, getIntakeSettings, getIntakeState, intakeContext, intakeDescription, intakePending, listSessions, originalRequest, parseAnalystNote, pendingRefinements, refineMessage, refinePrompt, setRefineCursor, storyComments, updateTask, type RefineComment, } from "@peppa/core"; import type { Db } from "@peppa/db"; import { claudePrint } from "./claude-print.ts"; import { resolveTaskById } from "./sessions.ts"; const inFlight = new Set(); export interface StoryRefineOptions { now?: Date; log?: (m: string) => void; /** Tests: wait for the model calls instead of leaving them in the background. */ wait?: boolean; } export async function storyRefineTick(db: Db, opts: StoryRefineOptions = {}): Promise { const log = opts.log ?? (() => {}); const jobs: Promise[] = []; for (const [taskId, fresh] of await pendingRefinements(db, { now: opts.now })) { if (inFlight.has(taskId)) continue; inFlight.add(taskId); jobs.push( refine(db, taskId, fresh, log) .catch((e) => log(`story refine ${taskId}: ${(e as Error).message}`)) .finally(() => inFlight.delete(taskId)), ); } if (opts.wait) await Promise.all(jobs); } const untouched = async (db: Db, taskId: number) => { const ref = await resolveTaskById(db, taskId).catch(() => null); if (!ref || ref.task.status !== "backlog" || ref.task.archivedAt) return null; const [live] = await listSessions(db, { active: true, taskId }); return live ? null : ref; }; async function refine(db: Db, taskId: number, fresh: RefineComment[], log: (m: string) => void): Promise { const upTo = fresh.at(-1)!.id; const ref = await untouched(db, taskId); // An agent is on it (or the story left the backlog): the agent reads the comment itself. if (!ref) return setRefineCursor(db, taskId, upTo); const state = await getIntakeState(db, taskId); // «Продакт» and «аналитик» (PEP-84) are still formulating the story: wait for them. if (intakePending(await getIntakeSettings(db, ref.project.id), ref.task, state)) return; const { project, task } = ref; // PEP-159: files attached to the new comments (and to the story itself) go to the analyst too. const attached = await attachmentsForModel(db, { eventIds: fresh.map((c) => c.id), taskOnly: taskId }); const prompt = refinePrompt(await intakeContext(db, project, task), { title: task.title, description: task.description ?? "" }, await storyComments(db, taskId), fresh, state?.product, attached.prompt); const out = await 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, files: attached.files, who: m("аналитик"), }); // Whatever happens, these comments are dealt with. await setRefineCursor(db, taskId, upTo); const now = await untouched(db, taskId); if (!now) { log(`${ref.key}: story refine dropped — the story was taken to work meanwhile`); return; } const note = out.ok ? parseAnalystNote(out.text) : null; if (!note) { const why = out.ok ? m("ответ не по форме") : /нет подписки/.test(out.error) ? m("у проекта не подключена подписка Claude — «⋯ Настройки проекта → Подписки»") : out.error.slice(0, 200); await addIntakeNote(db, task, "analyst", m("Не смог уточнить постановку ({why}). Описание задачи не менял — комментарий увидит агент, когда возьмётся за задачу.", { why })); log(`${ref.key}: story refine failed: ${why}`); return; } note.questions = []; await updateTask(db, now, { description: intakeDescription(originalRequest(now.task, state), note) }); await addIntakeNote(db, task, "analyst", refineMessage(note)); log(`${ref.key}: story refined after a comment`); }