«Peppa FACTORY» → «FORGE» в экранах, сообщениях, словарях en/kk, шаблоне и тестах; «Пеппа» → «FORGE» в подсказках агентам и правилах; логотип, значок, версия кэша service worker; в словаре старые названия — в «Нельзя». Внутренние имена (CLI peppa, PEPPA_*, MCP-сервер peppa, ключи PEP-N) не меняются. Второй адрес — в mac-route.sh. Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
198 lines
9.6 KiB
TypeScript
198 lines
9.6 KiB
TypeScript
// Epic planner (PEP-42): one short non-interactive Claude call that breaks an epic into
|
||
// stories with acceptance criteria and dependencies. The result is a draft (settings
|
||
// `planner.draft:<epicId>`) the PM edits and approves; approval creates the stories in the
|
||
// backlog under the epic, in plan order, with their dependencies. Tests use mock-planner.
|
||
import { m } from "@peppa/shared/i18n";
|
||
import {
|
||
addDependency,
|
||
createTask,
|
||
deleteSetting,
|
||
getGoal,
|
||
getSetting,
|
||
listTasks,
|
||
PeppaError,
|
||
resolveTask,
|
||
setSetting,
|
||
type Goal,
|
||
type Project,
|
||
type TaskRef,
|
||
} from "@peppa/core";
|
||
import type { Db } from "@peppa/db";
|
||
import { claudePrint } from "./claude-print.ts";
|
||
|
||
/** A dependency: 1-based number of another story in the plan, or the key of an existing story. */
|
||
export type PlanDep = number | string;
|
||
|
||
export interface PlannedStory {
|
||
title: string;
|
||
description: string;
|
||
dependsOn: PlanDep[];
|
||
}
|
||
|
||
export interface PlanDraft {
|
||
epicId: number;
|
||
stories: PlannedStory[];
|
||
/** The PM's wishes passed to the planner, if any. */
|
||
wishes: string | null;
|
||
createdAt: string;
|
||
createdBy: string;
|
||
}
|
||
|
||
export const PLAN_MAX_STORIES = 15;
|
||
const draftKey = (epicId: number) => `planner.draft:${epicId}`;
|
||
|
||
export function plannerPrompt(project: Pick<Project, "key" | "name">, epic: Pick<Goal, "title" | "description">, existing: Array<{ key: string; title: string; status: string }>, wishes?: string | null): string {
|
||
return [
|
||
"Ты — планировщик софтвейр-фабрики FORGE. Разбей эпик проекта на стори для AI-агентов.",
|
||
"Стори — одна законченная бизнес-история, которую агент делает за один PR (одна OpenSpec change):",
|
||
"не слишком мелкая (не «добавить поле»), не слишком крупная (не «сделать всё»). Обычно 3–8 стори, не больше " + PLAN_MAX_STORIES + ".",
|
||
"Для каждой стори: короткое название (до 80 символов), описание — кому и зачем, что сделать,",
|
||
"и раздел «Критерии готовности» списком; зависимости — какие стори должны быть готовы раньше.",
|
||
"Не повторяй уже существующие стори эпика; можешь зависеть от них по ключу.",
|
||
"",
|
||
`Проект: ${project.key} — ${project.name}`,
|
||
`Эпик: ${epic.title}`,
|
||
"Описание эпика:",
|
||
epic.description?.trim() || "(нет описания)",
|
||
"",
|
||
"Уже есть стори эпика:",
|
||
existing.length ? existing.map((t) => `- ${t.key} [${t.status}] ${t.title}`).join("\n") : "(нет)",
|
||
...(wishes?.trim() ? ["", "Пожелания PM:", wishes.trim()] : []),
|
||
"",
|
||
'Ответь ОДНОЙ строкой JSON без пояснений: {"stories":[{"title":"…","description":"…","depends_on":[1,"' + project.key + '-3"]}]}',
|
||
"depends_on — номера стори этого плана (с 1) или ключи существующих стори; пустой список, если зависимостей нет.",
|
||
].join("\n");
|
||
}
|
||
|
||
/** Extracts the plan from the CLI's text answer (bare JSON or JSON inside prose/code fences). */
|
||
export function parsePlannerOutput(text: string): PlannedStory[] | null {
|
||
const start = text.indexOf("{");
|
||
if (start < 0) return null;
|
||
// The first balanced JSON object that has "stories".
|
||
for (let i = start; i >= 0 && i < text.length; 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 { stories?: unknown };
|
||
if (Array.isArray(o.stories)) return normalizePlan(o.stories);
|
||
} catch {}
|
||
break;
|
||
}
|
||
}
|
||
}
|
||
return null;
|
||
}
|
||
|
||
function normalizePlan(raw: unknown[]): PlannedStory[] | null {
|
||
const out: PlannedStory[] = [];
|
||
for (const r of raw.slice(0, PLAN_MAX_STORIES)) {
|
||
if (!r || typeof r !== "object") continue;
|
||
const o = r as { title?: unknown; description?: unknown; depends_on?: unknown; dependsOn?: unknown };
|
||
const title = String(o.title ?? "").trim().slice(0, 200);
|
||
if (title.length < 3) continue;
|
||
const deps = (Array.isArray(o.depends_on) ? o.depends_on : Array.isArray(o.dependsOn) ? o.dependsOn : [])
|
||
.map((d) => (typeof d === "number" ? d : /^\d+$/.test(String(d).trim()) ? Number(d) : String(d).trim().toUpperCase()))
|
||
.filter((d) => (typeof d === "number" ? Number.isInteger(d) && d > 0 : d.length > 0));
|
||
out.push({ title, description: String(o.description ?? "").trim().slice(0, 8000), dependsOn: [...new Set(deps)] });
|
||
}
|
||
return out.length ? out : null;
|
||
}
|
||
|
||
export type PlanResult = { ok: true; draft: PlanDraft } | { ok: false; error: string };
|
||
|
||
/** Runs `$PEPPA_PLANNER_BIN -p` (default `claude`) on a Claude subscription of the project's pool; saves the draft. */
|
||
export async function planEpic(db: Db, project: Project, epicId: number, o: { wishes?: string | null; by: string }): Promise<PlanResult> {
|
||
const epic = await getGoal(db, project.id, epicId);
|
||
const existing = await listTasks(db, { projectId: project.id, goalId: epic.id });
|
||
const out = await claudePrint(db, project, {
|
||
bin: process.env.PEPPA_PLANNER_BIN ?? "claude",
|
||
model: process.env.PEPPA_PLANNER_MODEL ?? "sonnet",
|
||
timeoutMs: Number(process.env.PEPPA_PLANNER_TIMEOUT_MS ?? 180_000),
|
||
prompt: plannerPrompt(project, epic, existing.map((t) => ({ key: t.key, title: t.title, status: t.status })), o.wishes),
|
||
who: m("планировщик"),
|
||
});
|
||
if (!out.ok) return out;
|
||
const stories = parsePlannerOutput(out.text);
|
||
if (!stories) return { ok: false, error: m("планировщик ответил не по формату — попробуйте ещё раз или уточните описание эпика") };
|
||
const draft: PlanDraft = { epicId: epic.id, stories, wishes: o.wishes?.trim() || null, createdAt: new Date().toISOString(), createdBy: o.by };
|
||
await setSetting(db, draftKey(epic.id), draft);
|
||
return { ok: true, draft };
|
||
}
|
||
|
||
export async function getPlanDraft(db: Db, epicId: number): Promise<PlanDraft | null> {
|
||
return getSetting<PlanDraft>(db, draftKey(epicId));
|
||
}
|
||
|
||
export async function discardPlanDraft(db: Db, epicId: number): Promise<void> {
|
||
await deleteSetting(db, draftKey(epicId));
|
||
}
|
||
|
||
/** Plan numbers must point inside the plan and the plan must have no cycles. */
|
||
export function validatePlan(stories: PlannedStory[]): string | null {
|
||
if (!stories.length) return m("в плане нет задач");
|
||
if (stories.length > PLAN_MAX_STORIES) return m("не больше {n} задач за раз", { n: PLAN_MAX_STORIES });
|
||
for (const [i, s] of stories.entries()) {
|
||
if (s.title.trim().length < 3) return m("задача {n}: нужно название", { n: i + 1 });
|
||
for (const d of s.dependsOn) {
|
||
if (typeof d === "number" && (d < 1 || d > stories.length)) return m("задача {n}: в плане нет задачи №{dep}", { n: i + 1, dep: d });
|
||
if (d === i + 1) return m("задача {n} зависит от самой себя", { n: i + 1 });
|
||
}
|
||
}
|
||
const state = new Array<number>(stories.length).fill(0);
|
||
const visit = (i: number): boolean => {
|
||
if (state[i] === 1) return false;
|
||
if (state[i] === 2) return true;
|
||
state[i] = 1;
|
||
for (const d of stories[i]!.dependsOn) if (typeof d === "number" && !visit(d - 1)) return false;
|
||
state[i] = 2;
|
||
return true;
|
||
};
|
||
for (let i = 0; i < stories.length; i++) if (!visit(i)) return m("цикл зависимостей в плане");
|
||
return null;
|
||
}
|
||
|
||
/**
|
||
* Creates the approved plan: stories in the backlog under the epic, in plan order, then the
|
||
* dependencies. References to existing stories are checked before anything is created.
|
||
*/
|
||
export async function applyPlan(db: Db, project: Project, epicId: number, stories: PlannedStory[]): Promise<TaskRef[]> {
|
||
const epic = await getGoal(db, project.id, epicId);
|
||
const bad = validatePlan(stories);
|
||
if (bad) throw new PeppaError(m("План не принят: {reason}", { reason: bad }));
|
||
const existing = new Map<string, TaskRef>();
|
||
for (const s of stories) {
|
||
for (const d of s.dependsOn) {
|
||
if (typeof d !== "string" || existing.has(d)) continue;
|
||
const ref = await resolveTask(db, d, project.key).catch(() => null);
|
||
if (!ref || ref.project.id !== project.id) throw new PeppaError(m("План не принят: задачи {key} нет в проекте {project}", { key: d, project: project.key }));
|
||
existing.set(d, ref);
|
||
}
|
||
}
|
||
const created: TaskRef[] = [];
|
||
for (const s of stories) created.push(await createTask(db, { projectId: project.id, goalId: epic.id, title: s.title.trim(), description: s.description.trim() || undefined }));
|
||
for (const [i, s] of stories.entries()) {
|
||
for (const d of s.dependsOn) await addDependency(db, created[i]!, typeof d === "number" ? created[d - 1]! : existing.get(d)!);
|
||
}
|
||
await discardPlanDraft(db, epic.id);
|
||
return created;
|
||
}
|
||
|
||
/** "PAY-3, 2" → deps for a planned story (numbers stay plan numbers). */
|
||
export function parseDepsInput(s: string): PlanDep[] {
|
||
return s
|
||
.split(/[\s,;]+/)
|
||
.map((x) => x.trim())
|
||
.filter(Boolean)
|
||
.map((x) => (/^\d+$/.test(x) ? Number(x) : x.toUpperCase()));
|
||
}
|