Repository navigation
C3 health hooks: wire opencode-working into lane launchers and aggregator ticks (#9571) #12226
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Changes from all commits
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -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}` }, | ||
| }; | ||
| } |
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -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; | ||
| } | ||
| } | ||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -888,6 +888,9 @@ export function liveSource( | |
| cfg: Config, | ||
| opts?: { | ||
| standingAuto?: () => Promise<boolean>; | ||
| // 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<boolean>; | ||
| // 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"); | ||
|
Comment on lines
1386
to
+1388
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more.
If an outage lasts long enough for this hook to record Useful? React with 👍 / 👎. There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Close incidents that aggregator-tick failures open when the laptop recovers. An aggregator-tick failure runs Define how an aggregator-tick incident closes after the laptop recovers. The fix must ensure that a recovery closes an incident opened by this path, whether through the aggregator success path or the sentinel's state.
|
||
| } | ||
| return mapped; | ||
| })().finally(() => { | ||
|
|
||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -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 }); | ||
| } | ||
| }); | ||
| }); |
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -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], | ||
|
Comment on lines
+754
to
+755
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Make the health hook probe the OpenCode endpoint that the session reader uses.
Have the hook read
|
||
| 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, | ||
|
|
||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -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" | ||
| ) | ||
|
Comment on lines
+487
to
+489
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Isolate the health hook in
Patch the hook in Suggested fix
|
||
| return { | ||
| "task": task_id, | ||
| "queue": queue_name, | ||
|
|
||
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Resolve the hook path from the configured checkout.
fireOpenCodeWorkingHookhard-codes~/git/codefor the hook location. Other aggregator readers usecfg.codeCheckout, which honorsPM_AGG_CODE_CHECKOUT. When an operator sets that override to another checkout, the hard-coded path points to a file that may not exist. The spawn then fails, the error is logged, and the hook does not fire on lane-launch or aggregator-tick failures.Pass the configured checkout into the function and build the hook path from it, with
pm-stack/health-hooks/opencode-working.shrelative to that root. Update the call site atserver.ts:488to pass the same configured value. Keep the default-path behavior unchanged.