From 118c1fd4d4bc68a8cfa061e63317241202964fe3 Mon Sep 17 00:00:00 2001 From: Drewry Pope Date: Sat, 21 Nov 2026 05:46:12 -0600 Subject: [PATCH 1/2] C3 health hooks: wire opencode-working into lane launchers and aggregator ticks (#9571) Fire the opencode-working hook fire-and-forget when a lane launch cannot read OpenCode's session state (claimant cap step, launch_one) and when the aggregator's live source cannot map the laptop OpenCode sessions on a tick. Read-only probes only; the hook owns dedup and recording. Tests: claimant suite 240 OK; health-hooks 22 pass; aggregator laptop-map and health-hook-dispatch tests pass. --- pm-stack/aggregator/src/health-hook-fire.ts | 25 +++++++++++++++++++++ pm-stack/aggregator/src/server.ts | 4 ++++ pm-stack/aggregator/src/sources/live.ts | 4 ++++ pm-stack/health-hooks/README.md | 9 +++++--- pm-stack/opencode-claimant/claimant.py | 20 +++++++++++++++++ pm-stack/opencode-claimant/launch_one.py | 3 +++ pm-stack/opencode-claimant/test_claimant.py | 3 +++ 7 files changed, 65 insertions(+), 3 deletions(-) create mode 100644 pm-stack/aggregator/src/health-hook-fire.ts diff --git a/pm-stack/aggregator/src/health-hook-fire.ts b/pm-stack/aggregator/src/health-hook-fire.ts new file mode 100644 index 0000000000..2a4ba8b398 --- /dev/null +++ b/pm-stack/aggregator/src/health-hook-fire.ts @@ -0,0 +1,25 @@ +import { homedir } from "node:os"; +import { join } from "node:path"; + +// C3 health hook (#9571): fire-and-forget opencode-working from a caller +// that found OpenCode unreachable. One hook process at a time per +// aggregator; the hook dedupes its own incidents, so a skipped firing +// loses nothing. +let running: { exitCode: number | null } | null = null; + +export function fireOpenCodeWorkingHook(caller: string, detail: string): boolean { + if (running && running.exitCode === null) return false; + const hookPath = join(homedir(), "git", "code", "pm-stack", "health-hooks", "opencode-working.sh"); + try { + running = Bun.spawn([hookPath, "--caller", caller, "--detail", detail], { + stdout: "ignore", + stderr: "ignore", + }); + return true; + } catch (err) { + console.error( + `health-hook: failed to spawn opencode-working: ${err instanceof Error ? err.message : err}`, + ); + return false; + } +} diff --git a/pm-stack/aggregator/src/server.ts b/pm-stack/aggregator/src/server.ts index 57a13edb81..0b3962b496 100644 --- a/pm-stack/aggregator/src/server.ts +++ b/pm-stack/aggregator/src/server.ts @@ -237,6 +237,7 @@ import { SloJournal, groupSamplesByFacet } from "./slo-journal.ts"; import { sampleSloFacets } from "./slo-sampler.ts"; import { SLO_DEFINITIONS, summarizeSloFacet, type SloFacetSummary } from "./slo.ts"; import { computeFlowAnalytics } from "./flow-analytics.ts"; +import { fireOpenCodeWorkingHook } from "./health-hook-fire.ts"; import { FORECAST_CONTRACT_VERSION, quotaForecastContract, @@ -483,6 +484,9 @@ function pickSource(): Source { onSourceGap: recordSourceGap, seenActivityIds: (source) => activityStore.seenIds(source), snapshotRemote: storeRemotes?.usage, + onLaptopUnreachable: (detail) => { + fireOpenCodeWorkingHook("aggregator-tick", detail); + }, }) : fixtureSource(); } diff --git a/pm-stack/aggregator/src/sources/live.ts b/pm-stack/aggregator/src/sources/live.ts index 25feb83c80..90d15922aa 100644 --- a/pm-stack/aggregator/src/sources/live.ts +++ b/pm-stack/aggregator/src/sources/live.ts @@ -888,6 +888,9 @@ export function liveSource( cfg: Config, opts?: { standingAuto?: () => Promise; + // C3 health hook (#9571): fired when the laptop's OpenCode session + // map cannot be read on an aggregator tick. Fire-and-forget. + onLaptopUnreachable?: (detail: string) => void; onEvent?: (event: NewStreamEvent) => void; hasEvent?: (kind: string, ref: string) => Promise; // The handler's return is the ingestion acknowledgment (#3321, @@ -1382,6 +1385,7 @@ export function liveSource( laptopCache = { value: mapped, at: Date.now() }; } else { laptopFailureAt = Date.now(); + opts?.onLaptopUnreachable?.("laptop OpenCode session map unreachable on aggregator tick"); } return mapped; })().finally(() => { diff --git a/pm-stack/health-hooks/README.md b/pm-stack/health-hooks/README.md index a54d26104b..49d9cd1de1 100644 --- a/pm-stack/health-hooks/README.md +++ b/pm-stack/health-hooks/README.md @@ -18,9 +18,12 @@ 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 `. +diagnostics every 30 seconds. Secondary triggers invoke the wrappers +fire-and-forget with `--caller `: the OpenCode claimant's cap step and +per-task `launch_one.py` launch when OpenCode sessions cannot be read +(`lane-launch`), and the aggregator's live source when the laptop's OpenCode +session map is unreachable on a tick (`aggregator-tick`). PM-stack surfaces +remain unwired. ## Incident records diff --git a/pm-stack/opencode-claimant/claimant.py b/pm-stack/opencode-claimant/claimant.py index c75fc1406c..54cbbd6633 100755 --- a/pm-stack/opencode-claimant/claimant.py +++ b/pm-stack/opencode-claimant/claimant.py @@ -743,6 +743,25 @@ def cap_step() -> int: return cap_room +OPENCODE_WORKING_HOOK = Path(__file__).resolve().parent.parent / "health-hooks" / "opencode-working.sh" + + +def fire_opencode_working_hook(caller: str, detail: str) -> None: + """C3 health hook (#9571): fire-and-forget opencode-working when a + launch cannot read OpenCode's session state. Never raises and never + waits; the hook owns probing, dedup and recording.""" + try: + subprocess.Popen( + [str(OPENCODE_WORKING_HOOK), "--caller", caller, "--detail", detail], + stdin=subprocess.DEVNULL, + stdout=subprocess.DEVNULL, + stderr=subprocess.DEVNULL, + start_new_session=True, + ) + except OSError as e: + print(f"Warning: could not fire opencode-working hook: {e}") + + def _post_prompt(session_id: str, prompt: str) -> bool: """One prompt POST through the verified transport; True iff the server answered 2xx. A non-2xx POST did not land, whatever @@ -1532,6 +1551,7 @@ def _fire(mode: str): if cap_room == -1: print("Warning: Could not determine cap room. Exiting.") + fire_opencode_working_hook("lane-launch", "claimant cap step could not read OpenCode sessions") log_fire( mode, fire_candidates, diff --git a/pm-stack/opencode-claimant/launch_one.py b/pm-stack/opencode-claimant/launch_one.py index 1461b58b17..d732671b74 100644 --- a/pm-stack/opencode-claimant/launch_one.py +++ b/pm-stack/opencode-claimant/launch_one.py @@ -484,6 +484,9 @@ def launch(queue_name, task_id): cap_room = claimant.cap_step() if cap_room == -1: + claimant.fire_opencode_working_hook( + "lane-launch", f"launch_one {queue_name}:{task_id} could not read OpenCode sessions" + ) return { "task": task_id, "queue": queue_name, diff --git a/pm-stack/opencode-claimant/test_claimant.py b/pm-stack/opencode-claimant/test_claimant.py index 8d35633028..9113d00419 100644 --- a/pm-stack/opencode-claimant/test_claimant.py +++ b/pm-stack/opencode-claimant/test_claimant.py @@ -864,6 +864,7 @@ def test_cap_unknown_logs_cap_room_null_not_sentinel(self): ), patch.object(claimant, "STATE_DIR", state_dir), patch.object(claimant, "FIRES_FILE", fires), + patch.object(claimant, "fire_opencode_working_hook") as hook, ): self.assertEqual(claimant.main(), 1) entries = [ @@ -872,6 +873,8 @@ def test_cap_unknown_logs_cap_room_null_not_sentinel(self): self.assertEqual(len(entries), 1) self.assertIsNone(entries[0]["cap_room"]) self.assertEqual(entries[0]["skips"], [{"reason": "cap_unknown"}]) + self.assertEqual(hook.call_count, 1) + self.assertEqual(hook.call_args.args[0], "lane-launch") class TestGateUnknownFireLog(unittest.TestCase): From 1b4e841547d1b09f44d336f45d88594afd9af3c6 Mon Sep 17 00:00:00 2001 From: Drewry Pope Date: Sat, 21 Nov 2026 06:43:15 -0600 Subject: [PATCH 2/2] Record health hook incidents in audit stream --- .../aggregator/src/health-hook-audit-event.ts | 22 ++++++ pm-stack/aggregator/src/server.ts | 13 ++++ .../test/health-hook-audit-event.test.ts | 67 +++++++++++++++++++ 3 files changed, 102 insertions(+) create mode 100644 pm-stack/aggregator/src/health-hook-audit-event.ts create mode 100644 pm-stack/aggregator/test/health-hook-audit-event.test.ts diff --git a/pm-stack/aggregator/src/health-hook-audit-event.ts b/pm-stack/aggregator/src/health-hook-audit-event.ts new file mode 100644 index 0000000000..fff3ebcaac --- /dev/null +++ b/pm-stack/aggregator/src/health-hook-audit-event.ts @@ -0,0 +1,22 @@ +import type { NewAuditEvent } from "./events.ts"; +import type { StackHealthInput } from "./stack-health.ts"; + +/** Map an authenticated health-hook intake into the append-only audit stream. */ +export function healthHookAuditEvent(input: { + title: string; + source: string; + stackHealth: StackHealthInput; +}): NewAuditEvent | null { + if (input.source !== "health-hook") return null; + const { serviceId, state, since } = input.stackHealth; + return { + id: `health-hook/${serviceId}/${state}/${since}`, + at: since, + actor: "health-hook", + kind: "health-hook-incident", + ref: `health-hook:${serviceId}`, + summary: input.title, + attribution: { confidence: "unknown", asserted: false }, + source: { identity: `health-hook/${serviceId}` }, + }; +} diff --git a/pm-stack/aggregator/src/server.ts b/pm-stack/aggregator/src/server.ts index 0b3962b496..4ed3aa0fdc 100644 --- a/pm-stack/aggregator/src/server.ts +++ b/pm-stack/aggregator/src/server.ts @@ -50,6 +50,7 @@ import { GithubHotListConsumer, unconfiguredGithubStatus } from "./github-hot-li import { RoadmapAnnotationsStore, validateNewRoadmapAnnotation } from "./roadmap-annotations.ts"; import { createAccessAuthorEnforcer, enforceAccessAuthor } from "./access-identity.ts"; import { IdentityRegistryStore, identityMappingAuditEvent, validateIdentityMapping } from "./identity-registry.ts"; +import { healthHookAuditEvent } from "./health-hook-audit-event.ts"; import { computeCoverage, CoverageSnapshotStore, @@ -3735,6 +3736,18 @@ async function handler(req: Request): Promise { if (!v.ok) return json({ error: v.error }, 400); try { await setStackHealth(cfg.stackHealthFile, v.value); + const auditEvent = healthHookAuditEvent({ + title: parsed.value.title, + source: parsed.value.source, + stackHealth: v.value, + }); + if (auditEvent) { + try { + await eventsStore.record(auditEvent); + } catch (err) { + console.error(`alerts intake: health-hook audit append failed (${err instanceof Error ? err.message : "error"})`); + } + } if (v.value.state === "up") { await store.closeOpenIncidentByKey(parsed.value.source, parsed.value.key); } diff --git a/pm-stack/aggregator/test/health-hook-audit-event.test.ts b/pm-stack/aggregator/test/health-hook-audit-event.test.ts new file mode 100644 index 0000000000..51a0884374 --- /dev/null +++ b/pm-stack/aggregator/test/health-hook-audit-event.test.ts @@ -0,0 +1,67 @@ +import { describe, expect, test } from "bun:test"; +import { mkdtemp, rm } from "node:fs/promises"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { EventsStore } from "../src/events.ts"; +import { healthHookAuditEvent } from "../src/health-hook-audit-event.ts"; + +describe("health-hook audit event (#9571)", () => { + const stackHealth = { + serviceId: "opencode-working", + name: "OpenCode working", + state: "down" as const, + since: "2026-11-21T12:00:00.000Z", + detail: "connect failed", + }; + + test("maps an incident to the event-stream audit contract", () => { + expect( + healthHookAuditEvent({ source: "health-hook", title: "Health hook: OpenCode working is down", stackHealth }), + ).toEqual({ + id: "health-hook/opencode-working/down/2026-11-21T12:00:00.000Z", + at: "2026-11-21T12:00:00.000Z", + actor: "health-hook", + kind: "health-hook-incident", + ref: "health-hook:opencode-working", + summary: "Health hook: OpenCode working is down", + attribution: { confidence: "unknown", asserted: false }, + source: { identity: "health-hook/opencode-working" }, + }); + }); + + test("also records recoveries and ignores unrelated stack-health producers", () => { + expect( + healthHookAuditEvent({ + source: "health-hook", + title: "Health hook: OpenCode working is up", + stackHealth: { ...stackHealth, state: "up", since: "2026-11-21T12:05:00.000Z" }, + }), + ).toMatchObject({ kind: "health-hook-incident", ref: "health-hook:opencode-working", actor: "health-hook" }); + expect(healthHookAuditEvent({ source: "other", title: "other producer", stackHealth })).toBeNull(); + }); + + test("appends both down and recovery records to the versioned event stream", async () => { + const dir = await mkdtemp(join(tmpdir(), "health-hook-events-")); + try { + const store = new EventsStore(join(dir, "events.json")); + const down = healthHookAuditEvent({ source: "health-hook", title: "OpenCode down", stackHealth }); + const up = healthHookAuditEvent({ + source: "health-hook", + title: "OpenCode recovered", + stackHealth: { ...stackHealth, state: "up", since: "2026-11-21T12:05:00.000Z" }, + }); + if (!down || !up) throw new Error("health-hook events should be generated"); + await store.record(down); + await store.record(up); + const records = await store.list({ ref: "health-hook:opencode-working" }); + expect(records).toHaveLength(2); + expect(records.map((event) => event.summary).sort()).toEqual(["OpenCode down", "OpenCode recovered"]); + expect(records.every((event) => event.kind === "health-hook-incident")).toBe(true); + expect(records.every((event) => event.attribution.confidence === "unknown" && !event.attribution.asserted)).toBe( + true, + ); + } finally { + await rm(dir, { recursive: true, force: true }); + } + }); +});