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 new file mode 100644 index 0000000000..7d5e148b15 --- /dev/null +++ b/doc/2026-11-20T00-46-00Z_design_c3-health-hooks/note.md @@ -0,0 +1,280 @@ +# C3 — Health hooks: failure-triggered checks that troubleshoot and report + +Status: **draft (design-first slice for queue task 20429 / issue #9571). +Statement S1.3 of the reporting-architecture programme (starter epic +#9568). Successor to the disabled `opencode-session-minder` detection +role: hooks, not a revived cron.** + +## Request and intent + +Drew's directive, Reports side chat, 2026-11-13 09:11 CST (Thread 1): +"PM stack reachable" and "OpenCode working" stop being interval polls and +become **hook scripts that fire on failure-to-connect** from any caller. +On a failed connect the hook fires immediately, runs a bounded read-only +troubleshoot sequence (reachability, service state, auth/credential +health, recent changes), and **reports what occurred** — a note to the +queues/PM-health category chat, escalating to Reports when it is an +exception and to the main chat when Drew is blocked. The hook records the +incident into the PM-stack event store so C6 can render an incident page +and C8 can ingest it (first-appearance data for error strings starts +here). Recovery is also an event: the same hook reports the recovery (the +watchdog's new-alert/recovery pattern, event-driven). + +This component is the **successor to the disabled `opencode-session-minder`** +detection role — it closes the detection gap left by that disabled monitor +(no durable monitor covered sessions after 2026-11-08) by trigger, not by +schedule. `fleet-watchdog` / `fleet-minder` keep their current duties +until the hooks prove out; this design names the overlap and the cutover +test. + +## Boundaries / collisions (held) + +- **Hooks, not a revived cron.** No interval polling is added by this + component; the existing `stack-sentinel` (30 s probe loop) and + `fleet-watchdog` remain as-is until the cutover test passes. +- **Read-only probes first.** Troubleshoot actions are bounded and named; + no state-changing remediation ships in this component. Remediation is a + separate, gated design decision. +- **No C6 / C8 implementation.** This component only owes the incident + record shape those consumers read. +- **No retirement** of `fleet-watchdog` / `fleet-minder` before the hooks + prove out and the cutover test passes. + +## Trigger surface + +### What counts as failure-to-connect + +A *failure-to-connect* is any attempt by a caller to reach a monitored +target that does not yield the target's "alive" answer within the +target's timeout. Concretely, per target: + +| Target id | Monitored surface | Alive answer | Timeout | +|-----------|-------------------|--------------|---------| +| `pm-stack-reachable` | aggregator HTTP API (`$ALERTS_INTAKE_URL` / board) | HTTP 2xx | 10 s | +| `opencode-working` | OpenCode global health (`http://127.0.0.1:13420/global/health`) | HTTP 200 | 10 s | + +A *connect* is any of: an HTTP fetch that throws or times out, an HTTP +response outside the alive set, or a caller-reported failure (a lane +launch, an aggregator tick, a PM-stack surface) that names the target as +unreachable. The hook is **caller-agnostic**: any caller may invoke it; +the hook dedupes by `(target, incident key)` so a storm of callers does +not produce a storm of incidents. + +### Who calls the hooks + +1. **The stack sentinel** (`pm-stack/aggregator/scripts/stack-sentinel.ts`) + — on a 3-consecutive-failure transition (existing damping), instead of + only posting a `stackHealth` transition, it also fires the matching + hook. This is the primary trigger. +2. **Lane launchers** (`ready-for-agent` / `opencode-claimant`) — when a + lane cannot reach the aggregator or OpenCode at launch, they fire the + hook with `caller=lane-launch`. +3. **Aggregator ticks** — when an aggregator source reports the target + unreachable during a refresh, it fires the hook with + `caller=aggregator-tick`. +4. **PM-stack surfaces** (board, pages) — when a browser/API client + reports the target unreachable, it fires the hook with + `caller=pm-surface`. + +Callers invoke the hook **asynchronously and fire-and-forget**: a hook +failure never blocks the caller. Callers pass `{ target, caller, +observedAt, detail }`; the hook owns dedup, probing, reporting, and +recording. + +### Hook entry points + +Two hook scripts, one per target, sharing one implementation module: + +- `pm-stack/health-hooks/pm-stack-reachable.sh` (or `.py`) — fires on + `pm-stack-reachable` failure-to-connect. +- `pm-stack/health-hooks/opencode-working.sh` (or `.py`) — fires on + `opencode-working` failure-to-connect. + +Plus a shared runner `pm-stack/health-hooks/run.py` that takes +`--target {pm-stack-reachable,opencode-working}` and the caller context +on stdin/args. Shell wrappers exist so any caller (systemd, lane, cron) +can invoke them uniformly. + +## Bounded read-only probe sequence + +Each hook, on fire, runs this fixed sequence. Every step is read-only; +no step mutates state. Each step has a hard timeout; the whole sequence +is capped at 60 s. + +### Common prelude (both targets) + +1. **Confirm the failure** — re-probe the target once (same alive answer, + 5 s timeout). If it now answers, record a *transient* outcome and + exit (no incident, no report). This absorbs single slow probes. +2. **Timestamp + caller** — capture `firedAt` (ISO, UTC), `caller`, + `observedAt` (caller's observation), `target`. + +### `pm-stack-reachable` probe sequence + +3. **Reachability** — DNS resolve + TCP connect to the aggregator host/port; + HTTP GET `/board` with 5 s timeout; record status code or error string. +4. **Service state** — `systemctl --user is-active pm-aggregator` (and the + matching `.service`); record `ActiveState`, `SubState`, `Result`, + `ExecMainExitTimestamp`. If systemd is unavailable, record `unknown` + with reason (never invent healthy). +5. **Auth / credential health** — verify the alerts-intake bearer resolves + by name from Bitwarden Secrets Manager (`pm-aggregator.alerts-intake-token`); + record `resolved | missing | error:` (never print the secret). +6. **Recent changes** — last 5 git commits on `main` in `~/git/code` + (`git log --oneline -5`); the deploy marker file mtime if present; + whether `pm-git-sync` last run succeeded (from host-health snapshot). +7. **Host-health snapshot** — read `~/.local/state/pm-aggregator/host-health.json` + if present; record its `collectedAt` and any unit reported down. + +### `opencode-working` probe sequence + +3. **Reachability** — TCP connect to `127.0.0.1:13420`; HTTP GET + `/global/health`; record status or error. +4. **Service state** — `systemctl --user is-active opencode` (or the + opencode service unit name in use); record ActiveState/SubState/Result. + If no user unit exists, record `no-unit` (not `unknown`). +5. **Auth / credential health** — OpenCode's own health endpoint returns + the model route; record the declared route ref from + `.opencode/opencode.jsonc` default model (read-only, no secret). +6. **Recent changes** — last 5 git commits on `main`; whether a recent + deploy/merge landed in the last 15 min (from git log timestamps). +7. **Session liveness** — count of opencode sessions in the last hour from + the session store if readable; otherwise `unknown` with reason. + +### Sequence terminator + +After the probes, the hook computes a **verdict**: +`{ target, state: "down" | "transient" | "up", summary, evidence }` +where `evidence` is the structured probe output. `down` requires the +confirm-failure probe (step 1) to have failed AND at least one of +service-state / reachability to report down. Otherwise `transient`. + +## Report format + +### 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 +recorded as an `AuditEvent` (kind `health-hook-incident`) in the events +stream. Shape (JSON): + +```json +{ + "source": "health-hook", + "key": "health-hook::", + "severity": "critical | warning | info", + "title": "Health hook: is down" | "Health hook: recovered", + "body": "", + "target": "pm-stack-reachable | opencode-working", + "state": "down | up | transient", + "caller": "", + "firedAt": "", + "observedAt": "", + "incidentId": "", + "recoveryOf": "", + "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 }, + "recentChanges": { "commits": [string], "deployMarkerMtime": string|null, "gitSyncOk": bool|null }, + "hostHealth": { "collectedAt": string|null, "unitsDown": [string] } | null, + "sessionLiveness": { "sessionsLastHour": int|null } // opencode-working only + }, + "stackHealth": { "serviceId": "", "name": "", "state": "down|up", "since": "", "detail": "" } +} +``` + +`severity` uses the alert intake's accepted vocabulary: `critical` when +`pm-stack-reachable` is down (Drew is blocked), `warning` when +`opencode-working` is down, and `info` for recovery. `recoveryOf` links a +recovery incident to the down incident it closes (by `incidentId`). + +### Category-chat note (insert-only, never reads the chat) + +A one-line note is written to the **PM-health / queues** category chat +(Muse `msg` with `deliver: "none"` so it is recorded, not woken): + +``` +health-hook @ caller= incident= — +``` + +Escalation: +- **Exception** (target down AND not a known-flap per damping) → also + note to **Reports** category chat. +- **Drew blocked** (`pm-stack-reachable` down) → also note to **main chat** + (the `page-health-push` precedent). +- **Recovery** → note to PM-health only, plus Reports if the down was + escalated to Reports. + +### Event-store append (audit) + +The incident is appended to the events stream as an `AuditEvent`: +`kind = "health-hook-incident"`, `ref = "health-hook:"`, +`actor = "health-hook"`, `summary = `, attribution confidence +`unknown`/`asserted=false` (automated, not authenticated), source +identity `health-hook/<target>`. Retention follows the events stream +contract (30 days / 5000). + +## Escalation rules + +| Condition | PM-health note | Reports note | Main chat | +|-----------|---------------|--------------|-----------| +| target down, first occurrence | yes | no | no | +| target down, exception (not a known flap; damping confirms) | yes | yes | only if pm-stack-reachable | +| target down, Drew blocked (pm-stack-reachable) | yes | yes | yes | +| recovery (after a recorded down) | yes | yes if down was escalated | no | +| transient (confirm-failure passed) | no | no | no | + +Flap damping: a target flips to `down` only after 3 consecutive failed +hook firings within 5 minutes (reusing `src/sentinel-damping.ts` +semantics). A single firing records a *pending* incident that is +upgraded to a real incident on the 3rd consecutive failure; transient +firings in between reset the streak. Recovery posts only after a down +was actually posted. + +## Cutover test (overlap with fleet-watchdog / fleet-minder) + +The hooks prove out when, for **14 consecutive days**: +1. Every `pm-stack-reachable` and `opencode-working` down recorded by + `fleet-watchdog` is also recorded by the corresponding hook within + 60 s of the first caller failure, with matching `incidentId` lineage. +2. No false-positive hook incidents (transient probe that later + confirms up) are escalated to Reports or main chat. +3. The events stream contains at least one real failure + recovery cycle + per target with the full evidence shape above. + +Only after (1)–(3) hold may `fleet-watchdog`'s HTTP-probe duties for +these two targets be retired (its other duties remain). Retirement is a +separate, gated change with its own PR and Drew approval. + +## Implementation plan (slices) + +Slice A (this PR, design only): this document + the incident-record +shape + escalation table. No code. + +Slice B: shared runner `pm-stack/health-hooks/run.py` + shell wrappers; +common prelude + `pm-stack-reachable` probe sequence; wired into the +stack sentinel's transition path. Plus one recorded failure + recovery +cycle in a test fixture. + +Slice C: `opencode-working` probe sequence + wiring into lane launchers +and aggregator ticks. + +Slice D: real failure + recovery cycles recorded end-to-end in the event +store; verification against C6/C8 consumers. + +## Open questions + +1. Should hook firings from lane launchers be rate-limited per-caller, + or is the global dedup by `(target, incident key)` sufficient? + (Recommendation: global dedup is sufficient; per-caller rate limiting + adds state without benefit.) +2. Does the `incidentId` lineage need to survive process restarts? The + events stream is the source of truth; the hook reads the latest open + incident for the target from the stream to set `recoveryOf`. (Yes — + read from the stream, do not keep in-memory.) +3. Where do hook scripts live for non-laptop callers (Cloudflare Workers)? + Out of scope for V1; V1 hooks are laptop-local. Cloudflare-side + triggers are a C2 concern. +4. Is 60 s for the whole sequence too tight under load average 8–10? + Recommend measuring in Slice B and raising to 90 s if needed. diff --git a/pm-stack/aggregator/scripts/stack-sentinel.ts b/pm-stack/aggregator/scripts/stack-sentinel.ts index 3cee9d64a8..2f3437c091 100644 --- a/pm-stack/aggregator/scripts/stack-sentinel.ts +++ b/pm-stack/aggregator/scripts/stack-sentinel.ts @@ -34,6 +34,7 @@ import { dirname, join } from "node:path"; import { resolveBwsSecret } from "../src/secrets.ts"; import { applySentinelProbe, normalizeSentinelEntry, type SentinelServiceEntry } from "../src/sentinel-damping.ts"; import { checkPrimaryCheckout } from "../src/primary-checkout.ts"; +import { normalizeHookDispatchState, shouldDispatchHealthHook, type HealthHookState } from "../src/health-hook-dispatch.ts"; const LOOP_MS = 30_000; @@ -97,6 +98,8 @@ const LOCAL_CHECKS: LocalCheck[] = [ interface SentinelStateFile { services: Record<string, SentinelServiceEntry>; + /** Last C3 hook transition successfully spawned, independent of alert delivery. */ + hookDispatchedStates: Record<string, HealthHookState>; } const STATE_FILE = @@ -117,12 +120,15 @@ async function loadState(): Promise<SentinelStateFile> { const entry = normalizeSentinelEntry(raw); if (entry) services[id] = entry; } - return { services }; + return { + services, + hookDispatchedStates: normalizeHookDispatchState((parsed as Partial<SentinelStateFile>).hookDispatchedStates), + }; } } catch { // no state yet — first run } - return { services: {} }; + return { services: {}, hookDispatchedStates: {} }; } async function saveState(state: SentinelStateFile): Promise<void> { @@ -180,6 +186,11 @@ async function postTransition( } } +// A hook still running for a target holds that target's next dispatch: +// a slow down diagnostic must finish before its recovery runs, or the +// recovery finds no open incident and the late outage is never closed. +const runningHooks = new Map<string, { exitCode: number | null }>(); + async function round(state: SentinelStateFile): Promise<void> { const base = (process.env.ALERTS_INTAKE_URL ?? "http://127.0.0.1:4870").replace(/\/+$/, ""); let token: string | null = null; @@ -191,6 +202,33 @@ async function round(state: SentinelStateFile): Promise<void> { // the failure streak recorded on the entry. const entry = applySentinelProbe(state.services[target.id], verdict, now); state.services[target.id] = entry; + // C3 health hooks: fire the matching failure-triggered hook on a + // transition for the two monitored targets. Fire-and-forget; a hook + // failure never blocks the sentinel round. + const hookTarget = + target.id === "aggregator" ? "pm-stack-reachable" : + target.id === "opencode" ? "opencode-working" : null; + if (hookTarget && state.hookDispatchedStates[hookTarget] === undefined && entry.state === "up") { + // Baseline only; see shouldDispatchHealthHook. + state.hookDispatchedStates[hookTarget] = "up"; + } else if (hookTarget && shouldDispatchHealthHook(state.hookDispatchedStates, hookTarget, entry.state) + && runningHooks.get(hookTarget)?.exitCode === null) { + // Left undispatched, so a later round retries it once the + // running hook has exited. + console.log(`stack-sentinel: ${hookTarget} hook still running; ${entry.state} dispatch waits`); + } else if (hookTarget && shouldDispatchHealthHook(state.hookDispatchedStates, hookTarget, entry.state)) { + const caller = "stack-sentinel"; + const hookPath = join(homedir(), "git", "code", "pm-stack", "health-hooks", `${hookTarget}.sh`); + try { + const proc = Bun.spawn([hookPath, "--caller", caller, "--detail", entry.detail ?? ""], { + stdout: "ignore", stderr: "ignore", + }); + runningHooks.set(hookTarget, proc); + state.hookDispatchedStates[hookTarget] = entry.state; + } catch (err) { + console.error(`stack-sentinel: failed to spawn C3 hook ${hookTarget}: ${err instanceof Error ? err.message : err}`); + } + } if (entry.postedState !== entry.state) { if (!tokenResolved) { token = await resolveBwsSecret("pm-aggregator.alerts-intake-token"); diff --git a/pm-stack/aggregator/src/health-hook-dispatch.ts b/pm-stack/aggregator/src/health-hook-dispatch.ts new file mode 100644 index 0000000000..68ccaa3552 --- /dev/null +++ b/pm-stack/aggregator/src/health-hook-dispatch.ts @@ -0,0 +1,25 @@ +export type HealthHookState = "down" | "up"; + +/** True once for each hook target/state transition, including after restart. + * With no recorded state (first run, or a state file from before hooks + * existed) an "up" is only a baseline: launching a hook then could record + * an outage from a probe the sentinel has not yet folded into "down", and + * no recovery hook would follow. The caller records the baseline. */ +export function shouldDispatchHealthHook( + dispatched: Record<string, HealthHookState>, + target: string, + state: HealthHookState, +): boolean { + const previous = dispatched[target]; + if (previous === undefined) return state === "down"; + return previous !== state; +} + +export function normalizeHookDispatchState(value: unknown): Record<string, HealthHookState> { + if (!value || typeof value !== "object" || Array.isArray(value)) return {}; + const result: Record<string, HealthHookState> = {}; + for (const [target, state] of Object.entries(value)) { + if (state === "down" || state === "up") result[target] = state; + } + return result; +} diff --git a/pm-stack/aggregator/test/health-hook-dispatch.test.ts b/pm-stack/aggregator/test/health-hook-dispatch.test.ts new file mode 100644 index 0000000000..4875339cdc --- /dev/null +++ b/pm-stack/aggregator/test/health-hook-dispatch.test.ts @@ -0,0 +1,29 @@ +import { describe, expect, test } from "bun:test"; +import { normalizeHookDispatchState, shouldDispatchHealthHook } from "../src/health-hook-dispatch.ts"; + +describe("health hook dispatch transitions", () => { + test("dispatches once for an outage and again for recovery, not for intake retries", () => { + const dispatched: Record<string, "down" | "up"> = {}; + expect(shouldDispatchHealthHook(dispatched, "pm-stack-reachable", "down")).toBe(true); + dispatched["pm-stack-reachable"] = "down"; + expect(shouldDispatchHealthHook(dispatched, "pm-stack-reachable", "down")).toBe(false); + expect(shouldDispatchHealthHook(dispatched, "pm-stack-reachable", "up")).toBe(true); + dispatched["pm-stack-reachable"] = "up"; + expect(shouldDispatchHealthHook(dispatched, "pm-stack-reachable", "up")).toBe(false); + }); + + test("a first up with no recorded state is a baseline, not a dispatch", () => { + expect(shouldDispatchHealthHook({}, "opencode-working", "up")).toBe(false); + expect(shouldDispatchHealthHook({}, "opencode-working", "down")).toBe(true); + expect(shouldDispatchHealthHook({ "opencode-working": "up" }, "opencode-working", "down")).toBe(true); + }); + + test("normalizes persisted dispatch state and ignores malformed values", () => { + expect(normalizeHookDispatchState({ + "pm-stack-reachable": "down", + "opencode-working": "up", + bad: "unknown", + })).toEqual({ "pm-stack-reachable": "down", "opencode-working": "up" }); + expect(normalizeHookDispatchState(null)).toEqual({}); + }); +}); diff --git a/pm-stack/health-hooks/README.md b/pm-stack/health-hooks/README.md new file mode 100644 index 0000000000..a54d26104b --- /dev/null +++ b/pm-stack/health-hooks/README.md @@ -0,0 +1,41 @@ +# PM-stack health hooks (C3, issue #9571) + +Failure-triggered, read-only troubleshoot + report hooks for two monitored +targets: `pm-stack-reachable` and `opencode-working`. Successor to the +disabled `opencode-session-minder` detection role — hooks, not a cron. + +## Files + +- `run.py` — shared runner. `--target {pm-stack-reachable,opencode-working}`. +- `pm-stack-reachable.sh`, `opencode-working.sh` — shell wrappers so any + caller (systemd, lane, aggregator) can invoke uniformly. +- `test_run.py` — runner regression tests, including failure/recovery, the + collector schema, deadline enforcement, and executable wrapper checks. + +## Trigger + +Primary trigger: `pm-stack/aggregator/scripts/stack-sentinel.ts` fires the +matching hook once when a 3-consecutive-failure transition is first observed, +and once again on recovery. Hook dispatch is persisted separately from alert +delivery retries, so an unavailable intake does not launch duplicate +diagnostics every 30 seconds. Secondary triggers (lane launchers, aggregator +ticks, PM-stack surfaces) may invoke the wrappers directly with +`--caller <id>`. + +## Incident records + +Appended (JSONL) to `~/.local/state/pm-aggregator/health-hook-incidents.jsonl` +(override with `PM_HEALTH_HOOKS_INCIDENT_FILE`). Best-effort POST to the +alert throat (`$ALERTS_INTAKE_URL/api/alerts`) with the `stackHealth` +extension. Shape documented in +`doc/2026-11-20T00-46-00Z_design_c3-health-hooks/note.md`. + +The runner enforces one shared 60-second deadline across probes, +subprocesses, credential lookup, and alert delivery. A later successful +probe writes an `up` record linked through `recoveryOf` to the open local +down incident. + +## Probes are read-only + +No probe mutates state. No state-changing remediation ships in this +component. diff --git a/pm-stack/health-hooks/opencode-working.sh b/pm-stack/health-hooks/opencode-working.sh new file mode 100755 index 0000000000..e59308e934 --- /dev/null +++ b/pm-stack/health-hooks/opencode-working.sh @@ -0,0 +1,6 @@ +#!/usr/bin/env bash +# C3 health hook: OpenCode working. Fires on failure-to-connect. +# Usage: opencode-working.sh [--caller X] [--observed-at ISO] [--detail "..."] +set -euo pipefail +HERE="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" +exec python3 "$HERE/run.py" --target opencode-working "$@" diff --git a/pm-stack/health-hooks/pm-stack-reachable.sh b/pm-stack/health-hooks/pm-stack-reachable.sh new file mode 100755 index 0000000000..1442f70fbc --- /dev/null +++ b/pm-stack/health-hooks/pm-stack-reachable.sh @@ -0,0 +1,6 @@ +#!/usr/bin/env bash +# C3 health hook: PM stack reachable. Fires on failure-to-connect. +# Usage: pm-stack-reachable.sh [--caller X] [--observed-at ISO] [--detail "..."] +set -euo pipefail +HERE="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" +exec python3 "$HERE/run.py" --target pm-stack-reachable "$@" diff --git a/pm-stack/health-hooks/run.py b/pm-stack/health-hooks/run.py new file mode 100644 index 0000000000..d8d73a0366 --- /dev/null +++ b/pm-stack/health-hooks/run.py @@ -0,0 +1,632 @@ +#!/usr/bin/env python3 +"""C3 health hook runner (issue #9571). + +Failure-triggered, read-only troubleshoot + report for two monitored +targets: `pm-stack-reachable` and `opencode-working`. + +Usage: + python3 pm-stack/health-hooks/run.py --target pm-stack-reachable \\ + --caller lane-launch --observed-at 2026-...Z [--detail "..."] + + python3 pm-stack/health-hooks/run.py --target opencode-working \\ + --caller aggregator-tick + +Exit codes: + 0 hook completed (incident recorded or transient — see stdout JSON) + 2 usage error + 1 unexpected internal error + +The runner never mutates state: every probe is read-only. It writes an +incident record (JSON) to the incident store file and, best-effort, +posts the same record to the PM-stack alert throat. It prints one JSON +document on stdout describing what it did. + +Environment: + PM_HEALTH_HOOKS_INCIDENT_FILE override incident store path + (default ~/.local/state/pm-aggregator/health-hook-incidents.jsonl) + ALERTS_INTAKE_URL aggregator base (default http://127.0.0.1:4870) + PM_AGG_STACK_HEALTH_FILE stack-health state file (unused here, read for context) + PM_PRIMARY_CHECKOUT_DIR override primary checkout dir (default ~/git/code) +""" + +import argparse +import json +import os +import socket +import subprocess +import sys +import time +import uuid +from datetime import datetime, timezone +from pathlib import Path +from urllib.request import Request, urlopen +from urllib.error import URLError, HTTPError + +HOME = Path.home() +DEFAULT_INCIDENT_FILE = HOME / ".local" / "state" / "pm-aggregator" / "health-hook-incidents.jsonl" +DEFAULT_INTAKE = "http://127.0.0.1:4870" +PRIMARY_CHECKOUT = os.environ.get("PM_PRIMARY_CHECKOUT_DIR", "").strip() or str(HOME / "git" / "code") + +TARGETS = { + "pm-stack-reachable": "PM stack reachable", + "opencode-working": "OpenCode working", +} + +SEQ_CAP_SECONDS = 60 + + +def remaining_seconds(deadline): + if deadline is None: + return None + return max(0.0, deadline - time.monotonic()) + + +def bounded_timeout(timeout, deadline): + remaining = remaining_seconds(deadline) + if remaining is None: + return timeout + return min(timeout, remaining) + + +def now_iso() -> str: + return datetime.now(timezone.utc).isoformat().replace("+00:00", "Z") + + +def parse_args(argv): + # Each wrapper fixes its own --target; a second --target would let + # argparse take the last one and run the other target's diagnosis. + if sum(1 for a in argv if a == "--target" or a.startswith("--target=")) > 1: + print("run.py: --target may be given only once", file=sys.stderr) + raise SystemExit(2) + p = argparse.ArgumentParser(prog="run.py", allow_abbrev=False, + description="C3 health hook runner") + p.add_argument("--target", required=True, choices=sorted(TARGETS)) + p.add_argument("--caller", default="unknown", help="who fired the hook") + p.add_argument("--observed-at", default=None, help="caller's observation timestamp (ISO)") + p.add_argument("--detail", default="", help="caller-supplied failure detail") + p.add_argument("--json", action="store_true", help="print JSON (default)") + args = p.parse_args(argv) + return args + + +def tcp_probe(host, port, timeout=5, deadline=None): + t0 = time.monotonic() + try: + budget = bounded_timeout(timeout, deadline) + if budget <= 0: + raise TimeoutError("sequence deadline exceeded") + with socket.create_connection((host, port), timeout=budget): + return {"ok": True, "latencyMs": int((time.monotonic() - t0) * 1000), "error": None} + except Exception as e: # noqa: BLE001 + return {"ok": False, "latencyMs": int((time.monotonic() - t0) * 1000), "error": str(e)} + + +def http_probe(url, timeout=5, alive=None, deadline=None): + alive = alive or [200] + t0 = time.monotonic() + try: + budget = bounded_timeout(timeout, deadline) + if budget <= 0: + raise TimeoutError("sequence deadline exceeded") + req = Request(url, method="GET") + with urlopen(req, timeout=budget) as resp: + status = resp.getcode() + body = resp.read(256) + ok = (alive == "any") or (status in alive) + return {"ok": ok, "status": status, "error": None, + "latencyMs": int((time.monotonic() - t0) * 1000), + "bodyPreview": body.decode("utf-8", "replace")[:120]} + except HTTPError as e: + status = e.code + ok = (alive == "any") or (status in (alive if alive != "any" else [])) + return {"ok": ok, "status": status, "error": f"HTTP {status}", + "latencyMs": int((time.monotonic() - t0) * 1000)} + except (URLError, TimeoutError, OSError) as e: + return {"ok": False, "status": None, "error": str(e), + "latencyMs": int((time.monotonic() - t0) * 1000)} + except Exception as e: # noqa: BLE001 + return {"ok": False, "status": None, "error": str(e), + "latencyMs": int((time.monotonic() - t0) * 1000)} + + +def run_cmd(cmd, timeout=5, deadline=None, env=None): + try: + budget = bounded_timeout(timeout, deadline) + if budget <= 0: + return {"rc": -1, "stdout": "", "stderr": "sequence deadline exceeded"} + proc = subprocess.run(cmd, capture_output=True, text=True, timeout=budget, env=env) + return {"rc": proc.returncode, "stdout": proc.stdout.strip(), + "stderr": proc.stderr.strip()} + except subprocess.TimeoutExpired: + return {"rc": -1, "stdout": "", "stderr": "timeout"} + except FileNotFoundError: + return {"rc": 127, "stdout": "", "stderr": "command not found"} + except Exception as e: # noqa: BLE001 + return {"rc": -2, "stdout": "", "stderr": str(e)} + + +def systemctl_state(unit, deadline=None): + r = run_cmd(["systemctl", "--user", "is-active", unit], timeout=5, deadline=deadline) + # gather properties + props = {} + show = run_cmd(["systemctl", "--user", "show", unit, + "--property=ActiveState,SubState,Result,ExecMainExitTimestamp,ActiveEnterTimestamp"], + timeout=5, deadline=deadline) + if show["rc"] == 0: + for line in show["stdout"].splitlines(): + if "=" in line: + k, v = line.split("=", 1) + props[k] = v + if r["rc"] == 127: + return {"unit": unit, "activeState": "unknown", "subState": "unknown", + "result": "unknown", "exitTimestamp": None, + "reason": "systemctl not available"} + return { + "unit": unit, + "activeState": props.get("ActiveState") or ("active" if r["rc"] == 0 else "inactive"), + "subState": props.get("SubState", ""), + "result": props.get("Result", ""), + "exitTimestamp": props.get("ExecMainExitTimestamp") or None, + "activeEnterTimestamp": props.get("ActiveEnterTimestamp") or None, + } + + +def git_recent_commits(repo, n=5, deadline=None): + r = run_cmd(["git", "-C", repo, "log", "--oneline", f"-{n}"], timeout=5, deadline=deadline) + if r["rc"] != 0: + return {"ok": False, "commits": [], "error": r["stderr"] or "git failed"} + commits = [ln for ln in r["stdout"].splitlines() if ln.strip()] + return {"ok": True, "commits": commits, "error": None} + + +def _first_existing(paths): + for p in paths: + if p and Path(p).exists(): + return str(p) + return None + + +def bws_lookup(key, deadline=None): + """Resolve a Bitwarden Secrets Manager secret by its key. + + `bws secret get` takes a secret ID, not its key, so this lists the + secrets, finds the key's ID and fetches that, as the aggregator's + secrets.ts does. Returns (status, value): status is "resolved", + "missing" or "unknown"; value is only set when resolved and is never + logged or put in evidence. + """ + bws = os.environ.get("BWS_BIN") or _first_existing( + ["/run/current-system/sw/bin/bws", HOME / "tools" / "bin" / "bws"]) or "bws" + env = os.environ.copy() + if not env.get("BWS_ACCESS_TOKEN"): + token_file = os.environ.get("BWS_ACCESS_TOKEN_FILE") or _first_existing( + [HOME / ".config" / "bws" / "access-token", + HOME / ".config" / "bitwarden" / "access-token"]) + if not token_file: + return "unknown", None + try: + access = Path(token_file).read_text().strip() + except OSError: + return "unknown", None + if not access: + return "unknown", None + env["BWS_ACCESS_TOKEN"] = access + listed = run_cmd([bws, "secret", "list", "--output", "json"], timeout=10, + deadline=deadline, env=env) + if listed["rc"] == 127: + return "unknown", None + if listed["rc"] != 0: + return "unknown", None + try: + entries = json.loads(listed["stdout"] or "[]") + except json.JSONDecodeError: + return "unknown", None + secret_id = next((e.get("id") for e in entries + if isinstance(e, dict) and e.get("key") == key and e.get("id")), None) + if not secret_id: + return "missing", None + got = run_cmd([bws, "secret", "get", secret_id, "--output", "json"], timeout=10, + deadline=deadline, env=env) + if got["rc"] != 0: + return "unknown", None + try: + value = (json.loads(got["stdout"] or "{}").get("value") or "").strip() + except (json.JSONDecodeError, AttributeError): + return "unknown", None + return ("resolved", value) if value else ("missing", None) + + +def bws_resolve(name, deadline=None): + # Evidence only: whether the secret resolves, never its value. + status, _value = bws_lookup(name, deadline=deadline) + detail = { + "resolved": "secret resolved by key", + "missing": "no secret with that key", + "unknown": "bws unavailable or unreadable", + }[status] + return {"status": status, "detail": detail} + + +def read_host_health(path=None): + path = Path(path) if path else HOME / ".local" / "state" / "pm-aggregator" / "host-health.json" + if not path.exists(): + return {"collectedAt": None, "unitsDown": [], "present": False} + try: + data = json.loads(path.read_text()) + except Exception as e: # noqa: BLE001 + return {"collectedAt": None, "unitsDown": [], "present": True, "error": str(e)} + units_down = [] + # host-health-collector records user unit states; accept a few shapes. + units = data.get("units") or data.get("services") or {} + if isinstance(units, dict): + items = list(units.items()) + elif isinstance(units, list): + items = [((info or {}).get("id") or (info or {}).get("name"), info) for info in units] + else: + items = [] + for name, info in items: + if name and unit_is_down(info or {}): + units_down.append(name) + return { + "collectedAt": data.get("generatedAt") or data.get("collectedAt") or data.get("timestamp"), + "unitsDown": units_down, + "present": True, + } + + +def unit_is_down(info): + """A unit is down when it failed, not merely when it is inactive. + + Timer-driven oneshots (pm-git-sync, pm-projector-reconcile) sit at + activeState "inactive" with result "success" between runs; that is + healthy. A unit counts as down when systemd says it failed, or when + it is inactive after a run whose result was not success. + """ + st = info.get("activeState") or info.get("state") or info.get("ActiveState") + if not isinstance(st, str): + return False + st = st.lower() + if st in ("active", "up", "running", "activating", "reloading"): + return False + if st in ("failed", "down"): + return True + result = info.get("result") or info.get("Result") + if isinstance(result, str) and result: + return result.lower() != "success" + # Inactive with no recorded result: no evidence of a failure. + return False + + +def opencode_route_ref(): + # Read-only: declared default model route from opencode.jsonc + cfg = Path(PRIMARY_CHECKOUT) / ".opencode" / "opencode.jsonc" + if not cfg.exists(): + # try relative to cwd + cfg = Path(".opencode") / "opencode.jsonc" + if not cfg.exists(): + return {"status": "unknown", "detail": "config not found"} + try: + text = cfg.read_text() + except Exception as e: # noqa: BLE001 + return {"status": "error", "detail": str(e)} + # naive: find "model" key + import re + m = re.search(r'"model"\s*:\s*"([^"]+)"', text) + if m: + return {"status": "resolved", "detail": m.group(1)} + return {"status": "unknown", "detail": "no model key found"} + + +def count_sessions_last_hour(db_path=None, now_ms=None): + """Sessions updated in the trailing hour, read from the live OpenCode + store (session_v2 in ~/.local/share/opencode/opencode.db, per + pm-stack/opencode-usage-export/README.md). Opened read-only; returns + None when the store or its v2 table is not there.""" + import sqlite3 + path = Path(db_path or os.environ.get("OPENCODE_USAGE_DB", "").strip() + or HOME / ".local" / "share" / "opencode" / "opencode.db") + if not path.exists(): + return None + now_ms = int(time.time() * 1000) if now_ms is None else now_ms + try: + db = sqlite3.connect(f"{path.resolve().as_uri()}?mode=ro", uri=True, timeout=2) + except sqlite3.Error: + return None + try: + row = db.execute("SELECT count(*) FROM session_v2 WHERE time_updated >= ?", + (now_ms - 3_600_000,)).fetchone() + return int(row[0]) if row else 0 + except sqlite3.Error: + return None + finally: + db.close() + + +def probe_pm_stack(caller_detail, deadline=None): + evidence = {} + # 1. confirm failure: re-probe aggregator + intake = os.environ.get("ALERTS_INTAKE_URL", DEFAULT_INTAKE).rstrip("/") + # derive host/port from intake + host = "127.0.0.1" + port = 4870 + try: + from urllib.parse import urlparse + u = urlparse(intake) + host = u.hostname or host + port = u.port or (443 if u.scheme == "https" else 80) + except Exception: + pass + reprobe = http_probe(f"{intake}/board", timeout=5, alive=[200], deadline=deadline) + evidence["confirmFailure"] = not reprobe["ok"] + + # 3. reachability + tcp = tcp_probe(host, port, timeout=5, deadline=deadline) + http = http_probe(f"{intake}/board", timeout=5, alive=[200], deadline=deadline) + evidence["reachability"] = { + "ok": http["ok"], + "status": http.get("status"), + "error": http.get("error"), + "latencyMs": http.get("latencyMs"), + "tcpOk": tcp["ok"], + "tcpError": tcp.get("error"), + } + + # 4. service state + evidence["serviceState"] = systemctl_state("pm-aggregator", deadline=deadline) + + # 5. auth health + evidence["authHealth"] = bws_resolve("pm-aggregator.alerts-intake-token", deadline=deadline) + + # 6. recent changes + recent = git_recent_commits(PRIMARY_CHECKOUT, 5, deadline=deadline) + evidence["recentChanges"] = { + "commits": recent.get("commits", []), + "gitOk": recent.get("ok", False), + "deployMarkerMtime": None, + "gitSyncOk": None, + } + # host-health snapshot + hh = read_host_health() + evidence["hostHealth"] = { + "collectedAt": hh.get("collectedAt"), + "unitsDown": hh.get("unitsDown", []), + "present": hh.get("present", False), + } + + # verdict + down = not reprobe["ok"] and not http["ok"] + if reprobe["ok"]: + state = "transient" + elif down: + state = "down" + else: + state = "transient" + summary = { + "down": f"PM stack unreachable: {http.get('error') or 'HTTP ' + str(http.get('status'))}", + "transient": "PM stack probe recovered on re-check", + "up": "PM stack reachable", + }[state] + return state, summary, evidence + + +def probe_opencode(caller_detail, deadline=None): + evidence = {} + url = "http://127.0.0.1:13420/global/health" + reprobe = http_probe(url, timeout=5, alive=[200], deadline=deadline) + evidence["confirmFailure"] = not reprobe["ok"] + + tcp = tcp_probe("127.0.0.1", 13420, timeout=5, deadline=deadline) + http = http_probe(url, timeout=5, alive=[200], deadline=deadline) + evidence["reachability"] = { + "ok": http["ok"], + "status": http.get("status"), + "error": http.get("error"), + "latencyMs": http.get("latencyMs"), + "tcpOk": tcp["ok"], + "tcpError": tcp.get("error"), + } + + # service state: try opencode user unit + ss = systemctl_state("opencode", deadline=deadline) + if ss.get("activeState") == "unknown" and ss.get("reason") == "systemctl not available": + pass + # detect no-unit + show = run_cmd(["systemctl", "--user", "show", "opencode", "--property=Id"], timeout=5, deadline=deadline) + if show["rc"] != 0 or "opencode" not in (show["stdout"] or ""): + ss["noUnit"] = True + evidence["serviceState"] = ss + + evidence["authHealth"] = opencode_route_ref() + + rc = git_recent_commits(PRIMARY_CHECKOUT, 5, deadline=deadline) + evidence["recentChanges"] = { + "commits": rc.get("commits", []), + "gitOk": rc.get("ok", False), + } + evidence["sessionLiveness"] = {"sessionsLastHour": count_sessions_last_hour()} + + down = not reprobe["ok"] and not http["ok"] + if reprobe["ok"]: + state = "transient" + elif down: + state = "down" + else: + state = "transient" + summary = { + "down": f"OpenCode unreachable: {http.get('error') or 'HTTP ' + str(http.get('status'))}", + "transient": "OpenCode probe recovered on re-check", + "up": "OpenCode working", + }[state] + return state, summary, evidence + + +def post_to_throat(record, deadline=None): + intake = os.environ.get("ALERTS_INTAKE_URL", DEFAULT_INTAKE).rstrip("/") + # resolve token from bws best-effort; if unavailable, skip posting + _status, token = bws_lookup("pm-aggregator.alerts-intake-token", deadline=deadline) + if not token: + return {"posted": False, "reason": "intake token unavailable"} + body = { + "source": "health-hook", + "key": record["key"], + "severity": record["severity"], + "title": record["title"], + "body": record["body"], + "stackHealth": { + "serviceId": record["target"], + "name": TARGETS[record["target"]], + "state": "down" if record["state"] == "down" else "up", + "since": record["firedAt"], + "detail": record["body"], + }, + } + try: + data = json.dumps(body).encode() + req = Request(f"{intake}/api/alerts", data=data, method="POST", + headers={"Authorization": f"Bearer {token}", + "Content-Type": "application/json"}) + budget = bounded_timeout(10, deadline) + if budget <= 0: + return {"posted": False, "reason": "sequence deadline exceeded"} + with urlopen(req, timeout=budget) as resp: + resp.read() + return {"posted": True, "status": resp.getcode()} + except Exception as e: # noqa: BLE001 + return {"posted": False, "reason": str(e)} + + +def append_incident(record): + path = Path(os.environ.get("PM_HEALTH_HOOKS_INCIDENT_FILE", + str(DEFAULT_INCIDENT_FILE))) + path.parent.mkdir(parents=True, exist_ok=True) + with path.open("a") as f: + f.write(json.dumps(record) + "\n") + return str(path) + + +def find_open_incident(target): + path = Path(os.environ.get("PM_HEALTH_HOOKS_INCIDENT_FILE", str(DEFAULT_INCIDENT_FILE))) + if not path.exists(): + return None + open_by_id = {} + try: + with path.open() as f: + for line in f: + try: + record = json.loads(line) + except (json.JSONDecodeError, TypeError): + continue + if record.get("target") != target: + continue + if record.get("state") == "down" and record.get("incidentId"): + open_by_id[record["incidentId"]] = record + elif (record.get("state") == "up" and record.get("recoveryOf") + and record.get("recoveryDelivered", True)): + # A recovery closes its outage only once the intake + # took it; an undelivered one leaves the outage open + # so the next hook run posts the recovery again. + # Records written before this field count as delivered. + open_by_id.pop(record["recoveryOf"], None) + except OSError: + return None + return next(reversed(open_by_id.values()), None) if open_by_id else None + + +def main(argv): + args = parse_args(argv) + target = args.target + fired_at = now_iso() + start = time.monotonic() + deadline = start + SEQ_CAP_SECONDS + + if target == "pm-stack-reachable": + state, summary, evidence = probe_pm_stack(args.detail, deadline=deadline) + else: + state, summary, evidence = probe_opencode(args.detail, deadline=deadline) + + # A down diagnosis during an open outage reuses that outage (its id + # and intake key) instead of opening a second alert that a single + # recovery could not close. + open_incident = find_open_incident(target) if state in ("transient", "up", "down") else None + recovery_of = None + if open_incident and state != "down": + state = "up" + recovery_of = open_incident["incidentId"] + summary = f"{TARGETS[target]} recovered after incident {recovery_of}" + + # severity + if target == "pm-stack-reachable" and state == "down": + severity = "critical" + elif state == "down": + severity = "warning" + else: + severity = "info" + + if state == "down" and open_incident: + incident_id = open_incident["incidentId"] + else: + incident_id = str(uuid.uuid4()) + # A recovery reuses its outage's intake key: the intake closes only + # the incident whose source and key match. + intake_key = (open_incident or {}).get("key") or f"health-hook:{target}:{incident_id}" + record = { + "source": "health-hook", + "key": intake_key, + "severity": severity, + "title": f"Health hook: {TARGETS[target]} is {state}", + "body": summary, + "target": target, + "state": state, + "caller": args.caller, + "firedAt": fired_at, + "observedAt": args.observed_at, + "incidentId": incident_id, + "recoveryOf": recovery_of, + "evidence": evidence, + } + + # Only record incidents for down/transient? Record all for audit, but + # transient ones are marked. We record down + recovery; transient + # recorded as audit-only (no throat post) to keep noise low. + throat_result = {"posted": False, "reason": "transient/not-posted"} + stored_path = None + if state == "up" and recovery_of: + # Post first, then record whether the intake took the recovery. + throat_result = post_to_throat(record, deadline=deadline) + record["recoveryDelivered"] = bool(throat_result.get("posted")) + stored_path = append_incident(record) + elif state in ("down", "up"): + stored_path = append_incident(record) + throat_result = post_to_throat(record, deadline=deadline) + + # category chat note via Muse is left to the caller environment; we + # print the note text for the caller to dispatch. + note = f"health-hook {target} {state} @{fired_at} caller={args.caller} incident={incident_id} — {summary}" + + elapsed = time.monotonic() - start + out = { + "target": target, + "state": state, + "severity": severity, + "incidentId": incident_id, + "summary": summary, + "caller": args.caller, + "firedAt": fired_at, + "elapsedSeconds": round(elapsed, 3), + "incidentFile": stored_path, + "throat": throat_result, + "categoryNote": note, + "withinCap": elapsed <= SEQ_CAP_SECONDS, + } + print(json.dumps(out, indent=2)) + return 0 + + +if __name__ == "__main__": + try: + sys.exit(main(sys.argv[1:])) + except SystemExit: + raise + except Exception as e: # noqa: BLE001 + print(json.dumps({"error": str(e)}), file=sys.stderr) + sys.exit(1) diff --git a/pm-stack/health-hooks/test_run.py b/pm-stack/health-hooks/test_run.py new file mode 100644 index 0000000000..ef5ca2b06a --- /dev/null +++ b/pm-stack/health-hooks/test_run.py @@ -0,0 +1,290 @@ +#!/usr/bin/env python3 +"""Tests for C3 health hook runner (pm-stack/health-hooks/run.py).""" +import json +import os +import subprocess +import sys +import tempfile +import time +from contextlib import redirect_stdout +from io import StringIO +from pathlib import Path +from unittest import mock + +HERE = Path(__file__).resolve().parent +RUNNER = HERE / "run.py" +sys.path.insert(0, str(HERE)) +import run as R # noqa: E402 + + +def test_argparse_requires_target(): + r = subprocess.run([sys.executable, str(RUNNER)], capture_output=True, text=True) + assert r.returncode == 2, r + + +def test_argparse_rejects_bad_target(): + r = subprocess.run([sys.executable, str(RUNNER), "--target", "nope"], capture_output=True, text=True) + assert r.returncode == 2, r + + +def test_targets_defined(): + assert set(R.TARGETS) == {"pm-stack-reachable", "opencode-working"} + + +def test_tcp_probe_shape(): + res = R.tcp_probe("127.0.0.1", 1, timeout=1) + assert "ok" in res and "latencyMs" in res and "error" in res + assert res["ok"] is False + + +def test_http_probe_shape(): + res = R.http_probe("http://127.0.0.1:1/nope", timeout=1, alive=[200]) + assert res["ok"] is False + assert res["status"] is None + + +def test_systemctl_state_shape(): + st = R.systemctl_state("definitely-not-a-unit-xyz") + assert "activeState" in st + assert "unit" in st + + +def test_git_recent_commits(): + r = R.git_recent_commits(str(Path(__file__).resolve().parents[2]), 3) + assert "commits" in r + # may be ok or not depending on git; shape check + assert isinstance(r["commits"], list) + + +def test_runner_runs_and_prints_json(): + env = os.environ.copy() + env["PM_HEALTH_HOOKS_INCIDENT_FILE"] = str(Path(tempfile.mkdtemp()) / "inc.jsonl") + r = subprocess.run([sys.executable, str(RUNNER), "--target", "opencode-working", + "--caller", "test", "--json"], capture_output=True, text=True, env=env) + assert r.returncode == 0, r.stderr + obj = json.loads(r.stdout) + assert obj["target"] == "opencode-working" + assert obj["state"] in ("down", "transient", "up") + assert "incidentId" in obj + assert "categoryNote" in obj + + +def test_runner_pm_stack(): + env = os.environ.copy() + env["PM_HEALTH_HOOKS_INCIDENT_FILE"] = str(Path(tempfile.mkdtemp()) / "inc.jsonl") + r = subprocess.run([sys.executable, str(RUNNER), "--target", "pm-stack-reachable", + "--caller", "test"], capture_output=True, text=True, env=env) + assert r.returncode == 0, r.stderr + obj = json.loads(r.stdout) + assert obj["target"] == "pm-stack-reachable" + assert "evidence" not in obj # evidence stays in record, not stdout? runner prints summary only + # actually runner prints out without evidence; ok + + +def test_host_health_collector_schema(): + with tempfile.TemporaryDirectory() as td: + path = Path(td) / "host-health.json" + path.write_text(json.dumps({ + "generatedAt": "2026-11-20T01:00:00Z", + "units": { + "pm-aggregator.service": {"activeState": "failed"}, + "opencode.service": {"activeState": "active"}, + }, + })) + result = R.read_host_health(path) + assert result["collectedAt"] == "2026-11-20T01:00:00Z" + assert result["unitsDown"] == ["pm-aggregator.service"] + + +def test_http_500_is_down_even_when_tcp_and_unit_are_healthy(): + failed = {"ok": False, "status": 500, "error": "HTTP 500", "latencyMs": 1} + healthy_tcp = {"ok": True, "latencyMs": 1, "error": None} + with mock.patch.object(R, "http_probe", return_value=failed), \ + mock.patch.object(R, "tcp_probe", return_value=healthy_tcp), \ + mock.patch.object(R, "systemctl_state", return_value={"activeState": "active"}), \ + mock.patch.object(R, "bws_resolve", return_value={"status": "resolved"}), \ + mock.patch.object(R, "git_recent_commits", return_value={"ok": True, "commits": []}), \ + mock.patch.object(R, "read_host_health", return_value={"collectedAt": None, "unitsDown": []}): + pm_state, _, _ = R.probe_pm_stack("") + with mock.patch.object(R, "http_probe", return_value=failed), \ + mock.patch.object(R, "tcp_probe", return_value=healthy_tcp), \ + mock.patch.object(R, "systemctl_state", return_value={"activeState": "active"}), \ + mock.patch.object(R, "run_cmd", return_value={"rc": 0, "stdout": "opencode", "stderr": ""}), \ + mock.patch.object(R, "opencode_route_ref", return_value={"status": "resolved"}), \ + mock.patch.object(R, "git_recent_commits", return_value={"ok": True, "commits": []}), \ + mock.patch.object(R, "count_sessions_last_hour", return_value=1): + oc_state, _, _ = R.probe_opencode("") + assert pm_state == "down" + assert oc_state == "down" + + +def test_recovery_links_to_open_down_incident(): + with tempfile.TemporaryDirectory() as td: + incident_file = Path(td) / "incidents.jsonl" + incident_file.write_text(json.dumps({ + "target": "opencode-working", "state": "down", "incidentId": "down-123", + }) + "\n") + env = mock.patch.dict(os.environ, {"PM_HEALTH_HOOKS_INCIDENT_FILE": str(incident_file)}) + with env, mock.patch.object(R, "probe_opencode", return_value=("transient", "probe recovered", {})), \ + mock.patch.object(R, "post_to_throat", return_value={"posted": True}): + stdout = StringIO() + with redirect_stdout(stdout): + assert R.main(["--target", "opencode-working"]) == 0 + out = json.loads(stdout.getvalue()) + records = [json.loads(line) for line in incident_file.read_text().splitlines()] + assert out["state"] == "up" + assert len(records) == 2 + assert records[-1]["state"] == "up" + assert records[-1]["recoveryOf"] == "down-123" + + +def test_undelivered_recovery_is_posted_again_on_the_next_run(): + with tempfile.TemporaryDirectory() as td: + incident_file = Path(td) / "incidents.jsonl" + incident_file.write_text(json.dumps({ + "target": "opencode-working", "state": "down", "incidentId": "down-123", + "key": "health-hook:opencode-working:down-123", + }) + "\n") + env = mock.patch.dict(os.environ, {"PM_HEALTH_HOOKS_INCIDENT_FILE": str(incident_file)}) + probe = mock.patch.object(R, "probe_opencode", return_value=("transient", "probe recovered", {})) + with env, probe, mock.patch.object(R, "post_to_throat", return_value={"posted": False, "reason": "HTTP 503"}): + with redirect_stdout(StringIO()): + assert R.main(["--target", "opencode-working"]) == 0 + assert R.find_open_incident("opencode-working")["incidentId"] == "down-123" + with env, probe, mock.patch.object(R, "post_to_throat", return_value={"posted": True}) as post: + stdout = StringIO() + with redirect_stdout(stdout): + assert R.main(["--target", "opencode-working"]) == 0 + assert R.find_open_incident("opencode-working") is None + out = json.loads(stdout.getvalue()) + records = [json.loads(line) for line in incident_file.read_text().splitlines()] + assert out["state"] == "up" + assert post.call_args.args[0]["key"] == "health-hook:opencode-working:down-123" + assert [r.get("recoveryDelivered") for r in records] == [None, False, True] + + +def test_pm_stack_down_uses_supported_critical_severity(): + with tempfile.TemporaryDirectory() as td: + incident_file = Path(td) / "incidents.jsonl" + with mock.patch.dict(os.environ, {"PM_HEALTH_HOOKS_INCIDENT_FILE": str(incident_file)}), \ + mock.patch.object(R, "probe_pm_stack", return_value=("down", "unreachable", {})), \ + mock.patch.object(R, "post_to_throat", return_value={"posted": False}): + stdout = StringIO() + with redirect_stdout(stdout): + assert R.main(["--target", "pm-stack-reachable"]) == 0 + output = json.loads(stdout.getvalue()) + record = json.loads(incident_file.read_text().splitlines()[0]) + assert output["severity"] == record["severity"] == "critical" + + +def test_run_cmd_caps_timeout_to_shared_deadline_and_skips_expired_work(): + with mock.patch.object(R.subprocess, "run", return_value=mock.Mock(returncode=0, stdout="", stderr="")) as run: + R.run_cmd(["example"], timeout=30, deadline=time.monotonic() + 2) + assert 0 < run.call_args.kwargs["timeout"] <= 2 + run.reset_mock() + result = R.run_cmd(["example"], timeout=30, deadline=time.monotonic() - 1) + run.assert_not_called() + assert result["stderr"] == "sequence deadline exceeded" + + +def test_recovery_reuses_the_outage_intake_key(): + with tempfile.TemporaryDirectory() as td: + incident_file = Path(td) / "incidents.jsonl" + incident_file.write_text(json.dumps({ + "target": "opencode-working", "state": "down", "incidentId": "down-123", + "key": "health-hook:opencode-working:down-123", + }) + "\n") + with mock.patch.dict(os.environ, {"PM_HEALTH_HOOKS_INCIDENT_FILE": str(incident_file)}), \ + mock.patch.object(R, "probe_opencode", return_value=("transient", "ok", {})), \ + mock.patch.object(R, "post_to_throat", return_value={"posted": True}) as post: + with redirect_stdout(StringIO()): + assert R.main(["--target", "opencode-working"]) == 0 + assert post.call_args.args[0]["key"] == "health-hook:opencode-working:down-123" + + +def test_repeated_down_reuses_the_open_outage(): + with tempfile.TemporaryDirectory() as td: + incident_file = Path(td) / "incidents.jsonl" + env = mock.patch.dict(os.environ, {"PM_HEALTH_HOOKS_INCIDENT_FILE": str(incident_file)}) + with env, mock.patch.object(R, "probe_opencode", return_value=("down", "unreachable", {})), \ + mock.patch.object(R, "post_to_throat", return_value={"posted": True}) as post: + with redirect_stdout(StringIO()): + assert R.main(["--target", "opencode-working"]) == 0 + assert R.main(["--target", "opencode-working"]) == 0 + keys = [c.args[0]["key"] for c in post.call_args_list] + with env, mock.patch.object(R, "probe_opencode", return_value=("transient", "ok", {})), \ + mock.patch.object(R, "post_to_throat", return_value={"posted": True}) as rec: + with redirect_stdout(StringIO()): + assert R.main(["--target", "opencode-working"]) == 0 + assert R.find_open_incident("opencode-working") is None + assert keys[0] == keys[1] + assert rec.call_args.args[0]["key"] == keys[0] + + +def test_wrapper_target_cannot_be_overridden(): + r = subprocess.run([str(HERE / "pm-stack-reachable.sh"), "--target", "opencode-working"], + capture_output=True, text=True) + assert r.returncode == 2, r + assert "only once" in r.stderr + + +def test_bws_lookup_resolves_the_key_to_its_id_before_get(): + calls = [] + + def fake(cmd, timeout=5, deadline=None, env=None): + calls.append(cmd[1:]) + assert env and env.get("BWS_ACCESS_TOKEN") == "access" + if cmd[1:3] == ["secret", "list"]: + return {"rc": 0, "stdout": json.dumps([{"id": "id-1", "key": "other"}, + {"id": "id-2", "key": "wanted"}]), "stderr": ""} + return {"rc": 0, "stdout": json.dumps({"id": "id-2", "value": " tok "}), "stderr": ""} + + with mock.patch.dict(os.environ, {"BWS_ACCESS_TOKEN": "access", "BWS_BIN": "bws"}), \ + mock.patch.object(R, "run_cmd", side_effect=fake): + assert R.bws_lookup("wanted") == ("resolved", "tok") + assert R.bws_lookup("absent")[0] == "missing" + evidence = R.bws_resolve("wanted") + assert calls[1] == ["secret", "get", "id-2", "--output", "json"] + assert evidence["status"] == "resolved" and "tok" not in json.dumps(evidence) + + +def test_inactive_successful_oneshot_is_not_down(): + assert not R.unit_is_down({"activeState": "inactive", "result": "success"}) + assert not R.unit_is_down({"activeState": "active"}) + assert R.unit_is_down({"activeState": "failed"}) + assert R.unit_is_down({"activeState": "inactive", "result": "exit-code"}) + + +def test_sessions_last_hour_reads_the_live_store(): + import sqlite3 + with tempfile.TemporaryDirectory() as td: + db_path = Path(td) / "opencode.db" + db = sqlite3.connect(db_path) + db.execute("CREATE TABLE session_v2 (id text, time_updated integer)") + now = 10_000_000_000 + db.executemany("INSERT INTO session_v2 VALUES (?, ?)", + [("a", now - 60_000), ("b", now - 3_000_000), ("c", now - 7_200_000)]) + db.commit() + db.close() + assert R.count_sessions_last_hour(db_path, now_ms=now) == 2 + assert R.count_sessions_last_hour(Path(td) / "missing.db", now_ms=now) is None + + +def test_shell_wrappers_are_executable(): + for wrapper in (HERE / "pm-stack-reachable.sh", HERE / "opencode-working.sh"): + assert wrapper.stat().st_mode & 0o111, wrapper + + +if __name__ == "__main__": + import traceback + tests = [v for k, v in globals().items() if k.startswith("test_")] + failed = 0 + for t in tests: + try: + t() + print("PASS", t.__name__) + except Exception as e: + failed += 1 + print("FAIL", t.__name__, "-", repr(e)) + traceback.print_exc() + sys.exit(1 if failed else 0)