@muggleai/works 5.26.0-staging.207 → 5.26.0-staging.208

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (52) hide show
  1. package/.claude-plugin/marketplace.json +1 -1
  2. package/dist/cli.js +1 -1
  3. package/dist/index.js +1 -1
  4. package/dist/plugin/.claude-plugin/plugin.json +1 -1
  5. package/dist/plugin/.codex-mcp.json +1 -1
  6. package/dist/plugin/.codex-plugin/plugin.json +1 -1
  7. package/dist/plugin/.cursor-plugin/plugin.json +1 -1
  8. package/dist/plugin/.mcp.json +1 -1
  9. package/dist/plugin/hooks/README.md +2 -1
  10. package/dist/plugin/hooks/codex-hooks.json +2 -2
  11. package/dist/plugin/hooks/hooks.json +1 -1
  12. package/dist/plugin/scripts/guardrail-watch-follow-through-gate.sh +48 -0
  13. package/dist/plugin/scripts/guardrails.mjs +282 -32
  14. package/dist/plugin/scripts/pr-watch-arm.sh +64 -37
  15. package/dist/plugin/scripts/pr-watch-due.sh +31 -0
  16. package/dist/plugin/scripts/pr-watch-events.sh +20 -6
  17. package/dist/plugin/scripts/pr-watch-loop.sh +21 -2
  18. package/dist/plugin/scripts/pr-watch-verdict.mjs +197 -0
  19. package/dist/plugin/skills/_shared/ci-check-to-command.md +2 -1
  20. package/dist/plugin/skills/do/fix-ci.md +24 -8
  21. package/dist/plugin/skills/do/resolve-conflicts.md +7 -3
  22. package/dist/plugin/skills/muggle-pr-followup/SKILL.md +1 -1
  23. package/dist/plugin/skills/muggle-pr-followup/arm-watcher.md +5 -3
  24. package/dist/plugin/skills/muggle-pr-followup/blocked-tick.md +2 -0
  25. package/dist/plugin/skills/muggle-pr-followup/contract.md +40 -25
  26. package/dist/plugin/skills/muggle-pr-followup/state-schemas.md +22 -8
  27. package/dist/release-manifest.json +3 -3
  28. package/package.json +1 -1
  29. package/plugin/.claude-plugin/plugin.json +1 -1
  30. package/plugin/.codex-mcp.json +1 -1
  31. package/plugin/.codex-plugin/plugin.json +1 -1
  32. package/plugin/.cursor-plugin/plugin.json +1 -1
  33. package/plugin/.mcp.json +1 -1
  34. package/plugin/hooks/README.md +2 -1
  35. package/plugin/hooks/codex-hooks.json +2 -2
  36. package/plugin/hooks/hooks.json +1 -1
  37. package/plugin/scripts/guardrail-watch-follow-through-gate.sh +48 -0
  38. package/plugin/scripts/guardrails.mjs +282 -32
  39. package/plugin/scripts/pr-watch-arm.sh +64 -37
  40. package/plugin/scripts/pr-watch-due.sh +31 -0
  41. package/plugin/scripts/pr-watch-events.sh +20 -6
  42. package/plugin/scripts/pr-watch-loop.sh +21 -2
  43. package/plugin/scripts/pr-watch-verdict.mjs +197 -0
  44. package/plugin/skills/_shared/ci-check-to-command.md +2 -1
  45. package/plugin/skills/do/fix-ci.md +24 -8
  46. package/plugin/skills/do/resolve-conflicts.md +7 -3
  47. package/plugin/skills/muggle-pr-followup/SKILL.md +1 -1
  48. package/plugin/skills/muggle-pr-followup/arm-watcher.md +5 -3
  49. package/plugin/skills/muggle-pr-followup/blocked-tick.md +2 -0
  50. package/plugin/skills/muggle-pr-followup/contract.md +40 -25
  51. package/plugin/skills/muggle-pr-followup/state-schemas.md +22 -8
  52. /package/dist/{chunk-HGN35NEP.js → chunk-HOKMW4AL.js} +0 -0
@@ -39,7 +39,7 @@ fi
39
39
  # gone. Guards missing means the plugin moved or upgraded underneath this loop —
40
40
  # a newer version's watcher owns the slot now, so step down rather than run on
41
41
  # without the supersede check.
42
- for lib in pr-watch-guards.sh pr-watch-events.sh pr-watch-fetch.sh; do
42
+ for lib in pr-watch-guards.sh pr-watch-events.sh pr-watch-fetch.sh pr-watch-due.sh; do
43
43
  [ -f "${script_dir}/${lib}" ] || exit 0
44
44
  # shellcheck source=/dev/null
45
45
  . "${script_dir}/${lib}"
@@ -66,6 +66,11 @@ floor_ci_red=""
66
66
  floor_rebase=""
67
67
  floor_blocked_digest=""
68
68
 
69
+ # What watch-due.env last recorded, so the file is rewritten only when the due
70
+ # work changes rather than every poll.
71
+ due_rebase_key=""
72
+ recorded_due_work="unrecorded"
73
+
69
74
  # Pin the token once: a detached loop can lose access to gh's OS keyring
70
75
  # mid-run, which surfaces as empty fetches rather than an error.
71
76
  pinned_token="$(gh auth token 2>/dev/null)"
@@ -202,13 +207,27 @@ while :; do
202
207
  fi
203
208
 
204
209
  rebase_key="${head_sha}..${base_tip_sha}"
205
- if [ "$rebase_key" != "$watermark_rebase" ] && [ "$rebase_key" != "$floor_rebase" ]; then
210
+ if [ "$rebase_key" = "$watermark_rebase" ] || [ "$rebase_key" = "$floor_rebase" ]; then
211
+ # Only a key already found due is ever floored, and the pair's standing
212
+ # cannot change until the head or the base moves, which mints a new key.
213
+ due_rebase_key="$rebase_key"
214
+ else
206
215
  behind_count=$(watch_fetch_behind_count "$repo" "$base_branch" "$head_sha" "$slot")
216
+ due_rebase_key=""
207
217
  if watch_wake_rebase "$pr_number" "$mergeable" "$behind_count" "$rebase_key" ""; then
208
218
  floor_rebase="$rebase_key"
219
+ due_rebase_key="$rebase_key"
209
220
  fi
210
221
  fi
211
222
 
223
+ ci_red_head=""
224
+ watch_checks_settled_red "$pending_checks" "$failed_checks" && ci_red_head="$head_sha"
225
+ due_work="${head_sha} ${due_rebase_key} ${ci_red_head}"
226
+ if [ "$due_work" != "$recorded_due_work" ]; then
227
+ watch_record_due_work "$slot" "$head_sha" "$due_rebase_key" "$ci_red_head"
228
+ recorded_due_work="$due_work"
229
+ fi
230
+
212
231
  # The tick owns clearing the block, and it may not run for a while. Holding
213
232
  # the emitted digest stops the loop repeating itself every iteration in the
214
233
  # meantime — the repeat nagging the design rules out — while a further move
@@ -0,0 +1,197 @@
1
+ import { readFileSync } from 'fs';
2
+ import { homedir } from 'os';
3
+ import { join, dirname } from 'path';
4
+ import { fileURLToPath } from 'url';
5
+
6
+ // src/pr-watch/cli.ts
7
+
8
+ // src/pr-watch/constants.ts
9
+ var MAX_REBASE_ATTEMPTS_PER_KEY = 2;
10
+ var MAX_CI_FIX_ATTEMPTS_PER_HEAD = 3;
11
+ var REBASE_KEY_SEPARATOR = "..";
12
+ var USER_PREFERENCES_PATH_SEGMENTS = [".muggle-ai", "preferences.json"];
13
+ var PREFERENCE_DEFAULTS_PATH_SEGMENTS = ["config", "preference-defaults.json"];
14
+ var AUTO_REBASE_PREFERENCE_KEY = "autoRebase";
15
+ var MAX_CATCH_UP_REBASES_PREFERENCE_KEY = "maxCatchUpRebases";
16
+ var UNBOUNDED_PREFERENCE_VALUE = "never";
17
+ var POSITIVE_INTEGER = /^[1-9]\d*$/;
18
+ var LINE_BREAK = /[\r\n]/;
19
+ var PR_KEY_FLAG = "pr-key";
20
+ var HEAD_FLAG = "head";
21
+ var REBASE_KEY_FLAG = "rebase-key";
22
+ var REBASE_DUE_FLAG = "rebase-due";
23
+ var CI_FLAG = "ci";
24
+ var REBASE_DUE_YES = "yes";
25
+ var USAGE_EXIT_CODE = 2;
26
+ var PR_WATCH_VERDICT_USAGE = "usage: pr-watch-verdict.mjs arm-floors --pr-key <owner/repo#n> --head <sha> --rebase-key <head..base-tip> < last_seen.json\n pr-watch-verdict.mjs tick --pr-key <owner/repo#n> --head <sha> --rebase-key <head..base-tip> --rebase-due <yes|no> --ci <red|pending|green> < last_seen.json";
27
+
28
+ // src/pr-watch/attempts.ts
29
+ function recordedCount(counts, key) {
30
+ const recorded = counts?.[key];
31
+ return typeof recorded === "number" && Number.isFinite(recorded) ? recorded : 0;
32
+ }
33
+ function rebaseAttemptsFor(lastSeenEntry, rebaseKey) {
34
+ return recordedCount(lastSeenEntry.conflict_resolve_attempts, rebaseKey);
35
+ }
36
+ function ciFixAttemptsFor(lastSeenEntry, headSha) {
37
+ return recordedCount(lastSeenEntry.ci_fix_attempts, headSha);
38
+ }
39
+ function isRebaseKeyAttempted(lastSeenEntry, rebaseKey) {
40
+ return rebaseAttemptsFor(lastSeenEntry, rebaseKey) >= 1;
41
+ }
42
+ function isCiHeadAttempted(lastSeenEntry, headSha) {
43
+ return ciFixAttemptsFor(lastSeenEntry, headSha) >= 1;
44
+ }
45
+ function isRebaseKeyEscalated(lastSeenEntry, rebaseKey) {
46
+ return rebaseKey.includes(REBASE_KEY_SEPARATOR) && (lastSeenEntry.conflict_escalated_keys ?? []).includes(rebaseKey) && isRebaseKeyAttempted(lastSeenEntry, rebaseKey);
47
+ }
48
+ function isCiHeadEscalated(lastSeenEntry, headSha) {
49
+ return (lastSeenEntry.ci_escalated_shas ?? []).includes(headSha) && isCiHeadAttempted(lastSeenEntry, headSha);
50
+ }
51
+ function isRebaseBudgetExhausted(lastSeenEntry, maxCatchUpRebases) {
52
+ const catchUpRebases = lastSeenEntry.catch_up_rebases;
53
+ return maxCatchUpRebases !== null && typeof catchUpRebases === "number" && catchUpRebases >= maxCatchUpRebases;
54
+ }
55
+
56
+ // src/pr-watch/armFloors.ts
57
+ function resolveArmFloorEvidence(lastSeenEntry, headSha, rebaseKey) {
58
+ const blockedCiDigest = lastSeenEntry.blocked?.fingerprint?.ci_digest;
59
+ return {
60
+ isRebaseKeyAttempted: rebaseKey !== "" && isRebaseKeyAttempted(lastSeenEntry, rebaseKey),
61
+ isCiHeadAttempted: headSha !== "" && isCiHeadAttempted(lastSeenEntry, headSha),
62
+ blockedCiDigest: typeof blockedCiDigest === "string" && !LINE_BREAK.test(blockedCiDigest) ? blockedCiDigest : ""
63
+ };
64
+ }
65
+ function readJsonRecord(filePath) {
66
+ try {
67
+ return asRecord(JSON.parse(readFileSync(filePath, "utf-8")));
68
+ } catch {
69
+ return {};
70
+ }
71
+ }
72
+ function asRecord(candidate) {
73
+ return candidate !== null && typeof candidate === "object" && !Array.isArray(candidate) ? candidate : {};
74
+ }
75
+ function lastSeenEntryFor(lastSeenJson, prKey) {
76
+ try {
77
+ return asRecord(asRecord(JSON.parse(lastSeenJson))[prKey]);
78
+ } catch {
79
+ return {};
80
+ }
81
+ }
82
+
83
+ // src/pr-watch/types.ts
84
+ var CiRollupBucket = /* @__PURE__ */ ((CiRollupBucket2) => {
85
+ CiRollupBucket2["Red"] = "red";
86
+ CiRollupBucket2["Pending"] = "pending";
87
+ CiRollupBucket2["Green"] = "green";
88
+ return CiRollupBucket2;
89
+ })(CiRollupBucket || {});
90
+
91
+ // src/pr-watch/tickVerdict.ts
92
+ function resolveWatchTickVerdict(lastSeenEntry, observation, preferences) {
93
+ const { headSha, rebaseKey } = observation;
94
+ if (observation.isRebaseDue) {
95
+ if (isRebaseBudgetExhausted(lastSeenEntry, preferences.maxCatchUpRebases)) {
96
+ return "block-rebase-budget-exhausted" /* BlockRebaseBudgetExhausted */;
97
+ }
98
+ const isRebaseKeyBudgetLeft = rebaseAttemptsFor(lastSeenEntry, rebaseKey) < MAX_REBASE_ATTEMPTS_PER_KEY;
99
+ if (isRebaseKeyBudgetLeft && !isRebaseKeyEscalated(lastSeenEntry, rebaseKey)) return "dispatch-rebase" /* DispatchRebase */;
100
+ }
101
+ if (observation.ciBucket === "red" /* Red */) {
102
+ const isCiHeadBudgetLeft = ciFixAttemptsFor(lastSeenEntry, headSha) < MAX_CI_FIX_ATTEMPTS_PER_HEAD;
103
+ if (isCiHeadBudgetLeft && !isCiHeadEscalated(lastSeenEntry, headSha)) return "dispatch-fix-ci" /* DispatchFixCi */;
104
+ }
105
+ if (isRebaseKeyEscalated(lastSeenEntry, rebaseKey)) return "block-conflict-escalated" /* BlockConflictEscalated */;
106
+ if (isCiHeadEscalated(lastSeenEntry, headSha)) return "block-ci-escalated" /* BlockCiEscalated */;
107
+ if ((lastSeenEntry.escalated_review_ids ?? []).length > 0) return "block-reviews-escalated" /* BlockReviewsEscalated */;
108
+ return "idle" /* Idle */;
109
+ }
110
+
111
+ // src/pr-watch/verdictCommand.ts
112
+ function parseVerdictArguments(flagTokens) {
113
+ const parsed = {};
114
+ for (let index = 0; index < flagTokens.length; index += 1) {
115
+ const token = flagTokens[index];
116
+ if (!token.startsWith("--")) continue;
117
+ const next = flagTokens[index + 1];
118
+ const hasValue = next !== void 0 && !next.startsWith("--");
119
+ parsed[token.slice(2)] = hasValue ? next : "";
120
+ if (hasValue) index += 1;
121
+ }
122
+ return parsed;
123
+ }
124
+ var usageFailure = (problem) => ({
125
+ stdout: "",
126
+ stderr: `pr-watch-verdict: ${problem}
127
+ ${PR_WATCH_VERDICT_USAGE}
128
+ `,
129
+ exitCode: USAGE_EXIT_CODE
130
+ });
131
+ function runPrWatchVerdictCommand(commandLine, lastSeenJson, resolvePreferences) {
132
+ const [subcommand, ...flagTokens] = commandLine;
133
+ const flags = parseVerdictArguments(flagTokens);
134
+ const prKey = flags[PR_KEY_FLAG];
135
+ if (!prKey) return usageFailure(`--${PR_KEY_FLAG} is required`);
136
+ const lastSeenEntry = lastSeenEntryFor(lastSeenJson, prKey);
137
+ const headSha = flags[HEAD_FLAG] ?? "";
138
+ const rebaseKey = flags[REBASE_KEY_FLAG] ?? "";
139
+ if (subcommand === "arm-floors" /* ArmFloors */) {
140
+ const evidence = resolveArmFloorEvidence(lastSeenEntry, headSha, rebaseKey);
141
+ return {
142
+ stdout: `REBASE_ATTEMPTED=${evidence.isRebaseKeyAttempted ? 1 : 0}
143
+ CI_ATTEMPTED=${evidence.isCiHeadAttempted ? 1 : 0}
144
+ BLOCKED_CIDIGEST=${evidence.blockedCiDigest}
145
+ `,
146
+ stderr: "",
147
+ exitCode: 0
148
+ };
149
+ }
150
+ if (subcommand === "tick" /* Tick */) {
151
+ const ciBucket = Object.values(CiRollupBucket).find((bucket) => bucket === flags[CI_FLAG]);
152
+ if (!ciBucket) return usageFailure(`--${CI_FLAG} must be one of ${Object.values(CiRollupBucket).join(", ")}`);
153
+ if (!headSha || !rebaseKey) return usageFailure(`--${HEAD_FLAG} and --${REBASE_KEY_FLAG} are required`);
154
+ const verdict = resolveWatchTickVerdict(
155
+ lastSeenEntry,
156
+ { headSha, rebaseKey, isRebaseDue: flags[REBASE_DUE_FLAG] === REBASE_DUE_YES, ciBucket },
157
+ resolvePreferences()
158
+ );
159
+ return { stdout: `VERDICT=${verdict}
160
+ `, stderr: "", exitCode: 0 };
161
+ }
162
+ return usageFailure(`unknown subcommand ${subcommand ?? "(none)"}`);
163
+ }
164
+ function resolvePluginRoot(env = process.env) {
165
+ return env.CLAUDE_PLUGIN_ROOT || env.CURSOR_PLUGIN_ROOT || dirname(dirname(fileURLToPath(import.meta.url)));
166
+ }
167
+
168
+ // src/pr-watch/watchPreferences.ts
169
+ function parseMaxCatchUpRebases(configuredValue) {
170
+ if (configuredValue === UNBOUNDED_PREFERENCE_VALUE) return null;
171
+ const spelled = typeof configuredValue === "number" ? String(configuredValue) : configuredValue;
172
+ return typeof spelled === "string" && POSITIVE_INTEGER.test(spelled) ? Number(spelled) : void 0;
173
+ }
174
+ function resolveWatchPreferences(homeDir = homedir(), pluginRoot = resolvePluginRoot()) {
175
+ const shippedDefaults = readJsonRecord(join(pluginRoot, ...PREFERENCE_DEFAULTS_PATH_SEGMENTS));
176
+ const userPreferences = asRecord(readJsonRecord(join(homeDir, ...USER_PREFERENCES_PATH_SEGMENTS)).preferences);
177
+ const autoRebase = userPreferences[AUTO_REBASE_PREFERENCE_KEY] ?? shippedDefaults[AUTO_REBASE_PREFERENCE_KEY];
178
+ const userCap = parseMaxCatchUpRebases(userPreferences[MAX_CATCH_UP_REBASES_PREFERENCE_KEY]);
179
+ const shippedCap = parseMaxCatchUpRebases(shippedDefaults[MAX_CATCH_UP_REBASES_PREFERENCE_KEY]);
180
+ return {
181
+ autoRebase: typeof autoRebase === "string" ? autoRebase : void 0,
182
+ maxCatchUpRebases: userCap !== void 0 ? userCap : shippedCap ?? null
183
+ };
184
+ }
185
+
186
+ // src/pr-watch/cli.ts
187
+ function readLastSeenFromStdin() {
188
+ try {
189
+ return readFileSync(0, "utf-8");
190
+ } catch {
191
+ return "";
192
+ }
193
+ }
194
+ var outcome = runPrWatchVerdictCommand(process.argv.slice(2), readLastSeenFromStdin(), () => resolveWatchPreferences());
195
+ process.stderr.write(outcome.stderr);
196
+ process.stdout.write(outcome.stdout);
197
+ process.exitCode = outcome.exitCode;
@@ -8,4 +8,5 @@ Map a red CI check to the local command that reproduces and fixes it. Repo-agnos
8
8
  | typecheck | Run the typecheck script; read the errors; edit the types. |
9
9
  | unit / test | Run the suite; read the failures; fix the code or the test. |
10
10
  | `muggle-walkthrough` — the Muggle E2E walkthrough check | In scope. Its check-run summary names each failed or inconclusive case with the failing step and a link to the run; the walkthrough comment's hidden `muggle-e2e-result` record carries the same cases with their test case ids. Repair each, re-run the **whole** E2E suite, and settle the walkthrough comment with the new result — editing the comment re-runs the check. A summary saying the comment is still empty means no run was ever posted: run the suite and post it. |
11
- | out of scope — any other E2E-in-CI, build/deploy infra, flaky / non-deterministic, or unknown | Do **not** attempt; record for escalation. |
11
+ | non-deterministic — an LLM-judged eval gate (e.g. `skill-routing-eval`, `skill-gate-eval`, `agent-gate-eval`) or another check whose verdict can flip with nothing changed | Re-run its failed jobs once per head, without a push: `gh run rerun <run-id> --failed` (GitLab: retry the failed job). The re-run counts as a fix attempt. Escalate only if it fails again on the same head. How long the check takes is never a reason to skip the re-run. |
12
+ | out of scope — any other E2E-in-CI, build/deploy infra, or unknown | Do **not** attempt; record for escalation. |
@@ -14,7 +14,7 @@ Resolve red CI on a PR's head — lint/format, typecheck, failing unit tests, an
14
14
 
15
15
  ## Inputs from disk
16
16
 
17
- From `~/.muggle-ai/muggle-do/sessions/<slug>/`: `prs.json` (PR + local checkout / branch), `last_seen.json` (`ci_fix_attempts`, `ci_escalated_shas`, `pushed_shas`), `state.md` (worktree path, validation strategy).
17
+ From `~/.muggle-ai/muggle-do/sessions/<slug>/`: `prs.json` (PR + local checkout / branch), `last_seen.json` (`ci_fix_attempts`, `ci_escalated_shas`, `ci_rerun_shas`, `pushed_shas`), `state.md` (worktree path, validation strategy).
18
18
 
19
19
  ## Procedure
20
20
 
@@ -22,9 +22,13 @@ From `~/.muggle-ai/muggle-do/sessions/<slug>/`: `prs.json` (PR + local checkout
22
22
 
23
23
  Check out the PR branch in the session's working tree (per `state.md`). Capture `red_sha = prs.json[0].head_sha` — this cycle's `pre_cycle_sha` ([`cycle-size.md`](cycle-size.md)).
24
24
 
25
+ Then increment `last_seen.ci_fix_attempts[red_sha]` — before any fix, re-run or escalation, as a whole-file rewrite (Read → change field → Write) per [`../_shared/session-state-writes.md`](../_shared/session-state-writes.md), never the Edit tool. Every dispatched cycle is an attempt, including one that only re-runs a check or escalates without pushing. That count is the only record the watcher and its turn-end gate accept that this red head was acted on; an escalation written without it is ignored and fix-ci is dispatched again ([`../muggle-pr-followup/state-schemas.md`](../muggle-pr-followup/state-schemas.md#last_seenjson)).
26
+
25
27
  ### Step 2 — Map each failing check to a local command
26
28
 
27
- Per [`../_shared/ci-check-to-command.md`](../_shared/ci-check-to-command.md). Fix the in-scope checks in the working tree; record out-of-scope checks for escalation (Step 6). A red `muggle-walkthrough` check takes Step 2.5.
29
+ Per [`../_shared/ci-check-to-command.md`](../_shared/ci-check-to-command.md). Fix the in-scope checks in the working tree; record out-of-scope checks for escalation (Step 6). A red `muggle-walkthrough` check takes Step 2.5; a red non-deterministic check takes Step 2.6.
30
+
31
+ How long a check takes to run — a 45-minute eval included — is never a reason to skip, defer or escalate it. A held fix needs the user's own words: a message they typed containing `HOLD WATCH #<pr-number>`.
28
32
 
29
33
  ### Step 2.5 — Red E2E walkthrough check
30
34
 
@@ -36,6 +40,18 @@ Per [`../_shared/ci-check-to-command.md`](../_shared/ci-check-to-command.md). Fi
36
40
 
37
41
  An empty-comment failure (no run ever posted) skips items 1–2: run the suite and settle the comment. Under a `unit-only` or `skip` validation in `state.md`, settle it with the verified skip code instead.
38
42
 
43
+ ### Step 2.6 — Red non-deterministic check: re-run once per head
44
+
45
+ A check whose verdict can change with nothing changed — an LLM-judged eval gate such as `skill-routing-eval`, `skill-gate-eval` or `agent-gate-eval` — gets one automatic re-run per head before anything escalates:
46
+
47
+ - **A deterministic check is also red and in scope** → skip the re-run. Fix that check (Steps 3–4); the push re-runs every check on the new head.
48
+ - **`red_sha` ∉ `last_seen.ci_rerun_shas`** → re-run the failed jobs of each such check's run, without pushing — the run id is the `/actions/runs/<run-id>/` segment of the check's `link` ([`../_shared/vcs/github/pr-checks.md`](../_shared/vcs/github/pr-checks.md)):
49
+ ```bash
50
+ gh run rerun <run-id> --failed --repo <owner>/<repo>
51
+ ```
52
+ GitLab retries the failed job instead ([`../_shared/vcs/gitlab/mr-pipeline.md`](../_shared/vcs/gitlab/mr-pipeline.md)). Append `red_sha` to `last_seen.ci_rerun_shas` (whole-file rewrite), skip Steps 3–4, and go to Step 5. The attempt was counted in Step 1; the watcher wakes on the re-run's verdict like any other.
53
+ - **`red_sha` ∈ `ci_rerun_shas`** — it already had its re-run and failed again → escalate per Step 6.
54
+
39
55
  ### Step 3 — Verify before push
40
56
 
41
57
  - Build (typecheck + lint on the changed surface) + unit suite must pass.
@@ -47,16 +63,15 @@ A fix that can't be made green locally is not pushed → Step 6.
47
63
 
48
64
  Commit per the `fix(ci): <check> — <what>` convention ([`../_shared/pr-followup-helpers/reply-routing.md`](../_shared/pr-followup-helpers/reply-routing.md)). Push. Append the new SHA to `last_seen.pushed_shas`. Then finish the tail [`cycle-size.md`](cycle-size.md) picked: a full fix reposts the walkthrough (a Step 2.5 repair settles it there instead), a minor one declares the skip. **No PR replies** — the fix commit is the response.
49
65
 
50
- ### Step 5 — Update state + respawn
66
+ ### Step 5 — Respawn
51
67
 
52
- - Increment `last_seen.ci_fix_attempts[red_sha]` — a whole-file rewrite (Read → change field → Write) per [`../_shared/session-state-writes.md`](../_shared/session-state-writes.md), never the Edit tool.
53
- - Respawn the watcher per [`respawn-watcher.md`](respawn-watcher.md). CI on the new SHA is the verify loop — a still-red SHA returns as a fresh dispatch, bounded by the per-SHA fix budget (Step 6).
68
+ Respawn the watcher per [`respawn-watcher.md`](respawn-watcher.md). CI on the new SHA — or the re-run's fresh verdict on the same one — is the verify loop: a still-red SHA returns as a fresh dispatch, bounded by the per-SHA fix budget (Step 6).
54
69
 
55
70
  ### Step 6 — Escalate (budget spent or out of scope)
56
71
 
57
- When the failing checks are all out of scope, or `ci_fix_attempts[red_sha]` has reached 3 with CI still red:
72
+ When the failing checks are all out of scope, a non-deterministic check is red again after its re-run on this head (Step 2.6), or this is the head's third cycle (`ci_fix_attempts[red_sha]` reached 3 in Step 1) and it could not push a fix:
58
73
 
59
- 1. Add `red_sha` to `last_seen.ci_escalated_shas` so the SHA is not re-fixed.
74
+ 1. Add `red_sha` to `last_seen.ci_escalated_shas` so the SHA is not re-fixed. This cycle's Step 1 attempt is what makes the entry count.
60
75
  2. Emit one terminal message naming the unresolved checks.
61
76
  3. Emit the cycle event with `outcome: "ci-escalated"` (Step 7).
62
77
  4. **Respawn the watcher** per [`respawn-watcher.md`](respawn-watcher.md). Escalation stops fix-ci from re-dispatching this SHA — but the poller must keep running: it reminds on the `ci_escalated` block and catches a new push, a new review, or the user's own fix. Skipping respawn here is the silent-stop bug the helper exists to prevent.
@@ -67,5 +82,6 @@ Emit one `muggle-do:cycle` event ([`../_shared/telemetry-events/muggle-do-cycle.
67
82
 
68
83
  ## Guardrails
69
84
 
70
- - Max 3 fix attempts per SHA; out-of-scope checks escalate immediately rather than churn. A walkthrough repair that pushes nothing keeps the head SHA, so the same budget bounds it.
85
+ - Max 3 fix attempts per SHA; out-of-scope checks escalate immediately rather than churn. A walkthrough repair or a re-run that pushes nothing keeps the head SHA, so the same budget bounds it.
86
+ - A non-deterministic check is re-run once per head before it escalates — never escalated on its first red, never re-run twice on one head.
71
87
  - No PR replies; the fix commit is the response.
@@ -22,6 +22,10 @@ From `~/.muggle-ai/muggle-do/sessions/<slug>/`: `prs.json` (PR + branch + `head_
22
22
 
23
23
  Materialize the PR branch in its worktree per [`../_shared/pr-branch-worktree.md`](../_shared/pr-branch-worktree.md) (or use `state.md`'s `worktreePath`). Capture `rebase_sha = prs.json[0].head_sha` and the base branch (`baseRefName` from [`../_shared/vcs/github/pr-metadata.md`](../_shared/vcs/github/pr-metadata.md)). Capture the base tip too — `.base_commit.sha` from that recipe's `compare` call — and form `rebase_key = "<rebase_sha>..<base_tip_sha>"`. Both budget fields below are keyed on that pair, matching the watcher's Step 5; writing a bare SHA instead leaves an entry the watcher ignores, and the rebase re-dispatches forever.
24
24
 
25
+ Then increment `last_seen.conflict_resolve_attempts[rebase_key]` — before rebasing, as a whole-file rewrite (Read → change field → Write) per [`../_shared/session-state-writes.md`](../_shared/session-state-writes.md), never the Edit tool. Every dispatched rebase is an attempt, including one that escalates on a conflict under `autoResolveConflicts=never` or fails verification. That count is the only record the watcher and its turn-end gate accept that this key was acted on; an entry in `conflict_escalated_keys` without it is ignored and the rebase is dispatched again ([`../muggle-pr-followup/state-schemas.md`](../muggle-pr-followup/state-schemas.md#last_seenjson)).
26
+
27
+ `autoRebase=always` makes this rebase binding. The CI or evals a force-push re-runs — however long they take — are never a reason to hold it; the only hold is the user's own message containing `HOLD WATCH #<pr-number>`.
28
+
25
29
  ### Step 2 — Rebase onto base (resolve conflicts if any)
26
30
 
27
31
  Run the rebase from [`../_shared/sync-branch-with-base.md`](../_shared/sync-branch-with-base.md) against the base branch, taking its `always` path unconditionally — this programmatic mode never asks, so skip the `autoRebase` prompt (the watcher already decided a rebase is due).
@@ -37,13 +41,13 @@ Build (typecheck + lint on the changed surface) + unit suite must pass. Size the
37
41
 
38
42
  ### Step 4 — Force-push + respawn
39
43
 
40
- Force-push per [`../_shared/vcs/common/push-to-branch.md`](../_shared/vcs/common/push-to-branch.md) (tool-agnostic instruction; handles the signing gate for rebased commits and directs to provider-specific force-push paths). Use `git push --force-with-lease` for the force operation. Append the new SHA to `last_seen.pushed_shas`; increment `last_seen.conflict_resolve_attempts[rebase_key]` **and** `last_seen.catch_up_rebases` — all whole-file rewrites (Read → change field → Write) per [`../_shared/session-state-writes.md`](../_shared/session-state-writes.md), never the Edit tool. The second counter is unkeyed on purpose: `rebase_key` carries the base tip, so it mints a fresh budget every time the base moves and cannot bound a PR on an active base. Increment it on every push here, including one that later escalates, or a branch that fails the same way twenty times reads as having spent nothing. Finish the tail [`cycle-size.md`](cycle-size.md) picked — a full rebase reposts the walkthrough, a minor one declares the skip — then respawn the watcher per [`respawn-watcher.md`](respawn-watcher.md). Its next tick re-checks the branch against its base on the new head — the rebase is its own verify loop, bounded by the per-SHA attempt budget.
44
+ Force-push per [`../_shared/vcs/common/push-to-branch.md`](../_shared/vcs/common/push-to-branch.md) (tool-agnostic instruction; handles the signing gate for rebased commits and directs to provider-specific force-push paths). Use `git push --force-with-lease` for the force operation. Append the new SHA to `last_seen.pushed_shas` and increment `last_seen.catch_up_rebases` (the per-key attempt was counted in Step 1) — both whole-file rewrites (Read → change field → Write) per [`../_shared/session-state-writes.md`](../_shared/session-state-writes.md), never the Edit tool. That counter is unkeyed on purpose: `rebase_key` carries the base tip, so it mints a fresh budget every time the base moves and cannot bound a PR on an active base. Increment it on every push here, including one that later escalates, or a branch that fails the same way twenty times reads as having spent nothing. Finish the tail [`cycle-size.md`](cycle-size.md) picked — a full rebase reposts the walkthrough, a minor one declares the skip — then respawn the watcher per [`respawn-watcher.md`](respawn-watcher.md). Its next tick re-checks the branch against its base on the new head — the rebase is its own verify loop, bounded by the per-SHA attempt budget.
41
45
 
42
46
  ### Step 5 — Escalate (can't resolve / budget spent)
43
47
 
44
- When `autoResolveConflicts=never`, the resolution failed verification, or `conflict_resolve_attempts[rebase_key]` has reached 2:
48
+ When `autoResolveConflicts=never`, the resolution failed verification, or this is the key's second attempt (`conflict_resolve_attempts[rebase_key]` reached 2 in Step 1) and it did not push:
45
49
 
46
- 1. Add `rebase_key` to `last_seen.conflict_escalated_keys` so the watcher does not re-dispatch this head against this base. If the base later moves, the key changes and the branch re-arms on its own — a conflict the user resolved upstream stops being this watcher's dead end.
50
+ 1. Add `rebase_key` to `last_seen.conflict_escalated_keys` so the watcher does not re-dispatch this head against this base. Step 1's attempt is what makes the entry count. If the base later moves, the key changes and the branch re-arms on its own — a conflict the user resolved upstream stops being this watcher's dead end.
47
51
  2. Emit one terminal escalation naming the PR and the conflicting files (or the failing verification, for a behind-only rebase that didn't verify).
48
52
  3. Respawn the watcher per [`respawn-watcher.md`](respawn-watcher.md) — it keeps polling for the user's manual resolution or any new reviews.
49
53
 
@@ -45,7 +45,7 @@ The skill recognizes its mode by inspecting `$ARGUMENTS` and falling back to on-
45
45
  | `reconcile` / `sweep` (optional `<slug>`) | — | **reconcile** → [`reconcile.md`](reconcile.md) |
46
46
  | `adopt` (optional `<slug>`) | — | **adopt** → [`adopt.md`](adopt.md) — take over a slot owned by a dead session; no slug lists the adoptable ones |
47
47
 
48
- **`--wake=<event>`** is passed only by an event wake's dispatch ([`arm-watcher.md`](arm-watcher.md) step 5) — it asserts the monitor already saw something new, so the tick's poll is justified. Manual invocations never pass it; with a live watcher they get watch-status, because a poll that nothing prompted is a main-session poll wasted. Recovery fires need no flag — a recoverable slot's watcher is dead by definition, so the gate falls through to tick. A stale cron firing against a re-armed slot hits the live-`watch.pid` branch and is absorbed as a status line, no provider calls.
48
+ **`--wake=<event>`** is passed only by an event wake's dispatch ([`arm-watcher.md`](arm-watcher.md) step 5), or by the follow-through Stop gate's instruction (`--wake=follow-through`) when the watch recorded due work nothing attempted — either asserts something is waiting, so the tick's poll is justified. Manual invocations never pass it; with a live watcher they get watch-status, because a poll that nothing prompted is a main-session poll wasted. Recovery fires need no flag — a recoverable slot's watcher is dead by definition, so the gate falls through to tick. A stale cron firing against a re-armed slot hits the live-`watch.pid` branch and is absorbed as a status line, no provider calls.
49
49
 
50
50
  Auto-track runs **reconcile** first, so a no-arg invocation also finalizes any slot whose PR merged or closed while its watcher was down (expired cron, ended session) and re-arms this session's own open slots whose watcher stopped silently (a dropped respawn). Reconcile recovers a watcher that was already running; it never seeds a first watcher for a PR — that is auto-track's / bootstrap's job — and never re-arms one this session does not own. A no-arg invocation is a request to track *your* PRs, so it can only ever end with the session watching PRs it pushed plus watchers it already had.
51
51
 
@@ -10,10 +10,10 @@ bash "<abs>/scripts/pr-watch-arm.sh" --slot "<slot>" --repo "<owner>/<repo>" --p
10
10
 
11
11
  The same argument that forbids authoring a per-slot `watch.sh` applies to arming itself. Performed from prose, the middle step — writing `watch-watermark.env` — is the one that gets dropped, and dropping it is silent: the loop gates every wake condition on that file, so it polls nothing, reports nothing and never reaches its terminal check, while still holding its PID lease and touching its heartbeat. Eleven such watchers once ran for hours across one session, missed nine merges and a red CI run between them, and every health signal said they were fine. Running one command cannot half-happen.
12
12
 
13
- Read the `DRAIN` lines it prints: they are the outstanding work the monitor will *not* tell you about, because the floors it just wrote mark that state as already seen. Steps 1-3 below are what the script does, and why.
13
+ Read the `DRAIN` lines it prints: they are the outstanding work as of the arm. Review ids and threads the drain read are floored, so the monitor will *not* tell you about those again. A stale branch or a red head is floored only when `last_seen.json` records a rebase or fix-ci cycle already attempted for that key or head ([`state-schemas.md`](state-schemas.md#watch-watermarkenv)); otherwise the drain line says `not floored: dispatch …` and the loop's first poll reports it as an event. Re-arming is never a way to set work aside — it neither handles nor silences anything. Steps 1-3 below are what the script does, and why.
14
14
 
15
15
  1. **Drain.** Run one tick per [`contract.md`](contract.md). It acts on everything already outstanding — actionable threads (`gitlab`: discussions), body-only reviews past the watermark (GitHub-only — GitLab has no review envelope), a stale branch, red CI — and finalizes a terminal PR. If the tick dispatched a cycle, stop here: the cycle's exit path settles the watch when it finishes.
16
- 2. **Seed the watermark.** *(`pr-watch-arm.sh` does this; the reasoning is kept because the floors are subtle and wrong ones are quiet.)* Resolve the provider once per [`../_shared/vcs/detect-vcs.md`](../_shared/vcs/detect-vcs.md) — every fetch in this sequence uses that provider's recipes. Write the slot's watch watermark ([`state-schemas.md`](state-schemas.md#watch-watermarkenv)) to the ids the **drain itself read** — the max review-id and comment-id observed at the drain's own fetch (Step 1), snapshotted at that read. Never let the loop capture its own baseline — the arming session writes it; and **never** from a fresh fetch taken after the drain, which would include a comment that arrived after the drain read the wave and mark it seen unread. Seeded to the drain's floor, anything landing after that read stays above the watermark and the monitor's first iteration surfaces it. Seed the CI floor (`CIRED`) from the same drain read: set it to the head SHA when the checks have **already settled red** at that read (no check pending, one or more in the `fail` bucket per [`../_shared/vcs/common/ci-rollup.md`](../_shared/vcs/common/ci-rollup.md)) — that red is what the drain just handled — and empty otherwise, so an escalated red head the drain already saw does not re-fire on the loop's first iteration. Seed the rebase floor (`REBASED`) the same way, from the drain's branch-standing read per [`../_shared/vcs/common/branch-standing.md`](../_shared/vcs/common/branch-standing.md): set it to the current `rebase_key` (`<head_sha>..<base_tip_sha>`) when the drain found the branch already behind or conflicting — that staleness is what the drain just handled — and empty otherwise, so a branch the drain already rebased or escalated does not re-fire on the loop's first iteration. Seed the blocked-CI floor (`BLOCKED_CIDIGEST`) to the blocked fingerprint's `ci_digest` when arming while `last_seen.blocked` is already set, and empty otherwise — empty is the not-blocked state, in which the loop's blocked-resume probe stays dormant.
16
+ 2. **Seed the watermark.** *(`pr-watch-arm.sh` does this; the reasoning is kept because the floors are subtle and wrong ones are quiet.)* Resolve the provider once per [`../_shared/vcs/detect-vcs.md`](../_shared/vcs/detect-vcs.md) — every fetch in this sequence uses that provider's recipes. Write the slot's watch watermark ([`state-schemas.md`](state-schemas.md#watch-watermarkenv)) to the ids the **drain itself read** — the max review-id and comment-id observed at the drain's own fetch (Step 1), snapshotted at that read. Never let the loop capture its own baseline — the arming session writes it; and **never** from a fresh fetch taken after the drain, which would include a comment that arrived after the drain read the wave and mark it seen unread. Seeded to the drain's floor, anything landing after that read stays above the watermark and the monitor's first iteration surfaces it. Seed the CI floor (`CIRED`) from the same drain read: set it to the head SHA only when the checks have **already settled red** at that read (no check pending, one or more in the `fail` bucket per [`../_shared/vcs/common/ci-rollup.md`](../_shared/vcs/common/ci-rollup.md)) **and** `last_seen.json` records a fix-ci attempt for that head — a cycle already ran for that red, so its escalation or retry is not news — and empty otherwise. Seed the rebase floor (`REBASED`) the same way, from the drain's branch-standing read per [`../_shared/vcs/common/branch-standing.md`](../_shared/vcs/common/branch-standing.md): the current `rebase_key` (`<head_sha>..<base_tip_sha>`) only when the drain found the branch behind or conflicting **and** a rebase attempt is recorded for that key, empty otherwise. An escalation entry alone never floors anything: one with no attempt behind it records a decision nobody acted on, and flooring it is how a re-arming session once kept a stale branch and a red head silent for a day ([`state-schemas.md`](state-schemas.md#watch-watermarkenv) names the fields). Seed the blocked-CI floor (`BLOCKED_CIDIGEST`) to the blocked fingerprint's `ci_digest` when arming while `last_seen.blocked` is already set, and empty otherwise — empty is the not-blocked state, in which the loop's blocked-resume probe stays dormant. The script reads all three facts from `last_seen.json` through [`../../scripts/pr-watch-verdict.mjs`](../../scripts/pr-watch-verdict.mjs) `arm-floors`, and records what it found due in `watch-due.env` ([`state-schemas.md`](state-schemas.md#watch-dueenv)).
17
17
  3. **Dedup, then watch.** First read `<slot>/watch.pid` ([`state-schemas.md`](state-schemas.md#watchpid)): if it names a live process (`kill -0 "$pid"` succeeds) **and `owner.json` records this session**, a watcher already owns this slot — **skip arming, do not start a second**. This is what stops orphaned watchers from accumulating: the in-session monitor dying does not stop the OS loop it launched (on Windows a detached Git Bash loop keeps running and polling `gh` forever after the session ends), so checking a live task list is not enough — the PID lease is.
18
18
 
19
19
  **A live lease owned by a different session does not count as owned** — check it with `watcher_lease_is_foreign` from [`../../scripts/pr-watch-guards.sh`](../../scripts/pr-watch-guards.sh). A live PID proves the loop is running, never that anything is listening: an orphan left by a dead session keeps polling and keeps touching its heartbeat while its stdout is that session's closed monitor pipe, so every liveness signal reads healthy and the events reach nobody. Skipping on the PID alone let such a corpse block this session from arming the PR for the whole lifetime cap — seven days, since the default moved off six hours. When the guard reports a foreign lease, kill that PID, delete `watch.pid`, and arm fresh; note it in the slot's `followup.log` so the reclaim is visible.
@@ -38,6 +38,8 @@ Read the `DRAIN` lines it prints: they are the outstanding work the monitor will
38
38
 
39
39
  The label is `PR #<n> — <title>`. Label and command both matter: some task surfaces show one, some the other, and a slot-bearing command keeps the watch identifiable everywhere a raw script blob would not. One monitor per PR at a time: it is the watch's visible handle, showing as a running task while the PR is polled, and replaced by a fresh one each time the loop rolls over. Its loop checks about every 60 seconds, re-reading the watermark and touching the slot's `watch-heartbeat` file each iteration — the liveness beacon that tells [`reconcile.md`](reconcile.md) a quiet watch is still alive; on a newer submitted review, a newer thread comment (`gitlab`: a newer discussion note), a thread newly unresolved (`gitlab`: discussion), **the head SHA's checks settling red** (no check pending and one or more in the `fail` bucket per [`../_shared/vcs/common/ci-rollup.md`](../_shared/vcs/common/ci-rollup.md)), **the branch falling behind or conflicting with its base** (`behind_by > 0` or the conflict signal per [`../_shared/vcs/common/branch-standing.md`](../_shared/vcs/common/branch-standing.md)), or — **only while the watch is blocked** (`BLOCKED_CIDIGEST` non-empty) — **the head's CI digest changing in any way** (not just to red) — it prints one line and **keeps watching**, advancing its in-memory floor so each event fires the tick exactly once. The review and thread floors are monotonic ids; the other three are not. The CI-red floor is the **head SHA**, because the check rollup is non-monotonic — it flips green↔red and resets on every push — so recording the red head SHA fires CI once per red head, and a later push re-arms it on the new SHA. The rebase floor (`REBASED`) is the **`rebase_key`** — `<head_sha>..<base_tip_sha>` — because staleness is a function of both sides: keying on the pair fires once per newly-due pair and re-arms when either the head or the base moves, where a head-only key would wedge permanently the first time the base advances (the head cannot change while nobody pushes). A head whose checks are still **pending** is never a red wake, and a branch with `behind_by == 0` and `mergeable == UNKNOWN` is never a rebase wake: pending checks may yet go green and conflict state is still computing, and the tick would idle on either (Steps 5–6) regardless. The blocked-CI signal is different in kind — a **resume** probe, live only while the watch is blocked: it wakes on any move of the head's CI digest (the same bucket-plus-sorted-name/conclusion signature the blocked fingerprint records — [`blocked-tick.md`](blocked-tick.md)) away from `BLOCKED_CIDIGEST`, so a block waiting on a green pass, a rerun, or an external deploy check resumes as promptly as one waiting on red. Quiet iterations print nothing and cost nothing — no model tokens are spent while the watch is quiet.
40
40
 
41
+ Each poll also rewrites the slot's `watch-due.env` whenever the due work changes — the rebase key found due and the head whose checks settled red, or an empty file when neither — so the session's turn-end gate can see work the watch reported without a provider call ([`state-schemas.md`](state-schemas.md#watch-dueenv)).
42
+
41
43
  The loop is **self-terminating**, so it never becomes one of those orphans. It claims the slot's `watch.pid`, then checks the guards from [`../../scripts/pr-watch-guards.sh`](../../scripts/pr-watch-guards.sh) at the top of every iteration before any `gh` call: `watcher_superseded` steps it down when a newer arm takes the slot; `watcher_window_elapsed` ends it one poll inside its monitor's timeout, printing a `ROLLOVER` line so the owning session re-arms; and `watcher_lifetime_exceeded` retires an orphan nothing supersedes. Every wait, a fetch backoff included, is clamped to the window, so no sleep carries the loop past its monitor. A failed fetch is never mistaken for a terminal PR — it counts toward `MUGGLE_PR_WATCH_MAX_FETCH_FAILURES` (60) with `watcher_fetch_backoff` between tries, so hours of outage are ridden out and the error lands in `<slot>/watch-fetch.log`. Terminal exit stays reserved for an observed `MERGED`/`CLOSED`.
42
44
 
43
45
  The lifetime cap comes from the [`watcherLifetime`](../muggle-preferences/preference-gates/watcherLifetime.md) preference — `7d` by default, `1d`, or `never` for unbounded. The loop cannot read preferences, so resolve the value at arm time, convert it to seconds, and export `MUGGLE_PR_WATCH_MAX_LIFETIME` into the monitor's environment; an already-set value wins and is never overwritten. `never` exports 0, which the guard reads as unbounded. Under a monitor the window ends each loop long before either cap, so it is the window, not this value, that retires a loop once its session is gone — within about 29 minutes. The lifetime bounds a loop run with the window disabled (`MUGGLE_PR_WATCH_MONITOR_WINDOW=0`).
@@ -45,7 +47,7 @@ Read the `DRAIN` lines it prints: they are the outstanding work the monitor will
45
47
  So it exits when the PR goes terminal, after `MUGGLE_PR_WATCH_MAX_FETCH_FAILURES` consecutive failed fetches, when a newer arm supersedes it, when its monitor window elapses, or once it passes the lifetime cap — never `while true` unbounded.
46
48
  4. **On event.** Polling never enters the session: the cadence lives entirely in the detached monitor loop (step 3), and the only thing the session ever receives is the monitor's one event line. That line wakes the session: the wake turn runs the tick (step 1) with `--wake=<event>` — the flag that tells routing's live-watcher gate this poll was prompted, not idle curiosity ([`SKILL.md`](SKILL.md#routing)) — and whatever cycle the tick produces runs **inline in the owning session** — never in a subagent. The session's full history is part of the cycle's context (decisions, review nuance, owner phrasing); a subagent only knows its briefing plus disk/provider state, and anything the briefing omits is silently missing from the cycle. The token cost of inline cycles is accepted — context beats cost. The tick still derives everything from live provider state; a terminal PR finalizes there while the monitor exits on its own. Persistent fetch failure → surface the reason; [`reconcile.md`](reconcile.md) re-arms the slot at the next start of the session that owns it.
47
49
 
48
- A `ROLLOVER` line is not an event to tick on: re-run [`pr-watch-arm.sh`](../../scripts/pr-watch-arm.sh) for the slot as a new monitor, without Step 3's dedup. Its `DRAIN` lines cover anything that landed between the old loop's last poll and the new one's first. Answer a monitor expiry notice for the slot the same way — it should not occur, since the window closes first, but if it does the loop is unheard and must be replaced.
50
+ A `ROLLOVER` line is not an event to tick on: re-run [`pr-watch-arm.sh`](../../scripts/pr-watch-arm.sh) for the slot as a new monitor, without Step 3's dedup. Its `DRAIN` lines cover anything that landed between the old loop's last poll and the new one's first, and work still unattempted wakes the new loop again — a rollover is not a reprieve. Answer a monitor expiry notice for the slot the same way — it should not occur, since the window closes first, but if it does the loop is unheard and must be replaced.
49
51
 
50
52
  **After a cycle** — advance the watermark to the **handled wave's snapshot**, in the same dispatched context that ran the cycle. Capture the max review-id and comment-id **at the start of handling** — the ids the cycle actually read when it derived the wave, before any reply is posted — and advance the watermark to exactly those. **Never** re-derive it from a live-max fetched after the replies land: a reviewer comment that arrives during the handling window — between reading the wave and posting the replies — lands below that post-reply max and is marked seen without ever being read. Snapshotting at the start-of-handling read keeps such a comment above the watermark, so the next tick surfaces it. That advance is also what stops the loop from reporting its own reply; a cycle that skips it leaves the watermark stale, and the next event is an echo.
51
53
 
@@ -2,6 +2,8 @@
2
2
 
3
3
  The watcher's conditional path for a PR **blocked pending a human** — a durable block only the user can clear (an escalated rebase or CI budget spent, or an ambiguous review awaiting direction). Entered from [`contract.md`](contract.md) Step 7 (flag), then driven on each subsequent tick by Step 2.5 (resume gate). None of this runs on a normal tick: when `last_seen.blocked` is absent, the watcher skips straight through.
4
4
 
5
+ A block is entered only on a `block-*` verdict from the Step 6 verdict script. An escalation entry no cycle attempted is not a block — the verdict dispatches the work instead — and neither is the cost of running it.
6
+
5
7
  **Governing rule — one reminder per block, and the watch never stops.** The tick that flags the block reminds the owner once; every later blocked tick is silent. The watch keeps standing — the monitor stays visible, and ticks still run at their normal cadence (historically `1m`) whenever a wake or recovery cron fires — with fingerprint-based auto-resume clearing the block the moment external state moves. No repeat nagging, no cadence swap, no separate `reminded` flag: `blocked` present means the reminder has already been sent.
6
8
 
7
9
  ## The fingerprint
@@ -103,23 +103,48 @@ The watcher does **not** classify. Classification, batching, replying, escalatio
103
103
  5. Emit a `tick` event with `actionable_threads: <count>`, `dispatched_review_ids: [<id>, ...]`.
104
104
  6. Exit. **Reviews preempt CI** — when there is actionable feedback, this tick dispatches address-reviews and never polls CI. The watcher is now stopped; the dev cycle owns the PR and restarts the watcher when it finishes. (The watcher also self-unschedules in Step 2, terminal.)
105
105
 
106
- ### Step 5 — No actionable feedback → keep the branch rebased on its base
106
+ ### Step 5 — No actionable feedback → read the branch's standing against its base
107
107
 
108
- A merge-ready branch is **current with its base** — neither conflicting nor behind. From the Step 1 metadata, the branch needs a rebase when either:
108
+ A merge-ready branch is **current with its base** — neither conflicting nor behind. From the Step 1 metadata, the branch needs a rebase (`rebase_due`) when either:
109
109
 
110
110
  - the branch **conflicts** with its base — the provider's conflict signal per [`../_shared/vcs/common/branch-standing.md`](../_shared/vcs/common/branch-standing.md), **or**
111
111
  - `behind_by > 0` — out of date with the base. Read this from the `compare` call (commit ancestry), **never** from `mergeStateStatus == BEHIND`: GitHub masks `BEHIND` behind `DIRTY`/`BLOCKED` and only surfaces it under "require branches up to date" protection, so a stale PR that is also awaiting review or has a red required check reports `BLOCKED` — and its staleness would go unseen. The compare recipe for this — and each provider's conflict signal — is dispatched in [`../_shared/vcs/common/branch-standing.md`](../_shared/vcs/common/branch-standing.md).
112
112
 
113
+ `mergeable == UNKNOWN` with `behind_by == 0` is not due; `behind_by` is exact while GitHub is still computing conflict state, so a stale branch still counts.
114
+
113
115
  This trigger is **independent of approval and CI state**: an out-of-date branch is rebased whether or not it has been reviewed, approved, or has green checks. The watcher acts on staleness directly — it never waits for an approval to surface it.
114
116
 
115
117
  Rebase dedup is keyed on the **pair** `rebase_key = "<head_sha>..<base_tip_sha>"`, not on the head alone. Whether a branch conflicts is a function of both sides, so a head-only key wedges a PR permanently the first time the base moves: the head cannot change while nobody pushes, so one stale entry suppresses every genuinely new conflict that base movement introduces, forever. Take `base_tip_sha` from the Step 1 compare's `.base_commit.sha` (the base branch tip, which advances when the base does) — **never** `.merge_base_commit.sha`, which does not move when only the base advances and so would never re-arm.
116
118
 
117
- Entries written by an older watcher are bare head SHAs with no `..` — ignore them when reading `conflict_escalated_keys`, which re-arms any slot a head-only key had wedged.
119
+ Entries written by an older watcher are bare head SHAs with no `..`; the Step 6 verdict script ignores them, which re-arms any slot a head-only key had wedged.
118
120
 
119
121
  `conflict_resolve_attempts` bounds one key, never the PR. Because `rebase_key` carries the base tip, every advance of the base mints a fresh key and hands the branch a fresh pair of attempts, so on an active base that budget can never stop anything. The per-PR budget is the one that binds: `last_seen.catch_up_rebases` counts every rebase this PR has been dispatched for, no key resets it, and [`../muggle-preferences/preference-gates/maxCatchUpRebases.md`](../muggle-preferences/preference-gates/maxCatchUpRebases.md) caps it at 20 by default.
120
122
 
121
- If a rebase is due **and** `catch_up_rebases < maxCatchUpRebases` **and** `conflict_resolve_attempts[rebase_key] < 2` **and** `rebase_key` ∉ `conflict_escalated_keys` → dispatch and exit:
123
+ ### Step 6 — Poll CI for the head SHA, then take the verdict
124
+
125
+ Fetch the CI rollup for `prs.json[0].head_sha` per [`../_shared/vcs/common/ci-rollup.md`](../_shared/vcs/common/ci-rollup.md), provider resolved as in Step 3, and fold it into its bucket: `red`, `pending`, or `green` (green includes skipped checks and no checks).
126
+
127
+ Then run the verdict script. It is the **only** place this tick decides between dispatching and holding — never re-derive the decision from `last_seen.json` by reading it yourself. `<abs>` resolves from `${CLAUDE_PLUGIN_ROOT}/scripts/` as in [`arm-watcher.md`](arm-watcher.md); a slot with no `last_seen.json` feeds `/dev/null` instead:
128
+
129
+ ```sh
130
+ node "<abs>/scripts/pr-watch-verdict.mjs" tick --pr-key "<owner>/<repo>#<n>" --head <head_sha> \
131
+ --rebase-key "<head_sha>..<base_tip_sha>" --rebase-due <yes|no> --ci <red|pending|green> < "<slot>/last_seen.json"
132
+ ```
133
+
134
+ It prints one line, `VERDICT=<verdict>`. A non-zero exit is a broken install: report it and stop, never improvise a verdict. What it applies, in order:
135
+
136
+ 1. A rebase is due and `catch_up_rebases >= maxCatchUpRebases` (the cap from the user's preferences; the `rebase_budget_exhausted` flag is not consulted) → `block-rebase-budget-exhausted`.
137
+ 2. A rebase is due, `conflict_resolve_attempts[rebase_key] < 2`, and `rebase_key` ∉ `conflict_escalated_keys` → `dispatch-rebase`. With the per-key budget spent — `conflict_resolve_attempts[rebase_key] >= 2` or `rebase_key` ∈ `conflict_escalated_keys` — it falls through to CI.
138
+ 3. CI is `red`, `ci_fix_attempts[head_sha] < 3`, and `head_sha` ∉ `ci_escalated_shas` → `dispatch-fix-ci`. Red with `ci_fix_attempts[head_sha] >= 3` or `head_sha` ∈ `ci_escalated_shas` dispatches nothing — the fix budget is spent and the watcher does not re-dispatch. A check still pending (`bucket == "pending"`) never dispatches: the tick idles until CI settles, and a green head idles too.
139
+ 4. Otherwise `block-conflict-escalated`, `block-ci-escalated`, or `block-reviews-escalated` when the matching escalation stands, else `idle`.
140
+
141
+ **An escalation counts only with an attempt behind it.** An entry in `conflict_escalated_keys` suppresses a rebase only when `conflict_resolve_attempts[rebase_key] >= 1`, and an entry in `ci_escalated_shas` suppresses fix-ci only when `ci_fix_attempts[head_sha] >= 1`: a cycle ran and gave up. An entry with no attempt is ignored, and the work dispatches. Those fields are the executor's record of what its cycles did — never write an escalation entry or an attempt counter by hand.
122
142
 
143
+ **The verdict is binding.** The watch exists to drive the PR to merge-ready, and `autoRebase=always` means rebase without asking. How long a CI run or an eval takes is never a reason to hold a dispatch, and neither is a guess that the work is not worth it. The only hold is the user's own: a message they typed containing `HOLD WATCH #<pr-number>` for this PR. Asking them is allowed; answering a wake with a question instead of the dispatch is not. A Stop gate holds the turn open while work the watch recorded as due has no attempt behind it ([`../../hooks/README.md`](../../hooks/README.md)).
144
+
145
+ Act on the verdict:
146
+
147
+ - `dispatch-rebase` → dispatch and exit:
123
148
  1. Reset `last_seen.idle_tick_count` to 0.
124
149
  2. **Stop this watcher (single-thread):** cancel its cron exactly as in Step 4 — `/muggle-do`'s rebase respawns it when the cycle is done.
125
150
  3. Dispatch `/muggle-do` with a *rebase* directive (PR URL + slug; no review ids, no check names):
@@ -128,21 +153,9 @@ If a rebase is due **and** `catch_up_rebases < maxCatchUpRebases` **and** `confl
128
153
  ```
129
154
  The executor rebases onto the base: a behind-only branch replays cleanly and force-pushes; a conflicting branch resolves behind the `autoResolveConflicts` gate. Both paths are `/muggle-do`'s — the watcher only decides *that* a rebase is due, never how.
130
155
  4. Append a dispatching line to `followup.log`; emit a `tick` event with `rebase_needed: true`, `dispatched_rebase: true`.
131
- 5. Exit. The dev cycle owns the PR; its respawn restarts the watcher, whose next tick re-checks the branch against its base on the new head — the rebase is its own verify loop, bounded by the per-SHA attempt budget.
132
-
133
- If a rebase is due **and** `catch_up_rebases >= maxCatchUpRebases` → the PR has spent its catch-up budget. Do **not** dispatch, and do **not** fall through quietly: set `last_seen.rebase_budget_exhausted` to `true`, block the watch with reason `rebase_budget_exhausted` (Step 7), and report the count, the cap and the preference key on the PR. Twenty rebases without converging is a branch its owner has to decide about — rebase it onto a different base, split it, or close it — and a watcher that merely stops leaves them to discover it days later.
134
-
135
- That block is the one reason a fingerprint move does not clear (Step 2.5): base movement is precisely what spent the budget, so resuming on it would restore the loop the cap exists to end. It clears when the owner raises `maxCatchUpRebases` or the PR goes terminal.
136
-
137
- Otherwise — `behind_by == 0` and not conflicting (`mergeable == UNKNOWN` is fine here: `behind_by` is exact while GitHub is still computing conflict state, so a stale branch still triggers), or the per-key budget is spent (`conflict_resolve_attempts[rebase_key] >= 2` or `rebase_key` ∈ `conflict_escalated_keys`) → fall through to CI.
138
-
139
- ### Step 6 — No actionable feedback, branch current → poll CI for the head SHA
140
-
141
- Fetch the CI rollup for `prs.json[0].head_sha` per [`../_shared/vcs/common/ci-rollup.md`](../_shared/vcs/common/ci-rollup.md), provider resolved as in Step 3 (failed/running/success fold into the same red/pending/green buckets). Then, on the bucket:
142
-
143
- - **Any check still pending** (`bucket == "pending"`) → idle (wait for checks to settle).
144
- - **All checks green / skipped, or no checks** → idle (green path).
145
- - **One or more checks red** (`bucket == "fail"`), **and** `ci_fix_attempts[head_sha] < 3`, **and** `head_sha` ∉ `ci_escalated_shas` → dispatch and exit:
156
+ 5. Exit. The dev cycle owns the PR; its respawn restarts the watcher, whose next tick re-checks the branch against its base on the new head — the rebase is its own verify loop, bounded by the per-key attempt budget.
157
+ - `block-rebase-budget-exhausted` → the PR has spent its catch-up budget. Do **not** dispatch, and do **not** fall through quietly: set `last_seen.rebase_budget_exhausted` to `true`, block the watch with reason `rebase_budget_exhausted` (Step 7), and report the count, the cap and the preference key on the PR. Twenty rebases without converging is a branch its owner has to decide about — rebase it onto a different base, split it, or close it — and a watcher that merely stops leaves them to discover it days later. That block is the one reason a fingerprint move does not clear (Step 2.5): base movement is precisely what spent the budget, so resuming on it would restore the loop the cap exists to end. It clears when the owner raises `maxCatchUpRebases` or the PR goes terminal.
158
+ - `dispatch-fix-ci` → dispatch and exit:
146
159
  1. Reset `last_seen.idle_tick_count` to 0.
147
160
  2. **Stop this watcher (single-thread):** cancel its cron exactly as in Step 4 — `/muggle-do`'s fix-ci respawns it when the cycle is done.
148
161
  3. Dispatch `/muggle-do` with a *fix-ci* directive carrying the PR URL, slug, and the red check names (no review ids):
@@ -151,17 +164,19 @@ Fetch the CI rollup for `prs.json[0].head_sha` per [`../_shared/vcs/common/ci-ro
151
164
  ```
152
165
  4. Append a dispatching line to `followup.log`; emit a `tick` event with `checks_red: <count>`, `dispatched_ci_fix: true`.
153
166
  5. Exit. The dev cycle owns the PR; its respawn restarts the watcher, whose next tick re-checks CI on the new head SHA — CI itself is the verify loop.
154
- - **One or more red, but `ci_fix_attempts[head_sha] >= 3` or `head_sha` ∈ `ci_escalated_shas`** → idle. The fix budget is spent; `/muggle-do`'s fix-ci stage already recorded the escalation. The watcher does not re-dispatch.
167
+ - `block-conflict-escalated`, `block-ci-escalated`, `block-reviews-escalated` → blocked pending a human (Step 7).
168
+ - `idle` → transient idle (Step 7).
155
169
 
156
170
  ### Step 7 — Idle (remind when blocked pending a human)
157
171
 
158
- Any idle branch (Steps 4–6 that did not dispatch). First classify **why** this tick idled. It is **blocked pending a human** when the head is under a durable block that only the user can clear:
172
+ Any tick that did not dispatch. The Step 6 verdict says **why** it idled. It is **blocked pending a human** on a `block-*` verdict, a durable block only the user can clear:
159
173
 
160
- - `rebase_key` ∈ `conflict_escalated_keys` — a rebase `/muggle-do` gave up on (a semantic conflict, or `autoResolveConflicts=never`), reason `conflict_escalated`. This block clears on its own when the base moves: the new `base_tip_sha` yields a key the set does not contain, and the branch re-arms for a fresh rebase attempt; or
161
- - `head_sha` ∈ `ci_escalated_shas` — CI the fix-ci stage gave up on, reason `ci_escalated`; or
162
- - `last_seen.escalated_review_ids` is non-empty with the actionable set empty — an ambiguous review awaiting the user's direction, reason `reviews_escalated`.
174
+ - `block-conflict-escalated` — a rebase `/muggle-do` attempted and gave up on (a semantic conflict, or `autoResolveConflicts=never`), reason `conflict_escalated`. This block clears on its own when the base moves: the new `base_tip_sha` yields a key the set does not contain, and the branch re-arms for a fresh rebase attempt;
175
+ - `block-ci-escalated` — CI the fix-ci stage attempted and gave up on, reason `ci_escalated`;
176
+ - `block-reviews-escalated` — an ambiguous review in `last_seen.escalated_review_ids` awaiting the user's direction, with the actionable set empty, reason `reviews_escalated`;
177
+ - `block-rebase-budget-exhausted` — reason `rebase_budget_exhausted` (Step 6).
163
178
 
164
- Everything else that idles is **transient** — green and waiting for the next review, CI still pending, or `mergeable == UNKNOWN` — and must keep the responsive `1m` cadence; those turn a state on their own and the watcher should catch it promptly.
179
+ `idle` is **transient** — green and waiting for the next review, CI still pending, or `mergeable == UNKNOWN` — and must keep the responsive `1m` cadence; those turn a state on their own and the watcher should catch it promptly.
165
180
 
166
181
  **Transient idle** (no durable block): unchanged — increment `last_seen.idle_tick_count`, append an idle line to `followup.log` per [`output-templates/watcher-log.md`](output-templates/watcher-log.md), emit a `tick` event with `idle: true`, `blocked: false`, `actionable_threads: 0`, `dispatched_review_ids: []`, `rebase_needed: <bool>`, `dispatched_rebase: false`, `checks_red: <count or 0>`, `dispatched_ci_fix: false`. Exit through Step 7.5. The next tick fires from the monitor ([`arm-watcher.md`](arm-watcher.md)).
167
182