peppa/packages/testkit/test/incidents.test.ts
Асель 3a282b8054 PEP-36 stage 2: SQLite (node:sqlite, WAL) instead of Postgres
- packages/db: schema on sqlite-core (timestamps as epoch ms → Date, JSON as text,
  booleans 0/1), one baseline migration; node:sqlite client under drizzle's
  better-sqlite3 session (busy_timeout first, WAL, BEGIN IMMEDIATE, retries on
  SQLITE_BUSY, lazy open, async transaction callbacks refused); PEPPA_DB
  (default ~/.peppa/peppa.db)
- live updates: notify() pokes the bot over a unix socket; the bot also watches
  PRAGMA data_version every second (writes by other processes)
- Postgres specifics ported: createTask transaction is synchronous, no
  `for update skip locked`, `count(*)`, json_extract instead of ->>, json_each
  instead of @>
- `peppa db migrate` and `peppa db migrate-to-sqlite <file>` (read-only
  snapshot of Postgres, FK order from the schema, row count + foreign key
  checks, file appears only when they pass); old Postgres schema kept in
  packages/cli/legacy-pg-migrations for the migration and its test
- daily VACUUM INTO backup from the watchdog (7 copies, admin alert on failure)
- tests: a temp SQLite file per test file; storage.test.ts (20 processes,
  per-project numbering across processes, socket/data_version, migration from
  Postgres incl. a dangling foreign key, backups); two test races fixed
- CI: no per-run Postgres database; PEPPA_TEST_PG only for the migration test

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-13 17:23:24 +05:00

512 lines
32 KiB
TypeScript
Raw Permalink 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-58: errors of running products → incidents → the project's incident policy.
// Real bot against mock-telegram, mock-bugsink (API + outgoing webhooks), mock-triage,
// mock agents in tmux; the webhook goes through an HTTP server shaped like the Next route.
import assert from "node:assert/strict";
import { execFileSync } from "node:child_process";
import { mkdtempSync, readFileSync, writeFileSync, existsSync } from "node:fs";
import { createServer } from "node:http";
import type { AddressInfo } from "node:net";
import { tmpdir } from "node:os";
import { join, resolve } from "node:path";
import { fileURLToPath } from "node:url";
import { after, before, describe, test } from "node:test";
// helpers must load first: it sets the isolated test env that runner modules read on load.
import { core, db, project, runner, setDefaultOwner, teardown, waitFor } from "./helpers.ts";
import { MockBugsink, type MockErrorEvent } from "../src/mock-bugsink.ts";
import { MockTelegram, type MockTgMessage } from "../src/mock-telegram.ts";
import type { Bot } from "@peppa/bot";
const { createBot } = await import("@peppa/bot");
const { TelegramApi } = await import("@peppa/bot/telegram");
const { createBugsinkClient, bugsinkFromEnv: bugsinkFromEnvSync } = await import("@peppa/bugsink");
const { formatTask } = await import("../../mcp/src/format.ts");
const ROOT = resolve(fileURLToPath(import.meta.url), "../../../..");
const TMP = mkdtempSync(join(tmpdir(), "peppa-incidents-"));
const SCENARIO = join(TMP, "triage.json");
process.env.PEPPA_SECRET = "mock-secret-for-tests";
process.env.PEPPA_WEB_URL = "http://peppa.test";
process.env.PEPPA_TRIAGE_BIN = join(ROOT, "packages/testkit/bin/mock-triage");
process.env.MOCK_TRIAGE_SCENARIO = SCENARIO;
process.env.PEPPA_TRIAGE_TIMEOUT_MS = "4000";
const bugsink = await new MockBugsink().start();
const client = createBugsinkClient({ url: bugsink.url, token: bugsink.token, teamId: bugsink.teamId, publicUrl: bugsink.url });
const liveClient = () => (process.env.PEPPA_LIVE_BUGSINK === "1" ? (bugsinkFromEnvSync() ?? client) : client);
const tg = await new MockTelegram().start();
const PM = { id: 601, chatId: 601, username: "pm" };
const STRANGER = { id: 602, chatId: 602, username: "stranger" };
let bot: Bot;
let pmUser: Awaited<ReturnType<typeof core.upsertUserFromGitea>>;
// The webhook entry point, shaped like apps/web/app/api/hooks/bugsink/[secret]/route.ts.
const hooks = createServer((req, res) => {
let body = "";
req.on("data", (c) => (body += c));
req.on("end", async () => {
const secret = decodeURIComponent(req.url!.split("/").pop() ?? "");
const r = await runner.receiveBugsinkWebhook(db, secret, body ? JSON.parse(body) : null, req.headers["user-agent"]?.includes("python") ? liveClient() : client);
res.writeHead(r.status, { "Content-Type": "application/json" }).end(JSON.stringify(r.body));
if (r.status === 200) void runner.processIncidents(db);
});
});
// Live run (PEPPA_LIVE_BUGSINK=1): the real Bugsink container posts to us via host.docker.internal.
const LIVE = process.env.PEPPA_LIVE_BUGSINK === "1";
await new Promise<void>((r) => hooks.listen(0, LIVE ? "0.0.0.0" : "127.0.0.1", r));
const hookBase = `http://127.0.0.1:${(hooks.address() as AddressInfo).port}`;
before(async () => {
pmUser = await core.upsertUserFromGitea(db, { id: 71, login: "mock-pm" }, { access_token: "x" });
const stranger = await core.upsertUserFromGitea(db, { id: 72, login: "mock-stranger" }, { access_token: "y" });
setDefaultOwner(pmUser.id);
for (const [u, t] of [[pmUser, PM], [stranger, STRANGER]] as const) {
await core.acceptPairing(db, tg.token, await core.createPairingCode(db, tg.token, u.id), { chatId: t.chatId, userId: t.id, username: t.username });
}
bot = createBot({ db, api: new TelegramApi(tg.token, tg.url), secret: tg.token, webUrl: "http://peppa.test", pollTimeoutSec: 1, outboxIntervalMs: 100, reconcileIntervalMs: 400 });
await bot.start();
});
after(async () => {
await bot.stop();
await tg.stop();
await bugsink.stop();
await new Promise<void>((r) => hooks.close(() => r()));
await teardown();
});
const AMOUNT: MockErrorEvent = {
type: "TypeError",
value: "amount is undefined",
environment: "prod",
release: "a1b2c3",
frames: [
{ filename: "server.ts", function: "handle", lineno: 10 },
{ filename: "billing/charge.ts", function: "charge", lineno: 42 },
{ filename: "node:internal/process", function: "tick", lineno: 1, in_app: false },
],
};
interface Connected {
key: string;
proj: Awaited<ReturnType<typeof core.getProject>>;
web: number;
api: number;
secret: string;
}
/** A fresh project connected to (mock) Bugsink, alerts pointed at Peppa, with this policy. */
async function connected(patch: Parameters<typeof core.updateIncidentSettings>[2] = {}, opts: { webhook?: boolean } = {}): Promise<Connected> {
const p = await project({ turns: [[{ say: "смотрю ошибку" }]] });
const proj = await core.getProject(db, p.key);
const r = await runner.connectErrorTracking(db, proj, client, hookBase);
const web = r.sources.find((s) => s.kind === "web")!.bugsinkProjectId;
const api = r.sources.find((s) => s.kind === "api")!.bugsinkProjectId;
// No docker container here: the PM pastes the shown webhook URL into Bugsink.
if (opts.webhook !== false) {
bugsink.setWebhook(web, r.webhookUrl);
bugsink.setWebhook(api, r.webhookUrl);
}
if (Object.keys(patch).length) await core.updateIncidentSettings(db, proj.id, patch);
return { key: p.key, proj, web, api, secret: r.settings.hookSecret };
}
const incidentsOf = (c: Connected) => core.listIncidents(db, c.proj.id);
const waitIncident = (c: Connected, title: string, pred: (i: Awaited<ReturnType<typeof incidentsOf>>[number]) => boolean = () => true, timeoutMs?: number) =>
waitFor(`incident «${title}»`, async () => (await incidentsOf(c)).find((i) => i.title === title && pred(i)), timeoutMs);
const tasksOf = async (c: Connected) => core.listTasks(db, { projectId: c.proj.id });
const pmMessages = (needle: string) => tg.botMessages(PM.chatId).filter((m) => m.text.includes(needle));
const waitPm = (needle: string, pred: (m: MockTgMessage) => boolean = () => true) =>
waitFor(`PM message with «${needle}»`, async () => pmMessages(needle).find(pred));
const buttons = (m: MockTgMessage) => ((m.reply_markup as { inline_keyboard?: Array<Array<{ text: string; callback_data: string }>> } | undefined)?.inline_keyboard ?? []).flat();
const triage = (sc: object) => writeFileSync(SCENARIO, JSON.stringify(sc));
const triageLog = () => (existsSync(`${SCENARIO}.log.jsonl`) ? readFileSync(`${SCENARIO}.log.jsonl`, "utf8").trim().split("\n").filter(Boolean).map((l) => JSON.parse(l)) : []);
async function stopSessions(taskId: number) {
for (const s of await core.listSessions(db, { active: true, taskId })) await runner.stopSession(db, s.id);
}
describe("Подключение проекта к Bugsink", () => {
test("Подключение: DSN фронта и бэка, цель «Стабильность», политика «в бэклог»", async () => {
const p = await project({ turns: [] });
const proj = await core.getProject(db, p.key);
assert.equal(await core.getIncidentSettings(db, proj.id), null);
const r = await runner.connectErrorTracking(db, proj, client, hookBase);
assert.deepEqual(r.sources.map((s) => s.kind).sort(), ["api", "web"]);
for (const s of r.sources) assert.match(s.dsn, /^https:\/\/\w+@bugsink\.mock\/\d+$/);
assert.ok(bugsink.projects.get(r.sources[0]!.bugsinkProjectId)!.name.startsWith(p.key));
const goals = await core.listGoals(db, proj.id);
assert.ok(goals.some((g) => g.title === "Стабильность" && g.status === "open"));
assert.equal(r.settings.policy, "backlog");
// No container to configure alerts in: the URL is shown for manual setup.
assert.equal(r.settings.webhookAuto, false);
assert.equal(r.webhookUrl, `${hookBase}/api/hooks/bugsink/${r.settings.hookSecret}`);
// Connecting again changes nothing.
const again = await runner.connectErrorTracking(db, proj, client, hookBase);
assert.deepEqual(again.sources.map((s) => s.id), r.sources.map((s) => s.id));
// Without Bugsink configured on the host, connecting is refused.
await assert.rejects(runner.connectErrorTracking(db, proj, null, hookBase), /Bugsink не настроен/);
});
});
describe("Новая ошибка становится инцидентом", () => {
test("Первая ошибка в проде: инцидент с источником, окружением, релизом, счётчиком", async () => {
const c = await connected({ policy: "notify" });
await bugsink.capture(c.api, AMOUNT);
const i = await waitIncident(c, "TypeError: amount is undefined");
assert.equal(i.source, "api");
assert.equal(i.environment, "prod");
assert.equal(i.lastRelease, "a1b2c3");
assert.equal(i.events, 1);
assert.equal(i.culprit, "billing/charge.ts");
// Innermost frame first; library frames are kept but not marked [app].
assert.match(i.stack!, /^node:internal\/process:1 in tick\nbilling\/charge\.ts:42 in charge \[app\]\nserver\.ts:10 in handle \[app\]$/);
assert.ok(!i.stack!.includes("mock-local-value"), "no locals in the stack");
assert.equal(bugsink.alerts.at(-1)!.status, 200);
});
test("Та же ошибка повторилась: один инцидент, счётчик 5, задач не прибавилось", async () => {
const c = await connected(); // backlog
await bugsink.capture(c.api, AMOUNT);
await waitIncident(c, "TypeError: amount is undefined", (i) => i.status === "task");
const tasksBefore = (await tasksOf(c)).length;
for (let n = 0; n < 4; n++) await bugsink.capture(c.api, AMOUNT, new Date(Date.now() + (n + 1) * 1000));
// Bugsink alerts only on new/regressed issues; repeats come in through the poll.
await runner.pollBugsink(db, client);
await runner.processIncidents(db);
const all = await incidentsOf(c);
assert.equal(all.length, 1);
assert.equal(all[0]!.events, 5);
assert.equal((await tasksOf(c)).length, tasksBefore);
// Same webhook delivered twice: still one incident.
const issueId = all[0]!.bugsinkIssueId;
const body = { ...bugsink.issueJson(bugsink.issues.get(issueId)!), title: "TypeError: amount is undefined", alert_reason: "NEW" };
const res = await fetch(`${hookBase}/api/hooks/bugsink/${c.secret}`, { method: "POST", body: JSON.stringify(body) });
assert.equal(res.status, 200);
assert.equal((await incidentsOf(c)).length, 1);
});
test("Запрос с неверным секретом отклонён, инцидентов не прибавилось", async () => {
const c = await connected();
const before = (await incidentsOf(c)).length;
await bugsink.capture(c.api, { ...AMOUNT, value: "secret probe" });
const body = { ...bugsink.alerts.at(-1)!.body };
for (const secret of ["wrong-secret-wrong-secret", c.secret.slice(0, -1), ""]) {
const res = await fetch(`${hookBase}/api/hooks/bugsink/${secret}`, { method: "POST", body: JSON.stringify(body) });
assert.equal(res.status, 404);
}
// A valid secret of another project can't feed this project's Bugsink issues.
const other = await connected();
const res = await fetch(`${hookBase}/api/hooks/bugsink/${other.secret}`, { method: "POST", body: JSON.stringify({ ...body, id: "00000000-0000-0000-0000-000000000000" }) });
assert.equal(res.status, 404);
await new Promise((r) => setTimeout(r, 300));
assert.equal((await incidentsOf(c)).filter((i) => i.title !== "TypeError: secret probe").length, before);
assert.equal((await incidentsOf(other)).length, 0);
});
test("Вебхук потерян: опрос вачдога находит ошибку", async () => {
const c = await connected({}, { webhook: false });
await bugsink.capture(c.web, { type: "ReferenceError", value: "cart is not defined", environment: "prod", release: "f00", frames: [{ filename: "app/cart.tsx", function: "Cart", lineno: 7 }] });
assert.equal((await incidentsOf(c)).length, 0);
await runner.pollBugsink(db, client);
await runner.processIncidents(db);
const i = await waitIncident(c, "ReferenceError: cart is not defined");
assert.equal(i.source, "web");
assert.equal(i.environment, "prod");
assert.equal(i.status, "task");
assert.match(i.url!, /\/issues\/issue\//);
});
});
describe("Политика инцидентов проекта", () => {
test("notify: только сообщение в Telegram, без задачи", async () => {
const c = await connected({ policy: "notify" });
await bugsink.capture(c.api, { ...AMOUNT, value: "notify only" });
const i = await waitIncident(c, "TypeError: notify only", (x) => x.status === "open");
assert.equal(i.taskId, null);
assert.equal((await tasksOf(c)).length, 1); // only the project's own test task
const m = await waitPm("TypeError: notify only");
assert.match(m.text, new RegExp(`${c.key}.*Новая ошибка \\(api, prod\\)`));
assert.equal(buttons(m).length, 0);
});
test("backlog: задача-баг под «Стабильностью» со стеком и ссылкой, PM получает сообщение со ссылкой", async () => {
const c = await connected({ policy: "backlog" });
await bugsink.capture(c.api, AMOUNT);
const i = await waitIncident(c, "TypeError: amount is undefined", (x) => x.status === "task");
const t = (await tasksOf(c)).find((x) => x.id === i.taskId)!;
assert.equal(t.title, "Ошибка: TypeError: amount is undefined (billing/charge.ts)");
assert.equal(t.status, "backlog");
const goal = (await core.listGoals(db, c.proj.id)).find((g) => g.id === t.goalId);
assert.equal(goal?.title, "Стабильность");
assert.match(t.description!, /billing\/charge\.ts:42 in charge/);
assert.ok(t.description!.includes(i.url!));
assert.match(t.description!, /Условия готовности/);
const m = await waitPm("TypeError: amount is undefined", (x) => x.text.includes(t.key));
assert.match(m.text, /Задача в бэклоге/);
assert.ok(m.text.includes(`http://peppa.test/t/${t.key}`));
});
test("start: задача сразу в работе, раннер запущен, PM знает", async () => {
const c = await connected({ policy: "start" });
await bugsink.capture(c.api, { ...AMOUNT, value: "start now" });
const i = await waitIncident(c, "TypeError: start now", (x) => x.status === "task");
// The incident points at its task before the task is moved to work.
const t = await waitFor("task in progress", async () => (await tasksOf(c)).find((x) => x.id === i.taskId && x.status === "in_progress"));
const s = await waitFor("runner started", async () => (await core.listSessions(db, { taskId: t.id }))[0]);
assert.ok(s);
await waitPm("TypeError: start now", (m) => /Агент взялся/.test(m.text));
await stopSessions(t.id);
});
test("ask: кнопки «В бэклог / В работу / Игнорировать», инцидент ждёт разбора", async () => {
const c = await connected({ policy: "ask" });
await bugsink.capture(c.api, { ...AMOUNT, value: "ask me" });
const i = await waitIncident(c, "TypeError: ask me", (x) => x.status === "pending");
assert.equal(i.taskId, null);
const m = await waitPm("TypeError: ask me");
assert.deepEqual(buttons(m).map((b) => b.callback_data), [`i:${i.id}:backlog`, `i:${i.id}:start`, `i:${i.id}:ignore`]);
assert.match(m.text, /Что делаем\?/);
});
test("PM решает по кнопке «В работу»: задача в работе, раннер, сообщение закрыто", async () => {
const c = await connected({ policy: "ask" });
await bugsink.capture(c.api, { ...AMOUNT, value: "decide by button" });
const i = await waitIncident(c, "TypeError: decide by button", (x) => x.status === "pending");
const m = await waitPm("TypeError: decide by button", (x) => buttons(x).length > 0);
tg.userClicks(PM, m.message_id, `i:${i.id}:start`);
const done = await waitFor("incident decided", async () => {
const x = await core.getIncident(db, i.id);
return x.taskId ? x : null;
});
assert.equal(done.decidedBy, "pm");
const t = (await tasksOf(c)).find((x) => x.id === done.taskId)!;
assert.equal(t.status, "in_progress");
await waitFor("runner started", async () => (await core.listSessions(db, { taskId: t.id }))[0]);
await waitFor("message closed", async () => {
const msg = tg.messages.get(m.message_id)!;
return msg.text.includes(`Решено (mock-pm): в работу → ${t.key}`) && buttons(msg).length === 0;
});
await waitFor("toast", async () => tg.callbackAnswers.some((a) => a.text?.includes(t.key)));
// A second press changes nothing.
await assert.rejects(runner.decideIncident(db, i.id, "backlog", "mock-pm"), /Уже решено/);
await stopSessions(t.id);
});
test("Чужой не может решить: без доступа к проекту кнопка не срабатывает", async () => {
const c = await connected({ policy: "ask" });
await bugsink.capture(c.api, { ...AMOUNT, value: "not yours" });
const i = await waitIncident(c, "TypeError: not yours", (x) => x.status === "pending");
assert.equal(tg.botMessages(STRANGER.chatId).filter((m) => m.text.includes("not yours")).length, 0);
const cb = tg.userClicks(STRANGER, 999999, `i:${i.id}:start`);
await waitFor("stranger refused", async () => tg.callbackAnswers.find((a) => a.id === cb && a.text === "Ошибка не найдена"));
const x = await core.getIncident(db, i.id);
assert.equal(x.status, "pending");
assert.equal(x.taskId, null);
});
test("triage, триажёр уверен: задача в работе, обоснование в задаче и в сообщении", async () => {
const prompt = "падения оплаты — сразу в работу, косметику фронта — в бэклог, остальное спроси";
triage({ rules: [{ match: "PaymentError", action: "start", confidence: 0.92, reason: "падает оплата — по правилам сразу в работу" }] });
const c = await connected({ policy: "triage", triagePrompt: prompt });
await bugsink.capture(c.api, { type: "PaymentError", value: "card declined handler crashed", environment: "prod", release: "a1b2c3", frames: [{ filename: "billing/pay.ts", function: "pay", lineno: 3 }] });
const i = await waitIncident(c, "PaymentError: card declined handler crashed", (x) => x.status === "task");
assert.equal(i.decidedBy, "triage");
assert.equal(i.decision, "start");
const t = (await tasksOf(c)).find((x) => x.id === i.taskId)!;
assert.equal(t.status, "in_progress");
assert.match(t.description!, /Решение триажёра: падает оплата — по правилам сразу в работу/);
const m = await waitPm("PaymentError: card declined", (x) => /Агент взялся/.test(x.text));
assert.match(m.text, /🤖 Триажёр: падает оплата/);
const call = triageLog().at(-1);
assert.equal(call.pmRules, prompt);
assert.deepEqual(call.args.slice(0, 3), ["-p", "--output-format", "json"]);
assert.ok(!call.cwd.includes(c.key.toLowerCase()), "triage runs outside the project workspace");
await stopSessions(t.id);
});
test("triage, триажёр не уверен: откат на «спросить» с пометкой", async () => {
triage({ rules: [{ match: "PaymentError", action: "start" }], default: { action: "backlog", confidence: 0.4, reason: "похоже на косметику, но не уверен" } });
const c = await connected({ policy: "triage", triagePrompt: "падения оплаты — сразу в работу, остальное спроси" });
await bugsink.capture(c.web, { type: "Error", value: "tooltip misplaced", environment: "prod", frames: [{ filename: "ui/tooltip.tsx", function: "place", lineno: 9 }] });
const i = await waitIncident(c, "Error: tooltip misplaced", (x) => x.status === "pending");
assert.equal(i.taskId, null);
const m = await waitPm("Error: tooltip misplaced");
assert.equal(buttons(m).length, 3);
assert.match(m.text, /Триажёр не уверен \(склоняется: в бэклог\): похоже на косметику/);
});
test("triage, триажёр недоступен (падает или молчит): откат на «спросить»", async () => {
triage({ fail: true });
const c = await connected({ policy: "triage", triagePrompt: "всё в бэклог" });
await bugsink.capture(c.api, { ...AMOUNT, value: "triage down" });
await waitIncident(c, "TypeError: triage down", (x) => x.status === "pending");
const m = await waitPm("TypeError: triage down");
assert.match(m.text, /Триажёр недоступен \(триажёр завершился с кодом 1/);
assert.equal(buttons(m).length, 3);
triage({ hang: true });
await bugsink.capture(c.api, { ...AMOUNT, value: "triage hangs" });
await waitIncident(c, "TypeError: triage hangs", (x) => x.status === "pending" && !!x.decisionReason, 15000);
const m2 = await waitPm("TypeError: triage hangs");
assert.match(m2.text, /не ответил за 4 с/);
});
test("Ошибка не из прода: видна, без задачи и без сообщения", async () => {
const c = await connected({ policy: "backlog" });
await bugsink.capture(c.api, { ...AMOUNT, value: "staging only", environment: "staging" });
const i = await waitIncident(c, "TypeError: staging only", (x) => x.status === "open");
assert.equal(i.environment, "staging");
assert.equal(i.taskId, null);
await new Promise((r) => setTimeout(r, 500));
assert.equal(pmMessages("staging only").length, 0);
});
test("Суточный предел: шестая ошибка за день — без задачи, ждёт разбора, сообщение с кнопками", async () => {
const c = await connected({ policy: "backlog" });
for (let n = 1; n <= 5; n++) {
await bugsink.capture(c.api, { ...AMOUNT, value: `limit ${n}` });
await waitIncident(c, `TypeError: limit ${n}`, (x) => x.status === "task");
}
await bugsink.capture(c.api, { ...AMOUNT, value: "limit 6" });
const i = await waitIncident(c, "TypeError: limit 6", (x) => x.status === "pending");
assert.equal(i.taskId, null);
assert.equal((await tasksOf(c)).filter((t) => t.title.startsWith("Ошибка:")).length, 5);
const m = await waitPm("TypeError: limit 6");
assert.match(m.text, /Суточный предел задач из ошибок \(5\) исчерпан/);
assert.equal(buttons(m).length, 3);
// The PM's own decision isn't capped.
const r = await runner.decideIncident(db, i.id, "backlog", "mock-pm");
assert.equal(r.task?.task.status, "backlog");
});
test("Смена политики: после выбора triage новые ошибки разбирает триажёр по промпту", async () => {
triage({ rules: [{ match: "Cosmetic", action: "backlog", confidence: 0.8, reason: "косметика — в бэклог" }] });
const c = await connected({ policy: "backlog" });
const calls = triageLog().length;
await bugsink.capture(c.web, { type: "CosmeticError", value: "before switch", environment: "prod" });
const first = await waitIncident(c, "CosmeticError: before switch", (x) => x.status === "task");
assert.equal(first.decidedBy, "policy");
assert.equal(triageLog().length, calls);
const s = await core.updateIncidentSettings(db, c.proj.id, { policy: "triage", triagePrompt: "косметику фронта — в бэклог" });
assert.equal(s.policy, "triage");
await bugsink.capture(c.web, { type: "CosmeticError", value: "after switch", environment: "prod" });
const second = await waitIncident(c, "CosmeticError: after switch", (x) => x.status === "task");
assert.equal(second.decidedBy, "triage");
assert.equal(triageLog().at(-1).pmRules, "косметику фронта — в бэклог");
await assert.rejects(core.updateIncidentSettings(db, c.proj.id, { policy: "panic" as never }), /Неизвестная политика/);
await assert.rejects(core.updateIncidentSettings(db, c.proj.id, { ignorePattern: "([" }), /регулярное выражение/);
});
});
describe("Агент видит ошибку", () => {
test("get_task задачи-бага: блок «Инцидент» со стеком, релизом и числом событий", async () => {
const c = await connected();
await bugsink.capture(c.api, AMOUNT);
const i = await waitIncident(c, "TypeError: amount is undefined", (x) => x.status === "task");
const t = (await tasksOf(c)).find((x) => x.id === i.taskId)!;
const text = formatTask(await core.getTaskDetails(db, await core.resolveTask(db, t.key)));
assert.match(text, /## Инцидент/);
assert.match(text, /Релиз: a1b2c3/);
assert.match(text, /Событий: 1/);
assert.match(text, /billing\/charge\.ts:42 in charge \[app\]/);
});
});
describe("Закрытие после исправления и возврат при повторе", () => {
test("Исправлено вручную, затем ошибка вернулась: задача снова в бэклоге, PM знает", async () => {
const c = await connected();
const issueId = await bugsink.capture(c.api, AMOUNT);
const i = await waitIncident(c, "TypeError: amount is undefined", (x) => x.status === "task");
const ref = await core.resolveTask(db, (await tasksOf(c)).find((x) => x.id === i.taskId)!.key);
await runner.moveTask(db, ref, "done");
const r = await runner.resolveIncident(db, i.id, { who: "mock-pm", client });
assert.equal(r.incident.status, "resolved");
assert.equal(r.bugsinkResolved, true);
assert.equal(bugsink.issues.get(issueId)!.resolved, true);
const details = await core.getTaskDetails(db, ref);
assert.ok(details.recentEvents.some((e) => e.type === "progress" && /отмечен исправленным вручную.*PEP-57/.test((e.payload as { text: string }).text)));
await bugsink.capture(c.api, { ...AMOUNT, release: "g7h8i9" }, new Date(Date.now() + 5000));
assert.equal(bugsink.alerts.at(-1)!.body.alert_reason, "REGRESSED");
const back = await waitIncident(c, "TypeError: amount is undefined", (x) => x.status === "regressed");
assert.equal(back.regressions, 1);
assert.equal(back.lastRelease, "g7h8i9");
const t = await core.resolveTask(db, ref.key);
assert.equal(t.task.status, "backlog");
assert.match(t.task.description!, /Ошибка вернулась .* в релизе g7h8i9 \(повтор №1\)/);
const m = await waitPm("Ошибка вернулась", (x) => x.text.includes(c.key));
assert.ok(m.text.includes(`${ref.key}`));
});
});
describe("Проект-образец SBX: ошибка → инцидент → задача → раннер видит стек", () => {
test("фронт и бэк с SDK (mock-bugsink), политика start, агент читает блок «Инцидент»", async () => {
const p = await project({ turns: [] });
const proj = await core.getProject(db, p.key);
// Task 1 is the project's own; the bug task will be <KEY>-2.
writeFileSync(join(p.dir, ".peppa/mock-scenario.json"), JSON.stringify({ turns: [[{ mcp: "get_task", args: { task: `${p.key}-2` } }, { say: "вижу стек, пишу тест" }]] }));
const r = await runner.connectErrorTracking(db, proj, client, hookBase);
for (const s of r.sources) bugsink.setWebhook(s.bugsinkProjectId, r.webhookUrl);
await core.updateIncidentSettings(db, proj.id, { policy: "start" });
const web = r.sources.find((s) => s.kind === "web")!.bugsinkProjectId;
await bugsink.capture(web, { type: "TypeError", value: "Cannot read properties of undefined (reading 'total')", environment: "prod", release: "sbx001", frames: [{ filename: "app/checkout/page.tsx", function: "Checkout", lineno: 21 }] });
const entry = await p.waitLog("agent read the bug task", (e) => e.ev === "mcp" && e.tool === "get_task");
assert.match(String(entry.text), /## Инцидент/);
assert.match(String(entry.text), /app\/checkout\/page\.tsx:21 in Checkout \[app\]/);
assert.match(String(entry.text), /Релиз: sbx001/);
const t = await core.resolveTask(db, `${p.key}-2`);
await stopSessions(t.task.id);
});
test("живой Bugsink (PEPPA_LIVE_BUGSINK=1): sentry_sdk → Bugsink → вебхук → инцидент → задача", { skip: !LIVE && "set PEPPA_LIVE_BUGSINK=1 with BUGSINK_* in env" }, async () => {
const { bugsinkFromEnv } = await import("@peppa/bugsink");
const real = bugsinkFromEnv()!;
const p = await project({ turns: [] });
const proj = await core.getProject(db, p.key);
const base = `http://host.docker.internal:${(hooks.address() as AddressInfo).port}`;
const liveHooks = await runner.connectErrorTracking(db, proj, real, base);
assert.equal(liveHooks.settings.webhookAuto, true, "webhook configured in the container");
const api = liveHooks.sources.find((s) => s.kind === "api")!;
// The real Python SDK inside the container, DSN pointed at Bugsink itself.
const dsn = api.dsn.replace(/@[^/]+\//, "@localhost:8000/").replace("https://", "http://");
const py = `import sentry_sdk\nsentry_sdk.init(dsn=${JSON.stringify(dsn)}, release="live01", environment="prod", send_default_pii=False)\ndef charge(o):\n return o["amount"] * 2\ntry:\n charge({})\nexcept Exception as e:\n sentry_sdk.capture_exception(e)\nsentry_sdk.flush()`;
execFileSync("docker", ["exec", process.env.BUGSINK_CONTAINER ?? "peppa-bugsink", "python", "-c", py]);
// Live hooks use the real client for enrichment.
const i = await waitFor("live incident", async () => (await core.listIncidents(db, proj.id)).find((x) => x.status === "task"), 40000);
assert.equal(i.title, "KeyError: 'amount'");
assert.equal(i.environment, "prod");
assert.equal(i.lastRelease, "live01");
assert.match(i.stack ?? "", /in charge/);
const r = await runner.resolveIncident(db, i.id, { who: "mock-pm", client: real });
assert.equal(r.bugsinkResolved, true);
});
});
describe("MCP для PM", () => {
test("политика и решения через MCP", async () => {
const { Client } = await import("@modelcontextprotocol/sdk/client/index.js");
const { InMemoryTransport } = await import("@modelcontextprotocol/sdk/inMemory.js");
const { createManagerServer } = await import("@peppa/mcp/manager");
const [a, b] = InMemoryTransport.createLinkedPair();
await createManagerServer(db, pmUser, "https://peppa.test").connect(a);
const mcp = new Client({ name: "mock-chatgpt", version: "0" });
await mcp.connect(b);
const call = async (name: string, args: Record<string, unknown>) => {
const r = await mcp.callTool({ name, arguments: args });
return (r.content as Array<{ text: string }>)[0]!.text;
};
const c = await connected({ policy: "ask" });
assert.match(await call("set_incident_policy", { project: c.key, policy: "triage", triage_prompt: "всё спроси" }), /triage — решает агент-триажёр; prompt: всё спроси/);
assert.match(await call("get_incident_policy", { project: c.key }), /Policy: triage/);
await call("set_incident_policy", { project: c.key, policy: "ask" });
await bugsink.capture(c.api, { ...AMOUNT, value: "via mcp" });
const i = await waitIncident(c, "TypeError: via mcp", (x) => x.status === "pending");
await waitPm("TypeError: via mcp", (m) => /Что делаем\?/.test(m.text)); // the PM has the buttons
assert.match(await call("list_incidents", { project: c.key, status: "pending" }), new RegExp(`#${i.id} \\[pending\\] TypeError: via mcp`));
assert.match(await call("decide_incident", { id: i.id, action: "backlog" }), /created in the backlog/);
assert.match(await call("resolve_incident", { id: i.id }), /Incident #\d+ resolved/);
await waitFor("ask message closed", async () => pmMessages("via mcp").some((m) => m.text.includes("Решено (mock-pm): в бэклог")));
});
});