Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
27 changes: 25 additions & 2 deletions doc/2026-11-20T00-46-00Z_design_c3-health-hooks/note.md
Original file line number Diff line number Diff line change
Expand Up @@ -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):

Expand All @@ -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
Expand All @@ -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, `<target>` 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
Expand Down
40 changes: 33 additions & 7 deletions pm-stack/aggregator/src/alerts.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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<string, unknown>,
): Promise<{ incident: Incident; created: boolean }> {
const inserted = await this.db.query<Incident>(
`insert into alerts.incidents (source, incident_key, severity, title, body)
values (${sqlStr(input.source)}, ${sqlStr(input.key)}, ${sqlStr(input.severity)}, ${sqlStr(input.title)}, ${
Expand All @@ -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<Incident>(
Expand Down Expand Up @@ -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<string, unknown>,
): Promise<{ incident: Incident | null; transitioned: boolean }> {
const rows = await this.db.query<Incident>(
`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<string, unknown>,
): Promise<{ incident: Incident | null; transitioned: boolean }> {
const rows = await this.db.query<Incident>(
`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<IncidentEvent[]> {
return this.db.query<IncidentEvent>(
`select * from alerts.incident_events where incident_id = ${sqlStr(incidentId)} order by id`,
);
}

async pendingDeliveries(limit = 20): Promise<Incident[]> {
return this.pendingBatch(
"status = 'open' and severity = 'critical' and delivered_at is null",
Expand Down
101 changes: 101 additions & 0 deletions pm-stack/aggregator/src/health-hook.ts
Original file line number Diff line number Diff line change
@@ -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<string, unknown>;
/** 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<string, unknown>;
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<string, unknown>,
...(stackHealth ? { stackHealth } : {}),
},
};
}
58 changes: 50 additions & 8 deletions pm-stack/aggregator/src/server.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down Expand Up @@ -3702,21 +3703,42 @@ async function handler(req: Request): Promise<Response> {
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<string, unknown>) : {};
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);
Expand Down Expand Up @@ -3750,7 +3772,13 @@ async function handler(req: Request): Promise<Response> {
}
}
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) {
Expand Down Expand Up @@ -4242,6 +4270,20 @@ async function handler(req: Request): Promise<Response> {
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) {
Expand Down
Loading