peppa/packages/runner/src/intake.ts
2026-11-17 21:17:44 +05:00

175 lines
9.6 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: «Аналитик» 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,
answerQuestion,
createTask,
getIntakeSettings,
getIntakeState,
intakeAnalystNote,
intakeContext,
intakeDescription,
intakeMessage,
intakePending,
intakePrompt,
listTasks,
markSplitPart,
openDecisions,
parseIntakeNote,
setDecisions,
setIntakeState,
updateTask,
type IntakeState,
type Project,
type Question,
type TaskRef,
pausedProjectIds,
} from "@peppa/core";
import type { Db } from "@peppa/db";
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<number>();
const ask = (db: Db, project: Project, prompt: string, who: string) =>
claudePrint(db, project, {
bin: process.env.PEPPA_INTAKE_BIN ?? "claude",
model: process.env.PEPPA_INTAKE_MODEL ?? "sonnet",
timeoutMs: Number(process.env.PEPPA_INTAKE_TIMEOUT_MS ?? 180_000),
prompt,
who,
});
/** 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("сервис разбора сейчас не отвечает"));
/** 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<IntakeState> {
const { project, task } = ref;
const context = await intakeContext(db, project, task);
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;
}
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 (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. */
async function goByDefaults(db: Db, ref: TaskRef, state: IntakeState): Promise<void> {
const a = state.analyst!;
const decided = a.questions.map((q) => `${q.q} — ${q.default} (ответа не было, взят вариант по умолчанию)`);
await updateTask(db, ref, { description: intakeDescription(state.original, a, decided) });
if (state.questionId) await answerQuestion(db, state.questionId, m("(ответа не было — аналитик взял варианты по умолчанию)"), "system").catch(() => {});
await addIntakeNote(db, ref.task, "analyst", `${m("Ответа не было — иду по вариантам по умолчанию:")}\n${a.questions.map((q) => `• ${q.q} → ${q.default}`).join("\n")}\n${m("Задача готова к работе.")}`);
await setIntakeState(db, ref.task.id, { ...state, stage: "done" });
}
async function advance(db: Db, taskId: number, now: Date, log: (m: string) => void): Promise<void> {
const ref = await resolveTaskById(db, taskId).catch(() => null);
if (!ref) return;
const settings = await getIntakeSettings(db, ref.project.id);
let state = await getIntakeState(db, taskId);
if (!intakePending(settings, ref.task, state)) return;
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);
log(`${ref.key}: intake — no answer, defaults taken`);
}
return;
}
try {
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 });
// 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}`);
}
}
export interface IntakeTickOptions {
now?: Date;
log?: (m: string) => void;
/** Tests: wait for the model calls instead of leaving them in the background. */
wait?: boolean;
}
export async function intakeTick(db: Db, opts: IntakeTickOptions = {}): Promise<void> {
const now = opts.now ?? new Date();
const log = opts.log ?? (() => {});
const jobs: Promise<void>[] = [];
const paused = await pausedProjectIds(db);
for (const { id } of await db.select({ id: projects.id }).from(projects).where(isNull(projects.deletedAt))) {
// PEP-174: the roles wait while the project is on pause.
if (paused.has(id)) continue;
const settings = await getIntakeSettings(db, id);
if (!settings.enabled) continue;
for (const t of await listTasks(db, { projectId: id, statuses: ["backlog"] })) {
if (inFlight.has(t.id) || !intakePending(settings, t, await getIntakeState(db, t.id))) continue;
inFlight.add(t.id);
jobs.push(advance(db, t.id, now, log).catch((e) => log(`intake ${t.id}: ${(e as Error).message}`)).finally(() => inFlight.delete(t.id)));
}
}
if (opts.wait) await Promise.all(jobs);
}
/** 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<boolean> {
if (!q.taskId) return false;
const state = await getIntakeState(db, q.taskId);
if (!state || state.stage !== "waiting" || state.questionId !== q.id) return false;
await setIntakeState(db, q.taskId, { ...state, stage: "finalize", answer, attempts: 0 });
return true;
}
onAnswer(onIntakeAnswer);
/** The PM dragged the card to work (or the story left the backlog): the roles let it go. */
export async function releaseIntake(db: Db, taskId: number): Promise<void> {
const state = await getIntakeState(db, taskId);
if (!state || state.stage === "done") return;
if (state.questionId) await answerQuestion(db, state.questionId, m("(задача взята в работу без ответа)"), "system").catch(() => {});
await setIntakeState(db, taskId, { ...state, stage: "done", note: m("взята в работу вручную") });
}