@muggleai/works 5.24.0-staging.180 → 5.24.0-staging.182

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.
@@ -9,7 +9,7 @@
9
9
  "name": "muggleai",
10
10
  "source": "./plugin",
11
11
  "description": "Real-browser E2E acceptance for your coding agent: test the flows you changed and open the PR with screenshots. Built for flows other tools can't reach: managed test identities with live inboxes (magic links, email OTP and 2FA, verification mail, password resets), an encrypted secret store for login and test credentials, and a test graph that runs prerequisite flows first. Plain-English tests become replayable scripts on localhost or preview URLs.",
12
- "version": "5.24.0-staging.180"
12
+ "version": "5.24.0-staging.182"
13
13
  }
14
14
  ]
15
15
  }
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "muggle",
3
3
  "description": "Real-browser E2E acceptance for your coding agent: test the flows you changed and open the PR with screenshots. Built for flows other tools can't reach: managed test identities with live inboxes (magic links, email OTP and 2FA, verification mail, password resets), an encrypted secret store for login and test credentials, and a test graph that runs prerequisite flows first. Plain-English tests become replayable scripts on localhost or preview URLs.",
4
- "version": "5.24.0-staging.180",
4
+ "version": "5.24.0-staging.182",
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.24.0-staging.180",
7
+ "@muggleai/works@5.24.0-staging.182",
8
8
  "serve"
9
9
  ],
10
10
  "env": {
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "muggle",
3
- "version": "5.24.0-staging.180",
3
+ "version": "5.24.0-staging.182",
4
4
  "description": "Real-browser E2E acceptance for your coding agent: test the flows you changed and open the PR with screenshots. Built for flows other tools can't reach: managed test identities with live inboxes (magic links, email OTP and 2FA, verification mail, password resets), an encrypted secret store for login and test credentials, and a test graph that runs prerequisite flows first. Plain-English tests become replayable scripts on localhost or preview URLs.",
5
5
  "author": {
6
6
  "name": "Muggle AI",
@@ -2,7 +2,7 @@
2
2
  "name": "muggle",
3
3
  "displayName": "Muggle AI",
4
4
  "description": "Real-browser E2E acceptance for your coding agent: test the flows you changed and open the PR with screenshots. Built for flows other tools can't reach: managed test identities with live inboxes (magic links, email OTP and 2FA, verification mail, password resets), an encrypted secret store for login and test credentials, and a test graph that runs prerequisite flows first. Plain-English tests become replayable scripts on localhost or preview URLs.",
5
- "version": "5.24.0-staging.180",
5
+ "version": "5.24.0-staging.182",
6
6
  "author": {
7
7
  "name": "Muggle AI",
8
8
  "email": "support@muggle-ai.com"
@@ -4,7 +4,7 @@
4
4
  "command": "npx",
5
5
  "args": [
6
6
  "-y",
7
- "@muggleai/works@5.24.0-staging.180",
7
+ "@muggleai/works@5.24.0-staging.182",
8
8
  "serve"
9
9
  ]
10
10
  }
@@ -46,7 +46,7 @@ Pre-filters are bash builtins only (`guardrail-lib.sh`), so an irrelevant event
46
46
  | `PreToolUse` (muggle local execute/replay) | `guardrail-classify-gate.sh` | **enforce** | `muggle-test` is the skill in play and the target test case has no `pre-execution-classification` this session | — | **deny** — run Step 6f first (it calls `muggle-remote-test-script-list`, which is where the run learns the case has never passed) or record a legitimate skip via `MUGGLE_CLASSIFY_SKIP`. Scoped to `muggle-test`, so the single-target skills that legitimately skip classification are untouched; fails open when the test case can't be resolved |
47
47
  | `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) |
48
48
  | `Stop` | `guardrail-terminal-gate.sh` | **enforce** | a PR went terminal this session and the AskUserQuestion next-options offer hasn't run since | — | **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) |
49
- | `Stop` | `guardrail-watch-gate.sh` | **enforce** | a PR opened this session that no `muggle-do` session slot tracks | `autoWatchPR` | **block** the turn until a slot is seeded via `muggle-pr-followup` or a `MUGGLE_WATCH_SKIP` marker records a legitimate skip (releases after 3 blocks) |
49
+ | `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 |
50
50
  | `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 | `postPRVisualWalkthrough` | **block** the turn until the walkthrough is posted via `muggle-pr-visual-walkthrough` or a `MUGGLE_WALKTHROUGH_SKIP` marker records a legitimate skip (releases after 3 blocks; an unreachable PR fails open to not-owed). 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 and stays open until one lands |
51
51
  | `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) |
52
52
  | `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) |
@@ -1,5 +1,5 @@
1
- import { readFileSync, existsSync, mkdirSync, readdirSync, writeFileSync, renameSync, openSync, writeSync, closeSync, unlinkSync } from 'fs';
2
- import { basename, join, isAbsolute, resolve, dirname } from 'path';
1
+ import { readFileSync, existsSync, readdirSync, mkdirSync, statSync, writeFileSync, renameSync, openSync, writeSync, closeSync, unlinkSync } from 'fs';
2
+ import { join, basename, isAbsolute, resolve, dirname } from 'path';
3
3
  import { homedir, hostname } from 'os';
4
4
  import { execFileSync, spawn } from 'child_process';
5
5
  import { fileURLToPath } from 'url';
@@ -31,6 +31,9 @@ var FILE_PRINTING_PROGRAMS = [
31
31
  "type"
32
32
  ];
33
33
  var MAX_WATCH_BLOCKS = 3;
34
+ var WATCH_HEARTBEAT_STALE_MS = 15 * 6e4;
35
+ var TERMINAL_SLOT_PR_STATES = ["merged", "closed"];
36
+ var STOPPED_SLOT_SUFFIX = ".stopped";
34
37
  var MAX_BUILD_BLOCKS = 3;
35
38
  var MAX_WALKTHROUGH_BLOCKS = 3;
36
39
  var GH_LOOKUP_TIMEOUT_MS = 1e4;
@@ -138,6 +141,7 @@ function withFileLock(lockPath, waitMs, run) {
138
141
  var baseDir = (override) => override ?? join(homedir(), ".muggle-ai", "guardrails");
139
142
  var fileFor = (sessionId2, override, suffix = ".json") => join(baseDir(override), `${sessionId2.replace(/[^A-Za-z0-9_-]/g, "_")}${suffix}`);
140
143
  var WALKTHROUGH_SCAN_SUFFIX = ".walkthrough-scan.json";
144
+ var PR_STATE_SCAN_SUFFIX = ".pr-state-scan.json";
141
145
  function writeAtomically(target, contents, dirOverride) {
142
146
  mkdirSync(baseDir(dirOverride), { recursive: true });
143
147
  const staging = `${target}.${process.pid}.tmp`;
@@ -167,6 +171,17 @@ function readWalkthroughScan(sessionId2, dirOverride) {
167
171
  function writeWalkthroughScan(sessionId2, scan, dirOverride) {
168
172
  writeAtomically(fileFor(sessionId2, dirOverride, WALKTHROUGH_SCAN_SUFFIX), scan, dirOverride);
169
173
  }
174
+ function readPrStateScan(sessionId2, dirOverride) {
175
+ try {
176
+ const parsed = JSON.parse(readFileSync(fileFor(sessionId2, dirOverride, PR_STATE_SCAN_SUFFIX), "utf-8"));
177
+ return parsed?.states && typeof parsed.states === "object" ? { states: parsed.states } : null;
178
+ } catch {
179
+ return null;
180
+ }
181
+ }
182
+ function writePrStateScan(sessionId2, scan, dirOverride) {
183
+ writeAtomically(fileFor(sessionId2, dirOverride, PR_STATE_SCAN_SUFFIX), scan, dirOverride);
184
+ }
170
185
  function commitState(sessionId2, mutate, dirOverride) {
171
186
  mkdirSync(baseDir(dirOverride), { recursive: true });
172
187
  return withFileLock(`${fileFor(sessionId2, dirOverride)}.lock`, SESSION_STATE_LOCK_WAIT_MS, () => {
@@ -194,8 +209,16 @@ var GuardrailBackgroundJob = /* @__PURE__ */ ((GuardrailBackgroundJob2) => {
194
209
  GuardrailBackgroundJob2["SettleWalkthroughSkipped"] = "settle-walkthrough-skipped";
195
210
  GuardrailBackgroundJob2["SettleWalkthroughUnreasoned"] = "settle-walkthrough-unreasoned";
196
211
  GuardrailBackgroundJob2["SettleWalkthroughNoAppLogicChange"] = "settle-walkthrough-no-app-logic-change";
212
+ GuardrailBackgroundJob2["ScanWatchPrStates"] = "scan-watch-pr-states";
197
213
  return GuardrailBackgroundJob2;
198
214
  })(GuardrailBackgroundJob || {});
215
+ var ProviderPrState = /* @__PURE__ */ ((ProviderPrState2) => {
216
+ ProviderPrState2["Open"] = "OPEN";
217
+ ProviderPrState2["Merged"] = "MERGED";
218
+ ProviderPrState2["Closed"] = "CLOSED";
219
+ ProviderPrState2["Unreachable"] = "UNREACHABLE";
220
+ return ProviderPrState2;
221
+ })(ProviderPrState || {});
199
222
 
200
223
  // src/guardrails/backgroundJob.ts
201
224
  function isBackgroundJob(subcommand) {
@@ -721,6 +744,100 @@ function e2eGateDecision(state, maxBlocks = MAX_E2E_BLOCKS) {
721
744
  if (blockCount >= maxBlocks) return { action: "release" /* Release */, blockCount };
722
745
  return { action: "block" /* Block */, blockCount: blockCount + 1 };
723
746
  }
747
+
748
+ // src/hook-budget/constants.ts
749
+ var HOOK_CHILD_PROCESS_DEADLINE_MS = 600;
750
+
751
+ // src/hook-budget/childProcessBudget.ts
752
+ var childProcessDeadlineEpochMs = null;
753
+ function enforceHookChildProcessDeadline(gatesStartEpochMs = Date.now()) {
754
+ childProcessDeadlineEpochMs = gatesStartEpochMs + HOOK_CHILD_PROCESS_DEADLINE_MS;
755
+ }
756
+ function boundedChildTimeoutMs(ceilingMs) {
757
+ if (childProcessDeadlineEpochMs === null) return ceilingMs;
758
+ const remainingMs = Math.floor(childProcessDeadlineEpochMs - Date.now());
759
+ return remainingMs > 0 ? Math.min(ceilingMs, remainingMs) : null;
760
+ }
761
+
762
+ // src/pr-walkthrough/constants.ts
763
+ var REPORT_SENTINEL = "muggle-pr-section";
764
+ var WALKTHROUGH_SLOT_MARKER = "<!-- muggle-pr-walkthrough:v1 -->";
765
+ var WALKTHROUGH_SKIPPED_MARKER = "<!-- muggle-pr-walkthrough-status:skipped -->";
766
+ var WALKTHROUGH_COMMENT_HEADING = "### Muggle AI \u2014 PR visual walkthrough";
767
+ var REPORT_SENTINEL_TAG = new RegExp(`<!--\\s*${REPORT_SENTINEL}[^>]*-->\\s*`, "g");
768
+ var LAST_FULL_RUN_OPENING = "<details><summary>Last full E2E run on this PR</summary>";
769
+ var SHORT_SHA_LENGTH = 7;
770
+ var GH_COMMENT_TIMEOUT_MS = 1e4;
771
+
772
+ // src/pr-walkthrough/gh.ts
773
+ var GITHUB_PR_URL = /^https:\/\/github\.com\/([^/\s]+)\/([^/\s]+)\/pull\/(\d+)/;
774
+ var GH_CALLS_ENV = "MUGGLE_GUARDRAIL_GH_CALLS";
775
+ var defaultGhRunner = (args, input2) => {
776
+ if (process.env[GH_CALLS_ENV] === "off") return null;
777
+ const timeoutMs = boundedChildTimeoutMs(GH_COMMENT_TIMEOUT_MS);
778
+ if (timeoutMs === null) return null;
779
+ try {
780
+ return execFileSync("gh", args, {
781
+ encoding: "utf-8",
782
+ input: input2,
783
+ timeout: timeoutMs,
784
+ stdio: ["pipe", "pipe", "ignore"],
785
+ windowsHide: true
786
+ });
787
+ } catch {
788
+ return null;
789
+ }
790
+ };
791
+ function parsePrUrl(prUrl) {
792
+ const parts = prUrl.match(GITHUB_PR_URL);
793
+ if (!parts) return null;
794
+ return { repo: `${parts[1]}/${parts[2]}`, prNumber: Number(parts[3]) };
795
+ }
796
+ function listPrComments(pr, run) {
797
+ let raw;
798
+ try {
799
+ raw = run(["api", "--paginate", `repos/${pr.repo}/issues/${pr.prNumber}/comments`]);
800
+ } catch {
801
+ return null;
802
+ }
803
+ if (!raw) return null;
804
+ try {
805
+ const parsed = JSON.parse(raw);
806
+ return Array.isArray(parsed) ? parsed : null;
807
+ } catch {
808
+ return null;
809
+ }
810
+ }
811
+ function readPrHeadSha(pr, run) {
812
+ try {
813
+ return run(["api", `repos/${pr.repo}/pulls/${pr.prNumber}`, "--jq", ".head.sha"])?.trim() || null;
814
+ } catch {
815
+ return null;
816
+ }
817
+ }
818
+ function writeJson(args, payload, run) {
819
+ try {
820
+ return run(args, JSON.stringify(payload)) !== null;
821
+ } catch {
822
+ return false;
823
+ }
824
+ }
825
+ function postPrComment(pr, body, run) {
826
+ return writeJson(
827
+ ["api", "--method", "POST", `repos/${pr.repo}/issues/${pr.prNumber}/comments`, "--input", "-"],
828
+ { body },
829
+ run
830
+ );
831
+ }
832
+ function patchPrComment(pr, commentId, body, run) {
833
+ return writeJson(
834
+ ["api", "--method", "PATCH", `repos/${pr.repo}/issues/comments/${commentId}`, "--input", "-"],
835
+ { body },
836
+ run
837
+ );
838
+ }
839
+
840
+ // src/guardrails/watchArmed.ts
724
841
  var WATCH_SKIP_MARKER = /^\s*echo\s+["']?MUGGLE_WATCH_SKIP\b/;
725
842
  function isWatchSkipMarker(cmd) {
726
843
  return WATCH_SKIP_MARKER.test(cmd);
@@ -729,38 +846,101 @@ function applyWatchSkip(state, skipped) {
729
846
  if (!skipped || state.watchSkipped === true) return state;
730
847
  return { ...state, watchSkipped: true };
731
848
  }
732
- function findUntrackedHandledPrs(handledUrls, sessionsDirOverride) {
849
+ function resolveWatchSlotStatus(evidence, nowMs, staleAfterMs = WATCH_HEARTBEAT_STALE_MS) {
850
+ if (evidence.isStopped) return "stopped" /* Stopped */;
851
+ const recordedState = evidence.recordedPrState?.toLowerCase() ?? "";
852
+ if (evidence.isFinalized || TERMINAL_SLOT_PR_STATES.includes(recordedState)) {
853
+ return "terminal" /* Terminal */;
854
+ }
855
+ const heartbeatAgeMs = evidence.heartbeatMtimeMs === void 0 ? Infinity : nowMs - evidence.heartbeatMtimeMs;
856
+ return heartbeatAgeMs <= staleAfterMs ? "live" /* Live */ : "stale" /* Stale */;
857
+ }
858
+ function readHeartbeatMtimeMs(slotPath) {
859
+ try {
860
+ return statSync(join(slotPath, "watch-heartbeat")).mtimeMs;
861
+ } catch {
862
+ return void 0;
863
+ }
864
+ }
865
+ function findUnwatchedHandledPrs(handledUrls, sessionsDirOverride) {
733
866
  if (handledUrls.length === 0) return [];
734
867
  const sessionsDir = join(homedir(), ".muggle-ai", "muggle-do", "sessions");
735
- if (!existsSync(sessionsDir)) return [...handledUrls];
736
- const trackedUrls = /* @__PURE__ */ new Set();
737
- for (const slug of readdirSync(sessionsDir)) {
738
- const prsFile = join(sessionsDir, slug, "prs.json");
739
- if (!existsSync(prsFile)) continue;
740
- let slotUrl;
868
+ let slugs;
869
+ try {
870
+ slugs = readdirSync(sessionsDir);
871
+ } catch {
872
+ return [...handledUrls];
873
+ }
874
+ const nowMs = Date.now();
875
+ const watchedUrls = /* @__PURE__ */ new Set();
876
+ for (const slug of slugs) {
877
+ const slotPath = join(sessionsDir, slug);
878
+ let slotPr;
741
879
  try {
742
- const parsed = JSON.parse(readFileSync(prsFile, "utf-8"));
743
- const entry = Array.isArray(parsed) ? parsed[0] : parsed;
744
- slotUrl = entry?.url;
880
+ const parsed = JSON.parse(readFileSync(join(slotPath, "prs.json"), "utf-8"));
881
+ slotPr = Array.isArray(parsed) ? parsed[0] : parsed;
745
882
  } catch {
746
883
  continue;
747
884
  }
748
- if (slotUrl) trackedUrls.add(slotUrl);
885
+ const slotUrl = slotPr?.url;
886
+ if (typeof slotUrl !== "string" || !handledUrls.includes(slotUrl)) continue;
887
+ const evidence = {
888
+ isStopped: slug.endsWith(STOPPED_SLOT_SUFFIX),
889
+ isFinalized: existsSync(join(slotPath, "result.md")),
890
+ recordedPrState: typeof slotPr?.state === "string" ? slotPr.state : void 0,
891
+ heartbeatMtimeMs: readHeartbeatMtimeMs(slotPath)
892
+ };
893
+ if (resolveWatchSlotStatus(evidence, nowMs) !== "stale" /* Stale */) watchedUrls.add(slotUrl);
894
+ }
895
+ return handledUrls.filter((url) => !watchedUrls.has(url));
896
+ }
897
+ function isTerminalThisSession(prUrl, state) {
898
+ const prNumber = parsePrUrl(prUrl)?.prNumber;
899
+ if (prNumber === void 0) return false;
900
+ return (state.terminalPending ?? []).includes(prNumber) || (state.terminalHandled ?? []).includes(prNumber);
901
+ }
902
+ function isEndState(providerState) {
903
+ return providerState === "MERGED" /* Merged */ || providerState === "CLOSED" /* Closed */;
904
+ }
905
+ function resolveOwedWatchPrs(unwatchedUrls, state, scan) {
906
+ return unwatchedUrls.filter((prUrl) => {
907
+ if (isTerminalThisSession(prUrl, state)) return false;
908
+ const providerState = scan?.states[prUrl];
909
+ return providerState === void 0 || providerState === "OPEN" /* Open */;
910
+ });
911
+ }
912
+ function prsAwaitingStateScan(unwatchedUrls, state, scan) {
913
+ return unwatchedUrls.filter(
914
+ (prUrl) => !isTerminalThisSession(prUrl, state) && !isEndState(scan?.states[prUrl])
915
+ );
916
+ }
917
+ function lookupProviderPrState(prUrl, run = defaultGhRunner) {
918
+ if (!parsePrUrl(prUrl)) return null;
919
+ const reportedState = run(["pr", "view", prUrl, "--json", "state", "-q", ".state"])?.trim();
920
+ return Object.values(ProviderPrState).find(
921
+ (providerState) => providerState === reportedState && providerState !== "UNREACHABLE" /* Unreachable */
922
+ ) ?? "UNREACHABLE" /* Unreachable */;
923
+ }
924
+ function scanProviderPrStates(prUrls, lookup = lookupProviderPrState) {
925
+ const states = {};
926
+ for (const prUrl of prUrls) {
927
+ const providerState = lookup(prUrl);
928
+ if (providerState !== null) states[prUrl] = providerState;
749
929
  }
750
- return handledUrls.filter((url) => !trackedUrls.has(url));
930
+ return { states };
751
931
  }
752
- function watchGateDecision(state, untrackedPrUrls, maxBlocks = MAX_WATCH_BLOCKS) {
932
+ function watchGateDecision(state, unwatchedPrUrls, maxBlocks = MAX_WATCH_BLOCKS) {
753
933
  const blockCount = state.watchBlockCount ?? 0;
754
- if (state.watchSkipped === true || untrackedPrUrls.length === 0) {
755
- return { action: "none" /* None */, blockCount, untracked: untrackedPrUrls };
934
+ if (state.watchSkipped === true || unwatchedPrUrls.length === 0) {
935
+ return { action: "none" /* None */, blockCount, unwatched: unwatchedPrUrls };
756
936
  }
757
937
  if (blockCount >= maxBlocks) {
758
- return { action: "release" /* Release */, blockCount, untracked: untrackedPrUrls };
938
+ return { action: "release" /* Release */, blockCount, unwatched: unwatchedPrUrls };
759
939
  }
760
940
  return {
761
941
  action: "block" /* Block */,
762
942
  blockCount: blockCount + 1,
763
- untracked: untrackedPrUrls
943
+ unwatched: unwatchedPrUrls
764
944
  };
765
945
  }
766
946
 
@@ -782,18 +962,6 @@ function buildFollowthroughDecision(state, maxBlocks = MAX_BUILD_BLOCKS) {
782
962
  }
783
963
  return { action: "block" /* Block */, blockCount: blockCount + 1 };
784
964
  }
785
-
786
- // src/pr-walkthrough/constants.ts
787
- var REPORT_SENTINEL = "muggle-pr-section";
788
- var WALKTHROUGH_SLOT_MARKER = "<!-- muggle-pr-walkthrough:v1 -->";
789
- var WALKTHROUGH_SKIPPED_MARKER = "<!-- muggle-pr-walkthrough-status:skipped -->";
790
- var WALKTHROUGH_COMMENT_HEADING = "### Muggle AI \u2014 PR visual walkthrough";
791
- var REPORT_SENTINEL_TAG = new RegExp(`<!--\\s*${REPORT_SENTINEL}[^>]*-->\\s*`, "g");
792
- var LAST_FULL_RUN_OPENING = "<details><summary>Last full E2E run on this PR</summary>";
793
- var SHORT_SHA_LENGTH = 7;
794
- var GH_COMMENT_TIMEOUT_MS = 1e4;
795
-
796
- // src/guardrails/prReportPost.ts
797
965
  var PR_PROSE_CMD = /\bgh\s+pr\s+(comment|create|edit)\b/;
798
966
  var GH_API_CMD = /\bgh\s+api\b/;
799
967
  var ISSUE_COMMENT_PATH = /\bissues\/comments\/\d+/;
@@ -856,22 +1024,6 @@ function applyWalkthroughSkip(state, skipped) {
856
1024
  if (!skipped || state.walkthroughSkipped === true) return state;
857
1025
  return { ...state, walkthroughSkipped: true };
858
1026
  }
859
-
860
- // src/hook-budget/constants.ts
861
- var HOOK_CHILD_PROCESS_DEADLINE_MS = 600;
862
-
863
- // src/hook-budget/childProcessBudget.ts
864
- var childProcessDeadlineEpochMs = null;
865
- function enforceHookChildProcessDeadline(gatesStartEpochMs = Date.now()) {
866
- childProcessDeadlineEpochMs = gatesStartEpochMs + HOOK_CHILD_PROCESS_DEADLINE_MS;
867
- }
868
- function boundedChildTimeoutMs(ceilingMs) {
869
- if (childProcessDeadlineEpochMs === null) return ceilingMs;
870
- const remainingMs = Math.floor(childProcessDeadlineEpochMs - Date.now());
871
- return remainingMs > 0 ? Math.min(ceilingMs, remainingMs) : null;
872
- }
873
-
874
- // src/guardrails/walkthroughOwed.ts
875
1027
  function runGh(args) {
876
1028
  const timeoutMs = boundedChildTimeoutMs(GH_LOOKUP_TIMEOUT_MS);
877
1029
  if (timeoutMs === null) return null;
@@ -1072,72 +1224,6 @@ function classifyComment(body) {
1072
1224
  if (body.includes(WALKTHROUGH_SKIPPED_MARKER)) return "skipped" /* Skipped */;
1073
1225
  return "pending" /* Pending */;
1074
1226
  }
1075
- var GITHUB_PR_URL = /^https:\/\/github\.com\/([^/\s]+)\/([^/\s]+)\/pull\/(\d+)/;
1076
- var GH_CALLS_ENV = "MUGGLE_GUARDRAIL_GH_CALLS";
1077
- var defaultGhRunner = (args, input2) => {
1078
- if (process.env[GH_CALLS_ENV] === "off") return null;
1079
- const timeoutMs = boundedChildTimeoutMs(GH_COMMENT_TIMEOUT_MS);
1080
- if (timeoutMs === null) return null;
1081
- try {
1082
- return execFileSync("gh", args, {
1083
- encoding: "utf-8",
1084
- input: input2,
1085
- timeout: timeoutMs,
1086
- stdio: ["pipe", "pipe", "ignore"],
1087
- windowsHide: true
1088
- });
1089
- } catch {
1090
- return null;
1091
- }
1092
- };
1093
- function parsePrUrl(prUrl) {
1094
- const parts = prUrl.match(GITHUB_PR_URL);
1095
- if (!parts) return null;
1096
- return { repo: `${parts[1]}/${parts[2]}`, prNumber: Number(parts[3]) };
1097
- }
1098
- function listPrComments(pr, run) {
1099
- let raw;
1100
- try {
1101
- raw = run(["api", "--paginate", `repos/${pr.repo}/issues/${pr.prNumber}/comments`]);
1102
- } catch {
1103
- return null;
1104
- }
1105
- if (!raw) return null;
1106
- try {
1107
- const parsed = JSON.parse(raw);
1108
- return Array.isArray(parsed) ? parsed : null;
1109
- } catch {
1110
- return null;
1111
- }
1112
- }
1113
- function readPrHeadSha(pr, run) {
1114
- try {
1115
- return run(["api", `repos/${pr.repo}/pulls/${pr.prNumber}`, "--jq", ".head.sha"])?.trim() || null;
1116
- } catch {
1117
- return null;
1118
- }
1119
- }
1120
- function writeJson(args, payload, run) {
1121
- try {
1122
- return run(args, JSON.stringify(payload)) !== null;
1123
- } catch {
1124
- return false;
1125
- }
1126
- }
1127
- function postPrComment(pr, body, run) {
1128
- return writeJson(
1129
- ["api", "--method", "POST", `repos/${pr.repo}/issues/${pr.prNumber}/comments`, "--input", "-"],
1130
- { body },
1131
- run
1132
- );
1133
- }
1134
- function patchPrComment(pr, commentId, body, run) {
1135
- return writeJson(
1136
- ["api", "--method", "PATCH", `repos/${pr.repo}/issues/comments/${commentId}`, "--input", "-"],
1137
- { body },
1138
- run
1139
- );
1140
- }
1141
1227
 
1142
1228
  // src/pr-walkthrough/reserve.ts
1143
1229
  function commentWithStatus(comments, status) {
@@ -1993,14 +2079,20 @@ function e2eGate() {
1993
2079
  }
1994
2080
  function watchGate() {
1995
2081
  const state = readState(sessionId);
1996
- const untrackedPrUrls = findUntrackedHandledPrs(state.prsHandled);
1997
- const decision = watchGateDecision(state, untrackedPrUrls);
2082
+ const unwatchedPrUrls = findUnwatchedHandledPrs(state.prsHandled);
2083
+ const prStateScan = readPrStateScan(sessionId);
2084
+ if (state.watchSkipped !== true && prsAwaitingStateScan(unwatchedPrUrls, state, prStateScan).length > 0) {
2085
+ startBackgroundJob("scan-watch-pr-states" /* ScanWatchPrStates */, [sessionId]);
2086
+ }
2087
+ const decision = watchGateDecision(state, resolveOwedWatchPrs(unwatchedPrUrls, state, prStateScan));
1998
2088
  if (decision.action === "release" /* Release */) return releaseGate("watchReleased");
1999
2089
  if (decision.action === "none" /* None */) return "{}";
2000
2090
  state.watchBlockCount = decision.blockCount;
2001
2091
  writeState(state);
2002
- const prList = decision.untracked.join(", ");
2003
- const reason = decision.blockCount === 1 ? `Do not end the turn yet. A PR was opened this session but no muggle-do session slot tracks it: ${prList}. Seed the slot and hand off per muggle-do Stage 8 \u2014 ${muggleSkill("/muggle:muggle-pr-followup")} ${decision.untracked[0]} does both. Seeding is what matters: once a slot exists, reconcile arms it at the next session start and finalizes it when the PR goes terminal, so an unarmed slot is fine but no slot means nothing ever picks this PR up. If it genuinely should not be tracked (autoWatchPR=never, handed off elsewhere), tell the user why and run \`echo "MUGGLE_WATCH_SKIP: <reason>"\` \u2014 that records the skip and keeps this gate quiet for the rest of the session.` : `PR hand-off still owed for ${prList} (reminder ${decision.blockCount}/${MAX_WATCH_BLOCKS}): seed a slot via ${muggleSkill("/muggle:muggle-pr-followup")}, or record a legitimate skip via \`echo "MUGGLE_WATCH_SKIP: <reason>"\`.`;
2092
+ const prList = decision.unwatched.join(", ");
2093
+ const staleMinutes = WATCH_HEARTBEAT_STALE_MS / 6e4;
2094
+ const armCommand = `${muggleSkill("/muggle:muggle-pr-followup")} ${decision.unwatched[0]}`;
2095
+ const reason = decision.blockCount === 1 ? `Do not end the turn yet. A PR opened this session is open with no live muggle-pr-followup watch: ${prList}. Arm its watch per the muggle-pr-followup arming procedure (arm-watcher.md) \u2014 invoking ${armCommand} bootstraps it and arms it that way (add --resume when its slot already exists). A seeded slot does not count: only a running watch loop does, shown by a watch-heartbeat it touches every poll and that goes stale after ${staleMinutes} minutes (a watch armed moments ago writes it on its first poll). If the PR already merged or closed, end the turn again \u2014 a provider check started now clears it. If it genuinely should not be watched (autoWatchPR=never, handed off elsewhere), tell the user why and run \`echo "MUGGLE_WATCH_SKIP: <reason>"\` \u2014 that records the skip and keeps this gate quiet for the rest of the session.` : `PR watch still owed for ${prList} (reminder ${decision.blockCount}/${MAX_WATCH_BLOCKS}): arm it per arm-watcher.md via ${armCommand} (--resume when its slot exists), or record a legitimate skip via \`echo "MUGGLE_WATCH_SKIP: <reason>"\`.`;
2004
2096
  return blockStop(reason, host);
2005
2097
  }
2006
2098
  function buildFollowthroughGate() {
@@ -2199,12 +2291,23 @@ function settleWalkthroughNoAppLogicChangeJob() {
2199
2291
  if (prUrl && detail) settleWalkthroughCommentForNoAppLogicChange(prUrl, detail);
2200
2292
  return "{}";
2201
2293
  }
2294
+ function scanWatchPrStatesJob() {
2295
+ const scannedSessionId = jobArgs[0] ?? "unknown";
2296
+ const state = readState(scannedSessionId);
2297
+ const previousScan = readPrStateScan(scannedSessionId);
2298
+ const awaitingPrUrls = prsAwaitingStateScan(findUnwatchedHandledPrs(state.prsHandled), state, previousScan);
2299
+ if (awaitingPrUrls.length === 0) return "{}";
2300
+ const freshScan = scanProviderPrStates(awaitingPrUrls);
2301
+ writePrStateScan(scannedSessionId, { states: { ...previousScan?.states, ...freshScan.states } });
2302
+ return "{}";
2303
+ }
2202
2304
  var backgroundJobs = {
2203
2305
  ["scan-walkthroughs" /* ScanWalkthroughs */]: scanWalkthroughsJob,
2204
2306
  ["reserve-walkthrough-comment" /* ReserveWalkthroughComment */]: reserveWalkthroughCommentJob,
2205
2307
  ["settle-walkthrough-skipped" /* SettleWalkthroughSkipped */]: settleWalkthroughSkippedJob,
2206
2308
  ["settle-walkthrough-unreasoned" /* SettleWalkthroughUnreasoned */]: settleWalkthroughUnreasonedJob,
2207
- ["settle-walkthrough-no-app-logic-change" /* SettleWalkthroughNoAppLogicChange */]: settleWalkthroughNoAppLogicChangeJob
2309
+ ["settle-walkthrough-no-app-logic-change" /* SettleWalkthroughNoAppLogicChange */]: settleWalkthroughNoAppLogicChangeJob,
2310
+ ["scan-watch-pr-states" /* ScanWatchPrStates */]: scanWatchPrStatesJob
2208
2311
  };
2209
2312
  var runSubcommand = isBackgroundJob(sub) ? backgroundJobs[sub] : handlers[sub] ?? (() => "{}");
2210
2313
  process.stdout.write(runSubcommand());
@@ -1,6 +1,6 @@
1
1
  # Open PR — forward mode
2
2
 
3
- Forward pipeline's Stage 7. Invoked by `/muggle-do` after stages 1–6 of a fresh feature. Opens the change — a PR on GitHub (`gh pr create`) or an MR on GitLab (`glab mr create`), provider resolved in Step 5 — then seeds session state and dispatches the first watcher.
3
+ Forward pipeline's Stage 7. Invoked by `/muggle-do` after stages 1–6 of a fresh feature. Opens the change — a PR on GitHub (`gh pr create`) or an MR on GitLab (`glab mr create`), provider resolved in Step 5 — then seeds session state and arms the first watch.
4
4
 
5
5
  ## Turn preamble
6
6
 
@@ -57,7 +57,7 @@ The E2E repair loop ([`../e2e-repair.md`](../e2e-repair.md)) runs once this stag
57
57
 
58
58
  ## Stage 8 handoff
59
59
 
60
- After every repo is processed and Stage 7.5 has cleared, build the watcher manifest and dispatch one watcher loop per opened PR. The dispatches are the LAST action this stage takes.
60
+ 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.
61
61
 
62
62
  Write `~/.muggle-ai/muggle-do/sessions/<slug>/prs.json` per [`../../muggle-pr-followup/state-schemas.md`](../../muggle-pr-followup/state-schemas.md#prsjson):
63
63
 
@@ -69,16 +69,13 @@ Seed `~/.muggle-ai/muggle-do/sessions/<slug>/last_seen.json` per [`../../muggle-
69
69
 
70
70
  **Do not** seed `cycle.json` or `requirements.md`. The watcher is a dumb pipe; `/muggle-do` reads reviews off GitHub.
71
71
 
72
- For each entry in `prs.json`, dispatch its watcher:
73
- ```
74
- /loop 1m /muggle:muggle-pr-followup <slug> <pr-number>
75
- ```
72
+ 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.
76
73
 
77
- If `prs.json` is empty, **do not dispatch** — record the reason in `result.md` and exit.
74
+ If `prs.json` is empty, **do not arm** — record the reason in `result.md` and exit.
78
75
 
79
76
  ## Invariants
80
77
 
81
- - Branch synced with its base before the push, never after; PR creation per non-skipped repo; 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 the dispatch; `/loop` dispatch is the last action.
78
+ - Branch synced with its base before the push, never after; PR creation per non-skipped repo; 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.
82
79
 
83
80
  ## Output
84
81
 
@@ -87,7 +84,7 @@ If `prs.json` is empty, **do not dispatch** — record the reason in `result.md`
87
84
  **Skipped:** repo → reason (when `autoCreatePR` short-circuited)
88
85
  **Overflow comments posted:** repo → PR #
89
86
  **Stage 7.5:** `green` | `waived — <reason>` | `iteration-cap`
90
- **Stage 8:** `Watching <N> PR(s) — one /loop 1m /muggle:muggle-pr-followup <slug> <pr#> per PR` | `No PRs to watch — stage 8 not dispatched`
87
+ **Stage 8:** `Watching <N> PR(s) — one monitor per PR, armed per arm-watcher.md` | `No PRs to watch — stage 8 not armed`
91
88
  **Errors:** repo → message
92
89
 
93
90
  ## Post-merge cleanup
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "release": "5.18.0",
3
- "buildId": "run-180-1",
4
- "commitSha": "ca07aa7cd59ad821268e29071be6cff177a23ce5",
5
- "buildTime": "2026-10-23T06:10:12Z",
3
+ "buildId": "run-182-1",
4
+ "commitSha": "b07a9bb4f2f438ccb0fffc84977117ff472dbb7e",
5
+ "buildTime": "2026-10-23T17:25:02Z",
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/muggle",
4
- "version": "5.24.0-staging.180",
4
+ "version": "5.24.0-staging.182",
5
5
  "description": "13 years of Microsoft hyperscale engineering, packaged as a harness for your AI coding agent.",
6
6
  "type": "module",
7
7
  "main": "dist/index.js",
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "muggle",
3
3
  "description": "Real-browser E2E acceptance for your coding agent: test the flows you changed and open the PR with screenshots. Built for flows other tools can't reach: managed test identities with live inboxes (magic links, email OTP and 2FA, verification mail, password resets), an encrypted secret store for login and test credentials, and a test graph that runs prerequisite flows first. Plain-English tests become replayable scripts on localhost or preview URLs.",
4
- "version": "5.24.0-staging.180",
4
+ "version": "5.24.0-staging.182",
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.24.0-staging.180",
7
+ "@muggleai/works@5.24.0-staging.182",
8
8
  "serve"
9
9
  ],
10
10
  "env": {
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "muggle",
3
- "version": "5.24.0-staging.180",
3
+ "version": "5.24.0-staging.182",
4
4
  "description": "Real-browser E2E acceptance for your coding agent: test the flows you changed and open the PR with screenshots. Built for flows other tools can't reach: managed test identities with live inboxes (magic links, email OTP and 2FA, verification mail, password resets), an encrypted secret store for login and test credentials, and a test graph that runs prerequisite flows first. Plain-English tests become replayable scripts on localhost or preview URLs.",
5
5
  "author": {
6
6
  "name": "Muggle AI",
@@ -2,7 +2,7 @@
2
2
  "name": "muggle",
3
3
  "displayName": "Muggle AI",
4
4
  "description": "Real-browser E2E acceptance for your coding agent: test the flows you changed and open the PR with screenshots. Built for flows other tools can't reach: managed test identities with live inboxes (magic links, email OTP and 2FA, verification mail, password resets), an encrypted secret store for login and test credentials, and a test graph that runs prerequisite flows first. Plain-English tests become replayable scripts on localhost or preview URLs.",
5
- "version": "5.24.0-staging.180",
5
+ "version": "5.24.0-staging.182",
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.24.0-staging.180",
7
+ "@muggleai/works@5.24.0-staging.182",
8
8
  "serve"
9
9
  ]
10
10
  }
@@ -46,7 +46,7 @@ Pre-filters are bash builtins only (`guardrail-lib.sh`), so an irrelevant event
46
46
  | `PreToolUse` (muggle local execute/replay) | `guardrail-classify-gate.sh` | **enforce** | `muggle-test` is the skill in play and the target test case has no `pre-execution-classification` this session | — | **deny** — run Step 6f first (it calls `muggle-remote-test-script-list`, which is where the run learns the case has never passed) or record a legitimate skip via `MUGGLE_CLASSIFY_SKIP`. Scoped to `muggle-test`, so the single-target skills that legitimately skip classification are untouched; fails open when the test case can't be resolved |
47
47
  | `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) |
48
48
  | `Stop` | `guardrail-terminal-gate.sh` | **enforce** | a PR went terminal this session and the AskUserQuestion next-options offer hasn't run since | — | **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) |
49
- | `Stop` | `guardrail-watch-gate.sh` | **enforce** | a PR opened this session that no `muggle-do` session slot tracks | `autoWatchPR` | **block** the turn until a slot is seeded via `muggle-pr-followup` or a `MUGGLE_WATCH_SKIP` marker records a legitimate skip (releases after 3 blocks) |
49
+ | `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 |
50
50
  | `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 | `postPRVisualWalkthrough` | **block** the turn until the walkthrough is posted via `muggle-pr-visual-walkthrough` or a `MUGGLE_WALKTHROUGH_SKIP` marker records a legitimate skip (releases after 3 blocks; an unreachable PR fails open to not-owed). 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 and stays open until one lands |
51
51
  | `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) |
52
52
  | `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) |
@@ -1,5 +1,5 @@
1
- import { readFileSync, existsSync, mkdirSync, readdirSync, writeFileSync, renameSync, openSync, writeSync, closeSync, unlinkSync } from 'fs';
2
- import { basename, join, isAbsolute, resolve, dirname } from 'path';
1
+ import { readFileSync, existsSync, readdirSync, mkdirSync, statSync, writeFileSync, renameSync, openSync, writeSync, closeSync, unlinkSync } from 'fs';
2
+ import { join, basename, isAbsolute, resolve, dirname } from 'path';
3
3
  import { homedir, hostname } from 'os';
4
4
  import { execFileSync, spawn } from 'child_process';
5
5
  import { fileURLToPath } from 'url';
@@ -31,6 +31,9 @@ var FILE_PRINTING_PROGRAMS = [
31
31
  "type"
32
32
  ];
33
33
  var MAX_WATCH_BLOCKS = 3;
34
+ var WATCH_HEARTBEAT_STALE_MS = 15 * 6e4;
35
+ var TERMINAL_SLOT_PR_STATES = ["merged", "closed"];
36
+ var STOPPED_SLOT_SUFFIX = ".stopped";
34
37
  var MAX_BUILD_BLOCKS = 3;
35
38
  var MAX_WALKTHROUGH_BLOCKS = 3;
36
39
  var GH_LOOKUP_TIMEOUT_MS = 1e4;
@@ -138,6 +141,7 @@ function withFileLock(lockPath, waitMs, run) {
138
141
  var baseDir = (override) => override ?? join(homedir(), ".muggle-ai", "guardrails");
139
142
  var fileFor = (sessionId2, override, suffix = ".json") => join(baseDir(override), `${sessionId2.replace(/[^A-Za-z0-9_-]/g, "_")}${suffix}`);
140
143
  var WALKTHROUGH_SCAN_SUFFIX = ".walkthrough-scan.json";
144
+ var PR_STATE_SCAN_SUFFIX = ".pr-state-scan.json";
141
145
  function writeAtomically(target, contents, dirOverride) {
142
146
  mkdirSync(baseDir(dirOverride), { recursive: true });
143
147
  const staging = `${target}.${process.pid}.tmp`;
@@ -167,6 +171,17 @@ function readWalkthroughScan(sessionId2, dirOverride) {
167
171
  function writeWalkthroughScan(sessionId2, scan, dirOverride) {
168
172
  writeAtomically(fileFor(sessionId2, dirOverride, WALKTHROUGH_SCAN_SUFFIX), scan, dirOverride);
169
173
  }
174
+ function readPrStateScan(sessionId2, dirOverride) {
175
+ try {
176
+ const parsed = JSON.parse(readFileSync(fileFor(sessionId2, dirOverride, PR_STATE_SCAN_SUFFIX), "utf-8"));
177
+ return parsed?.states && typeof parsed.states === "object" ? { states: parsed.states } : null;
178
+ } catch {
179
+ return null;
180
+ }
181
+ }
182
+ function writePrStateScan(sessionId2, scan, dirOverride) {
183
+ writeAtomically(fileFor(sessionId2, dirOverride, PR_STATE_SCAN_SUFFIX), scan, dirOverride);
184
+ }
170
185
  function commitState(sessionId2, mutate, dirOverride) {
171
186
  mkdirSync(baseDir(dirOverride), { recursive: true });
172
187
  return withFileLock(`${fileFor(sessionId2, dirOverride)}.lock`, SESSION_STATE_LOCK_WAIT_MS, () => {
@@ -194,8 +209,16 @@ var GuardrailBackgroundJob = /* @__PURE__ */ ((GuardrailBackgroundJob2) => {
194
209
  GuardrailBackgroundJob2["SettleWalkthroughSkipped"] = "settle-walkthrough-skipped";
195
210
  GuardrailBackgroundJob2["SettleWalkthroughUnreasoned"] = "settle-walkthrough-unreasoned";
196
211
  GuardrailBackgroundJob2["SettleWalkthroughNoAppLogicChange"] = "settle-walkthrough-no-app-logic-change";
212
+ GuardrailBackgroundJob2["ScanWatchPrStates"] = "scan-watch-pr-states";
197
213
  return GuardrailBackgroundJob2;
198
214
  })(GuardrailBackgroundJob || {});
215
+ var ProviderPrState = /* @__PURE__ */ ((ProviderPrState2) => {
216
+ ProviderPrState2["Open"] = "OPEN";
217
+ ProviderPrState2["Merged"] = "MERGED";
218
+ ProviderPrState2["Closed"] = "CLOSED";
219
+ ProviderPrState2["Unreachable"] = "UNREACHABLE";
220
+ return ProviderPrState2;
221
+ })(ProviderPrState || {});
199
222
 
200
223
  // src/guardrails/backgroundJob.ts
201
224
  function isBackgroundJob(subcommand) {
@@ -721,6 +744,100 @@ function e2eGateDecision(state, maxBlocks = MAX_E2E_BLOCKS) {
721
744
  if (blockCount >= maxBlocks) return { action: "release" /* Release */, blockCount };
722
745
  return { action: "block" /* Block */, blockCount: blockCount + 1 };
723
746
  }
747
+
748
+ // src/hook-budget/constants.ts
749
+ var HOOK_CHILD_PROCESS_DEADLINE_MS = 600;
750
+
751
+ // src/hook-budget/childProcessBudget.ts
752
+ var childProcessDeadlineEpochMs = null;
753
+ function enforceHookChildProcessDeadline(gatesStartEpochMs = Date.now()) {
754
+ childProcessDeadlineEpochMs = gatesStartEpochMs + HOOK_CHILD_PROCESS_DEADLINE_MS;
755
+ }
756
+ function boundedChildTimeoutMs(ceilingMs) {
757
+ if (childProcessDeadlineEpochMs === null) return ceilingMs;
758
+ const remainingMs = Math.floor(childProcessDeadlineEpochMs - Date.now());
759
+ return remainingMs > 0 ? Math.min(ceilingMs, remainingMs) : null;
760
+ }
761
+
762
+ // src/pr-walkthrough/constants.ts
763
+ var REPORT_SENTINEL = "muggle-pr-section";
764
+ var WALKTHROUGH_SLOT_MARKER = "<!-- muggle-pr-walkthrough:v1 -->";
765
+ var WALKTHROUGH_SKIPPED_MARKER = "<!-- muggle-pr-walkthrough-status:skipped -->";
766
+ var WALKTHROUGH_COMMENT_HEADING = "### Muggle AI \u2014 PR visual walkthrough";
767
+ var REPORT_SENTINEL_TAG = new RegExp(`<!--\\s*${REPORT_SENTINEL}[^>]*-->\\s*`, "g");
768
+ var LAST_FULL_RUN_OPENING = "<details><summary>Last full E2E run on this PR</summary>";
769
+ var SHORT_SHA_LENGTH = 7;
770
+ var GH_COMMENT_TIMEOUT_MS = 1e4;
771
+
772
+ // src/pr-walkthrough/gh.ts
773
+ var GITHUB_PR_URL = /^https:\/\/github\.com\/([^/\s]+)\/([^/\s]+)\/pull\/(\d+)/;
774
+ var GH_CALLS_ENV = "MUGGLE_GUARDRAIL_GH_CALLS";
775
+ var defaultGhRunner = (args, input2) => {
776
+ if (process.env[GH_CALLS_ENV] === "off") return null;
777
+ const timeoutMs = boundedChildTimeoutMs(GH_COMMENT_TIMEOUT_MS);
778
+ if (timeoutMs === null) return null;
779
+ try {
780
+ return execFileSync("gh", args, {
781
+ encoding: "utf-8",
782
+ input: input2,
783
+ timeout: timeoutMs,
784
+ stdio: ["pipe", "pipe", "ignore"],
785
+ windowsHide: true
786
+ });
787
+ } catch {
788
+ return null;
789
+ }
790
+ };
791
+ function parsePrUrl(prUrl) {
792
+ const parts = prUrl.match(GITHUB_PR_URL);
793
+ if (!parts) return null;
794
+ return { repo: `${parts[1]}/${parts[2]}`, prNumber: Number(parts[3]) };
795
+ }
796
+ function listPrComments(pr, run) {
797
+ let raw;
798
+ try {
799
+ raw = run(["api", "--paginate", `repos/${pr.repo}/issues/${pr.prNumber}/comments`]);
800
+ } catch {
801
+ return null;
802
+ }
803
+ if (!raw) return null;
804
+ try {
805
+ const parsed = JSON.parse(raw);
806
+ return Array.isArray(parsed) ? parsed : null;
807
+ } catch {
808
+ return null;
809
+ }
810
+ }
811
+ function readPrHeadSha(pr, run) {
812
+ try {
813
+ return run(["api", `repos/${pr.repo}/pulls/${pr.prNumber}`, "--jq", ".head.sha"])?.trim() || null;
814
+ } catch {
815
+ return null;
816
+ }
817
+ }
818
+ function writeJson(args, payload, run) {
819
+ try {
820
+ return run(args, JSON.stringify(payload)) !== null;
821
+ } catch {
822
+ return false;
823
+ }
824
+ }
825
+ function postPrComment(pr, body, run) {
826
+ return writeJson(
827
+ ["api", "--method", "POST", `repos/${pr.repo}/issues/${pr.prNumber}/comments`, "--input", "-"],
828
+ { body },
829
+ run
830
+ );
831
+ }
832
+ function patchPrComment(pr, commentId, body, run) {
833
+ return writeJson(
834
+ ["api", "--method", "PATCH", `repos/${pr.repo}/issues/comments/${commentId}`, "--input", "-"],
835
+ { body },
836
+ run
837
+ );
838
+ }
839
+
840
+ // src/guardrails/watchArmed.ts
724
841
  var WATCH_SKIP_MARKER = /^\s*echo\s+["']?MUGGLE_WATCH_SKIP\b/;
725
842
  function isWatchSkipMarker(cmd) {
726
843
  return WATCH_SKIP_MARKER.test(cmd);
@@ -729,38 +846,101 @@ function applyWatchSkip(state, skipped) {
729
846
  if (!skipped || state.watchSkipped === true) return state;
730
847
  return { ...state, watchSkipped: true };
731
848
  }
732
- function findUntrackedHandledPrs(handledUrls, sessionsDirOverride) {
849
+ function resolveWatchSlotStatus(evidence, nowMs, staleAfterMs = WATCH_HEARTBEAT_STALE_MS) {
850
+ if (evidence.isStopped) return "stopped" /* Stopped */;
851
+ const recordedState = evidence.recordedPrState?.toLowerCase() ?? "";
852
+ if (evidence.isFinalized || TERMINAL_SLOT_PR_STATES.includes(recordedState)) {
853
+ return "terminal" /* Terminal */;
854
+ }
855
+ const heartbeatAgeMs = evidence.heartbeatMtimeMs === void 0 ? Infinity : nowMs - evidence.heartbeatMtimeMs;
856
+ return heartbeatAgeMs <= staleAfterMs ? "live" /* Live */ : "stale" /* Stale */;
857
+ }
858
+ function readHeartbeatMtimeMs(slotPath) {
859
+ try {
860
+ return statSync(join(slotPath, "watch-heartbeat")).mtimeMs;
861
+ } catch {
862
+ return void 0;
863
+ }
864
+ }
865
+ function findUnwatchedHandledPrs(handledUrls, sessionsDirOverride) {
733
866
  if (handledUrls.length === 0) return [];
734
867
  const sessionsDir = join(homedir(), ".muggle-ai", "muggle-do", "sessions");
735
- if (!existsSync(sessionsDir)) return [...handledUrls];
736
- const trackedUrls = /* @__PURE__ */ new Set();
737
- for (const slug of readdirSync(sessionsDir)) {
738
- const prsFile = join(sessionsDir, slug, "prs.json");
739
- if (!existsSync(prsFile)) continue;
740
- let slotUrl;
868
+ let slugs;
869
+ try {
870
+ slugs = readdirSync(sessionsDir);
871
+ } catch {
872
+ return [...handledUrls];
873
+ }
874
+ const nowMs = Date.now();
875
+ const watchedUrls = /* @__PURE__ */ new Set();
876
+ for (const slug of slugs) {
877
+ const slotPath = join(sessionsDir, slug);
878
+ let slotPr;
741
879
  try {
742
- const parsed = JSON.parse(readFileSync(prsFile, "utf-8"));
743
- const entry = Array.isArray(parsed) ? parsed[0] : parsed;
744
- slotUrl = entry?.url;
880
+ const parsed = JSON.parse(readFileSync(join(slotPath, "prs.json"), "utf-8"));
881
+ slotPr = Array.isArray(parsed) ? parsed[0] : parsed;
745
882
  } catch {
746
883
  continue;
747
884
  }
748
- if (slotUrl) trackedUrls.add(slotUrl);
885
+ const slotUrl = slotPr?.url;
886
+ if (typeof slotUrl !== "string" || !handledUrls.includes(slotUrl)) continue;
887
+ const evidence = {
888
+ isStopped: slug.endsWith(STOPPED_SLOT_SUFFIX),
889
+ isFinalized: existsSync(join(slotPath, "result.md")),
890
+ recordedPrState: typeof slotPr?.state === "string" ? slotPr.state : void 0,
891
+ heartbeatMtimeMs: readHeartbeatMtimeMs(slotPath)
892
+ };
893
+ if (resolveWatchSlotStatus(evidence, nowMs) !== "stale" /* Stale */) watchedUrls.add(slotUrl);
894
+ }
895
+ return handledUrls.filter((url) => !watchedUrls.has(url));
896
+ }
897
+ function isTerminalThisSession(prUrl, state) {
898
+ const prNumber = parsePrUrl(prUrl)?.prNumber;
899
+ if (prNumber === void 0) return false;
900
+ return (state.terminalPending ?? []).includes(prNumber) || (state.terminalHandled ?? []).includes(prNumber);
901
+ }
902
+ function isEndState(providerState) {
903
+ return providerState === "MERGED" /* Merged */ || providerState === "CLOSED" /* Closed */;
904
+ }
905
+ function resolveOwedWatchPrs(unwatchedUrls, state, scan) {
906
+ return unwatchedUrls.filter((prUrl) => {
907
+ if (isTerminalThisSession(prUrl, state)) return false;
908
+ const providerState = scan?.states[prUrl];
909
+ return providerState === void 0 || providerState === "OPEN" /* Open */;
910
+ });
911
+ }
912
+ function prsAwaitingStateScan(unwatchedUrls, state, scan) {
913
+ return unwatchedUrls.filter(
914
+ (prUrl) => !isTerminalThisSession(prUrl, state) && !isEndState(scan?.states[prUrl])
915
+ );
916
+ }
917
+ function lookupProviderPrState(prUrl, run = defaultGhRunner) {
918
+ if (!parsePrUrl(prUrl)) return null;
919
+ const reportedState = run(["pr", "view", prUrl, "--json", "state", "-q", ".state"])?.trim();
920
+ return Object.values(ProviderPrState).find(
921
+ (providerState) => providerState === reportedState && providerState !== "UNREACHABLE" /* Unreachable */
922
+ ) ?? "UNREACHABLE" /* Unreachable */;
923
+ }
924
+ function scanProviderPrStates(prUrls, lookup = lookupProviderPrState) {
925
+ const states = {};
926
+ for (const prUrl of prUrls) {
927
+ const providerState = lookup(prUrl);
928
+ if (providerState !== null) states[prUrl] = providerState;
749
929
  }
750
- return handledUrls.filter((url) => !trackedUrls.has(url));
930
+ return { states };
751
931
  }
752
- function watchGateDecision(state, untrackedPrUrls, maxBlocks = MAX_WATCH_BLOCKS) {
932
+ function watchGateDecision(state, unwatchedPrUrls, maxBlocks = MAX_WATCH_BLOCKS) {
753
933
  const blockCount = state.watchBlockCount ?? 0;
754
- if (state.watchSkipped === true || untrackedPrUrls.length === 0) {
755
- return { action: "none" /* None */, blockCount, untracked: untrackedPrUrls };
934
+ if (state.watchSkipped === true || unwatchedPrUrls.length === 0) {
935
+ return { action: "none" /* None */, blockCount, unwatched: unwatchedPrUrls };
756
936
  }
757
937
  if (blockCount >= maxBlocks) {
758
- return { action: "release" /* Release */, blockCount, untracked: untrackedPrUrls };
938
+ return { action: "release" /* Release */, blockCount, unwatched: unwatchedPrUrls };
759
939
  }
760
940
  return {
761
941
  action: "block" /* Block */,
762
942
  blockCount: blockCount + 1,
763
- untracked: untrackedPrUrls
943
+ unwatched: unwatchedPrUrls
764
944
  };
765
945
  }
766
946
 
@@ -782,18 +962,6 @@ function buildFollowthroughDecision(state, maxBlocks = MAX_BUILD_BLOCKS) {
782
962
  }
783
963
  return { action: "block" /* Block */, blockCount: blockCount + 1 };
784
964
  }
785
-
786
- // src/pr-walkthrough/constants.ts
787
- var REPORT_SENTINEL = "muggle-pr-section";
788
- var WALKTHROUGH_SLOT_MARKER = "<!-- muggle-pr-walkthrough:v1 -->";
789
- var WALKTHROUGH_SKIPPED_MARKER = "<!-- muggle-pr-walkthrough-status:skipped -->";
790
- var WALKTHROUGH_COMMENT_HEADING = "### Muggle AI \u2014 PR visual walkthrough";
791
- var REPORT_SENTINEL_TAG = new RegExp(`<!--\\s*${REPORT_SENTINEL}[^>]*-->\\s*`, "g");
792
- var LAST_FULL_RUN_OPENING = "<details><summary>Last full E2E run on this PR</summary>";
793
- var SHORT_SHA_LENGTH = 7;
794
- var GH_COMMENT_TIMEOUT_MS = 1e4;
795
-
796
- // src/guardrails/prReportPost.ts
797
965
  var PR_PROSE_CMD = /\bgh\s+pr\s+(comment|create|edit)\b/;
798
966
  var GH_API_CMD = /\bgh\s+api\b/;
799
967
  var ISSUE_COMMENT_PATH = /\bissues\/comments\/\d+/;
@@ -856,22 +1024,6 @@ function applyWalkthroughSkip(state, skipped) {
856
1024
  if (!skipped || state.walkthroughSkipped === true) return state;
857
1025
  return { ...state, walkthroughSkipped: true };
858
1026
  }
859
-
860
- // src/hook-budget/constants.ts
861
- var HOOK_CHILD_PROCESS_DEADLINE_MS = 600;
862
-
863
- // src/hook-budget/childProcessBudget.ts
864
- var childProcessDeadlineEpochMs = null;
865
- function enforceHookChildProcessDeadline(gatesStartEpochMs = Date.now()) {
866
- childProcessDeadlineEpochMs = gatesStartEpochMs + HOOK_CHILD_PROCESS_DEADLINE_MS;
867
- }
868
- function boundedChildTimeoutMs(ceilingMs) {
869
- if (childProcessDeadlineEpochMs === null) return ceilingMs;
870
- const remainingMs = Math.floor(childProcessDeadlineEpochMs - Date.now());
871
- return remainingMs > 0 ? Math.min(ceilingMs, remainingMs) : null;
872
- }
873
-
874
- // src/guardrails/walkthroughOwed.ts
875
1027
  function runGh(args) {
876
1028
  const timeoutMs = boundedChildTimeoutMs(GH_LOOKUP_TIMEOUT_MS);
877
1029
  if (timeoutMs === null) return null;
@@ -1072,72 +1224,6 @@ function classifyComment(body) {
1072
1224
  if (body.includes(WALKTHROUGH_SKIPPED_MARKER)) return "skipped" /* Skipped */;
1073
1225
  return "pending" /* Pending */;
1074
1226
  }
1075
- var GITHUB_PR_URL = /^https:\/\/github\.com\/([^/\s]+)\/([^/\s]+)\/pull\/(\d+)/;
1076
- var GH_CALLS_ENV = "MUGGLE_GUARDRAIL_GH_CALLS";
1077
- var defaultGhRunner = (args, input2) => {
1078
- if (process.env[GH_CALLS_ENV] === "off") return null;
1079
- const timeoutMs = boundedChildTimeoutMs(GH_COMMENT_TIMEOUT_MS);
1080
- if (timeoutMs === null) return null;
1081
- try {
1082
- return execFileSync("gh", args, {
1083
- encoding: "utf-8",
1084
- input: input2,
1085
- timeout: timeoutMs,
1086
- stdio: ["pipe", "pipe", "ignore"],
1087
- windowsHide: true
1088
- });
1089
- } catch {
1090
- return null;
1091
- }
1092
- };
1093
- function parsePrUrl(prUrl) {
1094
- const parts = prUrl.match(GITHUB_PR_URL);
1095
- if (!parts) return null;
1096
- return { repo: `${parts[1]}/${parts[2]}`, prNumber: Number(parts[3]) };
1097
- }
1098
- function listPrComments(pr, run) {
1099
- let raw;
1100
- try {
1101
- raw = run(["api", "--paginate", `repos/${pr.repo}/issues/${pr.prNumber}/comments`]);
1102
- } catch {
1103
- return null;
1104
- }
1105
- if (!raw) return null;
1106
- try {
1107
- const parsed = JSON.parse(raw);
1108
- return Array.isArray(parsed) ? parsed : null;
1109
- } catch {
1110
- return null;
1111
- }
1112
- }
1113
- function readPrHeadSha(pr, run) {
1114
- try {
1115
- return run(["api", `repos/${pr.repo}/pulls/${pr.prNumber}`, "--jq", ".head.sha"])?.trim() || null;
1116
- } catch {
1117
- return null;
1118
- }
1119
- }
1120
- function writeJson(args, payload, run) {
1121
- try {
1122
- return run(args, JSON.stringify(payload)) !== null;
1123
- } catch {
1124
- return false;
1125
- }
1126
- }
1127
- function postPrComment(pr, body, run) {
1128
- return writeJson(
1129
- ["api", "--method", "POST", `repos/${pr.repo}/issues/${pr.prNumber}/comments`, "--input", "-"],
1130
- { body },
1131
- run
1132
- );
1133
- }
1134
- function patchPrComment(pr, commentId, body, run) {
1135
- return writeJson(
1136
- ["api", "--method", "PATCH", `repos/${pr.repo}/issues/comments/${commentId}`, "--input", "-"],
1137
- { body },
1138
- run
1139
- );
1140
- }
1141
1227
 
1142
1228
  // src/pr-walkthrough/reserve.ts
1143
1229
  function commentWithStatus(comments, status) {
@@ -1993,14 +2079,20 @@ function e2eGate() {
1993
2079
  }
1994
2080
  function watchGate() {
1995
2081
  const state = readState(sessionId);
1996
- const untrackedPrUrls = findUntrackedHandledPrs(state.prsHandled);
1997
- const decision = watchGateDecision(state, untrackedPrUrls);
2082
+ const unwatchedPrUrls = findUnwatchedHandledPrs(state.prsHandled);
2083
+ const prStateScan = readPrStateScan(sessionId);
2084
+ if (state.watchSkipped !== true && prsAwaitingStateScan(unwatchedPrUrls, state, prStateScan).length > 0) {
2085
+ startBackgroundJob("scan-watch-pr-states" /* ScanWatchPrStates */, [sessionId]);
2086
+ }
2087
+ const decision = watchGateDecision(state, resolveOwedWatchPrs(unwatchedPrUrls, state, prStateScan));
1998
2088
  if (decision.action === "release" /* Release */) return releaseGate("watchReleased");
1999
2089
  if (decision.action === "none" /* None */) return "{}";
2000
2090
  state.watchBlockCount = decision.blockCount;
2001
2091
  writeState(state);
2002
- const prList = decision.untracked.join(", ");
2003
- const reason = decision.blockCount === 1 ? `Do not end the turn yet. A PR was opened this session but no muggle-do session slot tracks it: ${prList}. Seed the slot and hand off per muggle-do Stage 8 \u2014 ${muggleSkill("/muggle:muggle-pr-followup")} ${decision.untracked[0]} does both. Seeding is what matters: once a slot exists, reconcile arms it at the next session start and finalizes it when the PR goes terminal, so an unarmed slot is fine but no slot means nothing ever picks this PR up. If it genuinely should not be tracked (autoWatchPR=never, handed off elsewhere), tell the user why and run \`echo "MUGGLE_WATCH_SKIP: <reason>"\` \u2014 that records the skip and keeps this gate quiet for the rest of the session.` : `PR hand-off still owed for ${prList} (reminder ${decision.blockCount}/${MAX_WATCH_BLOCKS}): seed a slot via ${muggleSkill("/muggle:muggle-pr-followup")}, or record a legitimate skip via \`echo "MUGGLE_WATCH_SKIP: <reason>"\`.`;
2092
+ const prList = decision.unwatched.join(", ");
2093
+ const staleMinutes = WATCH_HEARTBEAT_STALE_MS / 6e4;
2094
+ const armCommand = `${muggleSkill("/muggle:muggle-pr-followup")} ${decision.unwatched[0]}`;
2095
+ const reason = decision.blockCount === 1 ? `Do not end the turn yet. A PR opened this session is open with no live muggle-pr-followup watch: ${prList}. Arm its watch per the muggle-pr-followup arming procedure (arm-watcher.md) \u2014 invoking ${armCommand} bootstraps it and arms it that way (add --resume when its slot already exists). A seeded slot does not count: only a running watch loop does, shown by a watch-heartbeat it touches every poll and that goes stale after ${staleMinutes} minutes (a watch armed moments ago writes it on its first poll). If the PR already merged or closed, end the turn again \u2014 a provider check started now clears it. If it genuinely should not be watched (autoWatchPR=never, handed off elsewhere), tell the user why and run \`echo "MUGGLE_WATCH_SKIP: <reason>"\` \u2014 that records the skip and keeps this gate quiet for the rest of the session.` : `PR watch still owed for ${prList} (reminder ${decision.blockCount}/${MAX_WATCH_BLOCKS}): arm it per arm-watcher.md via ${armCommand} (--resume when its slot exists), or record a legitimate skip via \`echo "MUGGLE_WATCH_SKIP: <reason>"\`.`;
2004
2096
  return blockStop(reason, host);
2005
2097
  }
2006
2098
  function buildFollowthroughGate() {
@@ -2199,12 +2291,23 @@ function settleWalkthroughNoAppLogicChangeJob() {
2199
2291
  if (prUrl && detail) settleWalkthroughCommentForNoAppLogicChange(prUrl, detail);
2200
2292
  return "{}";
2201
2293
  }
2294
+ function scanWatchPrStatesJob() {
2295
+ const scannedSessionId = jobArgs[0] ?? "unknown";
2296
+ const state = readState(scannedSessionId);
2297
+ const previousScan = readPrStateScan(scannedSessionId);
2298
+ const awaitingPrUrls = prsAwaitingStateScan(findUnwatchedHandledPrs(state.prsHandled), state, previousScan);
2299
+ if (awaitingPrUrls.length === 0) return "{}";
2300
+ const freshScan = scanProviderPrStates(awaitingPrUrls);
2301
+ writePrStateScan(scannedSessionId, { states: { ...previousScan?.states, ...freshScan.states } });
2302
+ return "{}";
2303
+ }
2202
2304
  var backgroundJobs = {
2203
2305
  ["scan-walkthroughs" /* ScanWalkthroughs */]: scanWalkthroughsJob,
2204
2306
  ["reserve-walkthrough-comment" /* ReserveWalkthroughComment */]: reserveWalkthroughCommentJob,
2205
2307
  ["settle-walkthrough-skipped" /* SettleWalkthroughSkipped */]: settleWalkthroughSkippedJob,
2206
2308
  ["settle-walkthrough-unreasoned" /* SettleWalkthroughUnreasoned */]: settleWalkthroughUnreasonedJob,
2207
- ["settle-walkthrough-no-app-logic-change" /* SettleWalkthroughNoAppLogicChange */]: settleWalkthroughNoAppLogicChangeJob
2309
+ ["settle-walkthrough-no-app-logic-change" /* SettleWalkthroughNoAppLogicChange */]: settleWalkthroughNoAppLogicChangeJob,
2310
+ ["scan-watch-pr-states" /* ScanWatchPrStates */]: scanWatchPrStatesJob
2208
2311
  };
2209
2312
  var runSubcommand = isBackgroundJob(sub) ? backgroundJobs[sub] : handlers[sub] ?? (() => "{}");
2210
2313
  process.stdout.write(runSubcommand());
@@ -1,6 +1,6 @@
1
1
  # Open PR — forward mode
2
2
 
3
- Forward pipeline's Stage 7. Invoked by `/muggle-do` after stages 1–6 of a fresh feature. Opens the change — a PR on GitHub (`gh pr create`) or an MR on GitLab (`glab mr create`), provider resolved in Step 5 — then seeds session state and dispatches the first watcher.
3
+ Forward pipeline's Stage 7. Invoked by `/muggle-do` after stages 1–6 of a fresh feature. Opens the change — a PR on GitHub (`gh pr create`) or an MR on GitLab (`glab mr create`), provider resolved in Step 5 — then seeds session state and arms the first watch.
4
4
 
5
5
  ## Turn preamble
6
6
 
@@ -57,7 +57,7 @@ The E2E repair loop ([`../e2e-repair.md`](../e2e-repair.md)) runs once this stag
57
57
 
58
58
  ## Stage 8 handoff
59
59
 
60
- After every repo is processed and Stage 7.5 has cleared, build the watcher manifest and dispatch one watcher loop per opened PR. The dispatches are the LAST action this stage takes.
60
+ 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.
61
61
 
62
62
  Write `~/.muggle-ai/muggle-do/sessions/<slug>/prs.json` per [`../../muggle-pr-followup/state-schemas.md`](../../muggle-pr-followup/state-schemas.md#prsjson):
63
63
 
@@ -69,16 +69,13 @@ Seed `~/.muggle-ai/muggle-do/sessions/<slug>/last_seen.json` per [`../../muggle-
69
69
 
70
70
  **Do not** seed `cycle.json` or `requirements.md`. The watcher is a dumb pipe; `/muggle-do` reads reviews off GitHub.
71
71
 
72
- For each entry in `prs.json`, dispatch its watcher:
73
- ```
74
- /loop 1m /muggle:muggle-pr-followup <slug> <pr-number>
75
- ```
72
+ 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.
76
73
 
77
- If `prs.json` is empty, **do not dispatch** — record the reason in `result.md` and exit.
74
+ If `prs.json` is empty, **do not arm** — record the reason in `result.md` and exit.
78
75
 
79
76
  ## Invariants
80
77
 
81
- - Branch synced with its base before the push, never after; PR creation per non-skipped repo; 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 the dispatch; `/loop` dispatch is the last action.
78
+ - Branch synced with its base before the push, never after; PR creation per non-skipped repo; 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.
82
79
 
83
80
  ## Output
84
81
 
@@ -87,7 +84,7 @@ If `prs.json` is empty, **do not dispatch** — record the reason in `result.md`
87
84
  **Skipped:** repo → reason (when `autoCreatePR` short-circuited)
88
85
  **Overflow comments posted:** repo → PR #
89
86
  **Stage 7.5:** `green` | `waived — <reason>` | `iteration-cap`
90
- **Stage 8:** `Watching <N> PR(s) — one /loop 1m /muggle:muggle-pr-followup <slug> <pr#> per PR` | `No PRs to watch — stage 8 not dispatched`
87
+ **Stage 8:** `Watching <N> PR(s) — one monitor per PR, armed per arm-watcher.md` | `No PRs to watch — stage 8 not armed`
91
88
  **Errors:** repo → message
92
89
 
93
90
  ## Post-merge cleanup