peppa/packages/runner/src/triage.ts
2026-11-15 14:47:50 +05:00

79 lines
3.8 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.

// Incident triage agent (PEP-58): one short non-interactive Claude call that picks what to
// do with a new error, following the PM's mini-prompt. Tests use mock-triage (same contract).
import { m } from "@peppa/shared/i18n";
import type { Incident, Project } from "@peppa/core";
import type { Db } from "@peppa/db";
import { claudePrint } from "./claude-print.ts";
export interface TriageDecision {
action: "notify" | "backlog" | "start" | "ignore" | "ask";
confidence: number;
reason: string;
}
export type TriageResult = { ok: true; decision: TriageDecision } | { ok: false; error: string };
const ACTIONS = ["notify", "backlog", "start", "ignore", "ask"] as const;
/** Below this the triager is "not sure" and the PM decides. */
export const TRIAGE_MIN_CONFIDENCE = 0.6;
export function triagePrompt(project: Pick<Project, "key" | "name">, i: Incident, pmPrompt: string): string {
return [
"Ты — триажёр ошибок софтвейр-фабрики Пеппа. Новая ошибка пришла из работающего продукта.",
"Реши, что с ней делать, строго по правилам PM ниже. Варианты:",
'- "start" — завести стори и сразу отдать агенту;',
'- "backlog" — завести стори в бэклог;',
'- "notify" — только сообщить PM, стори не заводить;',
'- "ignore" — игнорировать;',
'- "ask" — спросить PM (если правила не дают ясного ответа).',
"",
"Правила PM:",
pmPrompt.trim() || "(правил нет — спроси PM)",
"",
`Проект: ${project.key} — ${project.name}`,
`Ошибка: ${i.title}`,
`Место: ${i.culprit ?? "—"}`,
`Источник: ${i.source}, окружение: ${i.environment ?? "—"}, релиз: ${i.lastRelease ?? "—"}, событий: ${i.events}`,
"Верх стека:",
(i.stack ?? "—").split("\n").slice(0, 15).join("\n"),
"",
'Ответь ОДНОЙ строкой JSON без пояснений: {"action":"start|backlog|notify|ignore|ask","confidence":0..1,"reason":"одно предложение по-русски"}',
].join("\n");
}
/** Extracts the decision from the CLI's `--output-format json` envelope (or bare JSON text). */
export function parseTriageOutput(stdout: string): TriageDecision | null {
let text = stdout.trim();
try {
const env = JSON.parse(text) as { result?: unknown; is_error?: boolean };
if (env && typeof env === "object" && "result" in env) {
if (env.is_error) return null;
text = String(env.result ?? "");
}
} catch {}
const m = /\{[^{}]*"action"[^{}]*\}/s.exec(text);
if (!m) return null;
try {
const d = JSON.parse(m[0]) as Partial<TriageDecision>;
if (!ACTIONS.includes(d.action as TriageDecision["action"])) return null;
const confidence = Number(d.confidence);
return { action: d.action as TriageDecision["action"], confidence: Number.isFinite(confidence) ? confidence : 0, reason: String(d.reason ?? "").slice(0, 500) };
} catch {
return null;
}
}
/** Runs `$PEPPA_TRIAGE_BIN -p` (default `claude`) on a Claude subscription of the project's pool (PEP-67). */
export async function runTriage(db: Db, project: Project, i: Incident, pmPrompt: string): Promise<TriageResult> {
const out = await claudePrint(db, project, {
bin: process.env.PEPPA_TRIAGE_BIN ?? "claude",
model: process.env.PEPPA_TRIAGE_MODEL ?? "haiku",
timeoutMs: Number(process.env.PEPPA_TRIAGE_TIMEOUT_MS ?? 90_000),
prompt: triagePrompt(project, i, pmPrompt),
who: m("триажёр"),
});
if (!out.ok) return out;
const decision = parseTriageOutput(out.text);
return decision ? { ok: true, decision } : { ok: false, error: m("триажёр ответил не по формату") };
}