// Incidents (PEP-58): Bugsink issues seen in Peppa, the project's incident policy settings, // bug tasks made from incidents and their Telegram messages. The policy itself (which may // start a runner) is applied in runner/incidents.ts. import { asIs, m as tr } from "@peppa/shared/i18n"; import { randomBytes } from "node:crypto"; import type { BugsinkIssue } from "@peppa/bugsink"; import { errorSources, incidentPolicies, incidents, incidentSettings, incidentStatuses, projects, telegramOutbox, type Db, type IncidentPolicy } from "@peppa/db"; import { loadEnv } from "@peppa/shared"; import { and, asc, desc, eq, gte, inArray, isNotNull, isNull, like, sql } from "drizzle-orm"; import { PeppaError } from "./errors.ts"; import { notify } from "./notify.ts"; import { createGoal, listGoals, type Project } from "./projects.ts"; import { createTask, type TaskRef } from "./tasks.ts"; import { enqueueTelegram } from "./telegram.ts"; import { deliverToUser, projectAudience } from "./notifications.ts"; export type Incident = typeof incidents.$inferSelect; export type IncidentStatus = Incident["status"]; export type IncidentSettings = typeof incidentSettings.$inferSelect; export type ErrorSource = typeof errorSources.$inferSelect; export type IncidentAction = "notify" | "backlog" | "start" | "ignore"; export { incidentPolicies, incidentStatuses, type IncidentPolicy }; export const INCIDENT_STATUS_RU: Record = { new: tr("новая"), open: tr("без задачи"), pending: tr("ждёт разбора"), task: tr("есть задача"), ignored: tr("игнорируется"), resolved: tr("исправлена"), regressed: tr("вернулась"), }; export const POLICY_RU: Record = { notify: tr("только уведомить"), backlog: tr("задача в бэклог"), start: tr("задача сразу в работу"), ask: tr("спросить в Telegram"), triage: tr("решает агент-триажёр"), }; export const STABILITY_GOAL = "Стабильность"; // ── settings ───────────────────────────────────────────────────────────────────── export async function getIncidentSettings(db: Db, projectId: number): Promise { const [row] = await db.select().from(incidentSettings).where(eq(incidentSettings.projectId, projectId)); return row ?? null; } export async function incidentSettingsBySecret(db: Db, secret: string): Promise { if (!secret || secret.length < 16) return null; const [row] = await db.select().from(incidentSettings).where(eq(incidentSettings.hookSecret, secret)); return row ?? null; } /** Turns error tracking on: webhook secret, default policy and the «Стабильность» epic. */ export async function enableIncidents(db: Db, projectId: number, o: { webhookAuto?: boolean } = {}): Promise { const existing = await getIncidentSettings(db, projectId); if (existing) return existing; const goal = (await listGoals(db, projectId)).find((g) => g.title === STABILITY_GOAL) ?? (await createGoal(db, projectId, STABILITY_GOAL, "Ошибки из работающего продукта: задачи на их исправление создаются в этом эпике.")); const [row] = await db .insert(incidentSettings) .values({ projectId, hookSecret: randomBytes(24).toString("base64url"), goalId: goal.id, webhookAuto: o.webhookAuto ?? false }) .returning(); return row!; } export interface IncidentSettingsPatch { policy?: IncidentPolicy; triagePrompt?: string | null; environments?: string[]; dailyLimit?: number; ignorePattern?: string | null; webhookAuto?: boolean; } export async function updateIncidentSettings(db: Db, projectId: number, patch: IncidentSettingsPatch): Promise { if (!(await getIncidentSettings(db, projectId))) throw new PeppaError(tr("Отслеживание ошибок в проекте не подключено")); if (patch.policy && !incidentPolicies.includes(patch.policy)) throw new PeppaError(tr("Неизвестная политика «{policy}»: {list}", { policy: patch.policy, list: incidentPolicies.join(", ") })); if (patch.ignorePattern) { try { new RegExp(patch.ignorePattern, "i"); } catch { throw new PeppaError(tr("Шаблон игнора — неверное регулярное выражение")); } } if (patch.dailyLimit != null && (!Number.isInteger(patch.dailyLimit) || patch.dailyLimit < 0)) throw new PeppaError(tr("Предел в сутки — целое число ≥ 0")); if (patch.environments) patch.environments = [...new Set(patch.environments.map((e) => e.trim()).filter(Boolean))]; const [row] = await db.update(incidentSettings).set(patch).where(eq(incidentSettings.projectId, projectId)).returning(); return row!; } export async function addErrorSource(db: Db, s: { projectId: number; kind: ErrorSource["kind"]; bugsinkProjectId: number; dsn: string }): Promise { const [row] = await db .insert(errorSources) .values(s) .onConflictDoUpdate({ target: [errorSources.projectId, errorSources.kind], set: { bugsinkProjectId: s.bugsinkProjectId, dsn: s.dsn } }) .returning(); return row!; } export async function listErrorSources(db: Db, projectId?: number): Promise { return db .select() .from(errorSources) .where(projectId != null ? eq(errorSources.projectId, projectId) : undefined) .orderBy(asc(errorSources.projectId), asc(errorSources.kind)); } // ── incidents ──────────────────────────────────────────────────────────────────── export interface IngestResult { incident: Incident; created: boolean; /** A resolved incident came back. */ regressed: boolean; } /** * Records a Bugsink issue (webhook or poll). Idempotent per issue: a repeat updates the * counters of the same incident. Null when the issue's Bugsink project isn't connected. */ export async function ingestIssue(db: Db, i: BugsinkIssue): Promise { const [src] = await db.select().from(errorSources).where(eq(errorSources.bugsinkProjectId, i.bugsinkProjectId)); if (!src) return null; const [old] = await db.select().from(incidents).where(eq(incidents.bugsinkIssueId, i.issueId)); if (!old) { const [row] = await db .insert(incidents) .values({ projectId: src.projectId, source: src.kind, bugsinkIssueId: i.issueId, friendlyId: i.friendlyId, title: i.title, culprit: i.culprit, level: i.level, environment: i.environment, firstRelease: i.release, lastRelease: i.release, events: Math.max(1, i.events), firstSeen: i.firstSeen, lastSeen: i.lastSeen, url: i.url, stack: i.stack, }) .onConflictDoNothing() .returning(); // Lost a race with the other entry point: treat it as a repeat. if (row) { await notify(db, { type: "incident", incidentId: row.id }); return { incident: row, created: true, regressed: false }; } return ingestIssue(db, i); } const newer = i.lastSeen.getTime() > old.lastSeen.getTime(); const regressed = old.status === "resolved" && (i.reason === "REGRESSED" || (!i.isResolved && old.resolvedAt != null && i.lastSeen.getTime() > old.resolvedAt.getTime())); const [row] = await db .update(incidents) .set({ events: Math.max(old.events, i.events), lastSeen: newer ? i.lastSeen : old.lastSeen, lastRelease: newer && i.release ? i.release : old.lastRelease, culprit: old.culprit ?? i.culprit, stack: old.stack ?? i.stack, environment: old.environment ?? i.environment, level: old.level ?? i.level, url: old.url ?? i.url, ...(regressed ? { status: "regressed" as const, regressions: old.regressions + 1 } : {}), }) .where(eq(incidents.id, old.id)) .returning(); if (newer || regressed) await notify(db, { type: "incident", incidentId: old.id }); return { incident: row!, created: false, regressed }; } export async function getIncident(db: Db, id: number): Promise { const [row] = await db.select().from(incidents).where(eq(incidents.id, id)); if (!row) throw new PeppaError(tr("Баг #{id} не найден", { id })); return row; } export async function incidentForTask(db: Db, taskId: number): Promise { const [row] = await db.select().from(incidents).where(eq(incidents.taskId, taskId)).orderBy(desc(incidents.id)).limit(1); return row ?? null; } export async function listIncidents(db: Db, projectId: number, statuses?: IncidentStatus[]): Promise { return db .select() .from(incidents) .where(and(eq(incidents.projectId, projectId), statuses?.length ? inArray(incidents.status, statuses) : undefined)) .orderBy(desc(incidents.lastSeen)) .limit(200); } export async function updateIncident(db: Db, id: number, patch: Partial>): Promise { const [row] = await db.update(incidents).set(patch).where(eq(incidents.id, id)).returning(); if (!row) throw new PeppaError(tr("Баг #{id} не найден", { id })); await notify(db, { type: "incident", incidentId: id }); return row; } /** Takes incidents nobody has applied the policy to yet; each one is returned once (one statement: SQLite runs writers one at a time). */ export async function claimNewIncidents(db: Db, limit = 20): Promise { return db .update(incidents) .set({ status: "pending" }) .where(inArray(incidents.id, sql`(select id from ${incidents} where ${incidents.status} = 'new' order by id limit ${limit})`)) .returning(); } /** Bug tasks created automatically (policy / triage) since local midnight. */ export async function autoIncidentTasksToday(db: Db, projectId: number, now = new Date()): Promise { const midnight = new Date(now); midnight.setHours(0, 0, 0, 0); const [r] = await db .select({ n: sql`count(*)` }) .from(incidents) .where(and(eq(incidents.projectId, projectId), gte(incidents.taskCreatedAt, midnight), inArray(incidents.decidedBy, ["policy", "triage"]))); return r?.n ?? 0; } // ── bug tasks ──────────────────────────────────────────────────────────────────── const clip = (s: string, n: number) => (s.length > n ? `${s.slice(0, n - 1)}…` : s); export function bugTaskTitle(i: Pick): string { return clip(`Ошибка: ${i.title}${i.culprit ? ` (${i.culprit})` : ""}`, 200); } export function bugTaskDescription(i: Incident, reason?: string | null): string { const fmt = (d: Date) => d.toISOString().slice(0, 16).replace("T", " "); const lines = [ `Ошибка из работающего продукта (Bugsink, инцидент #${i.id}).`, "", `- Ошибка: ${i.title}`, `- Место: ${i.culprit ?? "—"}`, `- Источник: ${i.source === "web" ? "фронт (web)" : "бэк (api)"}, окружение: ${i.environment ?? "—"}`, `- Релиз: ${i.lastRelease ?? "—"}${i.firstRelease && i.firstRelease !== i.lastRelease ? ` (впервые в ${i.firstRelease})` : ""}`, `- Событий: ${i.events}, впервые ${fmt(i.firstSeen)}, последний раз ${fmt(i.lastSeen)} UTC`, ]; if (i.url) lines.push(`- Bugsink: ${i.url}`); if (reason) lines.push("", `Решение триажёра: ${reason}`); lines.push("", "Верх стека:", "", "```", i.stack ?? "(стек недоступен — смотри Bugsink)", "```"); lines.push( "", "Условия готовности:", "- воспроизводящий тест (падает на текущем коде с этой ошибкой);", "- исправление, тест зелёный;", "- ошибка не повторяется в новом релизе.", "", "Подробности ошибки: MCP get_incident.", ); return lines.join("\n"); } /** Creates the bug task under «Стабильность» and links it to the incident. */ export async function createBugTask(db: Db, i: Incident, by: NonNullable, reason?: string | null): Promise { const settings = await getIncidentSettings(db, i.projectId); const ref = await createTask(db, { projectId: i.projectId, goalId: settings?.goalId ?? undefined, title: bugTaskTitle(i), description: bugTaskDescription(i, reason), }); await updateIncident(db, i.id, { taskId: ref.task.id, taskCreatedAt: new Date(), status: "task", decidedBy: by }); return ref; } // ── Telegram ───────────────────────────────────────────────────────────────────── const esc = (s: string) => s.replace(/&/g, "&").replace(//g, ">"); export type IncidentMessage = | { kind: "notify" } | { kind: "task"; task: TaskRef; started?: boolean; reason?: string | null } | { kind: "ask"; note?: string | null } | { kind: "regressed"; task?: TaskRef | null }; /** Callback data of the decision buttons: "i::". */ export function incidentButtons(id: number) { return [ [ { text: tr("📥 В бэклог"), callback_data: `i:${id}:backlog` }, { text: tr("▶️ В работу"), callback_data: `i:${id}:start` }, ], [{ text: tr("🙈 Игнорировать"), callback_data: `i:${id}:ignore` }], ]; } export function renderIncidentMessage(project: Pick, i: Incident, m: IncidentMessage, webUrl: string): string { const where = { source: i.source, env: esc(i.environment ?? "—") }; const head = m.kind === "regressed" ? `🔁 ${tr("Ошибка вернулась ({source}, {env})", where)}` : `🐞 ${tr("Новая ошибка ({source}, {env})", where)}`; const lines = [ `${esc(project.key)} · ${head}`, `${asIs(esc(clip(i.title, 300)))}`, [i.culprit && `📍 ${asIs(esc(i.culprit))}`, i.lastRelease && tr("версия {release}", { release: esc(i.lastRelease) }), tr("событий: {n}", { n: i.events })].filter(Boolean).join(" · "), ]; if (i.url) lines.push(`${tr("Подробности ошибки")}`); const taskLink = (t: TaskRef) => `${esc(t.key)}`; if (m.kind === "task") { lines.push("", m.started ? tr("▶️ Агент взялся: {link}", { link: taskLink(m.task) }) : tr("📥 Задача в бэклоге: {link}", { link: taskLink(m.task) })); if (m.reason) lines.push(tr("🤖 Триажёр: {reason}", { reason: asIs(esc(clip(m.reason, 500))) })); } else if (m.kind === "ask") { if (m.note) lines.push("", `${esc(clip(m.note, 500))}`); lines.push("", tr("Что делаем?")); } else if (m.kind === "regressed") { lines.push("", m.task ? tr("Задача {link} снова в бэклоге.", { link: taskLink(m.task) }) : tr("Задачи нет — решите, что делать.")); } else { lines.push("", `${tr("Ошибки проекта")}`); } return lines.join("\n"); } /** Sends an incident message to the project's people by their notification settings (PEP-35). */ export async function sendIncidentMessage(db: Db, i: Incident, m: IncidentMessage): Promise { const audience = await projectAudience(db, i.projectId); if (!audience.length) return 0; const [project] = await db.select().from(projects).where(eq(projects.id, i.projectId)); if (!project) return 0; const text = renderIncidentMessage(project, i, m, loadEnv().PEPPA_WEB_URL); const markup = m.kind === "ask" || (m.kind === "regressed" && !m.task) ? { inline_keyboard: incidentButtons(i.id) } : undefined; const kind = m.kind === "ask" || markup ? "ask" : m.kind; const taskKey = m.kind === "task" ? m.task.key : m.kind === "regressed" ? m.task?.key : null; let sent = 0; for (const u of audience) { const r = await deliverToUser(db, u, { event: "incidents", projectId: i.projectId, dedupeKey: `inc:${i.id}:${kind}:r${i.regressions}:${u.telegramChatId}`, pushKey: `inc:${i.id}:${kind}:r${i.regressions}:u${u.id}`, telegram: { params: { text, parse_mode: "HTML", link_preview_options: { is_disabled: true }, ...(markup ? { reply_markup: markup } : {}) } }, push: { title: m.kind === "regressed" ? tr("Ошибка вернулась в {project}", { project: asIs(project.name) }) : tr("Ошибка в {project}", { project: asIs(project.name) }), body: asIs(clip(i.title, 200)), url: taskKey ? `/t/${taskKey}` : `/p/${project.key}`, tag: `inc:${i.id}`, }, urgency: kind === "ask" ? "high" : "normal", }); if (r.telegram || r.push) sent++; } await notify(db, { type: "incident", incidentId: i.id }); return sent; } /** Closes delivered decision messages: original text + the decision, buttons removed. */ export async function closeIncidentAsks(db: Db, incidentId: number, decision: string): Promise { const sent = await db .select() .from(telegramOutbox) .where(and(like(telegramOutbox.dedupeKey, `inc:${incidentId}:ask:%`), eq(telegramOutbox.status, "sent"), isNotNull(telegramOutbox.telegramMessageId))); for (const row of sent) { await enqueueTelegram(db, { dedupeKey: `${row.dedupeKey}:done`, method: "editMessageText", params: { chat_id: row.params.chat_id, message_id: row.telegramMessageId, text: `${String(row.params.text).replace(/\n\nЧто делаем\?$/, "")}\n\n✅ ${esc(decision)}`, parse_mode: "HTML", link_preview_options: { is_disabled: true }, reply_markup: { inline_keyboard: [] }, }, }); } // Not delivered yet: no point in asking any more. await db .update(telegramOutbox) .set({ status: "sent", error: "decided before delivery" }) .where(and(like(telegramOutbox.dedupeKey, `inc:${incidentId}:ask:%`), eq(telegramOutbox.status, "pending"), eq(telegramOutbox.method, "sendMessage"), isNull(telegramOutbox.telegramMessageId))); await notify(db, { type: "incident", incidentId }); }