From 3e91ca6ef401f529d045a0c75d61d7cab6ea54f5 Mon Sep 17 00:00:00 2001 From: repo-worker-code-k Date: Tue, 10 Nov 2026 18:16:35 -0600 Subject: [PATCH 1/2] =?UTF-8?q?feat(pm-stack):=20rung-4=20watchdog=20escal?= =?UTF-8?q?ation=20hand-off=20=E2=80=94=20deduped=20queue=20task=20+=20inc?= =?UTF-8?q?ident=20issue,=20recovery,=20surfacing=20(#6033)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- pm-stack/exporters/README.md | 2 +- pm-stack/exporters/src/watchdog-escalation.ts | 270 ++++++++++++++++++ pm-stack/exporters/src/watchdog-state.ts | 38 +++ .../test/watchdog-escalation.test.ts | 193 +++++++++++++ 4 files changed, 502 insertions(+), 1 deletion(-) create mode 100644 pm-stack/exporters/src/watchdog-escalation.ts create mode 100644 pm-stack/exporters/test/watchdog-escalation.test.ts diff --git a/pm-stack/exporters/README.md b/pm-stack/exporters/README.md index 5acac95caa..8842d98a22 100644 --- a/pm-stack/exporters/README.md +++ b/pm-stack/exporters/README.md @@ -51,7 +51,7 @@ cd pm-stack/aggregator && bun test ../exporters/test/watchdog-state.test.ts - The repair executors for rungs 2 and 3 (CDP session re-validation, browser re-login driver), which stop dead at a human-only challenge and hand off to `recordRungOutcome`. -- The rung-4 escalation hand-off (contract owned by #6033). +- The rung-4 escalation hand-off module (#6033): plans the deduped queue-task + incident-issue effects behind injected effectors, records the refs on the incident, plans recovery (comment + close + complete), and renders the NEEDS DREW surfacing line (immediate when human-blocked, after 24 h unresolved otherwise). Production effectors (fleet CLI / gh) are wired by the entry point below. - Producer scaffolding under `pm-stack/exporters/` from the retired Meta producer pattern, and the gatherer `FILE_EXPORTS` registration. - `pm-stack/systemd/` oneshot + timer units on the gatherer cadence. diff --git a/pm-stack/exporters/src/watchdog-escalation.ts b/pm-stack/exporters/src/watchdog-escalation.ts new file mode 100644 index 0000000000..e44cc3a5ba --- /dev/null +++ b/pm-stack/exporters/src/watchdog-escalation.ts @@ -0,0 +1,270 @@ +// Rung 4 of the quota watchdog (#6033, design #6031): the escalation +// hand-off. The decision layer (watchdog-state.ts) says "escalate" once +// every repair rung is spent; this module is what that word MEANS in +// effects, kept behind injected effectors so the policy is testable +// without a queue, a network, or a browser: +// +// - exactly one fleet queue task and one GitHub incident issue per +// (source, failure class) while the incident is open — the dedupe +// record lives on the incident itself (Incident.escalation), so a +// second escalation tick for the same pair creates neither; +// - the queue task carries the full context packet (below), so a +// browser-enabled agent can start from the packet alone; +// - on the next producer success, the recovery plan comments the +// resolution on the incident issue, closes it, and completes the +// queue task — the watchdog's own state clears the incident in the +// same tick (decide's healthy path), nobody closes anything by hand; +// - surfacing follows the quiet-while-repairing rule: a human-blocked +// incident earns its NEEDS DREW line the same tick it is marked; an +// ordinary escalation stays quiet until it has been unresolved for +// ESCALATION_NEEDS_DREW_AFTER_MS (24 h default), then earns its line +// via the normal sweep path (surfacingLine is what a sweep renders). +// +// The production effectors (fleet queue enqueue via the fleet CLI, gh +// issue create/comment/close) are wired by the watchdog entry point — +// the #6032 remainder — which calls planEscalation / planRecovery with +// the tick's pre-decision health record and persists whatever +// recordEscalation returns. +import type { FailureClass, SourceHealth } from "./watchdog-state.ts"; + +/** How long an ordinary escalation stays quiet before it surfaces. */ +export const ESCALATION_NEEDS_DREW_AFTER_MS = 24 * 60 * 60_000; + +/** Per-source wiring the entry point supplies from the adapter. */ +export interface EscalationContext { + /** Repo that owns the adapter, e.g. "developing-today-forks/openchamber". */ + issueRepo: string; + /** Path of the watchdog state file, for the packet's context. */ + stateFilePath: string; + /** Adapter file reference, for the packet's context. */ + adapterRef: string; + /** Producer history reference (history.jsonl tail), for the packet. */ + historyRef: string; +} + +/** The full context packet carried by the rung-4 queue task (#6033). */ +export interface EscalationPacket { + schema: "watchdog-escalation/v1"; + kind: "small_fix"; + source: string; + /** Dedupe pair: (source, failure class). */ + dedupeKey: string; + outcomeWanted: string; + failure: { + class: FailureClass | null; + consecutiveFailures: number; + lastDetail: string; + /** The watchdog's persisted repair log — every rung tried. */ + repairLog: SourceHealth["repairLog"]; + historyRef: string; + stateFilePath: string; + adapterRef: string; + }; + requiredCapability: string; + acceptance: string; + stopConditions: string[]; +} + +export type EscalationAction = + | { type: "enqueue_task"; packet: EscalationPacket } + | { type: "open_issue"; repo: string; title: string; body: string; labels: string[] } + | { type: "comment_issue"; repo: string; issueNumber: number; body: string } + | { type: "close_issue"; repo: string; issueNumber: number } + | { type: "complete_task"; queueTaskId: string }; + +/** Side effects, injected. Production implementations shell to the + * fleet CLI / gh; tests count calls. */ +export interface EscalationEffectors { + enqueueTask(packet: EscalationPacket): Promise; + openIssue(action: Extract): Promise; + commentIssue(action: Extract): Promise; + closeIssue(action: Extract): Promise; + completeTask(action: Extract): Promise; +} + +export function escalationDedupeKey(source: string, cls: FailureClass | null): string { + return `watchdog-escalation:${source}:${cls ?? "unknown"}`; +} + +/** Build the queue-task packet for an incident that is escalating. */ +export function buildEscalationPacket(health: SourceHealth, ctx: EscalationContext): EscalationPacket { + const cls = health.currentClass; + return { + schema: "watchdog-escalation/v1", + kind: "small_fix", + source: health.source, + dedupeKey: escalationDedupeKey(health.source, cls), + outcomeWanted: `source \`${health.source}\` produces a fresh \`latest.json\` with real quota windows again`, + failure: { + class: cls, + consecutiveFailures: health.consecutiveFailures, + lastDetail: health.lastDetail, + repairLog: health.repairLog, + historyRef: ctx.historyRef, + stateFilePath: ctx.stateFilePath, + adapterRef: ctx.adapterRef, + }, + requiredCapability: + "browser-enabled agent; laptop Helium via CDP (:19222); adapter origins only", + acceptance: + "a fresh producer document lands and the watchdog auto-closes the incident (the fixer does not close anything by hand)", + stopConditions: [ + "a human-only challenge (2FA / verify-it's-you / passkey) -> stop, mark human-blocked, do not work around it", + "anything outside the adapter's origin allowlist -> stop and report on the incident issue", + ], + }; +} + +function issueTitle(health: SourceHealth): string { + return `watchdog incident: ${health.source} quota producer failing (${health.currentClass ?? "unknown"})`; +} + +function issueBody(health: SourceHealth, packet: EscalationPacket): string { + const rungs = health.repairLog.map((e) => `- ${e.at} rung ${e.rung}: ${e.outcome} — ${e.detail}`).join("\n"); + return [ + `The quota watchdog escalated source \`${health.source}\` after every repair rung was spent (#6033, design #6031).`, + "", + `- failure class: \`${packet.failure.class ?? "unknown"}\``, + `- consecutive failures: ${packet.failure.consecutiveFailures}`, + `- last detail: ${packet.failure.lastDetail || "(none)"}`, + `- incident id: \`${health.incident?.id ?? "?"}\``, + "", + "Repair log (every rung tried):", + rungs || "- (empty)", + "", + `A fleet queue task carries the full context packet (dedupe key \`${packet.dedupeKey}\`). This issue is the durable record and the fixing agent's reporting surface; the watchdog auto-closes it on the next producer success.`, + ].join("\n"); +} + +/** + * Plan the rung-4 effects for a tick whose health record carries an + * escalating incident. Pure: returns the actions to run, or an empty + * list when the (source, class) pair is already escalated (dedupe) or + * the incident is not in an escalating state. + */ +export function planEscalation( + health: SourceHealth, + ctx: EscalationContext, +): { actions: EscalationAction[]; deduped: boolean } { + const incident = health.incident; + if (!incident || incident.surfacing !== "escalate" || incident.humanBlocked) { + return { actions: [], deduped: false }; + } + const existing = incident.escalation; + if (existing && existing.class === health.currentClass) { + return { actions: [], deduped: true }; + } + const packet = buildEscalationPacket(health, ctx); + return { + deduped: false, + actions: [ + { type: "enqueue_task", packet }, + { + type: "open_issue", + repo: ctx.issueRepo, + title: issueTitle(health), + body: issueBody(health, packet), + labels: ["watchdog-incident"], + }, + ], + }; +} + +/** Persist the confirmed effect results onto the incident record. */ +export function recordEscalation( + health: SourceHealth, + ctx: EscalationContext, + refs: { queueTaskId: string | null; issueNumber: number | null }, + at: string, +): SourceHealth { + if (!health.incident) return health; + return { + ...health, + incident: { + ...health.incident, + escalation: { + class: health.currentClass ?? "unknown", + since: at, + queueTaskId: refs.queueTaskId, + issueRepo: ctx.issueRepo, + issueNumber: refs.issueNumber, + }, + }, + }; +} + +/** + * The NEEDS DREW line for this source, or null while it should stay + * quiet. Human-blocked surfaces the same tick it is marked; an ordinary + * escalation surfaces only once unresolved for the threshold. + */ +export function surfacingLine(health: SourceHealth, now: number): string | null { + const incident = health.incident; + if (!incident) return null; + if (incident.humanBlocked || incident.surfacing === "human-blocked") { + return `NEEDS DREW: ${health.source} quota producer is human-blocked (${health.currentClass ?? "unknown"}: ${health.lastDetail || "human-only challenge"}) — incident ${incident.id}`; + } + const esc = incident.escalation; + if (esc) { + const since = Date.parse(esc.since); + if (Number.isFinite(since) && now - since >= ESCALATION_NEEDS_DREW_AFTER_MS) { + return `NEEDS DREW: ${health.source} quota escalation unresolved for 24h (${esc.class}) — incident ${incident.id}, issue ${esc.issueRepo}#${esc.issueNumber ?? "?"}`; + } + } + return null; +} + +/** + * Plan the recovery effects for a source whose incident was escalated + * and whose latest observation is a producer success. Call with the + * PRE-tick health record (decide's healthy path clears the incident in + * the next record; the refs live on the old one). Pure. + */ +export function planRecovery(health: SourceHealth, recoveredAt: string): EscalationAction[] { + const esc = health.incident?.escalation; + if (!esc) return []; + const actions: EscalationAction[] = []; + if (esc.issueNumber !== null) { + actions.push({ + type: "comment_issue", + repo: esc.issueRepo, + issueNumber: esc.issueNumber, + body: `Recovered: source \`${health.source}\` produced a fresh document at ${recoveredAt}; the watchdog is auto-closing this incident (#6033).`, + }); + actions.push({ type: "close_issue", repo: esc.issueRepo, issueNumber: esc.issueNumber }); + } + if (esc.queueTaskId !== null) { + actions.push({ type: "complete_task", queueTaskId: esc.queueTaskId }); + } + return actions; +} + +/** Run planned actions through the effectors, in order, collecting the + * refs recordEscalation needs. */ +export async function applyEscalationActions( + actions: EscalationAction[], + effectors: EscalationEffectors, +): Promise<{ queueTaskId: string | null; issueNumber: number | null }> { + let queueTaskId: string | null = null; + let issueNumber: number | null = null; + for (const action of actions) { + switch (action.type) { + case "enqueue_task": + queueTaskId = await effectors.enqueueTask(action.packet); + break; + case "open_issue": + issueNumber = await effectors.openIssue(action); + break; + case "comment_issue": + await effectors.commentIssue(action); + break; + case "close_issue": + await effectors.closeIssue(action); + break; + case "complete_task": + await effectors.completeTask(action); + break; + } + } + return { queueTaskId, issueNumber }; +} diff --git a/pm-stack/exporters/src/watchdog-state.ts b/pm-stack/exporters/src/watchdog-state.ts index d5e8a30c00..0544e9b6c6 100644 --- a/pm-stack/exporters/src/watchdog-state.ts +++ b/pm-stack/exporters/src/watchdog-state.ts @@ -80,6 +80,25 @@ export interface Incident { humanBlocked: boolean; /** Surfacing flag the stewardship/orchestration sweeps read. */ surfacing: "none" | "human-blocked" | "escalate"; + /** Rung-4 hand-off record (#6033), set once the escalation effects + * have run for this incident. Its (source, class) pair is the dedupe + * key: while it is present, no second queue task or incident issue + * is created for the same failure. Absent/null = not yet escalated. */ + escalation?: EscalationRecord | null; +} + +/** What rung 4 created for one incident (#6033). */ +export interface EscalationRecord { + /** Failure class at escalation time — half of the dedupe pair. */ + class: FailureClass; + /** When the escalation effects ran. */ + since: string; + /** Fleet queue task id, or null if the enqueue has not confirmed. */ + queueTaskId: string | null; + /** Repo owning the adapter (and therefore the incident issue). */ + issueRepo: string; + /** Incident issue number, or null if creation has not confirmed. */ + issueNumber: number | null; } /** What one tick saw for one source. */ @@ -389,6 +408,24 @@ export function coerceHealth(source: string, raw: unknown): SourceHealth { })) .slice(-REPAIR_LOG_LIMIT); const incidentRaw = r.incident as Record | null | undefined; + const escRaw = (incidentRaw?.escalation ?? null) as Record | null; + const escalation: EscalationRecord | null = + typeof escRaw === "object" && + escRaw !== null && + FAILURE_CLASSES.includes(escRaw.class as FailureClass) && + typeof escRaw.since === "string" && + typeof escRaw.issueRepo === "string" + ? { + class: escRaw.class as FailureClass, + since: escRaw.since, + queueTaskId: typeof escRaw.queueTaskId === "string" ? escRaw.queueTaskId : null, + issueRepo: escRaw.issueRepo, + issueNumber: + typeof escRaw.issueNumber === "number" && Number.isFinite(escRaw.issueNumber) + ? escRaw.issueNumber + : null, + } + : null; const incident: Incident | null = typeof incidentRaw === "object" && incidentRaw !== null && typeof incidentRaw.id === "string" ? { @@ -398,6 +435,7 @@ export function coerceHealth(source: string, raw: unknown): SourceHealth { surfacing: (["none", "human-blocked", "escalate"].includes(incidentRaw.surfacing as string) ? incidentRaw.surfacing : "none") as Incident["surfacing"], + escalation, } : null; return { diff --git a/pm-stack/exporters/test/watchdog-escalation.test.ts b/pm-stack/exporters/test/watchdog-escalation.test.ts new file mode 100644 index 0000000000..8e7c0893c9 --- /dev/null +++ b/pm-stack/exporters/test/watchdog-escalation.test.ts @@ -0,0 +1,193 @@ +// Rung-4 escalation hand-off (#6033) — oracle: the acceptance criteria +// on issue #6033, exercised against fixture health records and counting +// fake effectors. No queue, network, or browser is touched. +import { describe, expect, test } from "bun:test"; +import { + applyEscalationActions, + buildEscalationPacket, + ESCALATION_NEEDS_DREW_AFTER_MS, + planEscalation, + planRecovery, + recordEscalation, + surfacingLine, + type EscalationContext, + type EscalationEffectors, +} from "../src/watchdog-escalation.ts"; +import { coerceHealth, initialHealth, type SourceHealth } from "../src/watchdog-state.ts"; + +const CTX: EscalationContext = { + issueRepo: "developing-today-forks/openchamber", + stateFilePath: "/home/user/atlas/watchdog-state.json", + adapterRef: "pm-stack/exporters/adapters/mistral.ts", + historyRef: "quota-watchdog-history.jsonl (tail)", +}; + +const T0 = "2026-11-10T00:00:00Z"; + +function escalatingHealth(): SourceHealth { + const h = initialHealth("mistral"); + return { + ...h, + consecutiveFailures: 9, + currentClass: "session-expired", + lastDetail: "login redirected to auth wall", + lastAttemptAt: T0, + repairLog: [ + { at: T0, rung: 1, outcome: "failed", detail: "retry: still redirected" }, + { at: T0, rung: 3, outcome: "failed", detail: "re-login: session not accepted" }, + { at: T0, rung: 3, outcome: "failed", detail: "all rungs exhausted; escalating" }, + ], + incident: { + id: "mistral:2026-11-09T20:00:00Z", + openedAt: "2026-11-09T20:00:00Z", + humanBlocked: false, + surfacing: "escalate", + escalation: null, + }, + }; +} + +function countingEffectors() { + const calls: string[] = []; + const effectors: EscalationEffectors = { + enqueueTask: async () => { + calls.push("enqueue"); + return "task-4242"; + }, + openIssue: async () => { + calls.push("open"); + return 777; + }, + commentIssue: async () => { + calls.push("comment"); + }, + closeIssue: async () => { + calls.push("close"); + }, + completeTask: async () => { + calls.push("complete"); + }, + }; + return { calls, effectors }; +} + +describe("planEscalation + dedupe (#6033 acceptance 1)", () => { + test("first escalation plans exactly one task and one issue; the recorded second creates neither", async () => { + const health = escalatingHealth(); + const plan = planEscalation(health, CTX); + expect(plan.deduped).toBe(false); + expect(plan.actions.map((a) => a.type)).toEqual(["enqueue_task", "open_issue"]); + + const { calls, effectors } = countingEffectors(); + const refs = await applyEscalationActions(plan.actions, effectors); + expect(calls).toEqual(["enqueue", "open"]); + expect(refs).toEqual({ queueTaskId: "task-4242", issueNumber: 777 }); + + const recorded = recordEscalation(health, CTX, refs, T0); + expect(recorded.incident?.escalation?.class).toBe("session-expired"); + const again = planEscalation(recorded, CTX); + expect(again.deduped).toBe(true); + expect(again.actions).toEqual([]); + }); + + test("a different failure class for the same source is a new pair and plans again", () => { + const recorded = recordEscalation(escalatingHealth(), CTX, { queueTaskId: "t", issueNumber: 1 }, T0); + const changed: SourceHealth = { ...recorded, currentClass: "endpoint-changed" }; + const plan = planEscalation(changed, CTX); + expect(plan.deduped).toBe(false); + expect(plan.actions).toHaveLength(2); + }); + + test("no plan when the incident is quiet, absent, or human-blocked", () => { + const quiet = initialHealth("mistral"); + expect(planEscalation(quiet, CTX).actions).toEqual([]); + const hb = escalatingHealth(); + hb.incident = { ...hb.incident!, humanBlocked: true, surfacing: "human-blocked" }; + expect(planEscalation(hb, CTX).actions).toEqual([]); + }); +}); + +describe("packet completeness (#6033 acceptance 2)", () => { + test("packet carries outcome, failure context, capability, acceptance, stop conditions", () => { + const packet = buildEscalationPacket(escalatingHealth(), CTX); + expect(packet.outcomeWanted).toContain("mistral"); + expect(packet.outcomeWanted).toContain("latest.json"); + expect(packet.failure.class).toBe("session-expired"); + expect(packet.failure.consecutiveFailures).toBe(9); + expect(packet.failure.repairLog).toHaveLength(3); + expect(packet.failure.stateFilePath).toBe(CTX.stateFilePath); + expect(packet.failure.adapterRef).toBe(CTX.adapterRef); + expect(packet.failure.historyRef).toBe(CTX.historyRef); + expect(packet.requiredCapability).toContain("browser-enabled"); + expect(packet.requiredCapability).toContain(":19222"); + expect(packet.acceptance).toContain("auto-closes"); + expect(packet.stopConditions.join(" ")).toContain("human-only challenge"); + expect(packet.stopConditions.join(" ")).toContain("origin allowlist"); + expect(packet.dedupeKey).toBe("watchdog-escalation:mistral:session-expired"); + }); +}); + +describe("recovery (#6033 acceptance 3)", () => { + test("producer success plans comment + close + task completion against the recorded refs", async () => { + const recorded = recordEscalation( + escalatingHealth(), + CTX, + { queueTaskId: "task-4242", issueNumber: 777 }, + T0, + ); + const actions = planRecovery(recorded, "2026-11-10T06:00:00Z"); + expect(actions.map((a) => a.type)).toEqual(["comment_issue", "close_issue", "complete_task"]); + const { calls, effectors } = countingEffectors(); + await applyEscalationActions(actions, effectors); + expect(calls).toEqual(["comment", "close", "complete"]); + }); + + test("no recovery actions when nothing was escalated", () => { + expect(planRecovery(escalatingHealth(), T0)).toEqual([]); + expect(planRecovery(initialHealth("mistral"), T0)).toEqual([]); + }); +}); + +describe("surfacing (#6033 acceptance 4 + 5)", () => { + test("human-blocked surfaces the same tick, with a one-line reason", () => { + const hb = escalatingHealth(); + hb.incident = { ...hb.incident!, humanBlocked: true, surfacing: "human-blocked" }; + const line = surfacingLine(hb, Date.parse(T0)); + expect(line).toContain("NEEDS DREW"); + expect(line).toContain("human-blocked"); + expect(line).not.toContain("\n"); + }); + + test("ordinary escalation is quiet before 24h and surfaces at the threshold", () => { + const recorded = recordEscalation( + escalatingHealth(), + CTX, + { queueTaskId: "task-4242", issueNumber: 777 }, + T0, + ); + const t0 = Date.parse(T0); + expect(surfacingLine(recorded, t0 + ESCALATION_NEEDS_DREW_AFTER_MS - 1)).toBeNull(); + const line = surfacingLine(recorded, t0 + ESCALATION_NEEDS_DREW_AFTER_MS); + expect(line).toContain("NEEDS DREW"); + expect(line).toContain("777"); + }); +}); + +describe("state coercion keeps the escalation record", () => { + test("coerceHealth round-trips a valid escalation and drops a malformed one", () => { + const recorded = recordEscalation( + escalatingHealth(), + CTX, + { queueTaskId: "task-4242", issueNumber: 777 }, + T0, + ); + const back = coerceHealth("mistral", JSON.parse(JSON.stringify(recorded))); + expect(back.incident?.escalation?.queueTaskId).toBe("task-4242"); + expect(back.incident?.escalation?.issueNumber).toBe(777); + + const corrupt = JSON.parse(JSON.stringify(recorded)); + corrupt.incident.escalation = { class: "not-a-class", since: 5 }; + const dropped = coerceHealth("mistral", corrupt); + expect(dropped.incident?.escalation).toBeNull(); + }); +}); From 92193bfcd63b6610f2d97c0f1b45d60f766b47b1 Mon Sep 17 00:00:00 2001 From: repo-worker-tmp-code-b Date: Sat, 14 Nov 2026 14:59:43 -0600 Subject: [PATCH 2/2] fix(watchdog-escalation): preserve class-change hand-offs, surface partial-progress refs, use persisted challenge reason (Codex P2 x3 on #8357) --- pm-stack/exporters/src/watchdog-escalation.ts | 188 +++++++++++++----- pm-stack/exporters/src/watchdog-state.ts | 42 ++-- .../test/watchdog-escalation.test.ts | 99 +++++++++ 3 files changed, 263 insertions(+), 66 deletions(-) diff --git a/pm-stack/exporters/src/watchdog-escalation.ts b/pm-stack/exporters/src/watchdog-escalation.ts index e44cc3a5ba..484018b662 100644 --- a/pm-stack/exporters/src/watchdog-escalation.ts +++ b/pm-stack/exporters/src/watchdog-escalation.ts @@ -25,7 +25,7 @@ // the #6032 remainder — which calls planEscalation / planRecovery with // the tick's pre-decision health record and persists whatever // recordEscalation returns. -import type { FailureClass, SourceHealth } from "./watchdog-state.ts"; +import type { EscalationRecord, FailureClass, SourceHealth } from "./watchdog-state.ts"; /** How long an ordinary escalation stays quiet before it surfaces. */ export const ESCALATION_NEEDS_DREW_AFTER_MS = 24 * 60 * 60_000; @@ -150,23 +150,34 @@ export function planEscalation( if (!incident || incident.surfacing !== "escalate" || incident.humanBlocked) { return { actions: [], deduped: false }; } + const packet = buildEscalationPacket(health, ctx); + const openIssue: EscalationAction = { + type: "open_issue", + repo: ctx.issueRepo, + title: issueTitle(health), + body: issueBody(health, packet), + labels: ["watchdog-incident"], + }; + // Dedupe consults every hand-off this incident carries, not just + // the latest (Codex P2 on PR #8357): a failure class that changes + // back finds its original pair in `previous` instead of creating a + // third hand-off. const existing = incident.escalation; - if (existing && existing.class === health.currentClass) { - return { actions: [], deduped: true }; + const records: EscalationRecord[] = existing + ? [existing, ...(existing.previous ?? [])] + : []; + const forClass = records.find((r) => r.class === health.currentClass); + if (forClass) { + // Resume a partial hand-off: plan only the creations that never + // confirmed, so a retry cannot duplicate the confirmed half. + const actions: EscalationAction[] = []; + if (forClass.queueTaskId === null) actions.push({ type: "enqueue_task", packet }); + if (forClass.issueNumber === null) actions.push(openIssue); + return { actions, deduped: actions.length === 0 }; } - const packet = buildEscalationPacket(health, ctx); return { deduped: false, - actions: [ - { type: "enqueue_task", packet }, - { - type: "open_issue", - repo: ctx.issueRepo, - title: issueTitle(health), - body: issueBody(health, packet), - labels: ["watchdog-incident"], - }, - ], + actions: [{ type: "enqueue_task", packet }, openIssue], }; } @@ -178,18 +189,42 @@ export function recordEscalation( at: string, ): SourceHealth { if (!health.incident) return health; + const cls = health.currentClass ?? "unknown"; + const prev = health.incident.escalation; + let escalation: EscalationRecord; + if (prev && prev.class === cls) { + // Same pair: merge — a confirmed ref is never overwritten by a + // later partial result, and the original `since` stands. + escalation = { + ...prev, + queueTaskId: prev.queueTaskId ?? refs.queueTaskId, + issueNumber: prev.issueNumber ?? refs.issueNumber, + }; + } else if (prev) { + // Class changed: the displaced hand-off stays on the record + // (flattened into `previous`) so recovery can close and complete + // it and dedupe can find it again (Codex P2 on PR #8357). + const { previous: prevPrevious, ...prevFlat } = prev; + escalation = { + class: cls as EscalationRecord["class"], + since: at, + queueTaskId: refs.queueTaskId, + issueRepo: ctx.issueRepo, + issueNumber: refs.issueNumber, + previous: [...(prevPrevious ?? []), prevFlat], + }; + } else { + escalation = { + class: cls as EscalationRecord["class"], + since: at, + queueTaskId: refs.queueTaskId, + issueRepo: ctx.issueRepo, + issueNumber: refs.issueNumber, + }; + } return { ...health, - incident: { - ...health.incident, - escalation: { - class: health.currentClass ?? "unknown", - since: at, - queueTaskId: refs.queueTaskId, - issueRepo: ctx.issueRepo, - issueNumber: refs.issueNumber, - }, - }, + incident: { ...health.incident, escalation }, }; } @@ -198,11 +233,26 @@ export function recordEscalation( * quiet. Human-blocked surfaces the same tick it is marked; an ordinary * escalation surfaces only once unresolved for the threshold. */ +// Mirrors the human-only challenge pattern recordRungOutcome in +// watchdog-state.ts uses to mark an incident human-blocked. +const HUMAN_CHALLENGE_RE = /human[- ]only|2fa|passkey|verify[- ]it/i; + export function surfacingLine(health: SourceHealth, now: number): string | null { const incident = health.incident; if (!incident) return null; if (incident.humanBlocked || incident.surfacing === "human-blocked") { - return `NEEDS DREW: ${health.source} quota producer is human-blocked (${health.currentClass ?? "unknown"}: ${health.lastDetail || "human-only challenge"}) — incident ${incident.id}`; + // Surface the persisted challenge reason (Codex P2 on PR #8357): + // the repair-log entry that tripped the human-blocked mark names + // the intervention actually needed. health.lastDetail is the + // latest PRODUCER observation and can name a different, earlier + // symptom — and later blocked ticks can overwrite it again. + const challenge = [...health.repairLog] + .reverse() + .find((e) => e.outcome === "failed" && HUMAN_CHALLENGE_RE.test(e.detail)); + const reason = challenge + ? challenge.detail + : health.lastDetail || "human-only challenge"; + return `NEEDS DREW: ${health.source} quota producer is human-blocked (${health.currentClass ?? "unknown"}: ${reason}) — incident ${incident.id}`; } const esc = incident.escalation; if (esc) { @@ -223,24 +273,52 @@ export function surfacingLine(health: SourceHealth, now: number): string | null export function planRecovery(health: SourceHealth, recoveredAt: string): EscalationAction[] { const esc = health.incident?.escalation; if (!esc) return []; + // Close and complete EVERY hand-off the incident carries (Codex P2 + // on PR #8357): when the failure class changed mid-incident, the + // earlier pair in `previous` is just as open as the latest one. + const records: EscalationRecord[] = [esc, ...(esc.previous ?? [])]; const actions: EscalationAction[] = []; - if (esc.issueNumber !== null) { - actions.push({ - type: "comment_issue", - repo: esc.issueRepo, - issueNumber: esc.issueNumber, - body: `Recovered: source \`${health.source}\` produced a fresh document at ${recoveredAt}; the watchdog is auto-closing this incident (#6033).`, - }); - actions.push({ type: "close_issue", repo: esc.issueRepo, issueNumber: esc.issueNumber }); - } - if (esc.queueTaskId !== null) { - actions.push({ type: "complete_task", queueTaskId: esc.queueTaskId }); + for (const rec of records) { + if (rec.issueNumber !== null) { + actions.push({ + type: "comment_issue", + repo: rec.issueRepo, + issueNumber: rec.issueNumber, + body: `Recovered: source \`${health.source}\` produced a fresh document at ${recoveredAt}; the watchdog is auto-closing this incident (#6033).`, + }); + actions.push({ type: "close_issue", repo: rec.issueRepo, issueNumber: rec.issueNumber }); + } + if (rec.queueTaskId !== null) { + actions.push({ type: "complete_task", queueTaskId: rec.queueTaskId }); + } } return actions; } +/** A planned action failed after earlier actions in the same plan + * had already confirmed effects (Codex P2 on PR #8357). The + * confirmed refs ride on the error so the caller can persist them + * via recordEscalation before retrying — without them, the retry + * plan would re-create the confirmed half and duplicate repair + * work, and recovery could never complete the orphaned task. */ +export class EscalationPartialError extends Error { + readonly refs: { queueTaskId: string | null; issueNumber: number | null }; + constructor( + cause: unknown, + refs: { queueTaskId: string | null; issueNumber: number | null }, + ) { + super( + `escalation action failed after partial progress (queueTaskId=${refs.queueTaskId}, issueNumber=${refs.issueNumber}): ${cause instanceof Error ? cause.message : String(cause)}`, + ); + this.name = "EscalationPartialError"; + this.refs = refs; + this.cause = cause; + } +} + /** Run planned actions through the effectors, in order, collecting the - * refs recordEscalation needs. */ + * refs recordEscalation needs. On failure the thrown + * EscalationPartialError carries the refs confirmed so far. */ export async function applyEscalationActions( actions: EscalationAction[], effectors: EscalationEffectors, @@ -248,22 +326,26 @@ export async function applyEscalationActions( let queueTaskId: string | null = null; let issueNumber: number | null = null; for (const action of actions) { - switch (action.type) { - case "enqueue_task": - queueTaskId = await effectors.enqueueTask(action.packet); - break; - case "open_issue": - issueNumber = await effectors.openIssue(action); - break; - case "comment_issue": - await effectors.commentIssue(action); - break; - case "close_issue": - await effectors.closeIssue(action); - break; - case "complete_task": - await effectors.completeTask(action); - break; + try { + switch (action.type) { + case "enqueue_task": + queueTaskId = await effectors.enqueueTask(action.packet); + break; + case "open_issue": + issueNumber = await effectors.openIssue(action); + break; + case "comment_issue": + await effectors.commentIssue(action); + break; + case "close_issue": + await effectors.closeIssue(action); + break; + case "complete_task": + await effectors.completeTask(action); + break; + } + } catch (err) { + throw new EscalationPartialError(err, { queueTaskId, issueNumber }); } } return { queueTaskId, issueNumber }; diff --git a/pm-stack/exporters/src/watchdog-state.ts b/pm-stack/exporters/src/watchdog-state.ts index 84de27c16b..edd8fd9330 100644 --- a/pm-stack/exporters/src/watchdog-state.ts +++ b/pm-stack/exporters/src/watchdog-state.ts @@ -99,6 +99,13 @@ export interface EscalationRecord { issueRepo: string; /** Incident issue number, or null if creation has not confirmed. */ issueNumber: number | null; + /** Earlier hand-offs for OTHER failure classes of this same + * incident, displaced as "current" when the class changed but + * still open (Codex P2 on PR #8357): dedupe consults them (a class + * that changes back finds its pair here) and recovery closes and + * completes every one. Flat: entries carry no `previous` of their + * own. Absent = no earlier hand-off. */ + previous?: EscalationRecord[]; } /** What one tick saw for one source. */ @@ -407,24 +414,33 @@ export function coerceHealth(source: string, raw: unknown): SourceHealth { })) .slice(-REPAIR_LOG_LIMIT); const incidentRaw = r.incident as Record | null | undefined; - const escRaw = (incidentRaw?.escalation ?? null) as Record | null; - const escalation: EscalationRecord | null = - typeof escRaw === "object" && - escRaw !== null && - FAILURE_CLASSES.includes(escRaw.class as FailureClass) && - typeof escRaw.since === "string" && - typeof escRaw.issueRepo === "string" + const coerceEscalation = (raw: unknown): EscalationRecord | null => { + const e = raw as Record | null; + return typeof e === "object" && + e !== null && + FAILURE_CLASSES.includes(e.class as FailureClass) && + typeof e.since === "string" && + typeof e.issueRepo === "string" ? { - class: escRaw.class as FailureClass, - since: escRaw.since, - queueTaskId: typeof escRaw.queueTaskId === "string" ? escRaw.queueTaskId : null, - issueRepo: escRaw.issueRepo, + class: e.class as FailureClass, + since: e.since, + queueTaskId: typeof e.queueTaskId === "string" ? e.queueTaskId : null, + issueRepo: e.issueRepo, issueNumber: - typeof escRaw.issueNumber === "number" && Number.isFinite(escRaw.issueNumber) - ? escRaw.issueNumber + typeof e.issueNumber === "number" && Number.isFinite(e.issueNumber) + ? e.issueNumber : null, } : null; + }; + const escRaw = (incidentRaw?.escalation ?? null) as Record | null; + const escalation: EscalationRecord | null = coerceEscalation(escRaw); + if (escalation && Array.isArray(escRaw?.previous)) { + const previous = escRaw.previous + .map((entry) => coerceEscalation(entry)) + .filter((entry): entry is EscalationRecord => entry !== null); + if (previous.length > 0) escalation.previous = previous; + } const incident: Incident | null = typeof incidentRaw === "object" && incidentRaw !== null && typeof incidentRaw.id === "string" ? { diff --git a/pm-stack/exporters/test/watchdog-escalation.test.ts b/pm-stack/exporters/test/watchdog-escalation.test.ts index 8e7c0893c9..82ba611072 100644 --- a/pm-stack/exporters/test/watchdog-escalation.test.ts +++ b/pm-stack/exporters/test/watchdog-escalation.test.ts @@ -5,6 +5,7 @@ import { describe, expect, test } from "bun:test"; import { applyEscalationActions, buildEscalationPacket, + EscalationPartialError, ESCALATION_NEEDS_DREW_AFTER_MS, planEscalation, planRecovery, @@ -191,3 +192,101 @@ describe("state coercion keeps the escalation record", () => { expect(dropped.incident?.escalation).toBeNull(); }); }); + +describe("Codex findings on PR #8357 (class change, partial progress, surfacing reason)", () => { + test("a class change preserves the earlier hand-off; recovery closes both pairs; changing back dedupes", () => { + const first = recordEscalation( + escalatingHealth(), + CTX, + { queueTaskId: "task-a", issueNumber: 111 }, + T0, + ); + const changed: SourceHealth = { ...first, currentClass: "endpoint-changed" }; + const second = recordEscalation(changed, CTX, { queueTaskId: "task-b", issueNumber: 222 }, T0); + expect(second.incident?.escalation?.class).toBe("endpoint-changed"); + expect(second.incident?.escalation?.previous).toHaveLength(1); + expect(second.incident?.escalation?.previous?.[0]).toMatchObject({ + class: "session-expired", + queueTaskId: "task-a", + issueNumber: 111, + }); + + const actions = planRecovery(second, "2026-11-10T06:00:00Z"); + expect(actions.map((a) => a.type)).toEqual([ + "comment_issue", + "close_issue", + "complete_task", + "comment_issue", + "close_issue", + "complete_task", + ]); + const completes = actions.filter((a) => a.type === "complete_task"); + expect(completes.map((a) => (a as { queueTaskId: string }).queueTaskId)).toEqual([ + "task-b", + "task-a", + ]); + + const backAgain: SourceHealth = { ...second, currentClass: "session-expired" }; + const plan = planEscalation(backAgain, CTX); + expect(plan.deduped).toBe(true); + expect(plan.actions).toEqual([]); + }); + + test("a failed openIssue surfaces the confirmed task id; the retry plans only the missing issue", async () => { + const health = escalatingHealth(); + const plan = planEscalation(health, CTX); + const failing: EscalationEffectors = { + enqueueTask: async () => "task-4242", + openIssue: async () => { + throw new Error("gh unavailable"); + }, + commentIssue: async () => {}, + closeIssue: async () => {}, + completeTask: async () => {}, + }; + const err = await applyEscalationActions(plan.actions, failing).catch((e: unknown) => e); + expect(err).toBeInstanceOf(EscalationPartialError); + expect((err as EscalationPartialError).refs).toEqual({ + queueTaskId: "task-4242", + issueNumber: null, + }); + + const recorded = recordEscalation(health, CTX, (err as EscalationPartialError).refs, T0); + const retry = planEscalation(recorded, CTX); + expect(retry.deduped).toBe(false); + expect(retry.actions.map((a) => a.type)).toEqual(["open_issue"]); + + const completed = recordEscalation(recorded, CTX, { queueTaskId: null, issueNumber: 777 }, T0); + expect(completed.incident?.escalation?.queueTaskId).toBe("task-4242"); + expect(completed.incident?.escalation?.issueNumber).toBe(777); + expect(completed.incident?.escalation?.since).toBe(T0); + expect(planEscalation(completed, CTX).deduped).toBe(true); + }); + + test("human-blocked surfacing names the persisted challenge reason, not the producer detail", () => { + const hb = escalatingHealth(); + hb.lastDetail = "HTTP 401"; + hb.repairLog = [ + ...hb.repairLog, + { at: T0, rung: 4, outcome: "failed", detail: "passkey required on the laptop" }, + ]; + hb.incident = { ...hb.incident!, humanBlocked: true, surfacing: "human-blocked" }; + const line = surfacingLine(hb, Date.parse(T0)); + expect(line).toContain("passkey required on the laptop"); + expect(line).not.toContain("HTTP 401"); + }); + + test("coerceHealth round-trips the previous hand-offs", () => { + const first = recordEscalation( + escalatingHealth(), + CTX, + { queueTaskId: "task-a", issueNumber: 111 }, + T0, + ); + const changed: SourceHealth = { ...first, currentClass: "endpoint-changed" }; + const second = recordEscalation(changed, CTX, { queueTaskId: "task-b", issueNumber: 222 }, T0); + const back = coerceHealth("mistral", JSON.parse(JSON.stringify(second))); + expect(back.incident?.escalation?.previous).toHaveLength(1); + expect(back.incident?.escalation?.previous?.[0].queueTaskId).toBe("task-a"); + }); +});