From 7fe455e20fcc197b1a903eb328fbda4f1d44c3a3 Mon Sep 17 00:00:00 2001 From: Drewry Pope Date: Sun, 22 Nov 2026 12:05:45 -0600 Subject: [PATCH] =?UTF-8?q?aggregator:=20throat=20healthHook=20extension?= =?UTF-8?q?=20=E2=80=94=20full=20C3=20incident=20record=20in=20the=20alert?= =?UTF-8?q?s=20ledger=20(#12602)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit #12599 decision b: the alerts ledger is the C3 incident record of detail; the events stream stays the thin audit index. - Intake: POST /api/alerts accepts a `healthHook` extension carrying the full incident record (C3 design shape), health-hook source only, validated by a dedicated validator in the validateStackHealth house style (src/health-hook.ts) — malformed = 400 naming the field, before anything is stored. The mutual-exclusion rule is amended for exactly one pairing: healthHook may co-ride with stackHealth (health-hook source only); every other pairing stays exclusive. - Storage (the named ledger slot): the record rides the incident events — the down record on the `opened` event's `detail` (merged into postIncident's opened detail), the recovery record on the `closed` event's `detail` (via closeOpenIncidentByKey / closeIncident). No new tables. - Read projection: new per-incident read GET /api/alerts/:id returns the incident plus its full event history (C6's detail path); the records also ride the existing /api/alerts.json events projection. The #12226 AuditEvent append is untouched and composes in the same stackHealth branch. - Design amendment (same PR): doc note states the two-store contract, the authHealth.status vocabulary resolved|missing| unknown (unknown = the lookup itself could not run; reason in detail), and the title template's as the display name. Tests (oracle: the C3 design record shape / Slice D harness record): test/health-hook.test.ts — validator accept/reject per field, and a store round-trip drill (down + recovery pair reads back from listIncidentEvents with incidentId/recoveryOf lineage and full evidence intact; extension-less posts byte-identical details). Existing alerts suite 55/55 and the health-hook suites pass; typecheck clean. Closes #12602 --- .../note.md | 27 +- pm-stack/aggregator/src/alerts.ts | 40 +- pm-stack/aggregator/src/health-hook.ts | 101 +++++ pm-stack/aggregator/src/server.ts | 58 ++- pm-stack/aggregator/test/health-hook.test.ts | 369 ++++++++++++++++++ 5 files changed, 578 insertions(+), 17 deletions(-) create mode 100644 pm-stack/aggregator/src/health-hook.ts create mode 100644 pm-stack/aggregator/test/health-hook.test.ts diff --git a/doc/2026-11-20T00-46-00Z_design_c3-health-hooks/note.md b/doc/2026-11-20T00-46-00Z_design_c3-health-hooks/note.md index 61644be574..5c2ebe0cc4 100644 --- a/doc/2026-11-20T00-46-00Z_design_c3-health-hooks/note.md +++ b/doc/2026-11-20T00-46-00Z_design_c3-health-hooks/note.md @@ -154,7 +154,8 @@ service-state / reachability to report down. Otherwise `transient`. ### Incident record (event-store shape, C6/C8 contract) Posted to the PM-stack event store via the alert throat (`POST /api/alerts` -with the `stackHealth` extension, source `health-hook`), and also +with the `stackHealth` extension and the full record riding as the +`healthHook` extension, source `health-hook`), and also recorded as an `AuditEvent` (kind `health-hook-incident`) in the events stream. Shape (JSON): @@ -175,7 +176,7 @@ stream. Shape (JSON): "evidence": { "reachability": { "ok": bool, "status": int|null, "error": string|null, "latencyMs": int }, "serviceState": { "unit": string, "activeState": string, "subState": string, "result": string, "exitTimestamp": string|null }, - "authHealth": { "status": "resolved|missing|error", "detail": string }, + "authHealth": { "status": "resolved|missing|unknown", "detail": string }, "recentChanges": { "commits": [string], "deployMarkerMtime": string|null, "gitSyncOk": bool|null }, "hostHealth": { "collectedAt": string|null, "unitsDown": [string] } | null, "sessionLiveness": { "sessionsLastHour": int|null } // opencode-working only @@ -189,6 +190,28 @@ stream. Shape (JSON): `opencode-working` is down, and `info` for recovery. `recoveryOf` links a recovery incident to the down incident it closes (by `incidentId`). +### Where the record lives (two-store contract, #12599 decision b) + +The **alerts ledger** is the record of detail: the throat POST carries +the full record as the `healthHook` extension alongside `stackHealth`, +and the aggregator stores it on the incident's `opened` event `detail` +(a down) and `closed` event `detail` (its recovery), readable per +incident from the alerts read surface (`GET /api/alerts/:id`; the +events also ride `/api/alerts.json`). The **events stream** is the +audit index only: the `AuditEvent` of the append section below carries +kind / ref / summary, never the evidence. The hook-local JSONL file is +the hook's dedup/lineage working state, not a consumer surface — +C6/C8 read the ledger, never the JSONL. + +`authHealth.status` vocabulary is `resolved | missing | unknown`: +`resolved` — the lookup ran and the secret is there; `missing` — the +lookup ran and no secret with that key exists; `unknown` — the lookup +itself could not run, with the reason in `detail`. + +In the title templates above, `` is the target's display name +(e.g. `PM stack reachable`), the same name the `stackHealth` member +carries as `name`. + ### Category-chat note (insert-only, never reads the chat) A one-line note is written to the **PM-health / queues** category chat diff --git a/pm-stack/aggregator/src/alerts.ts b/pm-stack/aggregator/src/alerts.ts index 789602895b..1819247539 100644 --- a/pm-stack/aggregator/src/alerts.ts +++ b/pm-stack/aggregator/src/alerts.ts @@ -497,9 +497,15 @@ export class AlertsStore { * incident_key) WHERE status <> 'closed': a fresh insert opens the * incident (+ `opened` event); a conflict bumps occurrences / * last_seen_at (+ `duplicate_suppressed` event only when a delivery - * would otherwise repeat). + * would otherwise repeat). `openedEventDetail` merges extra members + * into the `opened` event's detail — the `healthHook` incident + * record rides there (#12602: the ledger is the C3 record of + * detail, so the down record lands on the event that opens it). */ - async postIncident(input: NewIncident): Promise<{ incident: Incident; created: boolean }> { + async postIncident( + input: NewIncident, + openedEventDetail?: Record, + ): Promise<{ incident: Incident; created: boolean }> { const inserted = await this.db.query( `insert into alerts.incidents (source, incident_key, severity, title, body) values (${sqlStr(input.source)}, ${sqlStr(input.key)}, ${sqlStr(input.severity)}, ${sqlStr(input.title)}, ${ @@ -509,7 +515,12 @@ export class AlertsStore { returning *`, ); if (inserted[0]) { - await this.addEvent(inserted[0].id, "opened", { source: input.source, key: input.key, severity: input.severity }); + await this.addEvent(inserted[0].id, "opened", { + source: input.source, + key: input.key, + severity: input.severity, + ...openedEventDetail, + }); return { incident: inserted[0], created: true }; } const bumped = await this.db.query( @@ -563,31 +574,46 @@ export class AlertsStore { /** #8568: close the open incident for a (source, key) pair — the * sentinel's "up" transition resolves the incident its "down" post - * opened. Reuses closeIncident for the transition + event. */ + * opened. Reuses closeIncident for the transition + event. + * `closedEventDetail` becomes the `closed` event's detail — the + * `healthHook` recovery record rides there (#12602). */ async closeOpenIncidentByKey( source: string, key: string, + closedEventDetail?: Record, ): Promise<{ incident: Incident | null; transitioned: boolean }> { const rows = await this.db.query( `select * from alerts.incidents where source = ${sqlStr(source)} and incident_key = ${sqlStr(key)} and status <> 'closed' order by first_seen_at limit 1`, ); const open = rows[0]; if (!open) return { incident: null, transitioned: false }; - return this.closeIncident(open.id); + return this.closeIncident(open.id, closedEventDetail); } - async closeIncident(id: string): Promise<{ incident: Incident | null; transitioned: boolean }> { + async closeIncident( + id: string, + closedEventDetail?: Record, + ): Promise<{ incident: Incident | null; transitioned: boolean }> { const rows = await this.db.query( `update alerts.incidents set status = 'closed', closed_at = now() where id = ${sqlStr(id)} and status <> 'closed' returning *`, ); if (rows[0]) { - await this.addEvent(id, "closed", {}); + await this.addEvent(id, "closed", closedEventDetail ?? {}); return { incident: rows[0], transitioned: true }; } return { incident: await this.getIncident(id), transitioned: false }; } + /** Every ledger event for one incident, oldest first — the + * per-incident read behind GET /api/alerts/:id, C6's detail path + * for health-hook incident records (#12602). */ + async listIncidentEvents(incidentId: string): Promise { + return this.db.query( + `select * from alerts.incident_events where incident_id = ${sqlStr(incidentId)} order by id`, + ); + } + async pendingDeliveries(limit = 20): Promise { return this.pendingBatch( "status = 'open' and severity = 'critical' and delivered_at is null", diff --git a/pm-stack/aggregator/src/health-hook.ts b/pm-stack/aggregator/src/health-hook.ts new file mode 100644 index 0000000000..e45d1a2e59 --- /dev/null +++ b/pm-stack/aggregator/src/health-hook.ts @@ -0,0 +1,101 @@ +// C3 health-hook incident records (#12599 decision b, #12602): a +// health hook posts its full incident record to the alert throat as +// the `healthHook` extension (source "health-hook", normally co-riding +// the `stackHealth` extension). The alerts ledger is the record of +// detail: the intake validates the record here and stores it on the +// incident's `opened` / `closed` event detail (see src/alerts.ts); +// the events stream stays the thin audit index (the AuditEvent append +// lives in src/health-hook-audit-event.ts). The record shape is the +// C3 design's "Report format" +// (doc/2026-11-20T00-46-00Z_design_c3-health-hooks/note.md). +import { validateStackHealth, type StackHealthInput } from "./stack-health.ts"; + +export type HealthHookState = "down" | "up" | "transient"; + +/** The full C3 incident record, as stored in the alerts ledger. */ +export interface HealthHookRecord { + target: string; + state: HealthHookState; + caller: string; + /** When the hook fired (ISO), as reported. */ + firedAt: string; + /** When the caller observed the failure (ISO), or null. */ + observedAt: string | null; + incidentId: string; + /** The down incident a recovery closes (its incidentId), or null. */ + recoveryOf: string | null; + /** Structured probe output; members vary by target and evolve with + * the probes, so only the container is validated (see below). */ + evidence: Record; + /** The record's own stackHealth member (same shape the throat's + * stackHealth extension carries), when the poster includes it. */ + stackHealth?: StackHealthInput; +} + +/** + * Validate the intake `healthHook` extension object (C3 design shape). + * Scalar fields are validated strictly, in the validateStackHealth + * house style, and every error names its field. `evidence` is + * validated as an object only: its members are probe-defined + * (reachability / serviceState / authHealth / recentChanges / + * hostHealth / sessionLiveness, plus probe additions such as + * confirmFailure) and must not 400 a poster whose probes evolved. + * Envelope duplicates (source / key / severity / title / body) are + * type-checked when present but not stored — they already live on + * the incident row the post creates. + */ +export function validateHealthHook( + value: unknown, +): { ok: true; value: HealthHookRecord } | { ok: false; error: string } { + if (!value || typeof value !== "object" || Array.isArray(value)) { + return { ok: false, error: "healthHook must be an object" }; + } + const b = value as Record; + for (const field of ["source", "key", "severity", "title", "body"] as const) { + if (b[field] !== undefined && typeof b[field] !== "string") { + return { ok: false, error: `healthHook.${field} must be a string` }; + } + } + const target = typeof b.target === "string" ? b.target.trim() : ""; + if (!target) return { ok: false, error: "healthHook.target required" }; + if (b.state !== "down" && b.state !== "up" && b.state !== "transient") { + return { ok: false, error: 'healthHook.state must be "down" | "up" | "transient"' }; + } + const caller = typeof b.caller === "string" ? b.caller.trim() : ""; + if (!caller) return { ok: false, error: "healthHook.caller required" }; + const firedAt = typeof b.firedAt === "string" ? b.firedAt.trim() : ""; + if (!firedAt) return { ok: false, error: "healthHook.firedAt required" }; + if (b.observedAt === undefined) return { ok: false, error: "healthHook.observedAt required" }; + if (b.observedAt !== null && typeof b.observedAt !== "string") { + return { ok: false, error: "healthHook.observedAt must be a string or null" }; + } + const incidentId = typeof b.incidentId === "string" ? b.incidentId.trim() : ""; + if (!incidentId) return { ok: false, error: "healthHook.incidentId required" }; + if (b.recoveryOf === undefined) return { ok: false, error: "healthHook.recoveryOf required" }; + if (b.recoveryOf !== null && typeof b.recoveryOf !== "string") { + return { ok: false, error: "healthHook.recoveryOf must be a string or null" }; + } + if (!b.evidence || typeof b.evidence !== "object" || Array.isArray(b.evidence)) { + return { ok: false, error: "healthHook.evidence must be an object" }; + } + let stackHealth: StackHealthInput | undefined; + if (b.stackHealth !== undefined) { + const v = validateStackHealth(b.stackHealth); + if (!v.ok) return { ok: false, error: v.error.replace(/^stackHealth/, "healthHook.stackHealth") }; + stackHealth = v.value; + } + return { + ok: true, + value: { + target, + state: b.state, + caller, + firedAt, + observedAt: b.observedAt as string | null, + incidentId, + recoveryOf: b.recoveryOf as string | null, + evidence: b.evidence as Record, + ...(stackHealth ? { stackHealth } : {}), + }, + }; +} diff --git a/pm-stack/aggregator/src/server.ts b/pm-stack/aggregator/src/server.ts index ada2f73ec2..11d33f06cb 100644 --- a/pm-stack/aggregator/src/server.ts +++ b/pm-stack/aggregator/src/server.ts @@ -109,6 +109,7 @@ import { type DecisionEventInput, } from "./decision-events.ts"; import { listStackHealthDown, readStackHealthStates, setStackHealth, validateStackHealth } from "./stack-health.ts"; +import { validateHealthHook, type HealthHookRecord } from "./health-hook.ts"; import { buildHealth, pageRenderHealth, @@ -3702,21 +3703,42 @@ async function handler(req: Request): Promise { const rawBody: unknown = await readJsonBody(req); const parsed = validateNewIncident(rawBody); if (!parsed.ok) return json({ error: parsed.error }, 400); - const { incident, created } = await store.postIncident(parsed.value); - const status = created ? 201 : 200; - // #8568/#8766 producer extensions: exactly one of needsDrew / - // stackHealth / decisionSet may ride an incident post. The incident insert - // above is unchanged; a VALIDATION failure of an extension is a - // 400 (the poster's bug should be loud at the poster), while a - // store failure is logged and never fails the incident post. const ext = rawBody && typeof rawBody === "object" && !Array.isArray(rawBody) ? (rawBody as Record) : {}; const hasNeedsDrew = ext.needsDrew !== undefined; const hasStackHealth = ext.stackHealth !== undefined; const hasDecisionSet = ext.decisionSet !== undefined; + const hasHealthHook = ext.healthHook !== undefined; + // #12602 (#12599 decision b): the healthHook extension carries the + // full C3 incident record to the alerts ledger. It is gated and + // validated BEFORE the incident insert, unlike the extensions + // below, because a valid record rides the insert onto the opened + // event's detail; a malformed one is a 400 naming the field, + // before anything is stored. + let healthHook: HealthHookRecord | undefined; + if (hasHealthHook) { + if (parsed.value.source !== "health-hook") { + return json({ error: 'healthHook extension is only accepted for source "health-hook"' }, 400); + } + const hv = validateHealthHook(ext.healthHook); + if (!hv.ok) return json({ error: hv.error }, 400); + healthHook = hv.value; + } + const { incident, created } = await store.postIncident(parsed.value, healthHook ? { healthHook } : undefined); + const status = created ? 201 : 200; + // #8568/#8766 producer extensions: exactly one of needsDrew / + // stackHealth / decisionSet may ride an incident post; #12602 adds + // healthHook, which may co-ride with stackHealth (health-hook + // source only, gated above) and with nothing else. A VALIDATION + // failure of an extension is a 400 (the poster's bug should be + // loud at the poster), while a store failure is logged and never + // fails the incident post. if ([hasNeedsDrew, hasStackHealth, hasDecisionSet].filter(Boolean).length > 1) { return json({ error: "needsDrew, stackHealth and decisionSet extensions are mutually exclusive" }, 400); } + if (hasHealthHook && (hasNeedsDrew || hasDecisionSet)) { + return json({ error: "healthHook extension may only co-ride with stackHealth" }, 400); + } if (hasNeedsDrew) { const v = validateNeedsDrew(ext.needsDrew); if (!v.ok) return json({ error: v.error }, 400); @@ -3750,7 +3772,13 @@ async function handler(req: Request): Promise { } } if (v.value.state === "up") { - await store.closeOpenIncidentByKey(parsed.value.source, parsed.value.key); + // #12602: a healthHook recovery record rides the closed + // event's detail of the incident it closes. + await store.closeOpenIncidentByKey( + parsed.value.source, + parsed.value.key, + healthHook?.state === "up" ? { healthHook } : undefined, + ); } requestAlertTick(); } catch (err) { @@ -4242,6 +4270,20 @@ async function handler(req: Request): Promise { if (!result.incident) return json({ error: "no such incident", id }, 404); return json({ incident: result.incident, transitioned: result.transitioned }); } + // Per-incident read (#12602): the incident plus its full ledger + // event history — C6's detail path for the healthHook incident + // records stored on the opened/closed event details. + const alertReadMatch = /^\/api\/alerts\/([\w-]+)$/.exec(path); + if (req.method === "GET" && alertReadMatch) { + const id = alertReadMatch[1]; + if (!UUID_RE.test(id)) return json({ error: "incident id must be a uuid" }, 400); + const store = await getAlertsStore(); + if (!store) return json({ error: "alerts store unavailable" }, 503); + const incident = await store.getIncident(id); + if (!incident) return json({ error: "no such incident", id }, 404); + const events = await store.listIncidentEvents(id); + return json({ incident, events }); + } if (path === "/alerts" || path === "/api/alerts.json") { const store = await getAlertsStore(); if (!store) { diff --git a/pm-stack/aggregator/test/health-hook.test.ts b/pm-stack/aggregator/test/health-hook.test.ts new file mode 100644 index 0000000000..3618d99bbc --- /dev/null +++ b/pm-stack/aggregator/test/health-hook.test.ts @@ -0,0 +1,369 @@ +import { describe, expect, test } from "bun:test"; +import { AlertsStore, type Incident, type IncidentEvent } from "../src/alerts.ts"; +import { validateHealthHook, type HealthHookRecord } from "../src/health-hook.ts"; +import type { SqlClient } from "../src/sql-client.ts"; + +// Oracle: the C3 design's incident-record shape +// (doc/2026-11-20T00-46-00Z_design_c3-health-hooks/note.md, "Report +// format"), in the exact shape the runner (pm-stack/health-hooks/ +// run.py) builds it — the Slice D harness record. The down record +// below is that shape verbatim, envelope fields included. +const downPost = { + source: "health-hook", + key: "health-hook:pm-stack-reachable:11111111-1111-4111-8111-111111111111", + severity: "critical", + title: "Health hook: PM stack reachable is down", + body: "PM stack unreachable: connect ECONNREFUSED", + target: "pm-stack-reachable", + state: "down", + caller: "lane-launch", + firedAt: "2026-11-22T10:00:00Z", + observedAt: "2026-11-22T09:59:58Z", + incidentId: "11111111-1111-4111-8111-111111111111", + recoveryOf: null, + evidence: { + confirmFailure: true, + reachability: { + ok: false, + status: null, + error: "connect ECONNREFUSED", + latencyMs: 12, + tcpOk: false, + tcpError: "connect ECONNREFUSED", + }, + serviceState: { + unit: "pm-aggregator", + activeState: "failed", + subState: "failed", + result: "exit-code", + exitTimestamp: "2026-11-22T09:58:00Z", + }, + authHealth: { status: "resolved", detail: "secret resolved by key" }, + recentChanges: { commits: ["abc1234 fix"], gitOk: true, deployMarkerMtime: null, gitSyncOk: null }, + hostHealth: { collectedAt: "2026-11-22T09:55:00Z", unitsDown: ["pm-aggregator"], present: true }, + }, + stackHealth: { + serviceId: "pm-stack-reachable", + name: "PM stack reachable", + state: "down", + since: "2026-11-22T10:00:00Z", + detail: "PM stack unreachable: connect ECONNREFUSED", + }, +} as const; + +const recoveryPost = { + ...downPost, + severity: "info", + title: "Health hook: PM stack reachable recovered", + body: "PM stack reachable recovered after incident 11111111-1111-4111-8111-111111111111", + state: "up", + firedAt: "2026-11-22T10:07:00Z", + observedAt: null, + incidentId: "22222222-2222-4222-8222-222222222222", + recoveryOf: "11111111-1111-4111-8111-111111111111", + evidence: { + confirmFailure: false, + reachability: { ok: true, status: 200, error: null, latencyMs: 30, tcpOk: true, tcpError: null }, + serviceState: { + unit: "pm-aggregator", + activeState: "active", + subState: "running", + result: "success", + exitTimestamp: null, + }, + authHealth: { status: "resolved", detail: "secret resolved by key" }, + recentChanges: { commits: ["abc1234 fix"], gitOk: true, deployMarkerMtime: null, gitSyncOk: null }, + hostHealth: { collectedAt: "2026-11-22T10:05:00Z", unitsDown: [], present: true }, + }, + stackHealth: { + serviceId: "pm-stack-reachable", + name: "PM stack reachable", + state: "up", + since: "2026-11-22T10:07:00Z", + detail: "PM stack reachable recovered after incident 11111111-1111-4111-8111-111111111111", + }, +}; + +describe("validateHealthHook (oracle: C3 design record shape)", () => { + test("a Slice D-shaped down record validates and normalizes", () => { + const v = validateHealthHook(downPost); + expect(v.ok).toBe(true); + if (!v.ok) return; + expect(v.value.target).toBe("pm-stack-reachable"); + expect(v.value.state).toBe("down"); + expect(v.value.incidentId).toBe(downPost.incidentId); + expect(v.value.recoveryOf).toBeNull(); + expect(v.value.evidence).toEqual(downPost.evidence); + expect(v.value.stackHealth).toEqual(downPost.stackHealth); + // Envelope duplicates live on the incident row, not the record. + expect(v.value).not.toHaveProperty("source"); + expect(v.value).not.toHaveProperty("title"); + }); + + test("a recovery record validates with its recoveryOf lineage", () => { + const v = validateHealthHook(recoveryPost); + expect(v.ok).toBe(true); + if (!v.ok) return; + expect(v.value.state).toBe("up"); + expect(v.value.recoveryOf).toBe(downPost.incidentId); + expect(v.value.observedAt).toBeNull(); + }); + + test("a record without the stackHealth member still validates", () => { + const { stackHealth: _drop, ...rest } = downPost; + const v = validateHealthHook(rest); + expect(v.ok).toBe(true); + if (!v.ok) return; + expect(v.value.stackHealth).toBeUndefined(); + }); + + test("malformed records are rejected with the field named", () => { + const cases: Array<[unknown, string]> = [ + [null, "healthHook must be an object"], + [[], "healthHook must be an object"], + [{ ...downPost, target: " " }, "healthHook.target required"], + [{ ...downPost, target: undefined }, "healthHook.target required"], + [{ ...downPost, state: "sideways" }, 'healthHook.state must be "down" | "up" | "transient"'], + [{ ...downPost, caller: "" }, "healthHook.caller required"], + [{ ...downPost, firedAt: 42 }, "healthHook.firedAt required"], + [{ ...downPost, incidentId: "" }, "healthHook.incidentId required"], + [{ ...downPost, observedAt: undefined }, "healthHook.observedAt required"], + [{ ...downPost, observedAt: 42 }, "healthHook.observedAt must be a string or null"], + [{ ...downPost, recoveryOf: undefined }, "healthHook.recoveryOf required"], + [{ ...downPost, recoveryOf: 7 }, "healthHook.recoveryOf must be a string or null"], + [{ ...downPost, evidence: [] }, "healthHook.evidence must be an object"], + [{ ...downPost, evidence: undefined }, "healthHook.evidence must be an object"], + [{ ...downPost, title: 3 }, "healthHook.title must be a string"], + [ + { ...downPost, stackHealth: { ...downPost.stackHealth, state: "sideways" } }, + 'healthHook.stackHealth.state must be "down" | "up"', + ], + ]; + for (const [input, error] of cases) { + const v = validateHealthHook(input); + expect(v.ok).toBe(false); + if (!v.ok) expect(v.error).toBe(error); + } + }); + + test("evidence members are not deep-validated (probe shapes evolve)", () => { + const v = validateHealthHook({ + ...downPost, + evidence: { brandNewProbe: { nested: [1, 2, 3] }, authHealth: { status: "error", detail: "boom" } }, + }); + expect(v.ok).toBe(true); + }); +}); + +// --- Store round-trip (oracle: #12602 acceptance — a drill down + +// recovery pair reads back with incidentId/recoveryOf lineage and +// full evidence intact). The fake implements exactly the statements +// AlertsStore issues for post / close-by-key / per-incident events, +// parsing the sqlStr/sqlJson literals the store builds. + +function parseValues(sql: string, count: number): Array { + const start = sql.indexOf("values (") + "values (".length; + const out: Array = []; + let i = start; + while (out.length < count) { + while (sql[i] === " " || sql[i] === "\n" || sql[i] === ",") i++; + if (sql.startsWith("null", i)) { + out.push(null); + i += 4; + continue; + } + if (sql[i] !== "'") throw new Error(`fake db: expected literal at ${i} in: ${sql}`); + let val = ""; + i++; + while (i < sql.length) { + if (sql[i] === "'") { + if (sql[i + 1] === "'") { + val += "'"; + i += 2; + continue; + } + i++; + break; + } + val += sql[i]; + i++; + } + out.push(val); + } + return out; +} + +function allLiterals(sql: string): string[] { + const out: string[] = []; + let i = 0; + while (i < sql.length) { + if (sql[i] !== "'") { + i++; + continue; + } + let val = ""; + i++; + while (i < sql.length) { + if (sql[i] === "'") { + if (sql[i + 1] === "'") { + val += "'"; + i += 2; + continue; + } + i++; + break; + } + val += sql[i]; + i++; + } + out.push(val); + } + return out; +} + +function fakeAlertsDb() { + const incidents: Incident[] = []; + const events: IncidentEvent[] = []; + let incidentSeq = 0; + let eventSeq = 0; + let clock = 0; + const now = () => `2026-11-22T10:00:${String(clock++).padStart(2, "0")}Z`; + const db: SqlClient = { + ref: "fake", + async query(sql: string): Promise { + const flat = sql.trim().replace(/\s+/g, " "); + if (flat.startsWith("insert into alerts.incidents")) { + const [source, key, severity, title, body] = parseValues(sql, 5); + if (incidents.some((r) => r.source === source && r.incident_key === key && r.status !== "closed")) { + return []; + } + const row: Incident = { + id: `00000000-0000-4000-8000-${String(++incidentSeq).padStart(12, "0")}`, + source: source!, + incident_key: key!, + severity: severity as Incident["severity"], + title: title!, + body, + status: "open", + first_seen_at: now(), + last_seen_at: now(), + delivered_at: null, + escalated_at: null, + acked_at: null, + closed_at: null, + occurrences: 1, + }; + incidents.push(row); + return [row] as T[]; + } + if (flat.startsWith("insert into alerts.incident_events")) { + const [incidentId, kind, detailJson] = parseValues(sql, 3); + events.push({ + id: ++eventSeq, + incident_id: incidentId!, + at: now(), + kind: kind as IncidentEvent["kind"], + detail: detailJson ? (JSON.parse(detailJson) as Record) : null, + }); + return []; + } + if (flat.startsWith("update alerts.incidents set occurrences")) { + const [source, key] = allLiterals(sql); + const row = incidents.find((r) => r.source === source && r.incident_key === key && r.status !== "closed"); + if (!row) return []; + row.occurrences += 1; + row.last_seen_at = now(); + return [row] as T[]; + } + if (flat.startsWith("update alerts.incidents set status = 'closed'")) { + const id = allLiterals(sql)[1]; + const row = incidents.find((r) => r.id === id && r.status !== "closed"); + if (!row) return []; + row.status = "closed"; + row.closed_at = now(); + return [row] as T[]; + } + if (flat.startsWith("select * from alerts.incidents where id =")) { + const [id] = allLiterals(sql); + return incidents.filter((r) => r.id === id) as T[]; + } + if (flat.startsWith("select * from alerts.incidents where source =")) { + const [source, key] = allLiterals(sql); + return incidents.filter((r) => r.source === source && r.incident_key === key && r.status !== "closed") as T[]; + } + if (flat.startsWith("select * from alerts.incident_events where incident_id =")) { + const [id] = allLiterals(sql); + return events.filter((e) => e.incident_id === id) as T[]; + } + throw new Error(`fake db: unexpected query: ${flat}`); + }, + }; + return { db, incidents, events }; +} + +describe("healthHook ledger storage (oracle: #12602 acceptance drill)", () => { + const key = downPost.key; + const downRecord = (validateHealthHook(downPost) as { ok: true; value: HealthHookRecord }).value; + const recoveryRecord = (validateHealthHook(recoveryPost) as { ok: true; value: HealthHookRecord }).value; + + test("a down + recovery pair stores both records against the incident, lineage intact", async () => { + const { db } = fakeAlertsDb(); + const store = new AlertsStore(db); + + const down = await store.postIncident( + { source: "health-hook", key, severity: "critical", title: downPost.title, body: downPost.body }, + { healthHook: downRecord }, + ); + expect(down.created).toBe(true); + + let events = await store.listIncidentEvents(down.incident.id); + expect(events.map((e) => e.kind)).toEqual(["opened"]); + expect(events[0].detail?.healthHook).toEqual(downRecord); + // The opened detail's pre-existing members are unchanged. + expect(events[0].detail?.source).toBe("health-hook"); + expect(events[0].detail?.key).toBe(key); + expect(events[0].detail?.severity).toBe("critical"); + + // The recovery post reuses the outage key (runner behaviour), so + // it dedupes onto the same incident instead of opening a second. + const recovery = await store.postIncident( + { source: "health-hook", key, severity: "info", title: recoveryPost.title, body: recoveryPost.body }, + { healthHook: recoveryRecord }, + ); + expect(recovery.created).toBe(false); + expect(recovery.incident.id).toBe(down.incident.id); + + const closed = await store.closeOpenIncidentByKey("health-hook", key, { healthHook: recoveryRecord }); + expect(closed.transitioned).toBe(true); + expect(closed.incident?.status).toBe("closed"); + + events = await store.listIncidentEvents(down.incident.id); + expect(events.map((e) => e.kind)).toEqual(["opened", "closed"]); + const storedRecovery = events[1].detail?.healthHook as HealthHookRecord; + expect(storedRecovery.recoveryOf).toBe(downRecord.incidentId); + expect(storedRecovery.incidentId).toBe(recoveryRecord.incidentId); + expect(storedRecovery.evidence).toEqual(recoveryRecord.evidence); + }); + + test("posts without the extension keep the opened/closed details unchanged", async () => { + const { db } = fakeAlertsDb(); + const store = new AlertsStore(db); + const posted = await store.postIncident({ source: "stack-sentinel", key: "k1", severity: "warning", title: "t" }); + const closed = await store.closeIncident(posted.incident.id); + expect(closed.transitioned).toBe(true); + const events = await store.listIncidentEvents(posted.incident.id); + expect(events.map((e) => e.kind)).toEqual(["opened", "closed"]); + expect(events[0].detail).toEqual({ source: "stack-sentinel", key: "k1", severity: "warning" }); + expect(events[1].detail).toEqual({}); + }); + + test("listIncidentEvents returns only the incident's own events", async () => { + const { db } = fakeAlertsDb(); + const store = new AlertsStore(db); + const a = await store.postIncident({ source: "s", key: "a", severity: "info", title: "a" }); + await store.postIncident({ source: "s", key: "b", severity: "info", title: "b" }); + const events = await store.listIncidentEvents(a.incident.id); + expect(events).toHaveLength(1); + expect(events[0].incident_id).toBe(a.incident.id); + }); +});