From 024ee1898293d7815b8a6117618b7c8398dda0e6 Mon Sep 17 00:00:00 2001 From: peppa-bot Date: Tue, 17 Nov 2026 21:17:44 +0500 Subject: [PATCH] =?UTF-8?q?PEP-198:=20=D0=BE=D0=B4=D0=B8=D0=BD=20=D0=90?= =?UTF-8?q?=D0=BD=D0=B0=D0=BB=D0=B8=D1=82=D0=B8=D0=BA=20=D0=BD=D0=B0=20?= =?UTF-8?q?=D0=B2=D1=85=D0=BE=D0=B4=D0=B5=20=D0=B7=D0=B0=D0=B4=D0=B0=D1=87?= =?UTF-8?q?=D0=B8,=20=D1=80=D0=B5=D1=88=D0=B5=D0=BD=D0=B8=D1=8F=20=D0=B8?= =?UTF-8?q?=20=D1=80=D0=B0=D0=B7=D0=B1=D0=B8=D0=B2=D0=BA=D0=B0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-Authored-By: Claude Opus 5.5 --- packages/core/src/attachments.ts | 2 +- packages/core/src/chats.ts | 4 +- packages/core/src/index.ts | 1 + packages/core/src/intake.ts | 181 +++++++++++++++--------- packages/core/src/product-review.ts | 7 +- packages/core/src/task-decisions.ts | 135 ++++++++++++++++++ packages/core/src/tasks.ts | 7 +- packages/runner/src/autonomy.ts | 5 +- packages/runner/src/decisions.ts | 81 +++++++++++ packages/runner/src/index.ts | 1 + packages/runner/src/intake.ts | 121 +++++++--------- packages/runner/src/product-review.ts | 8 +- packages/testkit/src/mock-intake.ts | 36 ++++- packages/testkit/test/intake.test.ts | 193 +++++++++++++++++++------- 14 files changed, 586 insertions(+), 196 deletions(-) create mode 100644 packages/core/src/task-decisions.ts create mode 100644 packages/runner/src/decisions.ts diff --git a/packages/core/src/attachments.ts b/packages/core/src/attachments.ts index 43adced2..af2b4524 100644 --- a/packages/core/src/attachments.ts +++ b/packages/core/src/attachments.ts @@ -356,5 +356,5 @@ export async function attachmentsForModel(db: Db, o: { messageIds?: number[]; ev lines.push(`- ${label} — документ Office (${a.file.split(".").pop()}); содержимое тебе пока недоступно, опирайся на название и слова продакта`); } } - return { files, prompt: lines.length ? ["Продакт приложил файлы:", ...lines].join("\n") : "" }; + return { files, prompt: lines.length ? ["Владелец продукта приложил файлы:", ...lines].join("\n") : "" }; } diff --git a/packages/core/src/chats.ts b/packages/core/src/chats.ts index 1680a948..02d147e4 100644 --- a/packages/core/src/chats.ts +++ b/packages/core/src/chats.ts @@ -422,8 +422,8 @@ const EVENT_TEXT: Record { text: string; important?: boolean; pm_comment: () => null, // handled separately: a person's message // PEP-4: the project's repo moved to another Gitea namespace. repo_transferred: (p) => ({ text: tr("📦 Код проекта переехал: {from} → {to}", { from: s(p.from), to: s(p.to) }) }), - // PEP-84: «продакт» and «аналитик» talk to the PM in the story's thread. - intake_note: (p) => ({ text: p.role === "product" ? tr("🧭 Продакт: {text}", { text: asIs(cut(s(p.text), 3000)) }) : tr("🔎 Аналитик: {text}", { text: asIs(cut(s(p.text), 3000)) }), important: true, author: "agent" }), + // PEP-84 / PEP-198: the analyst talks to the PM in the story's thread (the acceptance agent's remark — by its name). + intake_note: (p) => ({ text: p.role === "acceptance" ? tr("🧭 Агент приёмки: {text}", { text: asIs(cut(s(p.text), 3000)) }) : tr("🔎 Аналитик: {text}", { text: asIs(cut(s(p.text), 3000)) }), important: true, author: "agent" }), pr_merged_in_gitea: (p) => ({ text: p.by ? tr("🔀 Изменения задачи приняты в код проекта ({by})", { by: s(p.by) }) : tr("🔀 Изменения задачи приняты в код проекта") }), // PEP-174: the project's pause — one line each; what happened inside it is not sent later. project_paused: () => ({ text: tr("⏸ Проект поставлен на паузу: агенты остановлены, уведомлений нет"), important: true }), diff --git a/packages/core/src/index.ts b/packages/core/src/index.ts index 55996635..f794ee62 100644 --- a/packages/core/src/index.ts +++ b/packages/core/src/index.ts @@ -6,6 +6,7 @@ export * from "./project-trash.ts"; export * from "./tasks.ts"; export * from "./task-origin.ts"; export * from "./task-dedup.ts"; +export * from "./task-decisions.ts"; export * from "./questions.ts"; export * from "./agent-message.ts"; export * from "./message-details.ts"; diff --git a/packages/core/src/intake.ts b/packages/core/src/intake.ts index 043c3411..a9427a8a 100644 --- a/packages/core/src/intake.ts +++ b/packages/core/src/intake.ts @@ -1,9 +1,10 @@ -// 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. +// PEP-84 / PEP-198: «Аналитик» — one short LLM call a new story passes before any developer +// agent touches it: why and for whom, the smallest useful version, the split (at most four +// parts), what exactly must come out (acceptance criteria, out of scope) and the product +// decisions it took itself (core/task-decisions.ts shows them to the owner). It does not +// flatter, sees the project's context, asks nothing and never waits for permission. +// Until PEP-198 there were two roles («продакт» → «аналитик»); their old stages are finished by +// the same single step. State lives in `settings` (`intake.task:`, `project.intake:`). import { m as tr } from "@peppa/shared/i18n"; import { existsSync, readFileSync } from "node:fs"; import { join } from "node:path"; @@ -15,12 +16,14 @@ import { readMemory } from "./memory.ts"; import { notify } from "./notify.ts"; import type { Project } from "./projects.ts"; import { getSetting, setSetting } from "./settings.ts"; +import { getDecisions } from "./task-decisions.ts"; import type { Task } from "./tasks.ts"; -export type IntakeRole = "product" | "analyst"; -export const INTAKE_ROLE_RU: Record = { product: tr("Продакт"), analyst: tr("Аналитик") }; +/** `product` — the old intake role (before PEP-198), its work is the analyst's now; `acceptance` — the acceptance agent's remark (PEP-197). */ +export type IntakeRole = "product" | "analyst" | "acceptance"; +export const ACCEPTANCE_AGENT_NAME = "Агент приёмки"; +export const INTAKE_ROLE_RU: Record = { product: tr("Аналитик"), analyst: tr("Аналитик"), acceptance: tr("Агент приёмки") }; export const INTAKE_EVENT = "intake_note"; -export const INTAKE_MAX_QUESTIONS = 3; export const INTAKE_MAX_SPLIT = 4; export interface IntakeSettings { @@ -56,6 +59,7 @@ export interface IntakeQuestion { default: string; } +/** `analyst` — the one step (PEP-198); `product`, `waiting`, `finalize` — stages of the old two-role flow, finished by that step. */ export type IntakeStage = "product" | "analyst" | "waiting" | "finalize" | "done"; export interface IntakeState { @@ -112,9 +116,8 @@ export async function intakeContext(db: Db, project: Project, task: Pick t.id !== task.id); + const stories = (await db.select().from(tasks).where(and(eq(tasks.projectId, project.id), isNull(tasks.archivedAt))).orderBy(desc(tasks.id)).limit(80)).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}`, "", @@ -129,13 +132,36 @@ export async function intakeContext(db: Db, project: Project, task: Pick { + const RECENT_MS = 30 * 86_400_000; + const BUDGET = 12_000; + const flat = (s: string) => s.replace(/^## Исходный запрос[\s\S]*$/m, "").replace(/\s+/g, " ").trim(); + let used = 0; + const out: string[] = []; + for (const t of stories) { + const head = `- ${formatTaskKey(project.key, t.number)} [${t.status}] ${t.title}`; + const recent = t.status !== "done" || Date.now() - t.updatedAt.getTime() < RECENT_MS; + let line = head; + if (recent && used < BUDGET) { + const about = flat(t.description ?? ""); + if (about) line += ` — ${about.slice(0, t.status === "done" ? 200 : 400)}${about.length > (t.status === "done" ? 200 : 400) ? "…" : ""}`; + const owner = (await getDecisions(db, t.id)).filter((d) => d.status === "changed").map((d) => d.text); + if (owner.length) line += ` (решения владельца: ${owner.join("; ").slice(0, 300)})`; + } + used += line.length; + out.push(line); + } + return out.join("\n"); +} + export const INTAKE_TONE = [ "Тон: коллега, а не помощник. Не хвали и не благодари, без «отличная идея» и восклицаний. Слабое место называй прямо и коротко.", - "Пиши для продакт-менеджера, который не программист: простые слова, без жаргона (PR, CI, API — только если без них нельзя).", + "Пиши для владельца продукта, который не программист: простые слова, без жаргона (PR, CI, API — только если без них нельзя).", "Ты не спрашиваешь разрешений и не предлагаешь «могу сделать» — ты решаешь и пишешь, что решено.", ].join("\n"); @@ -150,27 +176,6 @@ export interface ProductNote { 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; @@ -182,27 +187,51 @@ export interface AnalystNote { comment: string; } -export function analystPrompt(context: string, story: { title: string; description: string }, product: ProductNote | undefined, answers?: { questions: IntakeQuestion[]; answer: string }): string { +/** PEP-198: the analyst's answer on intake — everything the two old roles gave, in one call. */ +export interface IntakeNote { + goal: string; + /** The title after the cut (the smallest useful version). */ + title: string; + /** What is postponed (not in this story nor in its parts). */ + deferred: string[]; + /** Other parts of the request (this story is the first one). */ + split: Array<{ title: string; description: string }>; + description: string; + criteria: string[]; + outOfScope: string[]; + /** Product decisions taken at forks, in the owner's words (no technical ones). */ + decisions: string[]; + /** Plain words to the owner: what is cut, what is risky, what is contradictory. */ + comment: string; +} + +export const INTAKE_PROMPT_HEAD = "Ты — аналитик софтвер-фабрики на входе задачи."; + +/** `legacy` — what the old two-role flow already had for a story caught on an old stage. */ +export function intakePrompt(context: string, story: { title: string; description: string }, legacy: { product?: ProductNote; analyst?: AnalystNote; answer?: string } = {}): string { return [ - "Ты — системный аналитик софтвер-фабрики. Преврати задачу в постановку, по которой ИИ-разработчик сделает ровно то, что нужно, а продакт сможет проверить результат.", - "1. Описание: что должно получиться и для кого — 3–8 фраз, без способа реализации.", - "2. Критерии приёмки: проверяемые снаружи утверждения («на странице каталога у товара видны фото, цена и кнопка „Купить“»), 3–8 штук.", - "3. Вне задачи: что сюда не входит, чтобы разработчик не сделал лишнего.", - "4. Сверь со стандартами, памятью и другими стори проекта: противоречия и пропущенные случаи назови в comment.", - "5. Вопросов продакту не задавай и ответа не жди: где есть развилка, выбери разумный вариант сам и запиши его в assumptions понятными продакту словами («Оплата — картой через ЮKassa; другой способ — напишите в комментарии»). Технические развилки (стек, библиотеки, база, архитектура) в assumptions не пиши — их решит разработчик. questions — всегда пустой список.", - ...(answers ? ["6. Продакт ответил на твои вопросы — учти ответ, новых вопросов не задавай (questions — пустой список)."] : []), + `${INTAKE_PROMPT_HEAD} К тебе пришло пожелание владельца продукта. За один раз реши, что из него делать, и напиши постановку, по которой ИИ-разработчик сделает ровно то, что нужно, а владелец сможет проверить результат.`, + "1. Цель: для кого это и какую проблему решает — одна-две фразы. Если пожелание проблему не решает — скажи в comment.", + "2. Урежь до самой маленькой версии, которая уже полезна; что отложено — в deferred.", + `3. Если это несколько задач — раздели: одна задача — один результат, который можно показать. Всего не больше ${INTAKE_MAX_SPLIT} частей, первая — эта задача (её постановку пишешь ниже); в split — остальные (без первой), мелкое не дроби. Проверь по списку задач проекта: не сделано ли уже — повтор существующей задачи в split не клади.`, + "4. Описание для разработчика: что должно получиться и для кого — 3–8 фраз, без способа реализации.", + "5. Критерии приёмки: проверяемые снаружи утверждения («на странице каталога у товара видны фото, цена и кнопка „Купить“»), 3–8 штук. Вне задачи: что сюда не входит.", + "6. Вопросов владельцу не задавай и ответа не жди: где есть развилка о продукте, выбери разумный вариант сам и запиши его в decisions понятными владельцу словами («Оплата — картой через ЮKassa»). Технические развилки (стек, библиотеки, база, архитектура, какой внешний сервис подключить) в decisions не пиши — их решит разработчик.", + "7. comment — 2–4 короткие фразы владельцу: что берём, что режем, что настораживает или противоречит стандартам, памяти и другим задачам проекта.", 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()] : []), + ...(legacy.product ? ["", "Прежний разбор этой задачи (учти, не повторяй разбивку):", `Цель: ${legacy.product.goal}`, legacy.product.comment] : []), + ...(legacy.analyst ? ["", "Прежняя постановка (возьми за основу):", legacy.analyst.description, ...legacy.analyst.criteria.map((c) => `- ${c}`)] : []), + ...(legacy.answer ? ["", "Владелец ответил на прежние вопросы:", legacy.answer.trim()] : []), "", - 'Ответь ОДНОЙ строкой JSON без пояснений: {"description":"…","criteria":["…"],"out_of_scope":["…"],"assumptions":["…"],"questions":[{"q":"…","default":"…"}],"comment":"…"}', + 'Ответь ОДНОЙ строкой JSON без пояснений: {"goal":"…","title":"…","deferred":["…"],"split":[{"title":"…","description":"…"}],"description":"…","criteria":["…"],"out_of_scope":["…"],"decisions":["…"],"comment":"…"}', + "title — название этой задачи после урезания (до 80 символов). description частей split — что должно получиться и критерии приёмки списком.", ].join("\n"); } @@ -235,6 +264,35 @@ function findJson(text: string, field: string): Record | 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 parseIntakeNote(text: string, fallbackTitle: string): IntakeNote | 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 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 - 1); + const title = str(o.title, 200); + // A question the model still asked becomes its decision (PEP-94: nobody is asked). + const asked = (Array.isArray(o.questions) ? o.questions : []).map((q) => `${str((q as { q?: unknown })?.q, 500)} — ${str((q as { default?: unknown })?.default, 500)}`).filter((x) => !x.startsWith(" — ") && !x.endsWith(" — ")); + return { + goal: str(o.goal, 1000), + title: title.length >= 3 ? title : fallbackTitle, + deferred: list(o.deferred, 10), + split, + description, + criteria, + outOfScope: list(o.out_of_scope ?? o.outOfScope, 10), + decisions: [...list(o.decisions ?? o.assumptions, 10), ...asked].slice(0, 12), + comment: str(o.comment, 3000), + }; +} + +/** The old analyst's note (PEP-84; still the shape kept in the state and used by the refine of PEP-115). */ +export const intakeAnalystNote = (n: IntakeNote): AnalystNote => ({ description: n.description, criteria: n.criteria, outOfScope: n.outOfScope, assumptions: n.decisions, questions: [], comment: n.comment }); + export function parseProductNote(text: string, fallbackTitle: string): ProductNote | null { const o = findJson(text, "goal"); if (!o) return null; @@ -255,7 +313,7 @@ export function parseAnalystNote(text: string): AnalystNote | 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); + .slice(0, 3); return { description, criteria, outOfScope: list(o.out_of_scope ?? o.outOfScope, 10), assumptions: list(o.assumptions, 10), questions, comment: str(o.comment, 3000) }; } @@ -275,27 +333,24 @@ export function intakeDescription(original: { title: string; description: string ].join("\n"); } -/** What the PM reads from the roles. */ -export function productMessage(p: ProductNote, splitKeys: string[]): string { - return [tr("Цель: {text}", { text: p.goal }), p.comment, ...(splitKeys.length ? [tr("Разделил на задачи: эта и {list}.", { list: splitKeys.join(", ") })] : [])].filter(Boolean).join("\n\n"); -} -export function analystMessage(a: AnalystNote): string { +/** + * PEP-198: what the owner reads from the analyst after intake. The first line says the story is + * ready and how many decisions were taken for the owner (5.5 of the story). + */ +export function intakeMessage(key: string, n: IntakeNote, o: { parts: string[]; repeats: string[]; decisions: number }): 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("Задача готова к работе. Если что-то из решённого нужно иначе — напишите в комментариях к задаче, агент учтёт."), + o.decisions ? tr("Задача {key} готова к работе. Фабрика решила за вас {n} пунктов — проверьте.", { key, n: o.decisions }) : tr("Задача {key} готова к работе.", { key }), + n.goal ? tr("Цель: {text}", { text: n.goal }) : "", + n.comment, + ...(o.parts.length ? [tr("Разделила на {n} задач: {list}. Остальные части ждут, пока примете эту.", { n: o.parts.length + 1, list: [key, ...o.parts].join(", ") })] : []), + ...(o.repeats.length ? [`${tr("Не завела повторно — такие задачи уже есть:")}\n${bullets(o.repeats)}`] : []), + ...(n.deferred.length ? [`${tr("Отложено:")}\n${bullets(n.deferred)}`] : []), + `${tr("Критерии приёмки:")}\n${bullets(n.criteria)}`, ] .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 { diff --git a/packages/core/src/product-review.ts b/packages/core/src/product-review.ts index c5da0cf9..bc4900e5 100644 --- a/packages/core/src/product-review.ts +++ b/packages/core/src/product-review.ts @@ -11,7 +11,8 @@ import type { Db } from "@peppa/db"; import { m as tr } from "@peppa/shared/i18n"; /** The product agent's name on its messages (an AI agent, shown with the robot badge). */ -export const PRODUCT_AGENT_NAME = "Продакт"; +/** PEP-198: the acceptance agent does not talk to people itself — its findings come from the analyst. */ +export const PRODUCT_AGENT_NAME = "Аналитик"; export const PRODUCT_REVIEW_MAX_STORIES = 5; export const PRODUCT_REVIEW_MAX_PAGES = 4; export const PRODUCT_PAGE_MAX_CHARS = 6000; @@ -127,7 +128,7 @@ const clip = (s: string, n: number) => (s.length > n ? `${s.slice(0, n)}\n…(о export function productReviewPrompt(i: ProductReviewInput): string { return [ - "Ты — продакт-менеджер софтвер-фабрики на приёмке. Агенты сделали и выкатили продукт. Владелец продукта — не программист. Посмотри на продукт глазами его пользователя и скажи владельцу, что получилось и что с этим делать. Ты ИИ-агент и не выдаёшь себя за человека.", + "Ты — агент приёмки софтвер-фабрики. Агенты сделали и выкатили продукт. Владелец продукта — не программист. Посмотри на продукт глазами его пользователя и скажи владельцу, что получилось и что с этим делать. Ты ИИ-агент и не выдаёшь себя за человека.", "1. summary — что получилось, 2–4 фразы: что продукт уже умеет для пользователя. Сверь со стори ниже: чего из обещанного на экране нет — скажи прямо.", "2. howto — как этим пользоваться в жизни, по шагам (3–7 шагов): открыть адрес, что нажать, что получится. Только то, что реально есть на экране.", "3. not_real — что пока не настоящее: демо-режим, вымышленные примеры, заглушки, «скоро», данные-образцы. Каждое — одной фразой простыми словами. Пусто, если всё настоящее.", @@ -200,7 +201,7 @@ export function productReviewMessage(r: ProductReviewReply, o: { env: "prod" | " const steps = (items: string[]) => items.map((x, i) => `${i + 1}. ${x}`).join("\n"); const bullets = (items: string[]) => items.map((x) => `• ${x}`).join("\n"); return [ - o.env === "prod" ? tr("Посмотрел рабочую версию: {url}", { url: o.url }) : tr("Посмотрел версию для проверки: {url}", { url: o.url }), + o.env === "prod" ? tr("Агент приёмки посмотрел рабочую версию: {url}", { url: o.url }) : tr("Агент приёмки посмотрел версию для проверки: {url}", { url: o.url }), r.summary, ...(r.howto.length ? [`${tr("Как пользоваться:")}\n${steps(r.howto)}`] : []), ...(r.notReal.length ? [`${tr("Пока не настоящее:")}\n${bullets(r.notReal)}`] : []), diff --git a/packages/core/src/task-decisions.ts b/packages/core/src/task-decisions.ts new file mode 100644 index 00000000..8b048c66 --- /dev/null +++ b/packages/core/src/task-decisions.ts @@ -0,0 +1,135 @@ +// PEP-198: «Фабрика решила за вас». The analyst takes the product decisions of a story itself +// (PEP-94: it asks nobody) — they are not hidden in the description any more but listed on the +// story page with «Подходит» / «Нужно иначе». Each decision has a status: by default (nobody +// looked), confirmed, changed (with what it was and who changed it). The split of a request into +// parts is a decision as well («Разделила на N задач»). The «Допущения» section of the story's +// description is built from the list. State lives in `settings` (`task.decisions:`, +// `task.split-of:`): no schema change. What a change sets in motion is runner/decisions.ts. +import { m as tr } from "@peppa/shared/i18n"; +import { settings, tasks, type Db } from "@peppa/db"; +import { and, eq, inArray, like } from "drizzle-orm"; +import { logEvent } from "./audit.ts"; +import { PeppaError } from "./errors.ts"; +import { notify } from "./notify.ts"; +import { deleteSetting, getSetting, setSetting } from "./settings.ts"; + +export type DecisionStatus = "default" | "confirmed" | "changed"; + +export interface Decision { + id: number; + text: string; + status: DecisionStatus; + /** `split` — the request was split into parts (`parts`: their task ids). */ + kind: "plain" | "split"; + /** Login of who confirmed or changed it. */ + by: string | null; + at: string | null; + /** The text before the change. */ + was: string | null; + parts?: number[]; + /** `split`: what the analyst postponed (goes back to the description on «Не делить»). */ + deferred?: string[]; +} + +export const DECISION_STATUS_LABEL: Record = { + default: tr("по умолчанию"), + confirmed: tr("подтверждено"), + changed: tr("изменено"), +}; + +const key = (taskId: number) => `task.decisions:${taskId}`; +const splitOfKey = (partId: number) => `task.split-of:${partId}`; +const SPLIT_OF_PREFIX = "task.split-of:"; + +export async function getDecisions(db: Db, taskId: number): Promise { + return (await getSetting(db, key(taskId))) ?? []; +} + +async function save(db: Db, taskId: number, list: Decision[]): Promise { + await setSetting(db, key(taskId), list); + await notify(db, { type: "task_updated", taskId }); +} + +/** The analyst's decisions after intake (replaces what it decided before; the owner's answers stay). */ +export async function setDecisions(db: Db, taskId: number, texts: string[], split?: { text: string; parts: number[]; deferred: string[] }): Promise { + const kept = (await getDecisions(db, taskId)).filter((d) => d.status !== "default"); + let id = kept.reduce((n, d) => Math.max(n, d.id), 0); + const fresh: Decision[] = texts + .map((t) => t.trim()) + .filter((t) => t && !kept.some((d) => d.text === t)) + .map((text) => ({ id: ++id, text, status: "default", kind: "plain", by: null, at: null, was: null })); + if (split && split.parts.length) fresh.push({ id: ++id, text: split.text, status: "default", kind: "split", by: null, at: null, was: null, parts: split.parts, deferred: split.deferred }); + const list = [...kept, ...fresh]; + await save(db, taskId, list); + return list; +} + +/** Decisions nobody has looked at yet («Фабрика решила за вас N пунктов — проверьте»). */ +export const openDecisions = (list: Decision[]) => list.filter((d) => d.status === "default").length; + +function find(list: Decision[], id: number): Decision { + const d = list.find((x) => x.id === id); + if (!d) throw new PeppaError(tr("Этого решения уже нет. Обновите страницу.")); + return d; +} + +/** «Подходит»: only the status changes, nothing is set in motion. */ +export async function confirmDecision(db: Db, task: { id: number; projectId: number }, id: number, by: string): Promise { + const list = await getDecisions(db, task.id); + const d = find(list, id); + if (d.status === "default") Object.assign(d, { status: "confirmed", by, at: new Date().toISOString() }); + await save(db, task.id, list); + await logEvent(db, { projectId: task.projectId, taskId: task.id, type: "decision_confirmed", payload: { id, text: d.text, login: by } }); + return d; +} + +/** «Нужно иначе»: the decision becomes the owner's words; returns the decision with `was`. */ +export async function changeDecision(db: Db, task: { id: number; projectId: number }, id: number, how: string, by: string): Promise { + const text = how.trim(); + if (!text) throw new PeppaError(tr("Напишите, как нужно.")); + const list = await getDecisions(db, task.id); + const d = find(list, id); + Object.assign(d, { was: d.status === "changed" ? d.was : d.text, text, status: "changed", by, at: new Date().toISOString() }); + await save(db, task.id, list); + await logEvent(db, { projectId: task.projectId, taskId: task.id, type: "decision_changed", payload: { id, was: d.was, text, login: by } }); + return d; +} + +/** Lines of the «Допущения» section for the developer. */ +export function decisionsAssumptions(list: Decision[]): string[] { + return list.filter((d) => d.kind === "plain").map((d) => (d.status === "changed" ? `${d.text} (решение владельца; было: ${d.was ?? "—"})` : d.text)); +} + +/** The description with its «Допущения» section rebuilt from the decisions. */ +export function withAssumptions(description: string, list: Decision[]): string { + const lines = decisionsAssumptions(list); + const section = lines.length ? `## Допущения\n${lines.map((l) => `- ${l}`).join("\n")}\n` : ""; + if (/^## Допущения\n/m.test(description)) return description.replace(/^## Допущения\n(?:- .*\n?)*\n?/m, section ? `${section}\n` : ""); + if (!section) return description; + // Before «Исходный запрос» when there is one, else at the end. + return /^## Исходный запрос$/m.test(description) ? description.replace(/^## Исходный запрос$/m, `${section}\n## Исходный запрос`) : `${description.trimEnd()}\n\n${section}`; +} + +// ── parts of a split ─────────────────────────────────────────────────────────── + +export async function markSplitPart(db: Db, partId: number, parentId: number): Promise { + await setSetting(db, splitOfKey(partId), parentId); +} +export const splitParent = (db: Db, partId: number) => getSetting(db, splitOfKey(partId)); +export const clearSplitPart = (db: Db, partId: number) => deleteSetting(db, splitOfKey(partId)); + +/** Parts of a split whose first story is not accepted yet: the dispatcher does not take them (4.1). */ +export async function splitWaiting(db: Db, projectId: number): Promise> { + const rows = await db.select().from(settings).where(like(settings.key, `${SPLIT_OF_PREFIX}%`)); + if (!rows.length) return new Set(); + const pairs = rows.map((r) => ({ part: Number(r.key.slice(SPLIT_OF_PREFIX.length)), parent: Number(r.value) })).filter((p) => p.part && p.parent); + const ids = [...new Set(pairs.flatMap((p) => [p.part, p.parent]))]; + const found = await db.select({ id: tasks.id, status: tasks.status, archivedAt: tasks.archivedAt, projectId: tasks.projectId }).from(tasks).where(and(inArray(tasks.id, ids), eq(tasks.projectId, projectId))); + const byId = new Map(found.map((t) => [t.id, t])); + const out = new Set(); + for (const p of pairs) { + const parent = byId.get(p.parent); + if (byId.has(p.part) && parent && parent.status !== "done" && !parent.archivedAt) out.add(p.part); + } + return out; +} diff --git a/packages/core/src/tasks.ts b/packages/core/src/tasks.ts index 66911fc0..c63406ab 100644 --- a/packages/core/src/tasks.ts +++ b/packages/core/src/tasks.ts @@ -274,7 +274,7 @@ export interface StoryComment { text: string; createdAt: Date; /** PEP-84: a note of «продакт» / «аналитик» rather than a person's comment. */ - role?: "product" | "analyst"; + role?: "product" | "analyst" | "acceptance"; } /** A PM comment on a story (PEP-32): an event the agent sees in get_task. */ @@ -297,8 +297,9 @@ export async function addStoryComment(db: Db, ref: TaskRef, author: { id: number export async function storyComments(db: Db, taskId: number): Promise { const rows = await db.select().from(events).where(and(eq(events.taskId, taskId), inArray(events.type, [COMMENT_EVENT, "intake_note"]))).orderBy(asc(events.id)); return rows.map((e) => { - const p = (e.payload ?? {}) as { login?: string; text?: string; role?: "product" | "analyst" }; - if (e.type === "intake_note") return { id: e.id, login: p.role === "product" ? tr("Продакт") : tr("Аналитик"), text: p.text ?? "", createdAt: e.createdAt, role: p.role ?? "analyst" }; + const p = (e.payload ?? {}) as { login?: string; text?: string; role?: "product" | "analyst" | "acceptance" }; + // PEP-198: the old «product» role is the analyst's work now; the acceptance agent keeps its name. + if (e.type === "intake_note") return { id: e.id, login: p.role === "acceptance" ? tr("Агент приёмки") : tr("Аналитик"), text: p.text ?? "", createdAt: e.createdAt, role: p.role ?? "analyst" }; return { id: e.id, login: p.login ?? "?", text: p.text ?? "", createdAt: e.createdAt }; }); } diff --git a/packages/runner/src/autonomy.ts b/packages/runner/src/autonomy.ts index 4f9e2ac0..508fbe8b 100644 --- a/packages/runner/src/autonomy.ts +++ b/packages/runner/src/autonomy.ts @@ -51,6 +51,7 @@ import { getAgentLimits, isAgentOrigin, mayAutoAcceptTask, + splitWaiting, } from "@peppa/core"; import { goals, incidents, questions, tasks, type Db } from "@peppa/db"; import { formatTaskKey } from "@peppa/shared"; @@ -365,7 +366,9 @@ export async function readyBacklog(db: // PEP-115: nor does a story whose fresh comment the analyst is still working into the description. const commented = await pendingRefinements(db, { projectId }); // PEP-197: «Предложено» — stories of agents the owner has not decided on — are not taken. - const open = list.filter((t) => !blocked.has(t.id) && !refining.has(t.id) && !commented.has(t.id) && !t.proposed); + // PEP-198: a part of a split waits until its first story is accepted (a dependency opens on review already). + const parts = await splitWaiting(db, projectId); + const open = list.filter((t) => !blocked.has(t.id) && !refining.has(t.id) && !commented.has(t.id) && !t.proposed && !parts.has(t.id)); // PEP-183: a story that fits a busy specialist waits for him (up to the platform's threshold). const held = await specialistHold(db, open); const ready = open.filter((t) => !held.has(t.id)); diff --git a/packages/runner/src/decisions.ts b/packages/runner/src/decisions.ts new file mode 100644 index 00000000..9d2fa067 --- /dev/null +++ b/packages/runner/src/decisions.ts @@ -0,0 +1,81 @@ +// PEP-198: what the owner's answer to «Фабрика решила за вас» sets in motion (core/task-decisions.ts). +// «Подходит» only marks the decision. «Нужно иначе» — the story is not started yet: the analyst +// rebuilds it (the comment goes to the refine of PEP-115); in work: the agent gets «было — …, +// нужно — …»; in review: it is «Поправить». «Не делить» archives the parts of a split and puts +// them back into the first story's description. +import { m } from "@peppa/shared/i18n"; +import { + addStoryComment, + changeDecision, + clearSplitPart, + confirmDecision, + getDecisions, + listSessions, + PeppaError, + updateTask, + withAssumptions, + type Decision, + type TaskRef, +} from "@peppa/core"; +import { tasks, type Db } from "@peppa/db"; +import { inArray } from "drizzle-orm"; +import { archiveTask, fixStory } from "./flow.ts"; +import { resolveTaskById, sendToSession } from "./sessions.ts"; + +export type DecisionOutcome = "confirmed" | "refine" | "agent" | "fix" | "noted" | "unsplit"; + +export async function confirmTaskDecision(db: Db, ref: TaskRef, id: number, by: { login: string }): Promise { + await confirmDecision(db, ref.task, id, by.login); + return "confirmed"; +} + +/** «Нужно иначе» → «Как нужно?». */ +export async function changeTaskDecision(db: Db, ref: TaskRef, id: number, how: string, by: { id: number; login: string }): Promise { + const before = (await getDecisions(db, ref.task.id)).find((d) => d.id === id); + if (before?.kind === "split") throw new PeppaError(m("Разбивку можно принять или отменить кнопкой «Не делить».")); + const d = await changeDecision(db, ref.task, id, how, by.login); + const remark = m("Решение нужно иначе: было — {was}, нужно — {how}.", { was: d.was ?? "—", how: d.text }); + // The developer's «Допущения» follow the list at once. + if (ref.task.description) await updateTask(db, ref, { description: withAssumptions(ref.task.description, await getDecisions(db, ref.task.id)) }); + const fresh = (await resolveTaskById(db, ref.task.id).catch(() => null)) ?? ref; + const status = fresh.task.status; + if (status === "review") { + await fixStory(db, fresh, by, remark); + return "fix"; + } + await addStoryComment(db, fresh, by, remark); + if (status === "backlog") return "refine"; // the analyst rebuilds the story (PEP-115 refine) + if (status === "done") return "noted"; + const [live] = await listSessions(db, { active: true, taskId: fresh.task.id }); + // i18n-ignore — text for the agent + if (live) await sendToSession(db, live.id, `Владелец изменил решение по ${fresh.key}: было — ${d.was ?? "—"}, нужно — ${d.text}. Учти это в работе и в design.md.`, { person: true }).catch(() => {}); + return "agent"; +} + +/** «Не делить»: the parts go to the archive, their titles and what was postponed — back into this story. */ +export async function undoSplit(db: Db, ref: TaskRef, id: number, by: { id: number; login: string }): Promise { + const d: Decision | undefined = (await getDecisions(db, ref.task.id)).find((x) => x.id === id); + if (!d || d.kind !== "split") throw new PeppaError(m("Этого решения уже нет. Обновите страницу.")); + const parts = d.parts?.length ? await db.select().from(tasks).where(inArray(tasks.id, d.parts)) : []; + const back: string[] = []; + for (const t of parts) { + const part = await resolveTaskById(db, t.id).catch(() => null); + await clearSplitPart(db, t.id); + if (!part || t.archivedAt) continue; + // A part already taken to work stays: someone decided on it. + if (t.status !== "backlog") continue; + await archiveTask(db, part, true); + const about = (t.description ?? "").replace(/\n*_[^_]*_\s*$/, "").trim(); + back.push(`- ${t.title}${about ? `: ${about.split("\n")[0]}` : ""}`); + } + for (const x of d.deferred ?? []) back.push(`- ${x}`); + await changeDecision(db, ref.task, id, m("Не делить: всё в одной задаче"), by.login); + const fresh = (await resolveTaskById(db, ref.task.id).catch(() => null)) ?? ref; + if (back.length) { + const desc = (fresh.task.description ?? "").trimEnd(); + const section = `## Тоже входит в задачу\n${back.join("\n")}`; + const next = /^## Исходный запрос$/m.test(desc) ? desc.replace(/^## Исходный запрос$/m, `${section}\n\n## Исходный запрос`) : `${desc}\n\n${section}`; + await updateTask(db, fresh, { description: next }); + } + return "unsplit"; +} diff --git a/packages/runner/src/index.ts b/packages/runner/src/index.ts index 51a2b2a1..287c7337 100644 --- a/packages/runner/src/index.ts +++ b/packages/runner/src/index.ts @@ -33,6 +33,7 @@ export * from "./agents-md.ts"; export * from "./project-subscription.ts"; export * from "./subscription-request.ts"; export * from "./intake.ts"; +export * from "./decisions.ts"; export * from "./project-trash.ts"; export * from "./branch-protection.ts"; export * from "./story-refine.ts"; diff --git a/packages/runner/src/intake.ts b/packages/runner/src/intake.ts index 3f2600c0..9c603a19 100644 --- a/packages/runner/src/intake.ts +++ b/packages/runner/src/intake.ts @@ -1,29 +1,30 @@ -// 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. +// PEP-84 / PEP-198: «Аналитик» over new backlog stories (see core/intake.ts). The watchdog calls +// `intakeTick`; one model call takes a story from `analyst` to done: the cut, the split (parts in +// the backlog, waiting for the first one to be accepted, repeats of existing stories skipped), +// the formulation and the decisions shown to the owner. Old two-role stages (`product`, +// `finalize`) are finished by the same call; `waiting` goes by its defaults at the deadline. LLM +// calls run in the background of the tick, so a slow model never holds the watchdog. The +// dispatcher skips stories the analyst has not finished with (`readyBacklog`); a PM who drags the +// card to work overrides it. import { m } from "@peppa/shared/i18n"; import { + addDependency, addIntakeNote, - analystMessage, - analystPrompt, answerQuestion, - askPm, createTask, - getAutonomy, getIntakeSettings, getIntakeState, - inAutonomyQuietHours, + intakeAnalystNote, intakeContext, intakeDescription, + intakeMessage, intakePending, + intakePrompt, listTasks, - parseAnalystNote, - parseProductNote, - productMessage, - productPrompt, - questionsText, + markSplitPart, + openDecisions, + parseIntakeNote, + setDecisions, setIntakeState, updateTask, type IntakeState, @@ -37,6 +38,7 @@ import { projects } from "@peppa/db"; import { isNull } from "drizzle-orm"; import { claudePrint } from "./claude-print.ts"; import { onAnswer, resolveTaskById } from "./sessions.ts"; +import { checkDuplicate } from "./task-dedup.ts"; const MAX_ATTEMPTS = 2; const inFlight = new Set(); @@ -50,54 +52,41 @@ const ask = (db: Db, project: Project, prompt: string, who: string) => 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(); -} +/** Plain words for the owner: why the analyst could not read the story (no technical text). */ +const failureReason = (error: string) => (/нет подписки|подписк/i.test(error) ? m("у проекта не подключена подписка") : /формат/i.test(error) ? m("ответ разбора пришёл не по форме") : m("сервис разбора сейчас не отвечает")); -/** 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 { +/** The one step (PEP-198): a single model call; returns the new state. Throws on a model failure (the caller counts attempts). */ +async function step(db: Db, ref: TaskRef, state: IntakeState, log: (m: string) => void): 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), m("продакт")); - if (!out.ok) throw new Error(out.error); - const note = parseProductNote(out.text, state.original.title); - if (!note) throw new Error(m("продакт ответил не по формату")); - 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, origin: "analyst" }); - // 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); + const legacy = { product: state.product, analyst: state.stage === "finalize" ? state.analyst : undefined, answer: state.stage === "finalize" ? state.answer : undefined }; + const out = await ask(db, project, intakePrompt(context, { title: task.title, description: state.original.description }, legacy), m("аналитик")); + if (!out.ok) throw new Error(out.error); + const note = parseIntakeNote(out.text, task.title); + if (!note) throw new Error(m("аналитик ответил не по формату")); + // The parts of the request: each checked for a repeat first (3.5), then filed after this story. + const parts: TaskRef[] = []; + const repeats: string[] = []; + for (const s of note.split) { + const dup = await checkDuplicate(db, project, s, { log, origin: "analyst" }); + if (dup.kind !== "none" && dup.task.id !== task.id) { + repeats.push(`«${s.title}» — ${dup.key}`); + continue; } - 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 }; + const part = await createTask(db, { projectId: project.id, goalId: task.goalId ?? undefined, title: s.title, description: `${s.description}\n\n_${m("Из разбивки {key}.", { key: ref.key })}_`, origin: "analyst" }); + // Formulated by the analyst already: the part does not go through intake again. + await setIntakeState(db, part.task.id, { stage: "done", original: { title: s.title, description: s.description }, attempts: 0, note: `из разбивки ${ref.key}` }); + await addDependency(db, part, ref).catch(() => {}); + await markSplitPart(db, part.task.id, task.id); + parts.push(part); } - 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), m("аналитик")); - if (!out.ok) throw new Error(out.error); - const note = parseAnalystNote(out.text); - if (!note) throw new Error(m("аналитик ответил не по формату")); - // PEP-94: the analyst doesn't ask the PM and doesn't wait — a question the model still sent - // becomes its default, decided now; the PM can correct it in the story's comments. - const decided = answers ? [] : note.questions.map((q) => `${q.q} — ${q.default}`); - note.assumptions = [...note.assumptions, ...decided]; - note.questions = []; - await updateTask(db, ref, { description: intakeDescription(state.original, note) }); - await addIntakeNote(db, task, "analyst", answers ? m("Учёл ответ. {message}", { message: analystMessage(note) }) : analystMessage(note)); - return { ...state, stage: "done", analyst: note, attempts: 0 }; - } - return state; + if (note.title !== task.title) await updateTask(db, ref, { title: note.title }); + const analyst = intakeAnalystNote(note); + await updateTask(db, ref, { description: intakeDescription(state.original, analyst) }); + const splitText = parts.length ? m("Разделила на {n} задач: {list}", { n: parts.length + 1, list: [ref.key, ...parts.map((p) => p.key)].join(", ") }) : ""; + const decisions = await setDecisions(db, task.id, note.decisions, parts.length ? { text: splitText, parts: parts.map((p) => p.task.id), deferred: note.deferred } : undefined); + await addIntakeNote(db, task, "analyst", intakeMessage(ref.key, note, { parts: parts.map((p) => p.key), repeats, decisions: openDecisions(decisions) })); + return { ...state, stage: "done", product: { goal: note.goal, comment: note.comment, title: note.title, split: note.split }, analyst, attempts: 0 }; } /** Nobody answered in time: the analyst's defaults become decisions, the story is ready. */ @@ -116,7 +105,7 @@ async function advance(db: Db, taskId: number, now: Date, log: (m: string) => vo 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 }; + state ??= { stage: "analyst", 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); @@ -125,18 +114,16 @@ async function advance(db: Db, taskId: number, now: Date, log: (m: string) => vo 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}`); - } + state = await step(db, ref, state, log); + 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", m("Не смог разобрать задачу ({error}) — задача идёт в работу как написана.", { error: (e as Error).message })); + // One message to the owner with the reason in plain words (3.3); the error itself is for the log. + await addIntakeNote(db, ref.task, "analyst", m("Аналитик не смог разобрать задачу: {why}. Задача идёт в работу как написана.", { why: failureReason((e as Error).message) })); } else await setIntakeState(db, taskId, { ...state, attempts }); log(`${ref.key}: intake failed (${attempts}): ${(e as Error).message}`); } @@ -168,7 +155,7 @@ export async function intakeTick(db: Db, opts: IntakeTickOptions = {}): Promise< if (opts.wait) await Promise.all(jobs); } -/** The PM answered the analyst's questions: the analyst finishes the story with the answer. */ +/** The PM answered the old analyst's questions (before PEP-94): 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); diff --git a/packages/runner/src/product-review.ts b/packages/runner/src/product-review.ts index 28be7797..f2f30522 100644 --- a/packages/runner/src/product-review.ts +++ b/packages/runner/src/product-review.ts @@ -150,7 +150,7 @@ async function review(db: Db, project: Project, rel: Release, pending: PendingPr bin: process.env.PEPPA_INTAKE_BIN ?? "claude", model: process.env.PEPPA_PRODUCT_REVIEW_MODEL ?? process.env.PEPPA_INTAKE_MODEL ?? "sonnet", timeoutMs: Number(process.env.PEPPA_INTAKE_TIMEOUT_MS ?? 180_000), - who: "продакт", + who: "агент приёмки", files, prompt: productReviewPrompt({ projectName: project.name, @@ -216,7 +216,7 @@ export async function fileStories(db: Db, project: Project, stories: ProductRevi if (s.severity === "breakage") breakage = true; const dup = await checkDuplicate(db, project, s, { log: o.log }); if (dup.kind === "open") { - await addIntakeNote(db, dup.task, "product", dedupRemark(s.title, s.description)); + await addIntakeNote(db, dup.task, "acceptance", dedupRemark(s.title, s.description)); o.log?.(`product review ${project.key}: «${s.title}» — повтор ${dup.key}, замечание дописано`); continue; } @@ -227,12 +227,12 @@ export async function fileStories(db: Db, project: Project, stories: ProductRevi continue; } // glossary-user: описание задачи, которое читает владелец - let description = `${s.description}\n\n_Заведено продакт-агентом на приёмке${o.url ? `: ${o.envLabel}, ${o.url}` : ""}._`; + let description = `${s.description}\n\n_Заведено агентом приёмки${o.url ? `: ${o.envLabel}, ${o.url}` : ""}._`; if (dup.kind === "done") description += `\n\n_${dedupSimilarNote(dup.key, dup.doneAt.toISOString().slice(0, 10))}_`; const isBreakage = s.severity === "breakage"; const ref = await createTask(db, { projectId: project.id, title: s.title, description, origin: "acceptance", severity: s.severity, proposed: !isBreakage }); // Already formulated: «продакт» and «аналитик» of the intake skip it. - await setIntakeState(db, ref.task.id, { stage: "done", original: { title: s.title, description }, attempts: 0, note: "заведена продакт-агентом на приёмке" }); + await setIntakeState(db, ref.task.id, { stage: "done", original: { title: s.title, description }, attempts: 0, note: "заведена агентом приёмки" }); created.push({ id: ref.task.id, key: ref.key, title: s.title, severity: s.severity }); } return { created, breakage, kept }; diff --git a/packages/testkit/src/mock-intake.ts b/packages/testkit/src/mock-intake.ts index 21ef0098..8c7b6f8a 100644 --- a/packages/testkit/src/mock-intake.ts +++ b/packages/testkit/src/mock-intake.ts @@ -1,4 +1,9 @@ -// mock-intake (PEP-84): stands in for `claude -p --output-format json` as «продакт» and «аналитик». +// mock-intake (PEP-84): stands in for `claude -p --output-format json` as the AI roles of Peppa. +// PEP-198: role `intake` — the one analyst on intake ({goal, title, deferred[], split[], description, +// criteria[], out_of_scope[], decisions[], comment}; scenario key `intake`, merged over the default); +// role `relay` — the analyst deciding what of a developer's message reaches the owner +// ({verdict: product|technical|repeat, text, options[], default}; scenario key `relay`; without +// it: a question naming stack words is technical, one repeating an earlier question is a repeat). // Reads the prompt on stdin and answers with the CLI's JSON envelope. The role is read off the // prompt's first line. Behaviour comes from MOCK_INTAKE_SCENARIO (a JSON file): // { "product": {goal, comment, title, split[]}, "analyst": {description, criteria[], out_of_scope[], @@ -20,6 +25,10 @@ interface Scenario { chat?: object; /** PEP-115: the analyst reworking a backlog story after a comment (the analyst's JSON). */ refine?: object; + /** PEP-198: the analyst on intake (merged over the default answer). */ + intake?: Record; + /** PEP-198: the analyst relaying a developer's question. */ + relay?: object; /** Answer after this many ms (a race with the PM taking the story to work). */ slowMs?: number; product?: object; @@ -31,10 +40,10 @@ interface Scenario { const file = process.env.MOCK_INTAKE_SCENARIO; const sc: Scenario = file && existsSync(file) ? JSON.parse(readFileSync(file, "utf8")) : {}; const prompt = readFileSync(0, "utf8"); -const role = prompt.startsWith("Ты — проверка на повтор") ? "dedup" : prompt.startsWith("Ты — диспетчер сообщений") ? "intent" : prompt.startsWith("Ты — агент обратной связи") ? "feedback" : prompt.startsWith("Ты — продакт-менеджер софтвер-фабрики на приёмке") ? "accept" : prompt.startsWith("Ты — продакт-менеджер") ? "product" : prompt.startsWith("Ты — аналитик проекта в чате") ? "chat" : prompt.includes("## Новые комментарии продакта") ? "refine" : "analyst"; +const role = prompt.startsWith("Ты — аналитик софтвер-фабрики на входе задачи") ? "intake" : prompt.startsWith("Ты — аналитик софтвер-фабрики между агентами") ? "relay" : prompt.startsWith("Ты — проверка на повтор") ? "dedup" : prompt.startsWith("Ты — диспетчер сообщений") ? "intent" : prompt.startsWith("Ты — агент обратной связи") ? "feedback" : prompt.startsWith("Ты — агент приёмки софтвер-фабрики") ? "accept" : prompt.startsWith("Ты — продакт-менеджер") ? "product" : prompt.startsWith("Ты — аналитик проекта в чате") ? "chat" : prompt.includes("## Новые комментарии продакта") ? "refine" : "analyst"; const answered = /Ответ продакта:\n/.test(prompt); const title = /^Название: (.*)$/m.exec(prompt)?.[1] ?? ""; -if (file) appendFileSync(`${file}.log.jsonl`, JSON.stringify({ role, title, answered, answer: /Ответ продакта:\n([\s\S]*?)\n\n/.exec(prompt)?.[1] ?? null, hasContext: prompt.includes("## Стандарты проекта"), prompt, argv: process.argv.slice(2), files: role === "accept" || role === "dedup" || role === "feedback" || role === "chat" || role === "refine" ? readdirSync(process.cwd()) : undefined, token: process.env.CLAUDE_CODE_OAUTH_TOKEN ? "set" : null }) + "\n"); +if (file) appendFileSync(`${file}.log.jsonl`, JSON.stringify({ role, title, answered, answer: /Ответ продакта:\n([\s\S]*?)\n\n/.exec(prompt)?.[1] ?? null, hasContext: prompt.includes("## Стандарты проекта"), prompt, argv: process.argv.slice(2), files: role === "accept" || role === "dedup" || role === "intake" || role === "feedback" || role === "chat" || role === "refine" ? readdirSync(process.cwd()) : undefined, token: process.env.CLAUDE_CODE_OAUTH_TOKEN ? "set" : null }) + "\n"); if (!process.argv.includes("-p")) { console.error("mock-intake: expected -p (non-interactive print mode)"); process.exit(2); @@ -104,6 +113,25 @@ const words = (x: string) => new Set(x.toLowerCase().split(/[^\p{L}\p{N}]+/u).fi const newWords = words(/Название: (.*)/.exec(prompt)?.[1] ?? ""); const similar = [...prompt.matchAll(/^- (\S+) «(.*)» \[/gm)].find((c) => { const w = words(c[2]!); const common = [...newWords].filter((x) => w.has(x)).length; return newWords.size > 0 && common / Math.min(newWords.size, w.size || 1) >= 0.5; }); const dedup = sc.dedup ?? { duplicate_of: similar?.[1] ?? null, reason: similar ? "та же тема" : "" }; +// PEP-198, intake: the default keeps the story whole, decides one product fork. +const intake = { + goal: `Сделать: ${title}`, + title, + deferred: [], + split: [], + description: `Нужно: ${title}.`, + criteria: ["Результат виден пользователю", "Ошибки показаны понятным текстом"], + out_of_scope: ["Оформление сверх необходимого"], + decisions: ["Страница открывается с телефона"], + comment: "В запросе не сказано, кто пользователь.", + ...sc.intake, +}; +// PEP-198, relay: stack words — technical; the same words as an earlier question to the owner — a repeat. +const asked = /## Вопрос агента\n([\s\S]*?)\n\n/.exec(prompt)?.[1]?.trim() ?? ""; +const earlier = [...(/## Уже спрошено у владельца\n([\s\S]*?)\n\n/.exec(prompt)?.[1] ?? "").matchAll(/^- #(\d+): (.*)$/gm)]; +const askedWords = words(asked); +const repeatOf = earlier.find((e) => { const w = words(e[2]!); const common = [...askedWords].filter((x) => w.has(x)).length; return askedWords.size > 0 && common / Math.min(askedWords.size, w.size || 1) >= 0.5; }); +const relay = sc.relay ?? (/баз[аеуы] данных|библиотек|фреймворк|postgres|sqlite|стек|миграц/i.test(asked) ? { verdict: "technical", text: "", options: [], default: "" } : repeatOf ? { verdict: "repeat", repeat_of: Number(repeatOf[1]), text: "", options: [], default: "" } : { verdict: "product", text: `Агент спрашивает: ${asked.split("\n")[0]}`, options: (/Варианты агента: (.*)/.exec(prompt)?.[1] ?? "Да | Нет").split(" | "), default: /По умолчанию: (.*)/.exec(prompt)?.[1] ?? "Да" }); if (sc.slowMs) await new Promise((r) => setTimeout(r, sc.slowMs)); -const result = sc.garbage ? "Не могу помочь с этим." : JSON.stringify(role === "dedup" ? dedup : role === "intent" ? intent : role === "feedback" ? feedback : role === "accept" ? accept : role === "product" ? product : role === "chat" ? chat : role === "refine" ? refine : analyst); +const result = sc.garbage ? "Не могу помочь с этим." : JSON.stringify(role === "intake" ? intake : role === "relay" ? relay : role === "dedup" ? dedup : role === "intent" ? intent : role === "feedback" ? feedback : role === "accept" ? accept : role === "product" ? product : role === "chat" ? chat : role === "refine" ? refine : analyst); process.stdout.write(JSON.stringify({ type: "result", subtype: "success", is_error: false, num_turns: 1, result, session_id: "mock-intake" }) + "\n"); diff --git a/packages/testkit/test/intake.test.ts b/packages/testkit/test/intake.test.ts index b330bddd..9fcca9b2 100644 --- a/packages/testkit/test/intake.test.ts +++ b/packages/testkit/test/intake.test.ts @@ -1,4 +1,4 @@ -// PEP-84: «продакт» and «аналитик» refine a new story before the dispatcher takes it (mock-intake). +// PEP-84 / PEP-198: the analyst formulates a new story before the dispatcher takes it (mock-intake). import assert from "node:assert/strict"; import { mkdirSync, mkdtempSync, readFileSync, writeFileSync } from "node:fs"; import { tmpdir } from "node:os"; @@ -38,100 +38,142 @@ async function intakeProject() { const tick = (now?: Date) => runner.intakeTick(db, { wait: true, now }); const story = async (key: string) => (await core.resolveTask(db, key)).task; -describe("Продакт и аналитик", () => { - test("Scenario: стори проходит продакта и аналитика; развилку аналитик решает сам, продакта не спрашивает и не ждёт (PEP-94)", async () => { +describe("PEP-198: один Аналитик на входе задачи", () => { + test("Scenario: Новая задача — один вызов модели, критерии, решения на виду, владельцу ничего не задаётся", async () => { const p = await intakeProject(); - const done = await core.createTask(db, { projectId: p.id, title: "Каталог товаров" }); + const done = await core.createTask(db, { projectId: p.id, title: "Каталог товаров", description: "Список товаров с фото и ценой" }); await core.setIntakeState(db, done.task.id, { stage: "done", original: { title: "", description: "" }, attempts: 0 }); const ref = await core.createTask(db, { projectId: p.id, title: "Корзина", description: "Хочу чтобы можно было складывать товары" }); assert.deepEqual([...(await core.intakePendingTasks(db, p.id)).entries()], [[ref.task.id, "new"]]); - assert.deepEqual((await runner.readyBacklog(db, p.id)).map((t) => t.id), [done.task.id], "the dispatcher does not see a story the roles hold"); + assert.deepEqual((await runner.readyBacklog(db, p.id)).map((t) => t.id), [done.task.id], "the dispatcher does not see a story the analyst holds"); await tick(); const state = (await core.getIntakeState(db, ref.task.id))!; assert.equal(state.stage, "done", "no waiting for the PM"); const mine = calls().filter((c) => c.title === "Корзина"); - assert.deepEqual(mine.map((c) => c.role), ["product", "analyst"]); - assert.ok(mine.every((c) => c.hasContext), "the roles get the project's context"); + assert.deepEqual(mine.map((c) => c.role), ["intake"], "exactly one model call on intake"); + assert.ok(mine[0]!.hasContext, "the analyst gets the project's context"); assert.match(mine[0]!.prompt, /Интерфейс на русском/, "AGENTS.md"); assert.match(mine[0]!.prompt, /Оплата только картой/, "memory"); - assert.match(mine[0]!.prompt, /\[backlog\] Каталог товаров/, "other stories"); + assert.match(mine[0]!.prompt, /\[backlog\] Каталог товаров — Список товаров с фото и ценой/, "other stories with what they are about (6.1)"); assert.match(mine[0]!.prompt, /Не хвали/, "no flattery"); - assert.match(mine[1]!.prompt, /Вопросов продакту не задавай/, "the analyst asks nothing"); + assert.match(mine[0]!.prompt, /Вопросов владельцу не задавай/, "the analyst asks nothing"); + assert.doesNotMatch(mine[0]!.prompt, /продакт-менеджер/i); const t = await story(ref.key); assert.match(t.description!, /## Критерии приёмки\n- Результат виден пользователю/); + assert.match(t.description!, /## Допущения\n- Страница открывается с телефона/, "«Допущения» from the decisions"); assert.match(t.description!, /## Исходный запрос\nКорзина\n\nХочу чтобы можно было складывать товары/, "the PM's words are kept"); + const decisions = await core.getDecisions(db, ref.task.id); + assert.deepEqual(decisions.map((d) => [d.text, d.status]), [["Страница открывается с телефона", "default"]]); const comments = await core.storyComments(db, ref.task.id); - assert.deepEqual(comments.map((c) => c.role), ["product", "analyst"]); - assert.equal(comments[0]!.login, "Продакт"); - // A question the model still sent became its default, decided right away. + assert.deepEqual(comments.map((c) => [c.role, c.login]), [["analyst", "Аналитик"]], "one voice"); + assert.match(comments[0]!.text, new RegExp(`^Задача ${ref.key} готова к работе\\. Фабрика решила за вас 1 пунктов — проверьте\\.`)); assert.equal((await core.pendingQuestions(db, p.id)).length, 0, "nothing goes to the PM"); - assert.match(t.description!, /## Допущения[\s\S]*Нужна ли мобильная версия\? — Да, страница открывается с телефона/); - assert.match(comments[1]!.text, /напишите в комментариях к задаче/); - assert.deepEqual((await runner.readyBacklog(db, p.id)).map((x) => x.id).sort(), [done.task.id, ref.task.id].sort(), "the dispatcher may take it at once"); + assert.deepEqual((await runner.readyBacklog(db, p.id)).map((x) => x.id).sort(), [done.task.id, ref.task.id].sort(), "the dispatcher may take it at once (5.4)"); }); - test("a story left waiting by the old flow finishes by defaults at its deadline", async () => { + test("Scenario: Задача на старой стадии — product, finalize и waiting доводятся без потерь", async () => { const p = await intakeProject(); - const ref = await core.createTask(db, { projectId: p.id, title: "Оплата" }); - const q = await core.askPm(db, ref, { kind: "question", text: "старый вопрос аналитика" }); + // «product»: the old first role never ran — one call finishes it. + const a = await core.createTask(db, { projectId: p.id, title: "Старая корзина" }); + await core.setIntakeState(db, a.task.id, { stage: "product", original: { title: "Старая корзина", description: "складывать товары" }, attempts: 0 }); + // «analyst» after the old product role: its goal goes into the prompt. + const b = await core.createTask(db, { projectId: p.id, title: "Тележка" }); + await core.setIntakeState(db, b.task.id, { stage: "analyst", original: { title: "Тележка", description: "" }, product: { goal: "Покупатель копит товары", comment: "Доставку откладываю", title: "Тележка", split: [] }, attempts: 0 }); + // «finalize»: the PM answered the old questions — the answer is kept. + const c = await core.createTask(db, { projectId: p.id, title: "Оплата" }); + await core.setIntakeState(db, c.task.id, { stage: "finalize", original: { title: "Оплата", description: "" }, analyst: { description: "Оплата заказа", criteria: ["Можно оплатить"], outOfScope: [], assumptions: [], questions: [{ q: "Рассрочка?", default: "Нет" }], comment: "" }, answer: "Рассрочка нужна", attempts: 0 }); + // «waiting»: goes by its defaults at the deadline, no model call. + const d = await core.createTask(db, { projectId: p.id, title: "Доставка" }); + const q = await core.askPm(db, d, { kind: "question", text: "старый вопрос аналитика" }); const t0 = new Date("2026-11-16T10:00:00"); - await core.setIntakeState(db, ref.task.id, { - stage: "waiting", - original: { title: "Оплата", description: "" }, - analyst: { description: "Оплата заказа", criteria: ["Можно оплатить"], outOfScope: [], assumptions: [], questions: [{ q: "Нужна ли рассрочка?", default: "Нет" }], comment: "" }, - questionId: q.id, - deadline: t0.getTime() + 60_000, - attempts: 0, - }); + await core.setIntakeState(db, d.task.id, { stage: "waiting", original: { title: "Доставка", description: "" }, analyst: { description: "Доставка", criteria: ["Курьер"], outOfScope: [], assumptions: [], questions: [{ q: "Самовывоз?", default: "Нет" }], comment: "" }, questionId: q.id, deadline: t0.getTime() + 60_000, attempts: 0 }); + await tick(new Date(t0.getTime() + 2 * 60_000)); - assert.equal((await core.getIntakeState(db, ref.task.id))!.stage, "done"); - assert.equal((await core.pendingQuestions(db, p.id)).length, 0, "the question is closed"); - assert.match((await story(ref.key)).description!, /Нужна ли рассрочка\? — Нет/); + for (const r of [a, b, c, d]) assert.equal((await core.getIntakeState(db, r.task.id))!.stage, "done", r.key); + assert.match((await story(a.key)).description!, /## Исходный запрос\nСтарая корзина\n\nскладывать товары/); + const byTitle = (t: string) => calls().filter((x) => x.title === t); + assert.equal(byTitle("Старая корзина").length, 1); + assert.match(byTitle("Тележка")[0]!.prompt, /Цель: Покупатель копит товары/); + assert.match(byTitle("Оплата")[0]!.prompt, /Владелец ответил на прежние вопросы:\nРассрочка нужна/); + assert.equal(byTitle("Доставка").length, 0); + assert.match((await story(d.key)).description!, /Самовывоз\? — Нет/); + assert.equal((await core.pendingQuestions(db, p.id)).length, 0, "the old question is closed"); }); - test("Scenario: продакт делит запрос на стори и переименовывает; без вопросов стори сразу готова", async () => { + test("Scenario: Разбивка на три части — в бэклоге с пометкой и зависимостью, ждут приёмки первой; «Не делить» возвращает их", async () => { const p = await intakeProject(); - setScenario({ - product: { goal: "Продавать онлайн", comment: "Это три задачи. Доставку откладываю.", title: "Каталог: список товаров", split: [{ title: "Тележка", description: "Сложить товары" }, { title: "Оплата картой", description: "Оплатить заказ" }] }, - analyst: { questions: [] }, - }); + setScenario({ intake: { title: "Каталог: список товаров", deferred: ["Доставка"], split: [{ title: "Тележка покупателя", description: "Сложить товары" }, { title: "Оплата заказа картой", description: "Оплатить заказ" }], decisions: ["Цены в тенге"] } }); const ref = await core.createTask(db, { projectId: p.id, title: "Сделай интернет-магазин" }); await tick(); - const all = await core.listTasks(db, { projectId: p.id }); - assert.deepEqual(all.map((t) => t.title).sort(), ["Каталог: список товаров", "Оплата картой", "Тележка"]); - assert.equal((await core.getIntakeState(db, ref.task.id))!.stage, "done"); - assert.match((await core.storyComments(db, ref.task.id))[0]!.text, /Разделил на задачи: эта и MIN\w-2, MIN\w-3/); - // The split stories skip the product manager: the analyst takes them on the next tick. - await tick(); - for (const t of all) assert.equal((await core.getIntakeState(db, t.id))!.stage, "done"); - assert.equal(calls().filter((c) => c.role === "product" && ["Тележка", "Оплата картой"].includes(c.title)).length, 0); - assert.equal((await core.pendingQuestions(db, p.id)).length, 0); setScenario({}); + const all = await core.listTasks(db, { projectId: p.id }); + assert.deepEqual(all.map((t) => t.title).sort(), ["Каталог: список товаров", "Оплата заказа картой", "Тележка покупателя"]); + const parts = all.filter((t) => t.id !== ref.task.id); + for (const t of parts) { + assert.match(t.description!, new RegExp(`Из разбивки ${ref.key}`)); + assert.equal(t.origin, "analyst"); + assert.equal((await core.getIntakeState(db, t.id))!.stage, "done", "a part does not go through intake again"); + assert.deepEqual((await core.blockersOf(db, await core.resolveTask(db, t.key))).map((b) => b.key), [ref.key]); + } + const note = (await core.storyComments(db, ref.task.id))[0]!.text; + assert.match(note, /Фабрика решила за вас 2 пунктов/); + assert.match(note, new RegExp(`Разделила на 3 задач: ${ref.key}, ${parts.map((t) => t.key).join(", ")}`)); + assert.equal(calls().filter((c) => c.role === "intake" && ["Тележка покупателя", "Оплата заказа картой"].includes(c.title)).length, 0); + + // The dispatcher takes the first one only; review is not enough, accepted is. + assert.deepEqual((await runner.readyBacklog(db, p.id)).map((t) => t.id), [ref.task.id]); + await core.updateTask(db, ref, { status: "review" }); + assert.deepEqual((await runner.readyBacklog(db, p.id)).map((t) => t.id), [], "the first one is in review — parts still wait"); + await core.updateTask(db, await core.resolveTask(db, ref.key), { status: "backlog" }); + + // «Не делить»: the parts go to the archive and come back into the first story. + const split = (await core.getDecisions(db, ref.task.id)).find((d) => d.kind === "split")!; + assert.equal(split.status, "default"); + assert.equal(await runner.undoSplit(db, await core.resolveTask(db, ref.key), split.id, pm), "unsplit"); + for (const t of parts) assert.ok((await core.resolveTask(db, t.key)).task.archivedAt, `${t.key} archived`); + const desc = (await story(ref.key)).description!; + assert.match(desc, /## Тоже входит в задачу\n- Тележка покупателя: Сложить товары\n- Оплата заказа картой: Оплатить заказ\n- Доставка/); + assert.equal((await core.getDecisions(db, ref.task.id)).find((d) => d.kind === "split")!.status, "changed"); }); - test("роли не держат стори: сбой модели, ручной запуск, выключенное уточнение, старый бэклог", async () => { + test("Scenario: Повтор существующей задачи в разбивке не заводится", async () => { + const p = await intakeProject(); + await core.createTask(db, { projectId: p.id, title: "Страница отзывов", origin: "human" }).then((r) => core.setIntakeState(db, r.task.id, { stage: "done", original: { title: "", description: "" }, attempts: 0 })); + setScenario({ intake: { split: [{ title: "Страница отзывов", description: "Отзывы клиентов" }] } }); + const ref = await core.createTask(db, { projectId: p.id, title: "Отзывы и рейтинг" }); + await tick(); + setScenario({}); + assert.equal((await core.listTasks(db, { projectId: p.id })).filter((t) => t.title === "Страница отзывов").length, 1); + assert.match((await core.storyComments(db, ref.task.id))[0]!.text, /Не завела повторно — такие задачи уже есть:\n• «Страница отзывов» — MIN\w-1/); + assert.equal((await core.getDecisions(db, ref.task.id)).filter((d) => d.kind === "split").length, 0); + }); + + test("Scenario: Две неудачи модели — задача идёт как написана, владельцу одно сообщение с причиной", async () => { const p = await intakeProject(); setScenario({ garbage: true }); const broken = await core.createTask(db, { projectId: p.id, title: "Сломанная" }); await tick(); - assert.equal((await core.getIntakeState(db, broken.task.id))!.stage, "product", "one failure — try again"); + assert.equal((await core.getIntakeState(db, broken.task.id))!.stage, "analyst", "one failure — try again"); + assert.equal((await core.storyComments(db, broken.task.id)).length, 0, "nothing said after the first failure"); await tick(); const gaveUp = (await core.getIntakeState(db, broken.task.id))!; assert.equal(gaveUp.stage, "done"); assert.match(gaveUp.note!, /не по формату/); assert.equal((await story(broken.key)).description ?? "", "", "the story goes on as written"); - assert.match((await core.storyComments(db, broken.task.id)).at(-1)!.text, /задача идёт в работу как написана/); + const said = await core.storyComments(db, broken.task.id); + assert.equal(said.length, 1, "one message"); + assert.equal(said[0]!.text, "Аналитик не смог разобрать задачу: ответ разбора пришёл не по форме. Задача идёт в работу как написана."); + await tick(); + assert.equal((await core.storyComments(db, broken.task.id)).length, 1, "not repeated"); setScenario({}); - // Roles never hold a story waiting for the PM; taking it to work afterwards changes nothing. const manual = await core.createTask(db, { projectId: p.id, title: "Ручная" }); await tick(); assert.equal((await core.getIntakeState(db, manual.task.id))!.stage, "done"); await runner.releaseIntake(db, manual.task.id); assert.equal((await core.getIntakeState(db, manual.task.id))!.stage, "done"); - assert.equal((await core.pendingQuestions(db, p.id)).length, 0); // Off by default; turning it on leaves the old backlog alone. const off = await core.createProject(db, { slug: "mock-intake-off", key: "MINOFF", name: "Off", giteaOwner: "x", workspacePath: join(TMP, "off"), ownerId: pm.id }); @@ -144,3 +186,58 @@ describe("Продакт и аналитик", () => { assert.equal(await core.getIntakeState(db, old.task.id), null); }); }); + +describe("PEP-198: решения на виду — «Подходит» и «Нужно иначе»", () => { + async function decided(status: "backlog" | "in_progress" | "review") { + const p = await intakeProject(); + setScenario({ intake: { decisions: ["Оплата картой"] } }); + const ref = await core.createTask(db, { projectId: p.id, title: `Оплата ${status}` }); + await tick(); + setScenario({}); + if (status !== "backlog") await core.updateTask(db, await core.resolveTask(db, ref.key), { status }); + const d = (await core.getDecisions(db, ref.task.id))[0]!; + return { p, ref: await core.resolveTask(db, ref.key), d }; + } + + test("Scenario: «Подходит» — только статус, ничего не запускается", async () => { + const { p, ref, d } = await decided("backlog"); + const before = { desc: (await story(ref.key)).description, comments: (await core.storyComments(db, ref.task.id)).length }; + assert.equal(await runner.confirmTaskDecision(db, ref, d.id, pm), "confirmed"); + const after = (await core.getDecisions(db, ref.task.id))[0]!; + assert.equal(after.status, "confirmed"); + assert.equal(after.by, pm.login); + assert.equal((await story(ref.key)).description, before.desc); + assert.equal((await core.storyComments(db, ref.task.id)).length, before.comments, "no comment, no refine"); + assert.equal((await core.pendingRefinements(db, { projectId: p.id })).size, 0); + assert.equal((await core.listSessions(db, { active: true, taskId: ref.task.id })).length, 0); + }); + + test("Scenario: «Нужно иначе» в бэклоге — Аналитик пересобирает постановку", async () => { + const { p, ref, d } = await decided("backlog"); + assert.equal(await runner.changeTaskDecision(db, ref, d.id, "Только наличные", pm), "refine"); + const after = (await core.getDecisions(db, ref.task.id))[0]!; + assert.deepEqual([after.status, after.text, after.was], ["changed", "Только наличные", "Оплата картой"]); + assert.match((await story(ref.key)).description!, /## Допущения\n- Только наличные \(решение владельца; было: Оплата картой\)/); + assert.ok((await core.pendingRefinements(db, { projectId: p.id })).has(ref.task.id), "the analyst's refine picks it up"); + assert.match((await core.storyComments(db, ref.task.id)).at(-1)!.text, /было — Оплата картой, нужно — Только наличные/); + }); + + test("Scenario: «Нужно иначе» в работе — агент получает «было — …, нужно — …»", async () => { + const { ref, d } = await decided("in_progress"); + assert.equal(await runner.changeTaskDecision(db, ref, d.id, "Только наличные", pm), "agent"); + assert.equal((await core.getDecisions(db, ref.task.id))[0]!.status, "changed"); + assert.match((await core.storyComments(db, ref.task.id)).at(-1)!.text, /было — Оплата картой, нужно — Только наличные/, "the agent reads it in get_task"); + assert.equal((await core.resolveTask(db, ref.key)).task.status, "in_progress"); + }); + + test("Scenario: «Нужно иначе» на ревью — как «Поправить»", async () => { + const { ref, d } = await decided("review"); + const q = await core.askPm(db, ref, { kind: "attention", text: "✅ готово к ревью" }); + assert.equal(await runner.changeTaskDecision(db, ref, d.id, "Только наличные", pm), "fix"); + const now = await core.resolveTask(db, ref.key); + assert.equal(now.task.status, "in_progress"); + assert.ok((await core.getQuestion(db, q.id)).answeredAt); + const [live] = await core.listSessions(db, { active: true, taskId: now.task.id }); + if (live) await runner.stopSession(db, live.id); + }); +});