111 lines
5.5 KiB
TypeScript
111 lines
5.5 KiB
TypeScript
// 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 { spawn } from "node:child_process";
|
||
import { mkdtempSync, rmSync } from "node:fs";
|
||
import { tmpdir } from "node:os";
|
||
import { join } from "node:path";
|
||
import { claudeTokenForProject, type Incident, type Project } from "@peppa/core";
|
||
import type { Db } from "@peppa/db";
|
||
|
||
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 bin = process.env.PEPPA_TRIAGE_BIN ?? "claude";
|
||
const TIMEOUT_MS = Number(process.env.PEPPA_TRIAGE_TIMEOUT_MS ?? 90_000);
|
||
const token = await claudeTokenForProject(db, project).catch(() => null);
|
||
// An empty cwd: no project CLAUDE.md, MCP servers or hooks get pulled in.
|
||
const cwd = mkdtempSync(join(tmpdir(), "peppa-triage-"));
|
||
try {
|
||
const out = await new Promise<{ code: number | null; stdout: string; stderr: string }>((resolve, reject) => {
|
||
const child = spawn(bin, ["-p", "--output-format", "json", "--max-turns", "1", "--model", process.env.PEPPA_TRIAGE_MODEL ?? "haiku"], {
|
||
cwd,
|
||
env: { ...process.env, ...(token ? { CLAUDE_CODE_OAUTH_TOKEN: token } : {}) },
|
||
stdio: ["pipe", "pipe", "pipe"],
|
||
// Own process group: a timeout kills the CLI with whatever it spawned.
|
||
detached: true,
|
||
});
|
||
let stdout = "";
|
||
let stderr = "";
|
||
const timer = setTimeout(() => {
|
||
try {
|
||
process.kill(-child.pid!, "SIGKILL");
|
||
} catch {
|
||
child.kill("SIGKILL");
|
||
}
|
||
child.stdout.destroy();
|
||
child.stderr.destroy();
|
||
reject(new Error(`триажёр не ответил за ${Math.round(TIMEOUT_MS / 1000)} с`));
|
||
}, TIMEOUT_MS);
|
||
child.stdout.on("data", (d) => (stdout += d));
|
||
child.stderr.on("data", (d) => (stderr += d));
|
||
child.on("error", (e) => (clearTimeout(timer), reject(e)));
|
||
child.on("close", (code) => (clearTimeout(timer), resolve({ code, stdout, stderr })));
|
||
child.stdin.end(triagePrompt(project, i, pmPrompt));
|
||
});
|
||
if (out.code !== 0) return { ok: false, error: `триажёр завершился с кодом ${out.code}: ${out.stderr.trim().slice(0, 200)}` };
|
||
const decision = parseTriageOutput(out.stdout);
|
||
return decision ? { ok: true, decision } : { ok: false, error: "триажёр ответил не по формату" };
|
||
} catch (e) {
|
||
return { ok: false, error: (e as Error).message };
|
||
} finally {
|
||
rmSync(cwd, { recursive: true, force: true });
|
||
}
|
||
}
|