peppa/packages/core/src/intake.ts
Асель 43e1319c5f PEP-156: кто говорит — события от имени Peppa FACTORY, агент под кличкой, роли на «вы»
Проекция событий в чаты подписывает то, что сделала фабрика или агент, «Peppa FACTORY»;
логин — только под словами человека. Слова агента — с кличкой (чат, карточка вопроса,
Telegram «🤖 Шустрик: …»), роли — «Аналитик» и «Продакт-агент». «Агент <кличка> взял
задачу в работу» ждёт запуска агента. Промпты ролей требуют «вы» (ADDRESS_RULE),
informalAddress проверяет ответы моков. Change pep-156-who-speaks в архиве, спека
project-chats, тест who-speaks.test.ts.

Rebased on main (one commit on top of 1074d276).

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
2026-11-18 18:30:48 +05:00

370 lines
22 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

// 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:<taskId>`, `project.intake:<projectId>`).
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 { ADDRESS_RULE } from "./authors.ts";
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";
/** `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<IntakeRole, string> = { product: tr("Аналитик"), analyst: tr("Аналитик"), acceptance: tr("Агент приёмки") };
export const INTAKE_EVENT = "intake_note";
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<IntakeSettings> {
return { ...DEFAULT_INTAKE, ...((await getSetting<Partial<IntakeSettings>>(db, projectKey(projectId))) ?? {}) };
}
export async function setIntakeSettings(db: Db, projectId: number, patch: { enabled?: boolean; waitMin?: number }, now = new Date()): Promise<IntakeSettings> {
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;
}
/** `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 {
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<IntakeState | null> {
return getSetting<IntakeState>(db, taskKey(taskId));
}
export async function setIntakeState(db: Db, taskId: number, state: IntakeState): Promise<void> {
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<Task, "status" | "createdAt">, 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<Map<number, IntakeStage | "new">> {
const out = new Map<number, IntakeStage | "new">();
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<Task, "id" | "goalId">): Promise<string> {
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(80)).filter((t) => t.id !== task.id);
const epic = epics.find((e) => e.id === task.goalId);
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 ? await storyLines(db, project, stories) : "(нет — это первая стори проекта)",
].join("\n");
}
/** PEP-198 (6.1): open and recently done stories with what they are about and the owner's decisions; the rest — titles only; within a size limit. */
async function storyLines(db: Db, project: Project, stories: Task[]): Promise<string> {
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 — только если без них нельзя).",
"Ты не спрашиваешь разрешений и не предлагаешь «могу сделать» — ты решаешь и пишешь, что решено.",
// PEP-156: comment, assumptions and questions are read by the user.
ADDRESS_RULE,
].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 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;
}
/** 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 [
`${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() || "(только название)",
...(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 без пояснений: {"goal":"…","title":"…","deferred":["…"],"split":[{"title":"…","description":"…"}],"description":"…","criteria":["…"],"out_of_scope":["…"],"decisions":["…"],"comment":"…"}',
"title — название этой задачи после урезания (до 80 символов). description частей split — что должно получиться и критерии приёмки списком.",
].join("\n");
}
/** The first balanced JSON object of the text that has `field`. */
function findJson(text: string, field: string): Record<string, unknown> | 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<string, unknown>;
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 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;
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, 3);
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");
}
/**
* 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 [
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");
}
/** 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<Task, "id" | "projectId">, role: IntakeRole, text: string): Promise<void> {
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<Set<number>> {
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!));
}