// PEP-84: «продакт» and «аналитик» — two short LLM roles a new story passes before any developer // agent touches it. The product manager asks why and cuts the scope; the analyst writes what // exactly must come out (acceptance criteria, out of scope, assumptions) and asks at most three // questions, each with the default it will take if nobody answers. They do not flatter, see the // project's context, and never wait for permission: no answer in time — they go by the defaults. // State lives in `settings` (`intake.task:`, `project.intake:`): no schema change. import { m as tr } from "@peppa/shared/i18n"; import { existsSync, readFileSync } from "node:fs"; import { join } from "node:path"; import { events, goals, tasks, type Db } from "@peppa/db"; import { formatTaskKey } from "@peppa/shared"; import { and, asc, desc, eq, inArray, isNull } from "drizzle-orm"; import { actorColumns } from "./actor.ts"; import { readMemory } from "./memory.ts"; import { notify } from "./notify.ts"; import type { Project } from "./projects.ts"; import { getSetting, setSetting } from "./settings.ts"; import type { Task } from "./tasks.ts"; export type IntakeRole = "product" | "analyst"; export const INTAKE_ROLE_RU: Record = { product: tr("Продакт"), analyst: tr("Аналитик") }; export const INTAKE_EVENT = "intake_note"; export const INTAKE_MAX_QUESTIONS = 3; export const INTAKE_MAX_SPLIT = 4; export interface IntakeSettings { enabled: boolean; /** Minutes the analyst waits for the PM's answers before going by its defaults. */ waitMin: number; /** Stories created before this moment are left alone (ISO). */ since: string | null; } export const DEFAULT_INTAKE: IntakeSettings = { enabled: false, waitMin: 30, since: null }; const projectKey = (projectId: number) => `project.intake:${projectId}`; export async function getIntakeSettings(db: Db, projectId: number): Promise { return { ...DEFAULT_INTAKE, ...((await getSetting>(db, projectKey(projectId))) ?? {}) }; } export async function setIntakeSettings(db: Db, projectId: number, patch: { enabled?: boolean; waitMin?: number }, now = new Date()): Promise { const cur = await getIntakeSettings(db, projectId); const next: IntakeSettings = { ...cur }; if (patch.waitMin !== undefined) next.waitMin = Math.min(24 * 60, Math.max(0, Math.round(patch.waitMin) || 0)); if (patch.enabled !== undefined && patch.enabled !== cur.enabled) { next.enabled = patch.enabled; // Turning it on does not drag the old backlog through the roles. if (patch.enabled) next.since = now.toISOString(); } await setSetting(db, projectKey(projectId), next); return next; } export interface IntakeQuestion { q: string; /** What the analyst does if nobody answers. */ default: string; } export type IntakeStage = "product" | "analyst" | "waiting" | "finalize" | "done"; export interface IntakeState { stage: IntakeStage; /** The PM's words as they were written. */ original: { title: string; description: string }; product?: ProductNote; analyst?: AnalystNote; questionId?: number; /** When the analyst stops waiting (ms). */ deadline?: number; /** The PM's answer to the questions (stage "finalize"). */ answer?: string; attempts: number; /** Why the roles were skipped or gave up, if they did. */ note?: string; } const taskKey = (taskId: number) => `intake.task:${taskId}`; export async function getIntakeState(db: Db, taskId: number): Promise { return getSetting(db, taskKey(taskId)); } export async function setIntakeState(db: Db, taskId: number, state: IntakeState): Promise { await setSetting(db, taskKey(taskId), state); await notify(db, { type: "task_updated", taskId }); } /** Does this backlog story still belong to the roles (the dispatcher must not take it)? */ export function intakePending(settings: IntakeSettings, task: Pick, state: IntakeState | null): boolean { if (!settings.enabled || task.status !== "backlog") return false; if (state) return state.stage !== "done"; return !!settings.since && task.createdAt.getTime() >= Date.parse(settings.since); } /** Backlog stories of the project the roles have not finished with: taskId → stage ("new" = not started). */ export async function intakePendingTasks(db: Db, projectId: number): Promise> { const out = new Map(); const settings = await getIntakeSettings(db, projectId); if (!settings.enabled) return out; const backlog = await db.select().from(tasks).where(and(eq(tasks.projectId, projectId), eq(tasks.status, "backlog"), isNull(tasks.archivedAt))); for (const t of backlog) { const state = await getIntakeState(db, t.id); if (intakePending(settings, t, state)) out.set(t.id, state?.stage ?? "new"); } return out; } // ── what the roles see ─────────────────────────────────────────────────────────── const clip = (s: string, n: number) => (s.length > n ? `${s.slice(0, n)}\n…(обрезано)` : s); /** The project as the roles know it: standards, memory, epics, what was done and what is planned. */ export async function intakeContext(db: Db, project: Project, task: Pick): Promise { const agentsMd = existsSync(join(project.workspacePath, "AGENTS.md")) ? readFileSync(join(project.workspacePath, "AGENTS.md"), "utf8").trim() : ""; const memory = readMemory(project.workspacePath).trim(); const epics = await db.select().from(goals).where(and(eq(goals.projectId, project.id), eq(goals.status, "open"))).orderBy(asc(goals.id)); const stories = (await db.select().from(tasks).where(and(eq(tasks.projectId, project.id), isNull(tasks.archivedAt))).orderBy(desc(tasks.id)).limit(60)).filter((t) => t.id !== task.id); const epic = epics.find((e) => e.id === task.goalId); const line = (t: (typeof stories)[number]) => `- ${formatTaskKey(project.key, t.number)} [${t.status}] ${t.title}`; return [ `Проект: ${project.key} — ${project.name}`, "", "## Стандарты проекта (AGENTS.md)", agentsMd ? clip(agentsMd, 6000) : "(нет)", "", "## Память проекта", memory ? clip(memory, 4000) : "(пусто)", "", "## Эпики", epics.length ? epics.map((e) => `- #${e.id} ${e.title}${e.description ? ` — ${clip(e.description.replace(/\s+/g, " "), 300)}` : ""}`).join("\n") : "(нет)", ...(epic ? ["", `Эта стори относится к эпику «${epic.title}».`] : []), "", "## Другие стори проекта (новые сверху)", stories.length ? stories.map(line).join("\n") : "(нет — это первая стори проекта)", ].join("\n"); } export const INTAKE_TONE = [ "Тон: коллега, а не помощник. Не хвали и не благодари, без «отличная идея» и восклицаний. Слабое место называй прямо и коротко.", "Пиши для продакт-менеджера, который не программист: простые слова, без жаргона (PR, CI, API — только если без них нельзя).", "Ты не спрашиваешь разрешений и не предлагаешь «могу сделать» — ты решаешь и пишешь, что решено.", ].join("\n"); export interface ProductNote { /** What the PM actually wants, in one or two sentences. */ goal: string; /** Plain words to the PM: what is cut, what is risky, what is unclear. */ comment: string; /** A better title for this story (the smallest useful version), or the same one. */ title: string; /** Other stories this request breaks into (besides this one). */ split: Array<{ title: string; description: string }>; } export function productPrompt(context: string, story: { title: string; description: string }): string { return [ "Ты — продакт-менеджер софтвер-фабрики. К тебе пришло сырое пожелание. Реши, что из него делать.", "1. Пойми цель: для кого это и какую проблему решает. Если пожелание не решает проблему — скажи.", "2. Урежь до самой маленькой версии, которая уже полезна. Назови, что отложено.", `3. Если это несколько задач — раздели: одна стори — один результат, который можно показать. Не больше ${INTAKE_MAX_SPLIT} дополнительных стори; мелкое не дроби.`, "4. Проверь по списку стори проекта: не сделано ли уже, не противоречит ли, не нужно ли сначала другое.", INTAKE_TONE, "", context, "", "## Пожелание", `Название: ${story.title}`, "Текст:", story.description.trim() || "(только название)", "", 'Ответь ОДНОЙ строкой JSON без пояснений: {"goal":"…","comment":"…","title":"…","split":[{"title":"…","description":"…"}]}', "goal — цель одной-двумя фразами. comment — 2–5 коротких фраз продакту: что берём, что режем, что настораживает. title — название этой стори после урезания (до 80 символов). split — остальные стори (пустой список, если делить не надо).", ].join("\n"); } export interface AnalystNote { /** The story as the developer agent gets it. */ description: string; criteria: string[]; outOfScope: string[]; assumptions: string[]; questions: IntakeQuestion[]; /** Plain words to the PM: what is contradictory or missing. */ comment: string; } export function analystPrompt(context: string, story: { title: string; description: string }, product: ProductNote | undefined, answers?: { questions: IntakeQuestion[]; answer: string }): string { return [ "Ты — системный аналитик софтвер-фабрики. Преврати задачу в постановку, по которой ИИ-разработчик сделает ровно то, что нужно, а продакт сможет проверить результат.", "1. Описание: что должно получиться и для кого — 3–8 фраз, без способа реализации.", "2. Критерии приёмки: проверяемые снаружи утверждения («на странице каталога у товара видны фото, цена и кнопка „Купить“»), 3–8 штук.", "3. Вне задачи: что сюда не входит, чтобы разработчик не сделал лишнего.", "4. Сверь со стандартами, памятью и другими стори проекта: противоречия и пропущенные случаи назови в comment.", "5. Вопросов продакту не задавай и ответа не жди: где есть развилка, выбери разумный вариант сам и запиши его в assumptions понятными продакту словами («Оплата — картой через ЮKassa; другой способ — напишите в комментарии»). Технические развилки (стек, библиотеки, база, архитектура) в assumptions не пиши — их решит разработчик. questions — всегда пустой список.", ...(answers ? ["6. Продакт ответил на твои вопросы — учти ответ, новых вопросов не задавай (questions — пустой список)."] : []), INTAKE_TONE, "", context, "", "## Задача", `Название: ${story.title}`, "Текст продакта:", story.description.trim() || "(только название)", ...(product ? ["", "Решение продакт-менеджера фабрики:", `Цель: ${product.goal}`, product.comment] : []), ...(answers ? ["", "Твои вопросы:", ...answers.questions.map((q, i) => `${i + 1}. ${q.q} (по умолчанию: ${q.default})`), "Ответ продакта:", answers.answer.trim()] : []), "", 'Ответь ОДНОЙ строкой JSON без пояснений: {"description":"…","criteria":["…"],"out_of_scope":["…"],"assumptions":["…"],"questions":[{"q":"…","default":"…"}],"comment":"…"}', ].join("\n"); } /** The first balanced JSON object of the text that has `field`. */ function findJson(text: string, field: string): Record | null { for (let i = text.indexOf("{"); i >= 0; i = text.indexOf("{", i + 1)) { let depth = 0; let inStr = false; for (let j = i; j < text.length; j++) { const c = text[j]; if (inStr) { if (c === "\\") j++; else if (c === '"') inStr = false; continue; } if (c === '"') inStr = true; else if (c === "{") depth++; else if (c === "}" && --depth === 0) { try { const o = JSON.parse(text.slice(i, j + 1)) as Record; if (o && typeof o === "object" && field in o) return o; } catch {} break; } } } return null; } const str = (v: unknown, max: number) => String(v ?? "").trim().slice(0, max); const list = (v: unknown, max: number, each = 500) => (Array.isArray(v) ? v.map((x) => str(x, each)).filter(Boolean).slice(0, max) : []); export function parseProductNote(text: string, fallbackTitle: string): ProductNote | null { const o = findJson(text, "goal"); if (!o) return null; const split = (Array.isArray(o.split) ? o.split : []) .map((s) => ({ title: str((s as { title?: unknown })?.title, 200), description: str((s as { description?: unknown })?.description, 4000) })) .filter((s) => s.title.length >= 3) .slice(0, INTAKE_MAX_SPLIT); const title = str(o.title, 200); return { goal: str(o.goal, 1000), comment: str(o.comment, 3000), title: title.length >= 3 ? title : fallbackTitle, split }; } export function parseAnalystNote(text: string): AnalystNote | null { const o = findJson(text, "criteria"); if (!o) return null; const criteria = list(o.criteria, 12); const description = str(o.description, 6000); if (!description || !criteria.length) return null; const questions = (Array.isArray(o.questions) ? o.questions : []) .map((q) => ({ q: str((q as { q?: unknown })?.q, 500), default: str((q as { default?: unknown })?.default, 500) })) .filter((q) => q.q && q.default) .slice(0, INTAKE_MAX_QUESTIONS); return { description, criteria, outOfScope: list(o.out_of_scope ?? o.outOfScope, 10), assumptions: list(o.assumptions, 10), questions, comment: str(o.comment, 3000) }; } /** The story text the developer agent works from. */ export function intakeDescription(original: { title: string; description: string }, a: AnalystNote, decided: string[] = []): string { const bullets = (items: string[]) => items.map((x) => `- ${x}`).join("\n"); return [ a.description, "", "## Критерии приёмки", bullets(a.criteria), ...(a.outOfScope.length ? ["", "## Вне задачи", bullets(a.outOfScope)] : []), ...(a.assumptions.length || decided.length ? ["", "## Допущения", bullets([...a.assumptions, ...decided])] : []), "", "## Исходный запрос", original.title + (original.description.trim() ? `\n\n${original.description.trim()}` : ""), ].join("\n"); } /** What the PM reads from the roles. */ export function productMessage(p: ProductNote, splitKeys: string[]): string { return [tr("Цель: {goal}", { goal: p.goal }), p.comment, ...(splitKeys.length ? [tr("Разделил на задачи: эта и {list}.", { list: splitKeys.join(", ") })] : [])].filter(Boolean).join("\n\n"); } export function analystMessage(a: AnalystNote): string { const bullets = (items: string[]) => items.map((x) => `• ${x}`).join("\n"); return [ a.comment, `${tr("Критерии приёмки:")}\n${bullets(a.criteria)}`, ...(a.assumptions.length ? [`${tr("Решил сам:")}\n${bullets(a.assumptions)}`] : []), tr("Задача готова к работе. Если что-то из решённого нужно иначе — напишите в комментариях к задаче, агент учтёт."), ] .filter(Boolean) .join("\n\n"); } export function questionsText(key: string, qs: IntakeQuestion[], waitMin: number): string { return [ tr("Аналитик уточняет {key}. Ответьте одним сообщением — или не отвечайте: через {n} мин возьму варианты по умолчанию.", { key, n: waitMin }), ...qs.map((q, i) => `${i + 1}. ${q.q}\n ${tr("По умолчанию: {default}", { default: q.default })}`), ].join("\n\n"); } /** A role's note on the story: an event shown among the story's comments and in the project chat. */ export async function addIntakeNote(db: Db, task: Pick, role: IntakeRole, text: string): Promise { await db.insert(events).values({ projectId: task.projectId, taskId: task.id, type: INTAKE_EVENT, payload: { role, text }, ...actorColumns() }); await notify(db, { type: "task_updated", taskId: task.id }); } /** Ids of the tasks among `ids` that have intake notes (for tests and badges). */ export async function tasksWithIntakeNotes(db: Db, ids: number[]): Promise> { if (!ids.length) return new Set(); const rows = await db.select({ taskId: events.taskId }).from(events).where(and(inArray(events.taskId, ids), eq(events.type, INTAKE_EVENT))); return new Set(rows.map((r) => r.taskId!)); }