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

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 (74) 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/agents/acceptance-tester.md +18 -2
  10. package/dist/plugin/hooks/README.md +7 -5
  11. package/dist/plugin/hooks/codex-hooks.json +4 -4
  12. package/dist/plugin/hooks/hooks.json +3 -3
  13. package/dist/plugin/scripts/guardrail-record-delegation.sh +25 -0
  14. package/dist/plugin/scripts/guardrail-walkthrough-gate.sh +6 -6
  15. package/dist/plugin/scripts/guardrail-watch-follow-through-gate.sh +48 -0
  16. package/dist/plugin/scripts/guardrails.mjs +443 -64
  17. package/dist/plugin/scripts/pr-watch-arm.sh +64 -37
  18. package/dist/plugin/scripts/pr-watch-due.sh +31 -0
  19. package/dist/plugin/scripts/pr-watch-events.sh +20 -6
  20. package/dist/plugin/scripts/pr-watch-loop.sh +21 -2
  21. package/dist/plugin/scripts/pr-watch-verdict.mjs +197 -0
  22. package/dist/plugin/skills/_shared/ci-check-to-command.md +2 -1
  23. package/dist/plugin/skills/do/background-e2e.md +89 -0
  24. package/dist/plugin/skills/do/e2e-acceptance.md +4 -0
  25. package/dist/plugin/skills/do/e2e-repair.md +1 -1
  26. package/dist/plugin/skills/do/fix-ci.md +24 -8
  27. package/dist/plugin/skills/do/open-prs/forward.md +3 -3
  28. package/dist/plugin/skills/do/pre-flight.md +4 -3
  29. package/dist/plugin/skills/do/resolve-conflicts.md +7 -3
  30. package/dist/plugin/skills/do/wave-e2e.md +3 -3
  31. package/dist/plugin/skills/do/wave-or-stream.md +51 -0
  32. package/dist/plugin/skills/muggle-do/SKILL.md +6 -2
  33. package/dist/plugin/skills/muggle-pr-followup/SKILL.md +1 -1
  34. package/dist/plugin/skills/muggle-pr-followup/arm-watcher.md +5 -3
  35. package/dist/plugin/skills/muggle-pr-followup/blocked-tick.md +2 -0
  36. package/dist/plugin/skills/muggle-pr-followup/contract.md +40 -25
  37. package/dist/plugin/skills/muggle-pr-followup/state-schemas.md +22 -8
  38. package/dist/release-manifest.json +3 -3
  39. package/package.json +1 -1
  40. package/plugin/.claude-plugin/plugin.json +1 -1
  41. package/plugin/.codex-mcp.json +1 -1
  42. package/plugin/.codex-plugin/plugin.json +1 -1
  43. package/plugin/.cursor-plugin/plugin.json +1 -1
  44. package/plugin/.mcp.json +1 -1
  45. package/plugin/agents/acceptance-tester.md +18 -2
  46. package/plugin/hooks/README.md +7 -5
  47. package/plugin/hooks/codex-hooks.json +4 -4
  48. package/plugin/hooks/hooks.json +3 -3
  49. package/plugin/scripts/guardrail-record-delegation.sh +25 -0
  50. package/plugin/scripts/guardrail-walkthrough-gate.sh +6 -6
  51. package/plugin/scripts/guardrail-watch-follow-through-gate.sh +48 -0
  52. package/plugin/scripts/guardrails.mjs +443 -64
  53. package/plugin/scripts/pr-watch-arm.sh +64 -37
  54. package/plugin/scripts/pr-watch-due.sh +31 -0
  55. package/plugin/scripts/pr-watch-events.sh +20 -6
  56. package/plugin/scripts/pr-watch-loop.sh +21 -2
  57. package/plugin/scripts/pr-watch-verdict.mjs +197 -0
  58. package/plugin/skills/_shared/ci-check-to-command.md +2 -1
  59. package/plugin/skills/do/background-e2e.md +89 -0
  60. package/plugin/skills/do/e2e-acceptance.md +4 -0
  61. package/plugin/skills/do/e2e-repair.md +1 -1
  62. package/plugin/skills/do/fix-ci.md +24 -8
  63. package/plugin/skills/do/open-prs/forward.md +3 -3
  64. package/plugin/skills/do/pre-flight.md +4 -3
  65. package/plugin/skills/do/resolve-conflicts.md +7 -3
  66. package/plugin/skills/do/wave-e2e.md +3 -3
  67. package/plugin/skills/do/wave-or-stream.md +51 -0
  68. package/plugin/skills/muggle-do/SKILL.md +6 -2
  69. package/plugin/skills/muggle-pr-followup/SKILL.md +1 -1
  70. package/plugin/skills/muggle-pr-followup/arm-watcher.md +5 -3
  71. package/plugin/skills/muggle-pr-followup/blocked-tick.md +2 -0
  72. package/plugin/skills/muggle-pr-followup/contract.md +40 -25
  73. package/plugin/skills/muggle-pr-followup/state-schemas.md +22 -8
  74. /package/dist/{chunk-HGN35NEP.js → chunk-PQVRAFNE.js} +0 -0
@@ -11,6 +11,11 @@
11
11
  # The floors are taken from the drain's own read rather than from a fresh fetch
12
12
  # afterwards: anything that lands between the two would otherwise be marked seen
13
13
  # without ever being reported.
14
+ #
15
+ # A stale branch or a red head is floored only when the slot proves a cycle ran
16
+ # for it. Flooring whatever was outstanding at arm time let a session that never
17
+ # rebased or fixed anything re-arm at every rollover and silence the loop each
18
+ # time; the drain line said "handled" and nothing checked.
14
19
  set -uo pipefail
15
20
 
16
21
  script_dir="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
@@ -33,7 +38,7 @@ if [ -z "$slot" ] || [ -z "$repo" ] || [ -z "$pr_number" ] || [ -z "$base_branch
33
38
  exit 2
34
39
  fi
35
40
 
36
- for lib in pr-watch-guards.sh pr-watch-events.sh pr-watch-fetch.sh; do
41
+ for lib in pr-watch-guards.sh pr-watch-events.sh pr-watch-fetch.sh pr-watch-due.sh; do
37
42
  if [ ! -f "${script_dir}/${lib}" ]; then
38
43
  echo "pr-watch-arm: missing ${lib} beside this script" >&2
39
44
  exit 2
@@ -42,10 +47,12 @@ for lib in pr-watch-guards.sh pr-watch-events.sh pr-watch-fetch.sh; do
42
47
  . "${script_dir}/${lib}"
43
48
  done
44
49
 
45
- if [ ! -f "${script_dir}/pr-watch-state.jq" ]; then
46
- echo "pr-watch-arm: missing pr-watch-state.jq beside this script" >&2
47
- exit 2
48
- fi
50
+ for companion in pr-watch-state.jq pr-watch-verdict.mjs; do
51
+ if [ ! -f "${script_dir}/${companion}" ]; then
52
+ echo "pr-watch-arm: missing ${companion} beside this script" >&2
53
+ exit 2
54
+ fi
55
+ done
49
56
  state_projection="$(cat "${script_dir}/pr-watch-state.jq")"
50
57
 
51
58
  mkdir -p "$slot"
@@ -75,50 +82,68 @@ if [ "$pr_state" = "MERGED" ] || [ "$pr_state" = "CLOSED" ]; then
75
82
  exit 0
76
83
  fi
77
84
 
78
- # A red head at arm time is the drain's to hand over, so it goes into the floor
79
- # and does not re-fire on the loop's first pass. Pending checks are not red yet.
80
- ci_red_floor=""
81
- if [ "${pending_checks:-0}" -eq 0 ] 2>/dev/null && [ "${failed_checks:-0}" -gt 0 ] 2>/dev/null; then
82
- ci_red_floor="$head_sha"
83
- fi
85
+ ci_red_head=""
86
+ watch_checks_settled_red "$pending_checks" "$failed_checks" && ci_red_head="$head_sha"
84
87
 
85
- # Same for staleness: keyed on the head/base-tip pair, so it re-arms when either moves.
86
- rebase_floor=""
88
+ # Keyed on the head/base-tip pair, so it re-arms when either moves.
89
+ rebase_key="${head_sha}..${base_tip_sha}"
90
+ rebase_due_key=""
87
91
  behind_count="$(watch_fetch_behind_count "$repo" "$base_branch" "$head_sha" "$slot")"
88
- if [ "$mergeable" = "CONFLICTING" ] || { [ -n "$behind_count" ] && [ "$behind_count" -gt 0 ] 2>/dev/null; }; then
89
- rebase_floor="${head_sha}..${base_tip_sha}"
90
- fi
92
+ watch_branch_needs_rebase "$mergeable" "$behind_count" && rebase_due_key="$rebase_key"
91
93
 
92
- # A slot re-armed while blocked keeps its resume probe live. Empty is the
93
- # not-blocked state, so seeding it empty here would leave the loop asleep
94
- # through the very CI move the block is waiting on.
94
+ # Whether a cycle already ran for this key and this head, and the blocked
95
+ # fingerprint's digest. A slot re-armed while blocked keeps its resume probe
96
+ # live: empty is the not-blocked state, so seeding it empty would leave the loop
97
+ # asleep through the very CI move the block is waiting on.
95
98
  #
96
- # node rather than sed or jq: the digest sits under a per-PR key, jq is not
97
- # guaranteed present, and a malformed file must read as not blocked rather than
98
- # yield a partial match. The file goes in on stdin because Windows node cannot
99
- # open the POSIX path Git Bash hands it. A digest spanning lines is dropped:
100
- # written into the line-based watermark, it could forge another floor.
99
+ # The verdict script rather than sed or jq: the fields sit under a per-PR key,
100
+ # jq is not guaranteed present, and a malformed file must read as nothing
101
+ # recorded rather than yield a partial match. The file goes in on stdin because
102
+ # Windows node cannot open the POSIX path Git Bash hands it. Any failure leaves
103
+ # every floor empty, which wakes the loop rather than silencing it.
104
+ last_seen_file="${slot}/last_seen.json"
105
+ [ -f "$last_seen_file" ] || last_seen_file=/dev/null
106
+ rebase_attempted=0
107
+ ci_attempted=0
101
108
  blocked_digest_floor=""
102
- if [ -f "${slot}/last_seen.json" ]; then
103
- blocked_digest_floor="$(PR_KEY="${repo}#${pr_number}" node -e '
104
- try {
105
- const digest = JSON.parse(require("fs").readFileSync(0, "utf8"))[process.env.PR_KEY]?.blocked?.fingerprint?.ci_digest;
106
- if (typeof digest === "string" && !/[\r\n]/.test(digest)) process.stdout.write(digest);
107
- } catch {}
108
- ' < "${slot}/last_seen.json" 2>/dev/null)"
109
- fi
109
+ while IFS= read -r evidence_line; do
110
+ evidence_line="${evidence_line%$'\r'}"
111
+ case "$evidence_line" in
112
+ REBASE_ATTEMPTED=*) rebase_attempted="${evidence_line#REBASE_ATTEMPTED=}" ;;
113
+ CI_ATTEMPTED=*) ci_attempted="${evidence_line#CI_ATTEMPTED=}" ;;
114
+ BLOCKED_CIDIGEST=*) blocked_digest_floor="${evidence_line#BLOCKED_CIDIGEST=}" ;;
115
+ esac
116
+ done < <(node "${script_dir}/pr-watch-verdict.mjs" arm-floors --pr-key "${repo}#${pr_number}" \
117
+ --head "$head_sha" --rebase-key "$rebase_key" < "$last_seen_file" 2>/dev/null)
118
+
119
+ ci_red_floor=""
120
+ [ -n "$ci_red_head" ] && [ "$ci_attempted" = "1" ] && ci_red_floor="$ci_red_head"
121
+ rebase_floor=""
122
+ [ -n "$rebase_due_key" ] && [ "$rebase_attempted" = "1" ] && rebase_floor="$rebase_due_key"
110
123
 
111
124
  thread_count=0
112
125
  [ -n "$unresolved_threads" ] && thread_count=$(printf '%s' "$unresolved_threads" | tr ';' '\n' | grep -c .)
113
126
 
114
- # Printed, not swallowed: these are the things the arming session owes a decision
115
- # on before the monitor takes over, and the monitor only ever sees what arrives
116
- # after this point.
127
+ # Printed, not swallowed: these are the things the arming session owes action on
128
+ # before the monitor takes over. Unattempted work is left unfloored, so the
129
+ # loop's first pass reports it again as an event.
117
130
  echo "DRAIN pr=$pr_number state=$pr_state head=${head_sha:0:8}"
118
131
  echo "DRAIN unresolved-threads=$thread_count latest-review=${latest_review:-0} latest-comment=${latest_comment:-0}"
119
132
  echo "DRAIN checks pending=${pending_checks:-0} failed=${failed_checks:-0} behind-base=${behind_count:-unknown} mergeable=${mergeable:-UNKNOWN}"
120
- [ -n "$ci_red_floor" ] && echo "DRAIN ci already red at arm time — handled by the arming session, floored"
121
- [ -n "$rebase_floor" ] && echo "DRAIN branch already stale at arm time — handled by the arming session, floored"
133
+ if [ -n "$ci_red_head" ]; then
134
+ if [ -n "$ci_red_floor" ]; then
135
+ echo "DRAIN ci red at arm time — a fix-ci cycle already ran for head ${head_sha:0:8}, floored"
136
+ else
137
+ echo "DRAIN ci red at arm time — no fix-ci attempt recorded for head ${head_sha:0:8}, not floored: dispatch fix-ci"
138
+ fi
139
+ fi
140
+ if [ -n "$rebase_due_key" ]; then
141
+ if [ -n "$rebase_floor" ]; then
142
+ echo "DRAIN branch stale at arm time — a rebase already ran for key ${rebase_due_key}, floored"
143
+ else
144
+ echo "DRAIN branch stale at arm time — no rebase attempt recorded for key ${rebase_due_key}, not floored: dispatch rebase"
145
+ fi
146
+ fi
122
147
 
123
148
  {
124
149
  printf 'REV=%s\n' "${latest_review:-0}"
@@ -129,6 +154,8 @@ echo "DRAIN checks pending=${pending_checks:-0} failed=${failed_checks:-0} behin
129
154
  printf 'BLOCKED_CIDIGEST="%s"\n' "$blocked_digest_floor"
130
155
  } > "${slot}/watch-watermark.env"
131
156
 
157
+ watch_record_due_work "$slot" "$head_sha" "$rebase_due_key" "$ci_red_head"
158
+
132
159
  # Claim the slot for this session. watcher_lease_is_foreign reads an absent
133
160
  # owner.json as "not foreign", so a slot armed without one leases itself to a
134
161
  # live PID nothing can classify: once the arming session dies its watcher polls
@@ -0,0 +1,31 @@
1
+ #!/usr/bin/env bash
2
+
3
+ # Records the work a watch has seen due on its PR — a rebase or red CI — so the
4
+ # owning session's turn-end gate can tell an event it acted on from one it sat
5
+ # on. Sourced by pr-watch-arm.sh and pr-watch-loop.sh.
6
+ #
7
+ # The gate runs in a Stop hook with about a second to answer and no network, so
8
+ # it cannot ask the provider what is due; it reads this file and the slot's
9
+ # attempt counters instead. A session once held a stale branch and a red head
10
+ # for a day by re-arming its watch, whose drain floored both as "handled", and
11
+ # answering every wake with a question. Nothing on disk said the work was due,
12
+ # so nothing could notice. This file is that record.
13
+ #
14
+ # Rewritten whole each time what is due changes; left empty when nothing is, so
15
+ # the gate's shell pre-filter reads an empty file as nothing owed.
16
+
17
+ MUGGLE_PR_WATCH_DUE_FILE="watch-due.env"
18
+
19
+ # Writes <slot>/watch-due.env: the head the observation was made on, the
20
+ # `<head>..<base-tip>` key of a rebase found due (empty when the branch is
21
+ # current), and the head whose checks settled red (empty otherwise). Builtins
22
+ # only, since the loop writes it every time what is due changes.
23
+ watch_record_due_work() {
24
+ local slot="$1" head_sha="$2" rebase_due_key="$3" ci_red_head="$4"
25
+ if [ -z "$rebase_due_key" ] && [ -z "$ci_red_head" ]; then
26
+ : > "${slot}/${MUGGLE_PR_WATCH_DUE_FILE}"
27
+ return 0
28
+ fi
29
+ printf 'HEAD="%s"\nREBASE_DUE="%s"\nCI_RED_HEAD="%s"\n' "$head_sha" "$rebase_due_key" "$ci_red_head" \
30
+ > "${slot}/${MUGGLE_PR_WATCH_DUE_FILE}"
31
+ }
@@ -71,9 +71,16 @@ watch_wake_thread() {
71
71
  echo "EVENT pr=$pr thread newly unresolved id=$thread_id"
72
72
  }
73
73
 
74
- # The head's checks having **settled** red: nothing still pending and at least
75
- # one failure. Pending-with-a-failure is not a wake — a run in flight may still
76
- # go green, and the tick would idle on it anyway.
74
+ # True when the head's checks have **settled** red: nothing still pending and at
75
+ # least one failure. Pending-with-a-failure is not red yet — a run in flight may
76
+ # still go green, and the tick would idle on it anyway.
77
+ watch_checks_settled_red() {
78
+ local pending_count="$1" failed_count="$2"
79
+ [ "${pending_count:-0}" -eq 0 ] 2>/dev/null || return 1
80
+ [ "${failed_count:-0}" -gt 0 ] 2>/dev/null
81
+ }
82
+
83
+ # The head's checks having settled red (watch_checks_settled_red).
77
84
  #
78
85
  # The floor is the head SHA rather than a monotonic id because a check rollup is
79
86
  # not monotonic: it flips green to red and resets on every push. Keying on the
@@ -82,11 +89,18 @@ watch_wake_ci_red() {
82
89
  local pr="$1" pending_count="$2" failed_count="$3" head_sha="$4" floor="$5"
83
90
  [ -n "$head_sha" ] || return 1
84
91
  [ "$head_sha" != "$floor" ] || return 1
85
- [ "${pending_count:-0}" -eq 0 ] 2>/dev/null || return 1
86
- [ "${failed_count:-0}" -gt 0 ] 2>/dev/null || return 1
92
+ watch_checks_settled_red "$pending_count" "$failed_count" || return 1
87
93
  echo "EVENT pr=$pr checks settled red head=$head_sha"
88
94
  }
89
95
 
96
+ # True when the branch needs a rebase onto its base: conflicting with it, or
97
+ # behind it by a measured, positive count. An unreadable count is not behind.
98
+ watch_branch_needs_rebase() {
99
+ local mergeable="$1" behind_count="$2"
100
+ [ "$mergeable" = "CONFLICTING" ] && return 0
101
+ [ -n "$behind_count" ] && [ "$behind_count" -gt 0 ] 2>/dev/null
102
+ }
103
+
90
104
  # The branch needing a rebase onto its base — conflicting with it, or merely
91
105
  # behind it.
92
106
  #
@@ -106,11 +120,11 @@ watch_wake_rebase() {
106
120
  local pr="$1" mergeable="$2" behind_count="$3" rebase_key="$4" floor="$5"
107
121
  [ -n "$rebase_key" ] || return 1
108
122
  [ "$rebase_key" != "$floor" ] || return 1
123
+ watch_branch_needs_rebase "$mergeable" "$behind_count" || return 1
109
124
  if [ "$mergeable" = "CONFLICTING" ]; then
110
125
  echo "EVENT pr=$pr branch conflicting with base key=$rebase_key"
111
126
  return 0
112
127
  fi
113
- [ -n "$behind_count" ] && [ "$behind_count" -gt 0 ] 2>/dev/null || return 1
114
128
  echo "EVENT pr=$pr branch behind base by $behind_count — rebase due key=$rebase_key"
115
129
  }
116
130
 
@@ -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. |
@@ -0,0 +1,89 @@
1
+ # Background E2E — one acceptance run per change, off the main thread
2
+
3
+ A session that fixes several unrelated bugs opens several PRs, and each needs the E2E run of its own change: a walkthrough rendered from another change's run vouches for code that run never exercised. Running each Stage 6 inline also stalls the session on the browser while the next fix waits. So each change's Stage 6 runs in a background `muggle:acceptance-tester`, and the main session moves on to the next change.
4
+
5
+ ## Changes
6
+
7
+ A **change** is what gets one E2E run and one report: a whole wave, or one PR of a stream. How a session's PRs group into waves and streams is defined once, in [`wave-or-stream.md`](wave-or-stream.md); this lane runs every change of a stream, a wave included.
8
+
9
+ - Each change has its own session directory (`state.md`, `iterations/`), branch and worktree — one per member for a wave. Pre-flight splits a request that bundles unrelated fixes this way ([`pre-flight.md`](pre-flight.md)).
10
+ - Changes cannot share a checkout: the background run tests one change's tree while the session edits another's. Every change gets a worktree, whatever `autoUseWorktree` says.
11
+
12
+ ## Lane
13
+
14
+ `state.md` records the lane Stage 6 runs in:
15
+
16
+ - `E2E lane: background` — the session has other work in front of it when this change reaches Stage 6: another change still being built, queued, or in its own run.
17
+ - `E2E lane: inline` — a lone change with nothing else to do. Handing it off buys nothing and costs the run the session's context.
18
+
19
+ Decide the lane when the change reaches Stage 6, not at pre-flight; a change that ran inline in an earlier cycle can run in the background now.
20
+
21
+ ## One local run at a time
22
+
23
+ Local runs share one studio browser and the stack's ports, and two studio runs at once corrupt each other — both report infra failures that read as product signal. So:
24
+
25
+ - At most one local acceptance-tester is in flight from this session. Further changes queue in the order they reached Stage 6.
26
+ - No inline local run starts while a background one is in flight, and the main session neither starts nor stops services meanwhile — the agent owns the local stack for its run.
27
+ - A run against a preview or staging URL drives the cloud rather than the local studio and needs no queue.
28
+
29
+ Each change's `state.md` tracks its place: `E2E dispatch: queued` → `running — dispatched <ISO-8601>` → `reported — <verdict> (<runIds>)`.
30
+
31
+ ## Brief
32
+
33
+ The agent knows only its brief. Pass every value itself, never a pointer to the conversation:
34
+
35
+ - The change's slug and absolute session directory.
36
+ - Repo, worktree path, branch, base branch, and the head SHA under test — for a wave, one entry per member, from its `Wave members` block.
37
+ - The PR URL when the PR already exists (a repair re-run, or a PR opened outside `muggle-do`) — for a wave, every member's. Muggle reads PR URLs from the brief to know which PR's walkthrough is waiting on this run, so leave none out and add none that belong to another change.
38
+ - `Validation`, `localUrl`, `projectId`, and test-credential status from `state.md`.
39
+ - The `e2eScope` from impact analysis, verbatim; a Stage 7.5 re-run passes only its affected test cases.
40
+ - The acceptance criteria from `requirements.md`.
41
+ - `wallTimeBudgetSec`.
42
+ - The absolute path of [`e2e-acceptance.md`](e2e-acceptance.md) as the stage to execute — plus [`wave-e2e.md`](wave-e2e.md) for a wave — with the rules in the two sections below.
43
+
44
+ Dispatch it as `subagent_type: "muggle:acceptance-tester"` (bare `acceptance-tester` where the plugin namespace is absent), in the background. A harness with no background agents runs every change's Stage 6 inline, one after another.
45
+
46
+ ## The agent's run
47
+
48
+ 1. Start the stack from the change's worktree: [`muggle-test-prepare`](../muggle-test-prepare/SKILL.md) with the worktree as the directory override for the repo's services — for a wave, every member's worktree for its own repo's services, per [`wave-e2e.md`](wave-e2e.md) Stage 6. Confirm by process cwd that each service runs its worktree — a port that answers may be serving another change's branch.
49
+ 2. Execute `e2e-acceptance.md` from Step 0.5 through Step 7 over the brief's scope, in its own context. A wave runs each case once against the combined stack and names each failure's `implicatedRepo`.
50
+ 3. Append the Stage 6 marker to the change's `iterations/<NNN>.md`: that file's report, plus `Tested: <owner/repo>@<sha>` — one line per member for a wave.
51
+ 4. Return the same report as its final message.
52
+
53
+ ## What the agent never does
54
+
55
+ - Dispatch another agent or fork. It runs every step itself; a re-delegated run escapes the queue and lands on the browser alongside the next one.
56
+ - Edit code, commit, push, open or edit a PR, post or edit a comment, or arm a watcher. Every PR write stays in the main session, the one place that knows which change a PR belongs to.
57
+ - Declare a skip marker. A `SKIPPED` verdict returns its code; the main session declares it from the PR's worktree, where it is verified and where it settles that PR alone.
58
+ - Stop the stack it started.
59
+
60
+ ## When the report returns
61
+
62
+ On the agent's completion notification, the main session:
63
+
64
+ 1. **Checks freshness.** Every `Tested:` line must name its branch's current head. A branch that moved since dispatch — any member's, for a wave — makes the report stale: queue the change again and post nothing.
65
+ 2. **Records it** — `E2E dispatch: reported — …` in `state.md`.
66
+ 3. **Continues that change from Stage 7**, in its worktree. [`open-prs/forward.md`](open-prs/forward.md) opens its PR with this report — every member's PR for a wave, in the wave order of [`wave-e2e.md`](wave-e2e.md) Stage 7; when a PR already exists, the report settles that PR's walkthrough through Mode A with its number and repo passed explicitly — never from the current branch, since the session's cwd may be another change's worktree.
67
+ 4. **Runs Stage 7.5** inline. A repair pass's re-run returns to this lane, behind any local run in flight.
68
+ 5. **Arms the change's watcher** once 7.5 clears (Stage 8).
69
+ 6. **Dispatches the next queued change.**
70
+
71
+ An agent that ends without a report is dispatched once more; a second miss runs that change's Stage 6 inline.
72
+
73
+ ## PRs opened outside `muggle-do`
74
+
75
+ A session that fixed bugs by hand and opened each PR itself follows the same lane, one acceptance-tester per PR. With no pre-flight or impact analysis, the main session resolves the run first: `muggle-test`'s change detection and test-case selection over that PR's diff against its base, its questions answered in the main session — the agent has no user to ask. The brief then carries the selected test cases, project and URL in place of `e2eScope`, and names [`../_shared/dev-loop/run.md`](../_shared/dev-loop/run.md) as the procedure. The main session posts the returned report to that PR through [`muggle-pr-visual-walkthrough`](../muggle-pr-visual-walkthrough/SKILL.md) Mode A, number and repo explicit.
76
+
77
+ ## Enforcement
78
+
79
+ - Dispatching a background acceptance-tester holds the E2E and debug-path Stop gates off for a bounded window, and for that window the walkthrough gate sets aside the PRs its brief names — the session is never steered into a second browser run alongside the agent's.
80
+ - A walkthrough posted to one PR settles that PR only; every other PR the session opened is still checked for its own.
81
+ - A skip declaration settles only the PRs of the working tree it is declared in — the PRs opened from it and its branch's PR, never another change's.
82
+ - Every PR's walkthrough check stays red until its slot is settled, so a change whose run never came back cannot pass as tested.
83
+
84
+ ## Invariants
85
+
86
+ - One run and one report per change per full cycle; a wave is one change.
87
+ - At most one local acceptance run in flight from the session.
88
+ - Every PR write happens in the main session.
89
+ - A report settles only the PRs of the change it tested, at the SHA it tested.
@@ -67,6 +67,10 @@ For a `local-e2e` block, use `localUrl`, `projectId`, and the working-tree path
67
67
 
68
68
  `state.md` records `Wave: on` → this stage runs **once for the whole wave**, not per repo, per [`wave-e2e.md`](wave-e2e.md): the wave stack starts from every member's worktree, test cases are selected against the union of diffs, each case runs once, and each failure names its `implicatedRepo`. The steps below apply with those changes.
69
69
 
70
+ ### Step 0.45: Background lane
71
+
72
+ When other work is in front of the session as this change reaches Stage 6, the main session runs none of the steps below: it records `E2E lane: background`, queues the change, and dispatches a background `acceptance-tester` to execute them per [`background-e2e.md`](background-e2e.md). Executing as that agent, follow its rules — in particular, a `SKIPPED` exit returns its code in the report and runs no `MUGGLE_E2E_SKIP` echo; the main session declares it from the PR's worktree once the report returns.
73
+
70
74
  ### Step 0.5: Readiness check
71
75
 
72
76
  A `local-e2e` cycle runs these before any `muggle-local-execute-*` call, every cycle — even when pre-flight already reported the app ready, since a server can die while stages 2–5 run and a healthy one fast-exits:
@@ -78,7 +78,7 @@ One question, listing each unrepairable failure with its bucket, failing step, a
78
78
 
79
79
  ## Step 5: Close the loop
80
80
 
81
- After a `repair`, `regenerate`, or `retry` pass, re-run [`e2e-acceptance.md`](e2e-acceptance.md) over the affected test cases only, increment `repairIteration`, and return to Step 0.
81
+ After a `repair`, `regenerate`, or `retry` pass, re-run [`e2e-acceptance.md`](e2e-acceptance.md) over the affected test cases only, increment `repairIteration`, and return to Step 0. A change whose `state.md` records `E2E lane: background` re-runs through that lane ([`background-e2e.md`](background-e2e.md)), queued behind any local run in flight, with this PR's URL in the brief.
82
82
 
83
83
  The loop is bounded at **3** repair iterations, the same bound the cycle guardrail already applies to E2E failures. On the third exhausted iteration, waive automatically: retitle `[E2E FAILING]`, record the surviving failures in `result.md`, and clear to Stage 8. A PR a reviewer can see is worth more than a loop that never terminates.
84
84