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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 5 additions & 4 deletions pm-stack/exporters/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -28,9 +28,10 @@ of exactly this kind of state machine.

`src/watchdog-escalation.ts` — the **rung-4 hand-off** (#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). The hand-off creates
records the refs on the incident, plans recovery comments without
disposing of the issue or queue task, and renders the NEEDS DREW
surfacing line (immediate when human-blocked, after 24 h unresolved
otherwise). The hand-off creates
the incident issue **first**: fleet queue validation only accepts a
`small_fix` packet whose fix-family dedupe key names an existing issue
(`repo-health:v1:fix:<repo>:issue:<n>`, payload.issue.number matching),
Expand Down Expand Up @@ -100,7 +101,7 @@ challenge, quiet-when-healthy).
`test/watchdog.test.ts` covers the entry point end to end against a
scratch tree: the same four acceptance fixtures driven through `runTick`
(the ladder walk escalates exactly once and dedupes on later ticks;
recovery comments/closes/completes the hand-off), cross-invocation
recovery comments without disposing of the hand-off), cross-invocation
persistence (every tick re-reads the state file from disk — the #5928
oracle), the classification of missing-document / stale-read / dead-CDP
observations, and the adapter loader's defect handling.
Expand Down
54 changes: 21 additions & 33 deletions pm-stack/exporters/src/watchdog-escalation.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,18 +10,18 @@
// 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;
// - on producer success, the recovery plan comments the resolution on
// the incident issue and clears only the watchdog's operational state;
// issue closure and queue-task completion remain with their authorized
// disposition paths;
// - 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 —
// issue create/comment) 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.
Expand Down Expand Up @@ -87,18 +87,14 @@ export interface EscalationPacket {
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 };
| { type: "comment_issue"; repo: string; issueNumber: number; body: string };

/** Side effects, injected. Production implementations shell to the
* fleet CLI / gh; tests count calls. */
export interface EscalationEffectors {
enqueueTask(packet: EscalationPacket): Promise<string>;
openIssue(action: Extract<EscalationAction, { type: "open_issue" }>): Promise<number>;
commentIssue(action: Extract<EscalationAction, { type: "comment_issue" }>): Promise<void>;
closeIssue(action: Extract<EscalationAction, { type: "close_issue" }>): Promise<void>;
completeTask(action: Extract<EscalationAction, { type: "complete_task" }>): Promise<void>;
}

export function escalationDedupeKey(source: string, cls: FailureClass | null): string {
Expand Down Expand Up @@ -134,7 +130,7 @@ export function buildEscalationPacket(health: SourceHealth, ctx: EscalationConte
},
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)",
"a fresh producer document lands, the watchdog records recovery on the existing incident issue, and authorized disposition preserves any open issue, repair task, or PR",
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",
Expand All @@ -159,7 +155,7 @@ function issueBody(health: SourceHealth, packet: EscalationPacket): string {
"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.`,
`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 records recovery here but leaves disposition to the authorized authority.`,
].join("\n");
}

Expand Down Expand Up @@ -235,7 +231,7 @@ export function buildQueueTaskWrapper(packet: EscalationPacket, at: string): Que
body: [
packet.outcomeWanted,
"",
`Incident issue: ${repo}#${n} (the watchdog auto-closes it on the next producer success — do not close it by hand).`,
`Incident issue: ${repo}#${n} (the watchdog records recovery here but does not close the issue or complete the task).`,
`Required capability: ${packet.requiredCapability}`,
`Acceptance: ${packet.acceptance}`,
].join("\n"),
Expand All @@ -262,7 +258,7 @@ export function buildQueueTaskWrapper(packet: EscalationPacket, at: string): Que
],
acceptance: [
packet.acceptance,
`incident issue ${repo}#${n} is auto-commented and auto-closed by the watchdog on producer success (the fixer closes nothing by hand)`,
`a producer recovery is recorded on incident issue ${repo}#${n}; issue and task disposition remain with the authorized authority`,
],
tests: [
"the producer for this source writes a fresh latest.json with status ok and real quota windows",
Expand Down Expand Up @@ -320,8 +316,8 @@ export function recordEscalation(
};
} 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).
// (flattened into `previous`) so recovery can report on it and
// dedupe can find it again (Codex P2 on PR #8357).
const { previous: prevPrevious, ...prevFlat } = prev;
escalation = {
class: cls as EscalationRecord["class"],
Expand Down Expand Up @@ -382,16 +378,18 @@ export function surfacingLine(health: SourceHealth, now: number): string | 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.
* and whose latest observation is a producer success. Recovery is an
* operational update only: issue closure and queue-task completion are
* reserved for their authorized disposition paths. Call with the
* PRE-tick health 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 [];
// Close and complete EVERY hand-off the incident carries (Codex P2
// Report recovery for 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.
// earlier issue is just as open as the latest one. Disposition is not
// a watchdog recovery effect.
const records: EscalationRecord[] = [esc, ...(esc.previous ?? [])];
const actions: EscalationAction[] = [];
for (const rec of records) {
Expand All @@ -400,12 +398,8 @@ export function planRecovery(health: SourceHealth, recoveredAt: string): Escalat
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).`,
body: `Recovered: source \`${health.source}\` produced a fresh document at ${recoveredAt}. The watchdog resolved the operational attention state; the issue remains open for authorized disposition (#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;
Expand All @@ -416,7 +410,7 @@ export function planRecovery(health: SourceHealth, recoveredAt: string): Escalat
* 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. */
* work, and recovery must never dispose of its 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 }) {
Expand Down Expand Up @@ -459,12 +453,6 @@ export async function applyEscalationActions(
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 });
Expand Down
6 changes: 3 additions & 3 deletions pm-stack/exporters/src/watchdog-state.ts
Original file line number Diff line number Diff line change
Expand Up @@ -102,8 +102,8 @@ export interface EscalationRecord {
/** 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
* that changes back finds its pair here) and recovery comments on
* every existing issue without disposition. Flat: entries carry no `previous` of their
* own. Absent = no earlier hand-off. */
previous?: EscalationRecord[];
}
Expand Down Expand Up @@ -217,7 +217,7 @@ export function decide(
at,
rung: 1,
outcome: "succeeded",
detail: "source recovered; incident closed",
detail: "source recovered; operational attention cleared",
}),
incident: null,
};
Expand Down
45 changes: 0 additions & 45 deletions pm-stack/exporters/src/watchdog.ts
Original file line number Diff line number Diff line change
Expand Up @@ -362,51 +362,6 @@ function productionEscalationEffectors(live: boolean): EscalationEffectors {
await writeFile(file, action.body);
await run(["gh", "issue", "comment", String(action.issueNumber), "--repo", action.repo, "--body-file", file]);
},
async closeIssue(action) {
guard();
await run(["gh", "issue", "close", String(action.issueNumber), "--repo", action.repo]);
},
async completeTask(action) {
guard();
// Recovery resolution of the escalation task, best-effort at
// every step (task 20118 live demo): `complete` requires
// holding the claim, and the watchdog never claims — so for a
// task still sitting queued it always fails with "not claimed
// by repo-worker-code". That case is the common one (the
// source healed before any fixer picked the task up), and the
// honest terminal verb for it is `cancel` with the recovery
// reason — but cancel also cancels CLAIMED tasks, so it is
// only safe when the task is untouched: an unclaimed task has
// no timeline records. A task with records has an owner; leave
// it to them — the auto-closed incident issue is their signal,
// and their own completion closes the task out.
const completed = await run([
"fleet",
"queue",
"complete",
action.queueTaskId,
"--worker",
"repo-worker-code",
"--result",
JSON.stringify({ outcome: "already_done", note: "watchdog recovery: source healthy again (#6033)" }),
])
.then(() => true)
.catch(() => false);
if (completed) return;
const timeline = await run(["fleet", "queue", "timeline", action.queueTaskId]).catch(() => "");
if (timeline.includes("no timeline records")) {
await run([
"fleet",
"queue",
"cancel",
action.queueTaskId,
"--worker",
"repo-worker-code",
"--reason",
"watchdog recovery: source healthy again; the repair this task commissioned is no longer needed (#6033)",
]).catch(() => "");
}
},
};
}

Expand Down
39 changes: 14 additions & 25 deletions pm-stack/exporters/test/watchdog-escalation.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -63,12 +63,6 @@ function countingEffectors() {
commentIssue: async () => {
calls.push("comment");
},
closeIssue: async () => {
calls.push("close");
},
completeTask: async () => {
calls.push("complete");
},
};
return { calls, effectors };
}
Expand Down Expand Up @@ -122,7 +116,7 @@ describe("packet completeness (#6033 acceptance 2)", () => {
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.acceptance).toContain("authorized disposition");
expect(packet.stopConditions.join(" ")).toContain("human-only challenge");
expect(packet.stopConditions.join(" ")).toContain("origin allowlist");
expect(packet.dedupeKey).toBe("watchdog-escalation:mistral:session-expired");
Expand All @@ -143,8 +137,6 @@ describe("queue task wrapper — the repo-task/v1 contract (task 20118)", () =>
},
openIssue: async () => 777,
commentIssue: async () => {},
closeIssue: async () => {},
completeTask: async () => {},
};
const plan = planEscalation(escalatingHealth(), CTX);
const refs = await applyEscalationActions(plan.actions, effectors);
Expand Down Expand Up @@ -200,13 +192,20 @@ describe("queue task wrapper — the repo-task/v1 contract (task 20118)", () =>
});

describe("recovery (#6033 acceptance 3)", () => {
test("producer success plans comment + close + task completion against the recorded refs", async () => {
test("producer success records recovery without closing the issue or completing its task", 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"]);
expect(actions.map((a) => a.type)).toEqual(["comment_issue"]);
expect(actions).toEqual([
expect.objectContaining({
type: "comment_issue",
issueNumber: 777,
body: expect.stringContaining("issue remains open for authorized disposition"),
}),
]);
const { calls, effectors } = countingEffectors();
await applyEscalationActions(actions, effectors);
expect(calls).toEqual(["comment", "close", "complete"]);
expect(calls).toEqual(["comment"]);
});

test("no recovery actions when nothing was escalated", () => {
Expand Down Expand Up @@ -250,7 +249,7 @@ describe("state coercion keeps the escalation record", () => {
});

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", () => {
test("a class change preserves the earlier hand-off; recovery records both without disposition; 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);
Expand All @@ -263,16 +262,8 @@ describe("Codex findings on PR #8357 (class change, partial progress, surfacing
});

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"]);
expect(actions.map((a) => a.type)).toEqual(["comment_issue", "comment_issue"]);
expect(actions.map((a) => a.type === "comment_issue" ? a.issueNumber : null)).toEqual([222, 111]);

const backAgain: SourceHealth = { ...second, currentClass: "session-expired" };
const plan = planEscalation(backAgain, CTX);
Expand All @@ -289,8 +280,6 @@ describe("Codex findings on PR #8357 (class change, partial progress, surfacing
},
openIssue: async () => 777,
commentIssue: async () => {},
closeIssue: async () => {},
completeTask: async () => {},
};
const err = await applyEscalationActions(plan.actions, failing).catch((e: unknown) => e);
expect(err).toBeInstanceOf(EscalationPartialError);
Expand Down
12 changes: 3 additions & 9 deletions pm-stack/exporters/test/watchdog.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -101,12 +101,6 @@ async function harness(
commentIssue: async (a) => {
escCalls.push(`comment:${a.issueNumber}`);
},
closeIssue: async (a) => {
escCalls.push(`close:${a.issueNumber}`);
},
completeTask: async (a) => {
escCalls.push(`complete:${a.queueTaskId}`);
},
} satisfies EscalationEffectors,
log: (line) => logs.push(line),
},
Expand Down Expand Up @@ -223,7 +217,7 @@ describe("watchdog entry point — acceptance fixtures", () => {
await rm(h.dir, { recursive: true, force: true });
});

test("recovery: a healthy tick after escalation comments, closes, and completes the hand-off", async () => {
test("recovery: a healthy tick records recovery without disposing the issue or task", async () => {
const h = await harness();
for (let min = 0; min <= 6; min++) {
await h.setDoc(failDoc(min, "mystery-failure"));
Expand All @@ -234,8 +228,8 @@ describe("watchdog entry point — acceptance fixtures", () => {
const { state } = await h.tick(10);
expect(state.sources.fixture.incident).toBeNull();
expect(h.escCalls).toContain("comment:777");
expect(h.escCalls).toContain("close:777");
expect(h.escCalls).toContain("complete:4242");
expect(h.escCalls).not.toContain("close:777");
expect(h.escCalls).not.toContain("complete:4242");
await rm(h.dir, { recursive: true, force: true });
});
});
Expand Down