@muggleai/works 5.36.0-staging.336 → 5.36.0-staging.337

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 (46) hide show
  1. package/.claude-plugin/marketplace.json +1 -1
  2. package/dist/{chunk-X3GQII63.js → chunk-HTCBHSL6.js} +130 -38
  3. package/dist/cli.js +1 -1
  4. package/dist/index.js +1 -1
  5. package/dist/plugin/.claude-plugin/plugin.json +1 -1
  6. package/dist/plugin/.codex-mcp.json +1 -1
  7. package/dist/plugin/.codex-plugin/plugin.json +1 -1
  8. package/dist/plugin/.cursor-plugin/plugin.json +1 -1
  9. package/dist/plugin/.mcp.json +1 -1
  10. package/dist/plugin/hooks/README.md +1 -1
  11. package/dist/plugin/scripts/guardrail-watch-follow-through-gate.sh +22 -7
  12. package/dist/plugin/scripts/guardrails.mjs +21 -3
  13. package/dist/plugin/scripts/pr-watch-arm.sh +11 -6
  14. package/dist/plugin/scripts/pr-watch-loop.sh +3 -2
  15. package/dist/plugin/scripts/pr-watch-verdict.mjs +1 -0
  16. package/dist/plugin/skills/do/audit-trail.md +1 -1
  17. package/dist/plugin/skills/do/e2e-repair.md +1 -1
  18. package/dist/plugin/skills/do/open-prs/forward.md +17 -15
  19. package/dist/plugin/skills/do/open-prs.md +1 -1
  20. package/dist/plugin/skills/muggle-pr-followup/SKILL.md +1 -1
  21. package/dist/plugin/skills/muggle-pr-followup/arm-watcher.md +2 -2
  22. package/dist/plugin/skills/muggle-pr-followup/contract.md +6 -0
  23. package/dist/plugin/skills/muggle-pr-followup/reconcile.md +1 -1
  24. package/dist/plugin/skills/muggle-pr-followup/state-schemas.md +8 -2
  25. package/dist/release-manifest.json +4 -4
  26. package/package.json +1 -1
  27. package/plugin/.claude-plugin/plugin.json +1 -1
  28. package/plugin/.codex-mcp.json +1 -1
  29. package/plugin/.codex-plugin/plugin.json +1 -1
  30. package/plugin/.cursor-plugin/plugin.json +1 -1
  31. package/plugin/.mcp.json +1 -1
  32. package/plugin/hooks/README.md +1 -1
  33. package/plugin/scripts/guardrail-watch-follow-through-gate.sh +22 -7
  34. package/plugin/scripts/guardrails.mjs +21 -3
  35. package/plugin/scripts/pr-watch-arm.sh +11 -6
  36. package/plugin/scripts/pr-watch-loop.sh +3 -2
  37. package/plugin/scripts/pr-watch-verdict.mjs +1 -0
  38. package/plugin/skills/do/audit-trail.md +1 -1
  39. package/plugin/skills/do/e2e-repair.md +1 -1
  40. package/plugin/skills/do/open-prs/forward.md +17 -15
  41. package/plugin/skills/do/open-prs.md +1 -1
  42. package/plugin/skills/muggle-pr-followup/SKILL.md +1 -1
  43. package/plugin/skills/muggle-pr-followup/arm-watcher.md +2 -2
  44. package/plugin/skills/muggle-pr-followup/contract.md +6 -0
  45. package/plugin/skills/muggle-pr-followup/reconcile.md +1 -1
  46. package/plugin/skills/muggle-pr-followup/state-schemas.md +8 -2
@@ -1,6 +1,6 @@
1
1
  # Audit trail
2
2
 
3
- **Arm first.** If this cycle leaves a PR open and its watch is not armed yet, stop reading and arm it now ([`respawn-watcher.md`](respawn-watcher.md), or Stage 8 on a forward cycle). The block is written after the arm, never instead of it.
3
+ **Arm first.** If this cycle leaves a PR open and its watch is not armed yet, stop reading and arm it now ([`respawn-watcher.md`](respawn-watcher.md), or Stage 5.5 on a forward cycle, whose Stage 8 then lifts the hold). The block is written after the arm, never instead of it.
4
4
 
5
5
  What a cycle shows the user before it ends: the tests the change involved, their results, and links to the proof. It reports and gates nothing. Anything missing is stated in the block, never a reason to stop, retry, or ask.
6
6
 
@@ -1,6 +1,6 @@
1
1
  # E2E Repair Loop (Stage 7.5)
2
2
 
3
- Runs between Stage 7's posted walkthrough and Stage 8's watcher dispatch, and again whenever the watcher finds the PR's `muggle-walkthrough` check red on failed cases ([`fix-ci.md`](fix-ci.md) Step 2.5). A failing acceptance run means the change is not ready for a reviewer, so this stage root-causes every failure and either repairs it in-pipeline or puts one decision in front of the user. The watcher is armed only once this stage clears.
3
+ Runs between Stage 7's posted walkthrough and Stage 8's watcher dispatch, and again whenever the watcher finds the PR's `muggle-walkthrough` check red on failed cases ([`fix-ci.md`](fix-ci.md) Step 2.5). A failing acceptance run means the change is not ready for a reviewer, so this stage root-causes every failure and either repairs it in-pipeline or puts one decision in front of the user. The PR's watch is armed at Stage 5.5 but holds every cycle until this stage clears and Stage 8 lifts the hold.
4
4
 
5
5
  ## Turn preamble
6
6
 
@@ -1,6 +1,6 @@
1
1
  # Open PR — forward mode
2
2
 
3
- The forward pipeline's PR stages, which run on either side of Stage 6. **Stage 5.5** opens the change — a PR on GitHub (`gh pr create`) or an MR on GitLab (`glab mr create`), provider resolved in Step 5 — as soon as unit tests pass, before any browser run. **Stage 7** settles that run's result on it, then seeds session state and arms the first watch.
3
+ The forward pipeline's PR stages, which run on either side of Stage 6. **Stage 5.5** opens the change — a PR on GitHub (`gh pr create`) or an MR on GitLab (`glab mr create`), provider resolved in Step 5 — as soon as unit tests pass, before any browser run, and arms its watch with every cycle held. **Stage 7** settles that run's result on it, and **Stage 8** lifts the hold.
4
4
 
5
5
  The PR goes up first because opening it needs nothing from the run: CI and reviewers start on the diff while E2E runs, and the run's [PR progress](../../_shared/dev-loop/run.md#pr-progress) fills the PR's walkthrough comment case by case. The walkthrough check stays red until Stage 7 settles that comment, so an open PR never passes as tested before its run lands.
6
6
 
@@ -62,6 +62,16 @@ Per repo:
62
62
 
63
63
  A create that fails ends the cycle for that repo: report it under **Errors** and run no E2E for it, since the run would have no PR to settle.
64
64
 
65
+ 6. **Seed and arm the watch, held.** Write `~/.muggle-ai/muggle-do/sessions/<slug>/prs.json` per [`../../muggle-pr-followup/state-schemas.md`](../../muggle-pr-followup/state-schemas.md#prsjson), one entry per PR this stage opened:
66
+
67
+ ```json
68
+ [{ "repo": "owner/repo", "number": 142, "url": "...", "head_sha": "...", "state": "open" }]
69
+ ```
70
+
71
+ Seed `last_seen.json` per [`../../muggle-pr-followup/state-schemas.md`](../../muggle-pr-followup/state-schemas.md#last_seenjson): the empty-watermark shape with `pushed_shas: []`, `lastBodyReviewId: 0` and `lastConversationCommentId: 0` (forward mode has no prior reviews to skip), and `"forward_stages_in_flight": true`. **Do not** seed `cycle.json` or `requirements.md`. Then arm each PR's watch per [`../../muggle-pr-followup/arm-watcher.md`](../../muggle-pr-followup/arm-watcher.md). The arm writes `owner.json` and `watch-registration.json`, so from here on the PR is watched, owned by this session, and visible to the muggle watch service and to reconcile, however Stage 6 ends.
72
+
73
+ The flag is the hold. While it is set the watch still reports, but the tick dispatches nothing — no address-reviews, rebase, or fix-ci — and logs a `deferred` line instead (the verdict is `hold-forward-stages`), because Stage 6 is testing the head any such cycle would push over. A watch wake that arrives during Stages 6–7.5 runs that tick between steps of this cycle and goes back to the stage in flight; it never pre-empts it. Reviews, CI and branch drift wait in the watermarks, undispatched, for Stage 8.
74
+
65
75
  ## Stage 7 — report on the PR
66
76
 
67
77
  Runs once Stage 6 has recorded this change's verdict; a Stage 6 readiness halt never reaches it. Per repo, using the provider resolved in Stage 5.5:
@@ -86,25 +96,17 @@ The E2E repair loop ([`../e2e-repair.md`](../e2e-repair.md)) runs once Stage 7 h
86
96
 
87
97
  ## Stage 8 handoff
88
98
 
89
- After every repo is processed and Stage 7.5 has cleared, build the watcher manifest and arm one watch per opened PR. The arms are the LAST action this stage takes.
90
-
91
- Write `~/.muggle-ai/muggle-do/sessions/<slug>/prs.json` per [`../../muggle-pr-followup/state-schemas.md`](../../muggle-pr-followup/state-schemas.md#prsjson):
92
-
93
- ```json
94
- [{ "repo": "owner/repo", "number": 142, "url": "...", "head_sha": "...", "state": "open" }]
95
- ```
96
-
97
- Seed `~/.muggle-ai/muggle-do/sessions/<slug>/last_seen.json` per [`../../muggle-pr-followup/state-schemas.md`](../../muggle-pr-followup/state-schemas.md#last_seenjson) — empty-watermark shape with `pushed_shas: []`. Forward mode never has prior reviews to skip, so `lastBodyReviewId: 0` and `lastConversationCommentId: 0`.
99
+ After every repo is processed and Stage 7.5 has cleared, lift the hold Stage 5.5 set and hand each PR to its watch. The handoff ticks are the LAST action this stage takes.
98
100
 
99
- **Do not** seed `cycle.json` or `requirements.md`. The watcher is a dumb pipe; `/muggle-do` reads reviews off GitHub.
101
+ Per PR: rewrite `last_seen.json` without `forward_stages_in_flight` (whole-file rewrite), then run its tick, `/muggle:muggle-pr-followup <slug> <n> --wake=stage-handoff`. The tick refreshes `prs.json` from the provider (Stage 7 may have force-pushed the tested head), dispatches whatever the hold kept back — reviews first, then a rebase or fix-ci — or idles, and leaves one loop polling per [`../../muggle-pr-followup/arm-watcher.md`](../../muggle-pr-followup/arm-watcher.md), the same procedure [`../respawn-watcher.md`](../respawn-watcher.md) settles every later watch with. A loop that died during Stage 6 is re-armed there. Never a recurring `/loop` cron — every cron fire is a model turn, while the loop polls token-free. The PR counts as watched only while that loop is running; a seeded slot alone is not a watch.
100
102
 
101
- For each entry in `prs.json`, arm its watch per [`../../muggle-pr-followup/arm-watcher.md`](../../muggle-pr-followup/arm-watcher.md) — the same procedure [`../respawn-watcher.md`](../respawn-watcher.md) settles every later watch with: one drain tick, the watermark seeded from it, then one persistent labeled monitor. Never a recurring `/loop` cron — every cron fire is a model turn, while the monitor polls token-free. The PR counts as watched only once that monitor's loop is running; a seeded slot alone is not a watch.
103
+ Stage 7.5 keeps its meaning: it is still the gate in front of every cycle the watch dispatches, because nothing dispatches until this handoff lifts the hold. A cycle that exits before Stage 8 — a Stage 6 readiness halt, a stalled run — leaves the hold set and says so on the **Stage 8** line: the PR stays watched and its reports still reach this session, but no cycle runs on it until the forward cycle resumes or the user asks for the hold to be lifted.
102
104
 
103
- If `prs.json` is empty, **do not arm** — record the reason in `result.md` and exit.
105
+ If Stage 5.5 opened no PR, there is no slot and nothing to hand off — record the reason in `result.md` and exit.
104
106
 
105
107
  ## Invariants
106
108
 
107
- - Branch synced with its base before the push, never after; PR opened per non-skipped repo before Stage 6 starts, ready for review — never a draft; the tested head is the PR's head before its walkthrough settles; designated walkthrough comment settled via Mode A, or its skip reason stated; `prs.json`+`last_seen.json` seeded (no `cycle.json`, no `requirements.md`); Stage 7.5 cleared before arming; arming per `arm-watcher.md` is the last action.
109
+ - Branch synced with its base before the push, never after; PR opened per non-skipped repo before Stage 6 starts, ready for review — never a draft; the tested head is the PR's head before its walkthrough settles; designated walkthrough comment settled via Mode A, or its skip reason stated; `prs.json`+`last_seen.json` seeded and the watch armed, held, when the PR opens (no `cycle.json`, no `requirements.md`); Stage 7.5 cleared before the hold lifts; the handoff tick is the last action.
108
110
 
109
111
  ## Output
110
112
 
@@ -117,7 +119,7 @@ The cycle's closing message opens with the [audit trail](../audit-trail.md), on
117
119
  **Overflow comments posted:** repo → PR #
118
120
  **Recurring run:** `already scheduled` | `<recommended options>` (bug fixes only)
119
121
  **Stage 7.5:** `green` | `waived — <reason>` | `decision-pending`
120
- **Stage 8:** `Watching <N> PR(s) — one watch loop per PR, armed per arm-watcher.md` | `No PRs to watch — stage 8 not armed`
122
+ **Stage 8:** `Watching <N> PR(s) — hold lifted, one watch loop per PR` | `Held — <reason>; watched since Stage 5.5, cycles wait for the hold to lift` | `No PRs to watch — no slot seeded`
121
123
  **Errors:** repo → message
122
124
 
123
125
  ## Post-merge cleanup
@@ -4,5 +4,5 @@ Two modes, set by the `/muggle-do` invocation. Each consumer loads only its mode
4
4
 
5
5
  | Mode | When | Procedure |
6
6
  | :--- | :--- | :-------- |
7
- | Forward | A fresh feature, called by `/muggle-do`'s forward pipeline. Opens the PR after Stage 5 (Stage 5.5), settles its walkthrough after Stage 6 (Stage 7), seeds state, dispatches the first watcher. | [`open-prs/forward.md`](open-prs/forward.md) |
7
+ | Forward | A fresh feature, called by `/muggle-do`'s forward pipeline. Opens the PR after Stage 5 (Stage 5.5) and arms its watch with cycles held, settles its walkthrough after Stage 6 (Stage 7), lifts the hold at Stage 8. | [`open-prs/forward.md`](open-prs/forward.md) |
8
8
  | Update | The PR already exists; the address-reviews orchestrator called this stage to push + refresh title/description/walkthrough. | [`open-prs/update.md`](open-prs/update.md) |
@@ -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), 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.
48
+ **`--wake=<event>`** is passed only by an event wake's dispatch ([`arm-watcher.md`](arm-watcher.md) step 5), by the follow-through Stop gate's instruction (`--wake=follow-through`) when the watch recorded due work nothing attempted or holds a report that never reached the session, or by the pipeline that opened the PR when it hands the PR over (`--wake=stage-handoff`) — each asserts something is waiting, so the tick's poll is justified. A service wake may carry `--also=<slug>:<n>:<kind>,…`: the owner's other slots whose watch reports also wait. After this tick, run `/muggle:muggle-pr-followup <slug> <n> --wake=<kind>` for each listed slot, one at a time, so no owned PR's report is left unread. 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
 
@@ -16,13 +16,13 @@ The `DRAIN` lines it prints, in the watch's output, are the outstanding work as
16
16
 
17
17
  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), conversation comments past theirs (GitHub-only), 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.
18
18
  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, comment-id and human conversation-comment id (`CONV`) 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 loop's first iteration surfaces it. Seed the CI floor (`CIRED`) from the same drain read: set it to the red key (`<head_sha>@<red-check-runs>`) 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** fix-ci is finished with that head — it escalated, or spent the tick's per-head budget — and empty otherwise. A lone attempt does not floor: the count is written before the fix runs, so a cycle that recorded it and changed nothing would otherwise leave the red silent. 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. Seed the rebase hold (`REBASE_HELD`) to `1` when `last_seen.json`'s `catch_up_rebases` has reached `maxCatchUpRebases` — the same check the tick's verdict blocks on — and empty otherwise: while it is set the loop raises no rebase wake on any base move. The script reads all four 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)).
19
- 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 task 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.
19
+ 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), **`owner.json` records this session**, and the slot has no [`watch-listener`](state-schemas.md#watch-listener) file, a watcher already owns this slot — **skip arming, do not start a second**. A live loop whose `watch-listener` names `muggle-watch` was started by the muggle watch service and reports to the service, not to this session: arm over it. The new loop supersedes it, takes the slot back, and deletes the service's undelivered reports, which this arm's drain covers. This is what stops orphaned watchers from accumulating: the in-session task 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.
20
20
 
21
21
  **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 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.
22
22
 
23
23
  This is narrow on purpose. It reclaims only a lease held on behalf of *another* session, which is decidable from `owner.json` alone. A loop orphaned by its **own** session still reads as owned, and nothing on disk distinguishes it — so the signal comes from the reader instead. **When this arm answers the slot's own loop ending — its `EXPIRED` or `ROLLOVER` line, or a monitor's expiry notice — skip this dedup and arm.** Each means the previous loop is gone or no longer heard. The new loop writes its PID to `watch.pid`, and `watcher_superseded` retires any survivor at its next iteration. Treat an armed watcher as evidence a poller exists, never as proof a review will be seen.
24
24
 
25
- Otherwise **claim the slot for this session** before starting anything: write `owner.json` ([`state-schemas.md`](state-schemas.md#ownerjson)) with `session_id` from `$CLAUDE_CODE_SESSION_ID` and `claimed_at` now. Arming is what establishes ownership, so every arming point records it here rather than each caller remembering to. If `$CLAUDE_CODE_SESSION_ID` is unset, write no `owner.json` — an unidentifiable owner is worse than none, since [`reconcile.md`](reconcile.md) would read a bogus id as some other session's claim and could never recover the slot.
25
+ Otherwise **claim the slot for this session** before starting anything: write `owner.json` ([`state-schemas.md`](state-schemas.md#ownerjson)) with `session_id` from `$CLAUDE_CODE_SESSION_ID` and `claimed_at` now. `pr-watch-arm.sh --owner <session-id>` claims for that session instead; the muggle watch service passes the id `owner.json` already records, so the loops it restarts stay owned. Arming is what establishes ownership, so every arming point records it here rather than each caller remembering to. If `$CLAUDE_CODE_SESSION_ID` is unset, write no `owner.json` — an unidentifiable owner is worse than none, since [`reconcile.md`](reconcile.md) would read a bogus id as some other session's claim and could never recover the slot.
26
26
 
27
27
  The same claim **registers the slot with the muggle watch service**: `pr-watch-arm.sh` writes [`watch-registration.json`](state-schemas.md#watch-registrationjson) beside `owner.json`. The service is a per-user scheduled job that runs outside every session. When a registered slot's loop is gone, it starts the loop itself as a detached program, so no session spends a turn on it. When that loop reports, the service wakes the owner session with that one PR's tick, and only between turns. It never sends a session a reconcile or anything about another PR. A slot armed any other way is registered with `muggle watch register --slot <slot>`. `muggle watch unregister --slot <slot>` keeps a slot session-scoped. The service still reports on it, but never starts its loop or wakes its owner.
28
28
 
@@ -92,6 +92,10 @@ The watcher's dispatch trigger is **derived from current provider state**, not a
92
92
 
93
93
  - **`gitlab`** — single source. Fetch unresolved discussions per [`../_shared/vcs/gitlab/unresolved-discussions.md`](../_shared/vcs/gitlab/unresolved-discussions.md) (drop to [`../_shared/vcs/gitlab/mr-discussions.md`](../_shared/vcs/gitlab/mr-discussions.md) for the raw notes if a thread's classification needs them). A discussion is **actionable** when it is unresolved **and** its newest note lacks the loop marker `<!-- muggle-do:bot -->` — same marker classification, never `author.username`. There is no body-only watermark: discussion state is the sole authority. The dispatch list is the **discussion ids** of the actionable discussions.
94
94
 
95
+ ### Step 3.5 — Forward-stage hold
96
+
97
+ When `last_seen[<pr>].forward_stages_in_flight` is `true` ([`state-schemas.md`](state-schemas.md#last_seenjson)), the pipeline that opened this PR still owns it: it set the flag when it opened the PR and armed this watch, and clears it at its handoff, which then runs this tick with `--wake=stage-handoff`. Dispatch nothing, reviews included: that pipeline is still testing the head a cycle would push over, and it alone decides when the watch may act. Append a `deferred` line to `followup.log` naming what the tick would have dispatched (review ids, conversation comment ids), skip Steps 4–6 and exit as transient idle through Step 7.5, so the loop keeps watching. Nothing is lost: the review and conversation watermarks are not advanced, so the handoff's tick finds the same actionable set. A terminal PR still finalizes in Step 2.
98
+
95
99
  ### Step 4 — If the actionable set is non-empty → dispatch (reviews preempt CI)
96
100
 
97
101
  The watcher does **not** classify. Classification, batching, replying, escalation, and cycle execution all live in `/muggle-do`. The watcher hands over the dispatch ids from Step 3 (GitHub: owning review ids; GitLab: discussion ids) and exits — `/muggle-do`'s address-reviews re-derives the unresolved threads itself (its authority), so the watcher only needs to decide *that* there is work, not enumerate it exhaustively.
@@ -143,6 +147,7 @@ node "<abs>/scripts/pr-watch-verdict.mjs" tick --pr-key "<owner>/<repo>#<n>" --h
143
147
 
144
148
  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:
145
149
 
150
+ 0. `forward_stages_in_flight` is `true` → `hold-forward-stages`, whatever the branch and CI say (Step 3.5).
146
151
  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`.
147
152
  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.
148
153
  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; it holds as `block-ci-escalated` (Step 4) even when fix-ci never wrote the escalation, because idling there leaves a red PR with nobody told. A check still pending (`bucket == "pending"`) never dispatches: the tick idles until CI settles, and a green head idles too.
@@ -176,6 +181,7 @@ Act on the verdict:
176
181
  4. Append a dispatching line to `followup.log`; emit a `tick` event with `checks_red: <count>`, `dispatched_ci_fix: true`.
177
182
  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.
178
183
  - `block-conflict-escalated`, `block-ci-escalated`, `block-reviews-escalated` → blocked pending a human (Step 7).
184
+ - `hold-forward-stages` → transient idle (Step 7), with a `deferred` line in `followup.log` naming the rebase or fix-ci the hold kept back (Step 3.5).
179
185
  - `idle` → transient idle (Step 7).
180
186
 
181
187
  ### Step 7 — Idle (remind when blocked pending a human)
@@ -18,7 +18,7 @@ Two invariants hold on every trigger, however the sweep was reached: it never se
18
18
 
19
19
  A watcher reports to its session: a loop armed in a session prints into it, so a session that ends or hits its usage limit stops hearing its watches. No poller acts on a PR out of session. This is deliberate: a review is addressed only inside a session that carries the context to address it, never by a headless process that would reply without that context.
20
20
 
21
- What does run out of session is the muggle watch service (`muggle watch`, a per-user scheduled job). It addresses nothing on any PR, and it never sends a session this sweep. For a slot registered in [`watch-registration.json`](state-schemas.md#watch-registrationjson) whose loop is gone, it restarts the loop itself as a detached program, which costs no session a turn. When that loop reports, it wakes the **owning** session with that one PR's tick, `/muggle:muggle-pr-followup <slug> <n> --wake=<event>`. It does so only between turns, never while the session works or waits on its user. A plugin reload leaves a session that owns open watches running. A slot whose PR went terminal while neither its loop nor its owner is running it finalizes itself, as Step 3 would, leaving the post-merge cleanup unrun. Everything else it finds (red CI, a stale branch, a report its owner cannot take yet) it only reports.
21
+ What does run out of session is the muggle watch service (`muggle watch`, a per-user scheduled job). It addresses nothing on any PR, and it never sends a session this sweep. For a slot registered in [`watch-registration.json`](state-schemas.md#watch-registrationjson) whose loop is gone, it restarts the loop itself as a detached program, which costs no session a turn. When that loop reports, it wakes the **owning** session with that one PR's tick, `/muggle:muggle-pr-followup <slug> <n> --wake=<event>`, naming the owner's other waiting reports in `--also`. It does so only between turns, never while the session works or waits on its user. A report waiting on a busy owner never leaves the PR unwatched: the service queues it and restarts the loop, claimed for the owner `owner.json` records. A plugin reload leaves a session that owns open watches running. A slot whose PR went terminal while neither its loop nor its owner is running it finalizes itself, as Step 3 would, leaving the post-merge cleanup unrun. Everything else it finds (red CI, a stale branch, a report its owner cannot take yet) it only reports.
22
22
 
23
23
  **Ownership is session-scoped too, and that is what bounds recovery.** Each slot records the session that armed it in [`owner.json`](state-schemas.md#ownerjson). Step 3.6 re-arms only slots the running session owns — watchers it armed itself, whose poller died under it. A slot owned by another session, or by none, is **never** re-armed here however dead its poller looks. The same argument that forbids a headless daemon forbids a fresh session inheriting a stranger's PR: it would be picking up review work it has no context for, on a branch it never built, and every push it made would be as context-blind as the daemon the design already rejected. Adoption exists precisely so that step is a deliberate act by the owner ([`adopt.md`](adopt.md)) rather than a side effect of starting a session.
24
24
 
@@ -59,9 +59,9 @@ The slot's opt-in to recovery by the muggle watch service (`muggle watch`, a per
59
59
  }
60
60
  ```
61
61
 
62
- Recovery requires all of: the slot is registered, the PR is open on GitHub, no loop is heard (no loop process carries the slot's `--slot` path, or the one that does prints into a session that has ended), the heartbeat is older than the re-arm hand-off, `polling.disabled` is absent, `owner.json` names an owner, and that owner is not mid-turn. The service then runs `pr-watch-arm.sh` itself, detached, with `MUGGLE_PR_WATCH_LISTENER=muggle-watch`. The loop records [`watch-listener`](#watch-listener) and writes its output to [`watch-service.out`](#watch-serviceout), and no session spends a turn on it.
62
+ Recovery requires all of: the slot is registered, the PR is open on GitHub, no loop is heard (no loop process carries the slot's `--slot` path, or the one that does prints into a session that has ended), the heartbeat is older than the re-arm hand-off, `polling.disabled` is absent, `owner.json` names an owner, and that owner is not mid-turn. A report the owner has not been woken for never holds the PR unwatched: the service sets it aside in [`watch-service.queued.out`](#watch-servicequeuedout) and starts the fresh loop, mid-turn owner or not. The service then runs `pr-watch-arm.sh` itself, detached, with `MUGGLE_PR_WATCH_LISTENER=muggle-watch` and `--owner <session_id>` from `owner.json`, so the arm claims the slot for its recorded owner rather than leaving it unowned. The loop records [`watch-listener`](#watch-listener) and writes its output to [`watch-service.out`](#watch-serviceout), and no session spends a turn on it.
63
63
 
64
- When that loop exits on an `EVENT` or `TERMINAL` line, the service wakes the owner with `/muggle:muggle-pr-followup <slug> <n> --wake=<event|terminal>`, naming that slot and PR only. It resumes the owner in the background from the project dir its transcript records. A running owner is woken only as a background session idle between turns: it is stopped first, and only after a throwaway background launch confirms Claude will resume it in that workspace. The resume runs only once neither `claude agents` nor Claude's own session registry shows a process for the owner. If Claude still answers with a copy under a new id, the service stops and removes that copy and counts the wake as failed, so the agent view never gains a duplicate. An owner that is mid-turn, waiting on its user, or open in a terminal keeps the report, and the service alerts once the report is overdue. The service never wakes the ended owner of a merged or closed PR; it closes that slot out instead. An `EXPIRED` loop is restarted without waking anyone. The service caps loop starts and wakes per pass, caps failed wakes per owner, and holds every wake while the account sits at a usage limit.
64
+ When that loop exits on an `EVENT` or `TERMINAL` line, or a queued report waits, the service wakes the owner with `/muggle:muggle-pr-followup <slug> <n> --wake=<event|terminal>`, naming that slot and PR. Every other slot of the same owner with a report waiting rides along as `--also=<slug>:<n>:<kind>,…`, so one wake tells the session about all of them. It resumes the owner in the background from the project dir its transcript records. A running owner is woken only as a background session idle between turns: it is stopped first, and only after a throwaway background launch confirms Claude will resume it in that workspace. The resume runs only once neither `claude agents` nor Claude's own session registry shows a process for the owner. If Claude still answers with a copy under a new id, the service stops and removes that copy and counts the wake as failed, so the agent view never gains a duplicate. An owner that is mid-turn, waiting on its user, or open in a terminal keeps the report, the service alerts once the report is overdue, and the follow-through Stop gate names the report's tick at the owner's next turn end. The service never wakes the ended owner of a merged or closed PR; it closes that slot out instead. An `EXPIRED` loop is restarted without waking anyone. The service caps loop starts and wakes per pass, caps failed wakes per owner, and holds every wake while the account sits at a usage limit.
65
65
 
66
66
  **Absent ⇒ observed only.** The service still reports on the slot's watcher, CI and branch standing, but never starts its loop or wakes its owner. Slots armed before this file existed stay that way until their next arm. The file lives in the slot, so a `.stopped` rename or a `result.md` retires it with the slot.
67
67
 
@@ -73,6 +73,10 @@ Who hears the leased loop's exit. A loop started with `MUGGLE_PR_WATCH_LISTENER`
73
73
 
74
74
  The output of the last loop the muggle watch service started for the slot. Its `EVENT`, `TERMINAL`, `EXPIRED`, `WATCH-FAIL` or `ARM-FAIL` line says why the loop ended. Once the owner is woken for an `EVENT` or `TERMINAL` report, the file is renamed `watch-service.delivered.out`, so no later pass wakes the owner for it again. A loop a session arms deletes the file, because that arm's drain covers whatever it held.
75
75
 
76
+ ## `watch-service.queued.out`
77
+
78
+ Service loop reports the owner has not been woken for, set aside when the service starts a fresh loop over them, so the PR stays watched while the report waits. Each report is appended; the file's time is when the first one was reported. The owner's wake renames it, with any `watch-service.out` report, into `watch-service.delivered.out`, and a loop a session arms deletes it, as it does `watch-service.out`. While it is non-empty in a slot this session owns, the follow-through Stop gate blocks the turn end naming `/muggle:muggle-pr-followup <slug> <n> --wake=follow-through`.
79
+
76
80
  ## `cron.json`
77
81
 
78
82
  A durable, on-disk handle to this slot's watcher cron. Its whole reason to exist: `CronList` goes **blind to crons that outlive a session continue / compaction** (the watcher's `/loop` cron survives, but the tool can no longer enumerate it), so a teardown that can only find crons through `CronList` can never delete the orphan — it re-fires until the 7-day `/loop` expiry. A cron id recorded to disk **while the cron was still visible** stays a valid `CronDelete` target afterward. See [`record-cron-id.md`](record-cron-id.md) (who writes it) and [`cancel-cron.md`](cancel-cron.md) (who deletes by it).
@@ -112,6 +116,7 @@ Keyed by `"<owner>/<repo>#<n>"`. One key per PR in the slot.
112
116
  "conflict_escalated_keys": ["<head-sha>..<base-tip-sha>", ...],
113
117
  "catch_up_rebases": <int>,
114
118
  "rebase_budget_exhausted": <bool>,
119
+ "forward_stages_in_flight": <bool>,
115
120
  "e2e_decision": {
116
121
  "head_sha": "<sha>",
117
122
  "cases": [{ "name": "<test case>", "testCaseId": "<id>", "bucket": "<bucket>", "failedStep": <int>, "waived": <bool> }]
@@ -132,6 +137,7 @@ Keyed by `"<owner>/<repo>#<n>"`. One key per PR in the slot.
132
137
 
133
138
  - `lastBodyReviewId`: narrow watermark for **body-only** reviews (a submitted review carrying no line comments). The watcher dispatches a body-only review only when `id > lastBodyReviewId`. Line-comment threads do **not** use it — they are dispatched from live thread state (unresolved + not outdated + newest comment unmarked by the loop), so there is no cursor that can pin past them. Bootstrap sets it to the highest existing submitted review id with `--forward-only`, else `0`. The cursor keeps its name under GitLab, where it holds the highest note / discussion id.
134
139
  - `lastConversationCommentId` (GitHub only): narrow watermark for **conversation comments** — top-level PR comments on the Conversation tab, which belong to no review and no thread. The watcher dispatches one only when `id > lastConversationCommentId` ([`../_shared/vcs/github/conversation-comments.md`](../_shared/vcs/github/conversation-comments.md)). Issue-comment ids are their own sequence, so this never shares `lastBodyReviewId`. Bootstrap, auto-track and forward mode write it beside `lastBodyReviewId` — `0`, or the highest existing conversation comment id under `--forward-only`. An entry **without** the key predates conversation comments being watched: the tick seeds it to the highest actionable id it reads and dispatches none of them, so an upgrade never re-answers a PR's comment history.
140
+ - `forward_stages_in_flight`: `true` while the pipeline that opened the PR still owns it. That pipeline opens the PR, seeds the slot with the flag set and arms the watch in one step, so the PR is watched and registered with the muggle watch service from the moment it exists. While it is set the tick dispatches nothing ([`contract.md`](contract.md) Step 3.5), the verdict script answers `hold-forward-stages`, and the follow-through Stop gate owes nothing for the PR. The pipeline removes the key at its handoff and runs the tick with `--wake=stage-handoff`, which dispatches whatever the hold kept back. Absent means `false`.
135
141
  - `last_pushed_sha`: most recent SHA `/muggle-do` pushed in this PR's life; `null` until the first push.
136
142
  - `idle_tick_count`: incremented each tick whose actionable set is empty. Reset to 0 on any tick that dispatches `/muggle-do`. Diagnostic only — does not gate behavior.
137
143
  - `cycles_completed`: incremented each time `/muggle-do` completes an address-reviews invocation (regardless of actionable/ambiguous/mixed).
@@ -1,7 +1,7 @@
1
1
  {
2
- "release": "5.36.0-staging.336",
3
- "buildId": "run-336-1",
4
- "commitSha": "e6d98c8df9e83a493fe7413190a49a4fd3044608",
5
- "buildTime": "2026-11-11T09:40:14Z",
2
+ "release": "5.36.0-staging.337",
3
+ "buildId": "run-337-1",
4
+ "commitSha": "31b6432920f1e69a27b9aea7683fa09ac4f178ed",
5
+ "buildTime": "2026-11-12T00:30:39Z",
6
6
  "serviceName": "muggle-ai-works-mcp"
7
7
  }
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@muggleai/works",
3
3
  "mcpName": "io.github.multiplex-ai/muggleai",
4
- "version": "5.36.0-staging.336",
4
+ "version": "5.36.0-staging.337",
5
5
  "description": "Acceptance test agent for coding agents: real-browser tests, with screenshots on the PR.",
6
6
  "type": "module",
7
7
  "main": "dist/index.js",
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "muggle",
3
3
  "description": "Acceptance test agent for coding agents: real-browser tests, with screenshots on the PR.",
4
- "version": "5.36.0-staging.336",
4
+ "version": "5.36.0-staging.337",
5
5
  "author": {
6
6
  "name": "Muggle AI",
7
7
  "email": "support@muggle-ai.com"
@@ -4,7 +4,7 @@
4
4
  "command": "npx",
5
5
  "args": [
6
6
  "-y",
7
- "@muggleai/works@5.36.0-staging.336",
7
+ "@muggleai/works@5.36.0-staging.337",
8
8
  "serve"
9
9
  ],
10
10
  "env": {
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "muggle",
3
- "version": "5.36.0-staging.336",
3
+ "version": "5.36.0-staging.337",
4
4
  "description": "Acceptance test agent for coding agents: real-browser tests, with screenshots on the PR.",
5
5
  "author": {
6
6
  "name": "Muggle AI",
@@ -2,7 +2,7 @@
2
2
  "name": "muggle",
3
3
  "displayName": "Muggle AI",
4
4
  "description": "Acceptance test agent for coding agents: real-browser tests, with screenshots on the PR.",
5
- "version": "5.36.0-staging.336",
5
+ "version": "5.36.0-staging.337",
6
6
  "author": {
7
7
  "name": "Muggle AI",
8
8
  "email": "support@muggle-ai.com"
package/plugin/.mcp.json CHANGED
@@ -4,7 +4,7 @@
4
4
  "command": "npx",
5
5
  "args": [
6
6
  "-y",
7
- "@muggleai/works@5.36.0-staging.336",
7
+ "@muggleai/works@5.36.0-staging.337",
8
8
  "serve"
9
9
  ]
10
10
  }
@@ -52,7 +52,7 @@ Pre-filters are bash builtins only (`guardrail-lib.sh`), so an irrelevant event
52
52
  | `Stop` | `guardrail-e2e-gate.sh` | **enforce** | unit tests passed this session, no E2E ran yet, and no skip was recorded | `autoE2ETest` | **block** the turn until E2E runs via `muggle-test` or a `MUGGLE_E2E_SKIP` marker records a legitimate skip (full message once, one-line reminders after; releases after 3 blocks, leaving the PR's walkthrough comment unsettled). Quiet while a background acceptance-tester is in flight |
53
53
  | `Stop` | `guardrail-terminal-gate.sh` | **enforce** | a PR went terminal this session and the next-options offer hasn't run since — an AskUserQuestion, or, while the session owns an open PR's watch slot, a closing message that asks the user | — | **block** the turn until the post-merge handoff runs (full message once, one-line reminders after; releases after 3 blocks; nothing but the offer resets the counter) |
54
54
  | `Stop` | `guardrail-watch-gate.sh` | **enforce** | a PR opened this session that is still open and has no live watch — no session slot for it is terminal, stopped by its owner, or carries a `watch-heartbeat` touched within 15 minutes; a slot that is only seeded does not count | `autoWatchPR` | **block** the turn until the watch is armed per `muggle-pr-followup`'s `arm-watcher.md` or a `MUGGLE_WATCH_SKIP` marker records a legitimate skip (releases after 3 blocks). A PR clears once the session sees it go terminal or a provider lookup reports it merged or closed — what lets a PR whose slot post-merge cleanup deleted through. The lookup runs in a detached scan queued at turn end; a PR it has not reached yet still blocks, and one it could not reach fails open |
55
- | `Stop` | `guardrail-watch-follow-through-gate.sh` | **enforce** | a `muggle-pr-followup` watch this session owns (the slot's `owner.json`) recorded due work in `watch-due.env` — a branch behind or conflicting with its base, or a head whose checks settled red — and `last_seen.json` records no attempt for it: no `conflict_resolve_attempts` entry for the rebase key (enforced under `autoRebase=always` while catch-up budget is left), no `ci_fix_attempts` entry for the red head. An escalation entry with no attempt behind it counts for nothing, and re-arming the watch changes nothing | `autoRebase` | **block** the turn, naming each PR and its `/muggle-do rebase` or `fix ci` dispatch. No release after N blocks: only a recorded attempt, a newer head in the slot's `prs.json`, or the user's literal `HOLD WATCH #<pr-number>` clears it. The hold must come from a turn the user typed — never a tool result, a loaded skill, a hook's message, a task notification, a compaction summary, or the agent's own text — and is kept for the session once read. Reads local files only, never a provider: the pre-filter is a builtins glob for a non-empty `watch-due.env` whose `owner.json` names the session, so Node starts only when a slot has due work |
55
+ | `Stop` | `guardrail-watch-follow-through-gate.sh` | **enforce** | a `muggle-pr-followup` watch this session owns (the slot's `owner.json`) recorded due work in `watch-due.env` — a branch behind or conflicting with its base, or a head whose checks settled red — and `last_seen.json` records no attempt for it: no `conflict_resolve_attempts` entry for the rebase key (enforced under `autoRebase=always` while catch-up budget is left), no `ci_fix_attempts` entry for the red head. An escalation entry with no attempt behind it counts for nothing, and re-arming the watch changes nothing. Also fires when the slot holds a muggle watch service report the session was never woken for (`watch-service.queued.out`, or an `EVENT`/`TERMINAL` line in an exited service loop's `watch-service.out`). A PR whose `last_seen.json` sets `forward_stages_in_flight` owes nothing | `autoRebase` | **block** the turn, naming each PR and its `/muggle-do rebase` or `fix ci` dispatch, or for an undelivered report its `/muggle:muggle-pr-followup <slug> <n> --wake=follow-through` tick, which the re-arm it ends on clears. No release after N blocks: only a recorded attempt, a newer head in the slot's `prs.json`, or the user's literal `HOLD WATCH #<pr-number>` clears it. The hold must come from a turn the user typed — never a tool result, a loaded skill, a hook's message, a task notification, a compaction summary, or the agent's own text — and is kept for the session once read. Reads local files only, never a provider: the pre-filter is a builtins glob for a non-empty `watch-due.env` or an undelivered service report whose `owner.json` names the session, so Node starts only when a slot has due work |
56
56
  | `Stop` | `guardrail-walkthrough-gate.sh` | **enforce** | an E2E acceptance run happened this session and a PR in play — opened this session or on the working branch — carries no walkthrough in its body or comments, or only one under a "new E2E run in progress" banner; or an E2E skip was accepted and a PR it covers still shows the empty placeholder instead of the skip's record | `postPRVisualWalkthrough` | **block** the turn until the walkthrough is posted via `muggle-pr-visual-walkthrough` or a `MUGGLE_WALKTHROUGH_SKIP` marker records a legitimate skip. For a PR an accepted E2E skip covers, the block hands over the foreground `settle-walkthrough-skipped <pr> <session>` command, which prints `{"settled":true}` once the PR reads back the skip, and re-queues the detached write; a PR the skip does not cover is a different change and is told to run its own E2E or declare its own skip from its tree (releases after 3 blocks; an unreachable PR fails open to not-owed). A skip accepted before its PR existed is written straight into the PR's slot when it opens for the same repo and branch. The provider lookups run in a detached scan, queued when the gate arms, when a PR opens, and at each turn end; the gate decides on the last scan for the session's current PRs, begun after the last observed post, and stays open until one lands. Each PR is checked for its own walkthrough: a post to one PR settles only that one, and opening another re-arms the check. A PR whose own background run is in flight is set aside |
57
57
  | `Stop` | `guardrail-stage-gate.sh` | **enforce** | a skill invoked this session declared `mandatoryStages` and one of those files was never opened | — | **block** the turn until the stages are read or a `MUGGLE_STAGE_SKIP` marker records a legitimate skip (releases after 3 blocks) |
58
58
  | `Stop` | `guardrail-debug-path-gate.sh` | **enforce** | a local execution returned a non-passing run this session and nothing routed it through `_shared/debug-failed-run.md` | — | **block** the turn until the run is diagnosed (its `*-failure-classified` emit or feedback naming it) or a `MUGGLE_DEBUG_SKIP: <runId> <reason>` marker clears that run (releases after 3 blocks, leaving the PR's walkthrough comment unsettled). Quiet while a background acceptance-tester is in flight — its failed runs land in this session's state and it debugs them itself |
@@ -4,15 +4,18 @@ set -uo pipefail
4
4
  # watcher follow-through gate (Stop). When a muggle-pr-followup watch this
5
5
  # session owns has recorded due work — a rebase on a stale branch, a fix on a red
6
6
  # head — and no attempt for it is recorded, block the turn end and name the
7
- # dispatch. Released only by the attempt itself, a new head, or the user's own
7
+ # dispatch. A muggle watch service report the session was never woken for blocks
8
+ # the same way, naming its tick, so a busy owner still hears every slot it owns.
9
+ # Released only by the attempt itself (for a report, the re-arm its tick ends
10
+ # on), a new head, or the user's own
8
11
  # HOLD WATCH #<pr-number>: a session once sat on both for a day, re-arming its
9
12
  # watch and asking "needs input" at every wake, and every prose rule against it
10
13
  # held only as long as the session agreed with it.
11
14
  #
12
15
  # Synchronous (only a sync Stop hook can block the turn end) and fires on every
13
16
  # turn end, so the pre-filter is bash builtins only: a glob over the slots for a
14
- # non-empty watch-due.env (the watch loop empties it when nothing is due) whose
15
- # owner.json names this session. No slot has one on nearly every turn, so Node
17
+ # non-empty watch-due.env (the watch loop empties it when nothing is due) or an
18
+ # undelivered service report, whose owner.json names this session. No slot has one on nearly every turn, so Node
16
19
  # never starts. The attempt counters, preferences, and the hold are judged in
17
20
  # guardrails.mjs, from local files alone — no provider call. Degrades to {}.
18
21
 
@@ -30,11 +33,11 @@ guardrail_wants() {
30
33
  # A backslash in a glob escapes the next character, so a native Windows HOME
31
34
  # would match nothing; forward slashes name the same directory.
32
35
  local sessions_dir="${GUARDRAIL_HOME//\\//}/.muggle-ai/muggle-do/sessions"
33
- local due_file slot_dir owner_json
34
- for due_file in "$sessions_dir"/*/watch-due.env; do
35
- [[ -s $due_file ]] || continue
36
- slot_dir="${due_file%/watch-due.env}"
36
+ local slot_dir owner_json
37
+ for slot_dir in "$sessions_dir"/*/; do
38
+ slot_dir="${slot_dir%/}"
37
39
  [[ $slot_dir == *.stopped ]] && continue
40
+ guardrail_slot_has_news "$slot_dir" || continue
38
41
  [[ -f $slot_dir/owner.json ]] || continue
39
42
  owner_json=""
40
43
  IFS= read -r -d '' owner_json <"$slot_dir/owner.json" || true
@@ -43,6 +46,18 @@ guardrail_wants() {
43
46
  return 1
44
47
  }
45
48
 
49
+ # Whether a slot holds anything the gate judges: due work the watch recorded, or
50
+ # a muggle watch service report its owner was never woken for — queued while a
51
+ # fresh loop watches, or the exited service loop's own EVENT/TERMINAL line.
52
+ guardrail_slot_has_news() {
53
+ local slot_dir="$1" service_output=""
54
+ [[ -s $slot_dir/watch-due.env || -s $slot_dir/watch-service.queued.out ]] && return 0
55
+ [[ -s $slot_dir/watch-service.out ]] || return 1
56
+ IFS= read -r -d '' service_output <"$slot_dir/watch-service.out" || true
57
+ service_output=$'\n'"$service_output"
58
+ [[ $service_output == *$'\n'"EVENT "* || $service_output == *$'\n'"TERMINAL "* ]]
59
+ }
60
+
46
61
  if guardrail_is_hook_script; then
47
62
  guardrail_run_standalone "$GUARDRAIL_SUBCOMMAND"
48
63
  fi
@@ -933,6 +933,11 @@ var WATCH_DUE_FILE_NAME = "watch-due.env";
933
933
  var WATCH_DUE_HEAD_FIELD = "HEAD";
934
934
  var WATCH_DUE_REBASE_FIELD = "REBASE_DUE";
935
935
  var WATCH_DUE_CI_RED_FIELD = "CI_RED_HEAD";
936
+ var SERVICE_LOOP_OUTPUT_FILE = "watch-service.out";
937
+ var SERVICE_LOOP_QUEUED_WAKE_FILE = "watch-service.queued.out";
938
+ var SERVICE_LOOP_EVENT_LINE_PREFIX = "EVENT ";
939
+ var SERVICE_LOOP_TERMINAL_LINE_PREFIX = "TERMINAL ";
940
+ var OWNER_WAKE_LINE_PREFIXES = [SERVICE_LOOP_TERMINAL_LINE_PREFIX, SERVICE_LOOP_EVENT_LINE_PREFIX];
936
941
  var ENV_FILE_LINE = /^([A-Z_]+)="?([^"]*)"?$/;
937
942
  var USER_PREFERENCES_PATH_SEGMENTS = [".muggle-ai", "preferences.json"];
938
943
  var PREFERENCE_DEFAULTS_PATH_SEGMENTS = ["config", "preference-defaults.json"];
@@ -993,6 +998,13 @@ function parseWatchDueRecord(watchDueText) {
993
998
  };
994
999
  return dueRecord.rebaseDueKey || dueRecord.ciRedHeadSha ? dueRecord : null;
995
1000
  }
1001
+ function undeliveredWakeLineIn(slotPath) {
1002
+ for (const reportFile of [SERVICE_LOOP_QUEUED_WAKE_FILE, SERVICE_LOOP_OUTPUT_FILE]) {
1003
+ const wakeLine = readSlotText(join(slotPath, reportFile)).split(/\r?\n/).find((line) => OWNER_WAKE_LINE_PREFIXES.some((prefix) => line.startsWith(prefix)));
1004
+ if (wakeLine !== void 0) return wakeLine;
1005
+ }
1006
+ return void 0;
1007
+ }
996
1008
 
997
1009
  // src/guardrails/watchArmed.ts
998
1010
  var WATCH_SKIP_MARKER = /^\s*echo\s+["']?MUGGLE_WATCH_SKIP\b/;
@@ -1472,7 +1484,8 @@ function isDueRecordSuperseded(slotPath, slotPr, dueRecord) {
1472
1484
  function owedWorkInSlot(slotPath, slug, sessionId2, preferences) {
1473
1485
  if (slug.endsWith(STOPPED_SLOT_SUFFIX)) return [];
1474
1486
  const dueRecord = parseWatchDueRecord(readSlotText(join(slotPath, WATCH_DUE_FILE_NAME)));
1475
- if (!dueRecord) return [];
1487
+ const undeliveredWakeLine = undeliveredWakeLineIn(slotPath);
1488
+ if (!dueRecord && undeliveredWakeLine === void 0) return [];
1476
1489
  if (readJsonRecord(join(slotPath, OWNER_FILE_NAME)).session_id !== sessionId2) return [];
1477
1490
  if (existsSync(join(slotPath, RESULT_FILE_NAME))) return [];
1478
1491
  const slotPr = readSlotPr(slotPath);
@@ -1480,8 +1493,8 @@ function owedWorkInSlot(slotPath, slug, sessionId2, preferences) {
1480
1493
  const prNumber = slotPr?.number;
1481
1494
  if (!slotPr?.repo || typeof prUrl !== "string" || typeof prNumber !== "number") return [];
1482
1495
  if (TERMINAL_SLOT_PR_STATES.includes((slotPr.state ?? "").toLowerCase())) return [];
1483
- if (isDueRecordSuperseded(slotPath, slotPr, dueRecord)) return [];
1484
1496
  const lastSeenEntry = lastSeenEntryFor(readSlotText(join(slotPath, LAST_SEEN_FILE_NAME)), `${slotPr.repo}#${prNumber}`);
1497
+ if (lastSeenEntry.forward_stages_in_flight === true) return [];
1485
1498
  const workOn = (kind, dueOn) => ({
1486
1499
  kind,
1487
1500
  slug,
@@ -1490,6 +1503,8 @@ function owedWorkInSlot(slotPath, slug, sessionId2, preferences) {
1490
1503
  dueOn
1491
1504
  });
1492
1505
  const owed = [];
1506
+ if (undeliveredWakeLine !== void 0) owed.push(workOn("pending-wake" /* PendingWake */, undeliveredWakeLine));
1507
+ if (!dueRecord || isDueRecordSuperseded(slotPath, slotPr, dueRecord)) return owed;
1493
1508
  const isRebaseOwed = dueRecord.rebaseDueKey !== "" && preferences.autoRebase === ALWAYS_PREFERENCE_VALUE && !isRebaseBudgetExhausted(lastSeenEntry, preferences.maxCatchUpRebases) && !isRebaseKeyAttempted(lastSeenEntry, dueRecord.rebaseDueKey);
1494
1509
  if (isRebaseOwed) owed.push(workOn("rebase" /* Rebase */, dueRecord.rebaseDueKey));
1495
1510
  if (dueRecord.ciRedHeadSha !== "" && !isCiHeadAttempted(lastSeenEntry, dueRecord.ciRedHeadSha)) {
@@ -3461,6 +3476,9 @@ function watchGate() {
3461
3476
  }
3462
3477
  function owedWatchWorkLine(work) {
3463
3478
  const muggleDo = muggleSkill("/muggle-do");
3479
+ if (work.kind === "pending-wake" /* PendingWake */) {
3480
+ return `- PR #${work.prNumber} (${work.prUrl}): the muggle watch reported \`${work.dueOn}\` and it never reached this session: run \`${muggleSkill("/muggle:muggle-pr-followup")} ${work.slug} ${work.prNumber} --wake=follow-through\`.`;
3481
+ }
3464
3482
  if (work.kind === "rebase" /* Rebase */) {
3465
3483
  return `- PR #${work.prNumber} (${work.prUrl}) is behind or conflicting with its base (key ${work.dueOn}) and no rebase was attempted: dispatch \`${muggleDo} rebase on ${work.prUrl} slug=${work.slug}\`.`;
3466
3484
  }
@@ -3492,7 +3510,7 @@ function watchFollowThroughGate() {
3492
3510
  const holdInstruction = `Only the user can hold it: their own message containing \`${WATCH_HOLD_PHRASE_PREFIX}<pr-number>\` for that PR. Ask if you must; never decide it for them.`;
3493
3511
  const reason = decision.blockCount === 1 ? `Do not end the turn yet. A muggle-pr-followup watch this session owns found work due that nothing acted on:
3494
3512
  ${owedList}
3495
- autoRebase=always makes a due rebase binding, and how long a CI run or an eval takes is never a reason to wait. Act now: run the cycle the tick dispatches \u2014 if it finds actionable review feedback it dispatches that first. That cycle's first step records its attempt (conflict_resolve_attempts / ci_fix_attempts), which, like a new head, clears this. Writing the count without running the cycle \u2014 or for an E2E run queued for a different PR \u2014 leaves the PR red and the watch quiet. An escalation entry with no attempt behind it does not clear this, and neither does re-arming the watch. ${holdInstruction}` : `Watcher work still owed (reminder ${decision.blockCount}):
3513
+ autoRebase=always makes a due rebase binding, and how long a CI run or an eval takes is never a reason to wait. Act now: run the cycle the tick dispatches \u2014 if it finds actionable review feedback it dispatches that first. That cycle's first step records its attempt (conflict_resolve_attempts / ci_fix_attempts), which, like a new head, clears this. Writing the count without running the cycle \u2014 or for an E2E run queued for a different PR \u2014 leaves the PR red and the watch quiet. An escalation entry with no attempt behind it does not clear this, and neither does re-arming the watch. An undelivered watch report clears once the tick it names re-arms the watch from this session. ${holdInstruction}` : `Watcher work still owed (reminder ${decision.blockCount}):
3496
3514
  ${owedList}
3497
3515
  ${holdInstruction}`;
3498
3516
  return blockStop(reason, host);
@@ -23,7 +23,7 @@ set -uo pipefail
23
23
 
24
24
  script_dir="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
25
25
 
26
- slot="" repo="" pr_number="" base_branch="" exec_loop=1
26
+ slot="" repo="" pr_number="" base_branch="" owner_session="" exec_loop=1
27
27
 
28
28
  while [ $# -gt 0 ]; do
29
29
  case "$1" in
@@ -31,13 +31,14 @@ while [ $# -gt 0 ]; do
31
31
  --repo) repo="$2"; shift 2 ;;
32
32
  --pr) pr_number="$2"; shift 2 ;;
33
33
  --base) base_branch="$2"; shift 2 ;;
34
+ --owner) owner_session="$2"; shift 2 ;;
34
35
  --no-exec) exec_loop=0; shift ;;
35
36
  *) echo "pr-watch-arm: unknown argument $1" >&2; exit 2 ;;
36
37
  esac
37
38
  done
38
39
 
39
40
  if [ -z "$slot" ] || [ -z "$repo" ] || [ -z "$pr_number" ] || [ -z "$base_branch" ]; then
40
- echo "usage: pr-watch-arm.sh --slot <dir> --repo <owner/repo> --pr <n> --base <branch> [--no-exec]" >&2
41
+ echo "usage: pr-watch-arm.sh --slot <dir> --repo <owner/repo> --pr <n> --base <branch> [--owner <session-id>] [--no-exec]" >&2
41
42
  exit 2
42
43
  fi
43
44
 
@@ -199,17 +200,21 @@ fi
199
200
 
200
201
  watch_record_due_work "$slot" "$head_sha" "$recorded_rebase_due_key" "$ci_red_head"
201
202
 
202
- # Claim the slot for this session. watcher_lease_is_foreign reads an absent
203
+ # Claim the slot for its owner: the session --owner names, else this session.
204
+ # The muggle watch service arms outside every session, so it passes the owner
205
+ # the slot already records; without it every loop the service restarted left
206
+ # its slot unowned. watcher_lease_is_foreign reads an absent
203
207
  # owner.json as "not foreign", so a slot armed without one leases itself to a
204
208
  # live PID nothing can classify: once the arming session dies its watcher polls
205
209
  # into a closed pipe, and every later arm skips the slot as already owned until
206
210
  # the loop's monitor window ends it. An unset id writes nothing rather than a placeholder
207
211
  # — reconcile reads any id it does not recognise as another session's claim, and
208
212
  # a bogus one would strand the slot exactly as an absent file does.
209
- if [ -n "${CLAUDE_CODE_SESSION_ID:-}" ]; then
213
+ [ -n "$owner_session" ] || owner_session="${CLAUDE_CODE_SESSION_ID:-}"
214
+ if [ -n "$owner_session" ]; then
210
215
  claimed_at="$(date -u +%Y-%m-%dT%H:%M:%SZ)"
211
216
  printf '{\n "session_id": "%s",\n "claimed_at": "%s"\n}\n' \
212
- "$CLAUDE_CODE_SESSION_ID" "$claimed_at" > "${slot}/owner.json"
217
+ "$owner_session" "$claimed_at" > "${slot}/owner.json"
213
218
  # Register the slot with the muggle watch service, which restarts the loop
214
219
  # outside every session if it dies and wakes this owner only when that loop
215
220
  # reports on this PR. It lives in the slot, so a stop rename or a finalize
@@ -217,7 +222,7 @@ if [ -n "${CLAUDE_CODE_SESSION_ID:-}" ]; then
217
222
  printf '{\n "registered_at": "%s",\n "registered_by": "pr-watch-arm"\n}\n' \
218
223
  "$claimed_at" > "${slot}/watch-registration.json"
219
224
  else
220
- echo "pr-watch-arm: CLAUDE_CODE_SESSION_ID unset — slot left unowned, reconcile cannot re-arm it" >&2
225
+ echo "pr-watch-arm: no --owner and CLAUDE_CODE_SESSION_ID unset — slot left unowned, reconcile cannot re-arm it" >&2
221
226
  fi
222
227
 
223
228
  echo "ARMED pr=$pr_number watermark seeded at ${slot}/watch-watermark.env"
@@ -60,11 +60,12 @@ echo "$$" > "${slot}/watch.pid"
60
60
  # Who hears this loop's exit. A session hears the background command it armed;
61
61
  # a loop the muggle watch service started is heard by the service, which wakes
62
62
  # the owner session only when the loop reports. A session arming the slot takes
63
- # it back, and its own drain covers whatever an undelivered service report held.
63
+ # it back, and its own drain covers whatever an undelivered service report held,
64
+ # the ones queued while a service loop watched on included.
64
65
  if [ -n "${MUGGLE_PR_WATCH_LISTENER:-}" ]; then
65
66
  printf '%s\n' "$MUGGLE_PR_WATCH_LISTENER" > "${slot}/watch-listener"
66
67
  else
67
- rm -f "${slot}/watch-listener" "${slot}/watch-service.out"
68
+ rm -f "${slot}/watch-listener" "${slot}/watch-service.out" "${slot}/watch-service.queued.out"
68
69
  fi
69
70
  started=$(date +%s)
70
71
  fails=0
@@ -105,6 +105,7 @@ var CiRollupBucket = /* @__PURE__ */ ((CiRollupBucket2) => {
105
105
  // src/pr-watch/tickVerdict.ts
106
106
  function resolveWatchTickVerdict(lastSeenEntry, observation, preferences) {
107
107
  const { headSha, rebaseKey } = observation;
108
+ if (lastSeenEntry.forward_stages_in_flight === true) return "hold-forward-stages" /* HoldForwardStages */;
108
109
  if (observation.isRebaseDue) {
109
110
  if (isRebaseBudgetExhausted(lastSeenEntry, preferences.maxCatchUpRebases)) {
110
111
  return "block-rebase-budget-exhausted" /* BlockRebaseBudgetExhausted */;
@@ -1,6 +1,6 @@
1
1
  # Audit trail
2
2
 
3
- **Arm first.** If this cycle leaves a PR open and its watch is not armed yet, stop reading and arm it now ([`respawn-watcher.md`](respawn-watcher.md), or Stage 8 on a forward cycle). The block is written after the arm, never instead of it.
3
+ **Arm first.** If this cycle leaves a PR open and its watch is not armed yet, stop reading and arm it now ([`respawn-watcher.md`](respawn-watcher.md), or Stage 5.5 on a forward cycle, whose Stage 8 then lifts the hold). The block is written after the arm, never instead of it.
4
4
 
5
5
  What a cycle shows the user before it ends: the tests the change involved, their results, and links to the proof. It reports and gates nothing. Anything missing is stated in the block, never a reason to stop, retry, or ask.
6
6
 
@@ -1,6 +1,6 @@
1
1
  # E2E Repair Loop (Stage 7.5)
2
2
 
3
- Runs between Stage 7's posted walkthrough and Stage 8's watcher dispatch, and again whenever the watcher finds the PR's `muggle-walkthrough` check red on failed cases ([`fix-ci.md`](fix-ci.md) Step 2.5). A failing acceptance run means the change is not ready for a reviewer, so this stage root-causes every failure and either repairs it in-pipeline or puts one decision in front of the user. The watcher is armed only once this stage clears.
3
+ Runs between Stage 7's posted walkthrough and Stage 8's watcher dispatch, and again whenever the watcher finds the PR's `muggle-walkthrough` check red on failed cases ([`fix-ci.md`](fix-ci.md) Step 2.5). A failing acceptance run means the change is not ready for a reviewer, so this stage root-causes every failure and either repairs it in-pipeline or puts one decision in front of the user. The PR's watch is armed at Stage 5.5 but holds every cycle until this stage clears and Stage 8 lifts the hold.
4
4
 
5
5
  ## Turn preamble
6
6