@muggleai/works 5.22.0-staging.157 → 5.22.0-staging.159

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 (47) hide show
  1. package/.claude-plugin/marketplace.json +1 -1
  2. package/README.md +3 -1
  3. package/dist/{chunk-E3T2RN6R.js → chunk-M2PJRVCC.js} +16 -0
  4. package/dist/{chunk-DLBPRPUN.js → chunk-SF75W2SV.js} +217 -47
  5. package/dist/cli.js +2 -2
  6. package/dist/index.js +2 -2
  7. package/dist/plugin/.claude-plugin/plugin.json +1 -1
  8. package/dist/plugin/.codex-plugin/plugin.json +1 -1
  9. package/dist/plugin/.cursor-plugin/plugin.json +1 -1
  10. package/dist/plugin/config/preference-defaults.json +1 -0
  11. package/dist/plugin/hooks/README.md +15 -7
  12. package/dist/plugin/hooks/codex-hooks.json +3 -10
  13. package/dist/plugin/hooks/hooks.json +14 -20
  14. package/dist/plugin/scripts/ensure-electron-app.sh +133 -186
  15. package/dist/plugin/scripts/guardrail-lib.sh +15 -9
  16. package/dist/plugin/scripts/guardrails.mjs +137 -21
  17. package/dist/plugin/scripts/session-maintenance.sh +98 -0
  18. package/dist/plugin/skills/_shared/ci-check-to-command.md +2 -1
  19. package/dist/plugin/skills/_shared/vcs/github/pr-checks.md +9 -0
  20. package/dist/plugin/skills/do/fix-ci.md +14 -4
  21. package/dist/plugin/skills/do/open-prs/forward.md +2 -0
  22. package/dist/plugin/skills/do/pre-flight.md +2 -0
  23. package/dist/plugin/skills/muggle-do/SKILL.md +1 -0
  24. package/dist/plugin/skills/muggle-preferences/ops/configure.md +1 -0
  25. package/dist/plugin/skills/muggle-preferences/preference-gates/autoInstallCiWorkflow.md +13 -0
  26. package/dist/release-manifest.json +3 -3
  27. package/dist/{src-V245RV7L.js → src-5QO7XTIG.js} +1 -1
  28. package/package.json +2 -1
  29. package/plugin/.claude-plugin/plugin.json +1 -1
  30. package/plugin/.codex-plugin/plugin.json +1 -1
  31. package/plugin/.cursor-plugin/plugin.json +1 -1
  32. package/plugin/config/preference-defaults.json +1 -0
  33. package/plugin/hooks/README.md +15 -7
  34. package/plugin/hooks/codex-hooks.json +3 -10
  35. package/plugin/hooks/hooks.json +14 -20
  36. package/plugin/scripts/ensure-electron-app.sh +133 -186
  37. package/plugin/scripts/guardrail-lib.sh +15 -9
  38. package/plugin/scripts/guardrails.mjs +137 -21
  39. package/plugin/scripts/session-maintenance.sh +98 -0
  40. package/plugin/skills/_shared/ci-check-to-command.md +2 -1
  41. package/plugin/skills/_shared/vcs/github/pr-checks.md +9 -0
  42. package/plugin/skills/do/fix-ci.md +14 -4
  43. package/plugin/skills/do/open-prs/forward.md +2 -0
  44. package/plugin/skills/do/pre-flight.md +2 -0
  45. package/plugin/skills/muggle-do/SKILL.md +1 -0
  46. package/plugin/skills/muggle-preferences/ops/configure.md +1 -0
  47. package/plugin/skills/muggle-preferences/preference-gates/autoInstallCiWorkflow.md +13 -0
@@ -11,6 +11,7 @@
11
11
  GUARDRAIL_LIB_LOADED=1
12
12
 
13
13
  GUARDRAIL_PAYLOAD=""
14
+ GUARDRAIL_STATE_FILE=""
14
15
  GUARDRAIL_STATE=""
15
16
  GUARDRAIL_STATE_LOADED=""
16
17
  GUARDRAIL_HAS_STATE=""
@@ -50,20 +51,25 @@ guardrail_resolve_home() {
50
51
  fi
51
52
  }
52
53
 
54
+ # Sets GUARDRAIL_STATE_FILE to this session's guardrail state file, named as sessionState.ts names it.
55
+ guardrail_resolve_state_file() {
56
+ local session_id_pattern='"session_id"[[:space:]]*:[[:space:]]*"([^"]*)"'
57
+ local raw_session_id="unknown"
58
+ if [[ $GUARDRAIL_PAYLOAD =~ $session_id_pattern ]] && [[ -n ${BASH_REMATCH[1]} ]]; then
59
+ raw_session_id="${BASH_REMATCH[1]}"
60
+ fi
61
+ guardrail_resolve_home
62
+ GUARDRAIL_STATE_FILE="$GUARDRAIL_HOME/.muggle-ai/guardrails/${raw_session_id//[^A-Za-z0-9_-]/_}.json"
63
+ }
64
+
53
65
  # Loads this session's guardrail state once per process; returns 1 when the session has none.
54
66
  guardrail_load_state() {
55
67
  if [[ -z $GUARDRAIL_STATE_LOADED ]]; then
56
68
  GUARDRAIL_STATE_LOADED=1
57
- local session_id_pattern='"session_id"[[:space:]]*:[[:space:]]*"([^"]*)"'
58
- local raw_session_id="unknown"
59
- if [[ $GUARDRAIL_PAYLOAD =~ $session_id_pattern ]] && [[ -n ${BASH_REMATCH[1]} ]]; then
60
- raw_session_id="${BASH_REMATCH[1]}"
61
- fi
62
- guardrail_resolve_home
63
- local state_file="$GUARDRAIL_HOME/.muggle-ai/guardrails/${raw_session_id//[^A-Za-z0-9_-]/_}.json"
64
- if [[ -f $state_file ]]; then
69
+ guardrail_resolve_state_file
70
+ if [[ -f $GUARDRAIL_STATE_FILE ]]; then
65
71
  GUARDRAIL_HAS_STATE=1
66
- IFS= read -r -d '' GUARDRAIL_STATE <"$state_file" || true
72
+ IFS= read -r -d '' GUARDRAIL_STATE <"$GUARDRAIL_STATE_FILE" || true
67
73
  fi
68
74
  fi
69
75
  [[ -n $GUARDRAIL_HAS_STATE ]]
@@ -1,8 +1,8 @@
1
- import { readFileSync, existsSync, mkdirSync, writeFileSync, renameSync, readdirSync, openSync, writeSync, closeSync, unlinkSync } from 'fs';
1
+ import { readFileSync, existsSync, mkdirSync, readdirSync, writeFileSync, renameSync, openSync, writeSync, closeSync, unlinkSync } from 'fs';
2
2
  import { basename, join, isAbsolute, resolve, dirname } from 'path';
3
3
  import { homedir, hostname } from 'os';
4
+ import { execFileSync, spawn } from 'child_process';
4
5
  import { fileURLToPath } from 'url';
5
- import { execFileSync } from 'child_process';
6
6
 
7
7
  // src/guardrails/cli.ts
8
8
 
@@ -136,7 +136,14 @@ function withFileLock(lockPath, waitMs, run) {
136
136
 
137
137
  // src/guardrails/sessionState.ts
138
138
  var baseDir = (override) => override ?? join(homedir(), ".muggle-ai", "guardrails");
139
- var fileFor = (sessionId2, override) => join(baseDir(override), `${sessionId2.replace(/[^A-Za-z0-9_-]/g, "_")}.json`);
139
+ var fileFor = (sessionId2, override, suffix = ".json") => join(baseDir(override), `${sessionId2.replace(/[^A-Za-z0-9_-]/g, "_")}${suffix}`);
140
+ var WALKTHROUGH_SCAN_SUFFIX = ".walkthrough-scan.json";
141
+ function writeAtomically(target, contents, dirOverride) {
142
+ mkdirSync(baseDir(dirOverride), { recursive: true });
143
+ const staging = `${target}.${process.pid}.tmp`;
144
+ writeFileSync(staging, JSON.stringify(contents, null, 2));
145
+ renameSync(staging, target);
146
+ }
140
147
  function readState(sessionId2, dirOverride) {
141
148
  const f = fileFor(sessionId2, dirOverride);
142
149
  if (!existsSync(f)) return { sessionId: sessionId2, prsHandled: [] };
@@ -148,11 +155,17 @@ function readState(sessionId2, dirOverride) {
148
155
  }
149
156
  }
150
157
  function writeState(state, dirOverride) {
151
- mkdirSync(baseDir(dirOverride), { recursive: true });
152
- const target = fileFor(state.sessionId, dirOverride);
153
- const staging = `${target}.${process.pid}.tmp`;
154
- writeFileSync(staging, JSON.stringify(state, null, 2));
155
- renameSync(staging, target);
158
+ writeAtomically(fileFor(state.sessionId, dirOverride), state, dirOverride);
159
+ }
160
+ function readWalkthroughScan(sessionId2, dirOverride) {
161
+ try {
162
+ return JSON.parse(readFileSync(fileFor(sessionId2, dirOverride, WALKTHROUGH_SCAN_SUFFIX), "utf-8"));
163
+ } catch {
164
+ return null;
165
+ }
166
+ }
167
+ function writeWalkthroughScan(sessionId2, scan, dirOverride) {
168
+ writeAtomically(fileFor(sessionId2, dirOverride, WALKTHROUGH_SCAN_SUFFIX), scan, dirOverride);
156
169
  }
157
170
  function commitState(sessionId2, mutate, dirOverride) {
158
171
  mkdirSync(baseDir(dirOverride), { recursive: true });
@@ -174,6 +187,34 @@ function markPrHandled(sessionId2, prUrl, dirOverride) {
174
187
  writeState(state, dirOverride);
175
188
  }
176
189
 
190
+ // src/guardrails/types.ts
191
+ var GuardrailBackgroundJob = /* @__PURE__ */ ((GuardrailBackgroundJob2) => {
192
+ GuardrailBackgroundJob2["ScanWalkthroughs"] = "scan-walkthroughs";
193
+ GuardrailBackgroundJob2["ReserveWalkthroughComment"] = "reserve-walkthrough-comment";
194
+ GuardrailBackgroundJob2["SettleWalkthroughSkipped"] = "settle-walkthrough-skipped";
195
+ GuardrailBackgroundJob2["SettleWalkthroughUnreasoned"] = "settle-walkthrough-unreasoned";
196
+ return GuardrailBackgroundJob2;
197
+ })(GuardrailBackgroundJob || {});
198
+
199
+ // src/guardrails/backgroundJob.ts
200
+ function isBackgroundJob(subcommand) {
201
+ return Object.values(GuardrailBackgroundJob).includes(subcommand);
202
+ }
203
+ function startBackgroundJob(job, jobArgs2, cwd) {
204
+ try {
205
+ const child = spawn(process.execPath, [...process.execArgv, process.argv[1], job, ...jobArgs2], {
206
+ cwd,
207
+ detached: true,
208
+ stdio: "ignore",
209
+ windowsHide: true
210
+ });
211
+ child.on("error", () => void 0);
212
+ child.unref();
213
+ } catch {
214
+ return;
215
+ }
216
+ }
217
+
177
218
  // src/guardrails/shellTool.ts
178
219
  function isShellToolCall(input2) {
179
220
  return SHELL_TOOL_NAMES.includes(input2.tool_name ?? "");
@@ -809,11 +850,29 @@ function applyWalkthroughSkip(state, skipped) {
809
850
  if (!skipped || state.walkthroughSkipped === true) return state;
810
851
  return { ...state, walkthroughSkipped: true };
811
852
  }
853
+
854
+ // src/hook-budget/constants.ts
855
+ var HOOK_CHILD_PROCESS_DEADLINE_MS = 600;
856
+
857
+ // src/hook-budget/childProcessBudget.ts
858
+ var childProcessDeadlineEpochMs = null;
859
+ function enforceHookChildProcessDeadline(gatesStartEpochMs = Date.now()) {
860
+ childProcessDeadlineEpochMs = gatesStartEpochMs + HOOK_CHILD_PROCESS_DEADLINE_MS;
861
+ }
862
+ function boundedChildTimeoutMs(ceilingMs) {
863
+ if (childProcessDeadlineEpochMs === null) return ceilingMs;
864
+ const remainingMs = Math.floor(childProcessDeadlineEpochMs - Date.now());
865
+ return remainingMs > 0 ? Math.min(ceilingMs, remainingMs) : null;
866
+ }
867
+
868
+ // src/guardrails/walkthroughOwed.ts
812
869
  function runGh(args) {
870
+ const timeoutMs = boundedChildTimeoutMs(GH_LOOKUP_TIMEOUT_MS);
871
+ if (timeoutMs === null) return null;
813
872
  try {
814
873
  return execFileSync("gh", args, {
815
874
  encoding: "utf-8",
816
- timeout: GH_LOOKUP_TIMEOUT_MS,
875
+ timeout: timeoutMs,
817
876
  stdio: ["ignore", "pipe", "ignore"],
818
877
  windowsHide: true
819
878
  });
@@ -847,6 +906,13 @@ function scanForOwedWalkthroughs(state, lookup = defaultPrWalkthroughLookup) {
847
906
  }
848
907
  return { owed, verified: verified2 };
849
908
  }
909
+ function isWalkthroughGateArmed(state) {
910
+ return state.e2eRun === true && state.walkthroughPosted !== true && state.walkthroughSkipped !== true;
911
+ }
912
+ function isWalkthroughScanCurrent(scan, state) {
913
+ const scanned = new Set(scan.prsHandled);
914
+ return scanned.size === new Set(state.prsHandled).size && state.prsHandled.every((prUrl) => scanned.has(prUrl));
915
+ }
850
916
  function walkthroughGateDecision(state, owedPrUrls, maxBlocks = MAX_WALKTHROUGH_BLOCKS) {
851
917
  const blockCount = state.walkthroughBlockCount ?? 0;
852
918
  const alreadySettled = state.walkthroughPosted === true || state.walkthroughSkipped === true || state.e2eRun !== true;
@@ -884,6 +950,7 @@ var E2E_SKIP_CODE_CLAIMS = {
884
950
  };
885
951
  var USER_WAIVE_PHRASE = "SKIP E2E";
886
952
  var DEV_SERVER_PROBE_TIMEOUT_MS = 2e3;
953
+ var GIT_PROBE_TIMEOUT_MS = 5e3;
887
954
  var WEB_SERVER_COMMAND = /\b(vite|next\s+(dev|start)|react-scripts|ng\s+serve|nuxt|astro\s+dev|remix\s+dev|webpack(-dev)?-server|http-server|serve\s+-s|gatsby\s+develop|vue-cli-service\s+serve)\b/;
888
955
  var BROWSER_FRAMEWORK_PACKAGES = [
889
956
  "react-dom",
@@ -942,11 +1009,13 @@ var GITHUB_PR_URL = /^https:\/\/github\.com\/([^/\s]+)\/([^/\s]+)\/pull\/(\d+)/;
942
1009
  var GH_CALLS_ENV = "MUGGLE_GUARDRAIL_GH_CALLS";
943
1010
  var defaultGhRunner = (args, input2) => {
944
1011
  if (process.env[GH_CALLS_ENV] === "off") return null;
1012
+ const timeoutMs = boundedChildTimeoutMs(GH_COMMENT_TIMEOUT_MS);
1013
+ if (timeoutMs === null) return null;
945
1014
  try {
946
1015
  return execFileSync("gh", args, {
947
1016
  encoding: "utf-8",
948
1017
  input: input2,
949
- timeout: GH_COMMENT_TIMEOUT_MS,
1018
+ timeout: timeoutMs,
950
1019
  stdio: ["pipe", "pipe", "ignore"],
951
1020
  windowsHide: true
952
1021
  });
@@ -1184,10 +1253,13 @@ var listFiles = (dir) => {
1184
1253
  }
1185
1254
  };
1186
1255
  var runGit = (args, cwd) => {
1256
+ const timeoutMs = boundedChildTimeoutMs(GIT_PROBE_TIMEOUT_MS);
1257
+ if (timeoutMs === null) return null;
1187
1258
  try {
1188
1259
  return execFileSync("git", args, {
1189
1260
  cwd,
1190
1261
  encoding: "utf8",
1262
+ timeout: timeoutMs,
1191
1263
  stdio: ["ignore", "pipe", "ignore"],
1192
1264
  windowsHide: true
1193
1265
  });
@@ -1208,10 +1280,13 @@ var hostAndPort = (url) => {
1208
1280
  var isReachable = (url) => {
1209
1281
  const target = hostAndPort(url);
1210
1282
  if (!target) return false;
1211
- const script = `const net=require('net');const s=net.connect(${target.port},${JSON.stringify(target.host)});s.setTimeout(${DEV_SERVER_PROBE_TIMEOUT_MS});s.on('connect',()=>{s.destroy();process.exit(0)});s.on('timeout',()=>{s.destroy();process.exit(1)});s.on('error',()=>process.exit(1));`;
1283
+ const spawnTimeoutMs = boundedChildTimeoutMs(DEV_SERVER_PROBE_TIMEOUT_MS * 2);
1284
+ if (spawnTimeoutMs === null) return false;
1285
+ const socketTimeoutMs = Math.min(DEV_SERVER_PROBE_TIMEOUT_MS, Math.floor(spawnTimeoutMs / 2));
1286
+ const script = `const net=require('net');const s=net.connect(${target.port},${JSON.stringify(target.host)});s.setTimeout(${socketTimeoutMs});s.on('connect',()=>{s.destroy();process.exit(0)});s.on('timeout',()=>{s.destroy();process.exit(1)});s.on('error',()=>process.exit(1));`;
1212
1287
  try {
1213
1288
  execFileSync(process.execPath, ["-e", script], {
1214
- timeout: DEV_SERVER_PROBE_TIMEOUT_MS * 2,
1289
+ timeout: spawnTimeoutMs,
1215
1290
  stdio: "ignore",
1216
1291
  windowsHide: true
1217
1292
  });
@@ -1614,6 +1689,7 @@ function readStdin() {
1614
1689
  }
1615
1690
  var host = resolveHookHost();
1616
1691
  var sub = process.argv[2];
1692
+ if (!isBackgroundJob(sub)) enforceHookChildProcessDeadline();
1617
1693
  var input = readStdin();
1618
1694
  var sessionId = input.session_id ?? "unknown";
1619
1695
  function releaseGate(field) {
@@ -1634,7 +1710,10 @@ function prOpened() {
1634
1710
  if (!url) return "{}";
1635
1711
  if (readState(sessionId).prsHandled.includes(url)) return "{}";
1636
1712
  markPrHandled(sessionId, url);
1637
- reserveWalkthroughComment(url);
1713
+ startBackgroundJob("reserve-walkthrough-comment" /* ReserveWalkthroughComment */, [url]);
1714
+ if (isWalkthroughGateArmed(readState(sessionId))) {
1715
+ startBackgroundJob("scan-walkthroughs" /* ScanWalkthroughs */, [sessionId], input.cwd);
1716
+ }
1638
1717
  const ctx = `A pull request was just opened: ${url}
1639
1718
  Its Muggle AI visual-walkthrough comment is reserved and empty \u2014 settle it by posting the walkthrough there once E2E runs, or by recording why E2E does not apply.
1640
1719
  Per the autoWatchPR preference, a muggle-pr-followup watcher should handle its incoming reviews. If autoWatchPR=always, start it now by invoking ${muggleSkill("/muggle:muggle-pr-followup")} with the PR URL; if =ask, offer it to the user; if =never, do nothing.`;
@@ -1679,7 +1758,8 @@ function terminalGate() {
1679
1758
  }
1680
1759
  function recordTests() {
1681
1760
  const cmd = input.tool_input?.command ?? "";
1682
- const judgedSkip = judgeE2eSkip(input, readState(sessionId));
1761
+ const stateBefore = readState(sessionId);
1762
+ const judgedSkip = judgeE2eSkip(input, stateBefore);
1683
1763
  const run = {
1684
1764
  unitTestPassed: isTestCommand(cmd) && testsPassed(input),
1685
1765
  e2eRan: isE2ERun(input),
@@ -1696,6 +1776,9 @@ function recordTests() {
1696
1776
  return failedRunId ? applyFailedRun(withWalkthroughSkip, failedRunId) : withWalkthroughSkip;
1697
1777
  };
1698
1778
  const next = commitState(sessionId, record) ?? record(readState(sessionId));
1779
+ if (isWalkthroughGateArmed(next) && !isWalkthroughGateArmed(stateBefore)) {
1780
+ startBackgroundJob("scan-walkthroughs" /* ScanWalkthroughs */, [sessionId], input.cwd);
1781
+ }
1699
1782
  if (judgedSkip?.accepted) recordSkipReasonOnPrs(next, judgedSkip.skip);
1700
1783
  if (judgedSkip && !judgedSkip.accepted) {
1701
1784
  return envelope("PostToolUse", explainRejection(judgedSkip), host);
@@ -1704,7 +1787,7 @@ function recordTests() {
1704
1787
  }
1705
1788
  function recordSkipReasonOnPrs(state, skip) {
1706
1789
  for (const prUrl of state.prsHandled) {
1707
- settleWalkthroughCommentAsSkipped(prUrl, skip.code, skip.detail);
1790
+ startBackgroundJob("settle-walkthrough-skipped" /* SettleWalkthroughSkipped */, [prUrl, skip.code, skip.detail]);
1708
1791
  }
1709
1792
  }
1710
1793
  function skillStages() {
@@ -1778,7 +1861,9 @@ function e2eGate() {
1778
1861
  const state = readState(sessionId);
1779
1862
  const decision = e2eGateDecision(state);
1780
1863
  if (decision.action === "release" /* Release */) {
1781
- for (const prUrl of state.prsHandled) settleWalkthroughCommentAsUnreasoned(prUrl);
1864
+ for (const prUrl of state.prsHandled) {
1865
+ startBackgroundJob("settle-walkthrough-unreasoned" /* SettleWalkthroughUnreasoned */, [prUrl]);
1866
+ }
1782
1867
  return releaseGate("e2eReleased");
1783
1868
  }
1784
1869
  if (decision.action === "none" /* None */) return "{}";
@@ -1811,10 +1896,10 @@ function buildFollowthroughGate() {
1811
1896
  }
1812
1897
  function walkthroughGate() {
1813
1898
  const state = readState(sessionId);
1814
- if (state.e2eRun !== true || state.walkthroughPosted === true || state.walkthroughSkipped === true) {
1815
- return "{}";
1816
- }
1817
- const scan = scanForOwedWalkthroughs(state);
1899
+ if (!isWalkthroughGateArmed(state)) return "{}";
1900
+ const scan = readWalkthroughScan(sessionId);
1901
+ startBackgroundJob("scan-walkthroughs" /* ScanWalkthroughs */, [sessionId], input.cwd);
1902
+ if (!scan || !isWalkthroughScanCurrent(scan, state)) return "{}";
1818
1903
  if (scan.owed.length === 0) {
1819
1904
  if (scan.verified.length > 0) writeState({ ...state, walkthroughPosted: true });
1820
1905
  return "{}";
@@ -1965,4 +2050,35 @@ var handlers = {
1965
2050
  "stage-gate": stageGate,
1966
2051
  "debug-path-gate": debugPathGate
1967
2052
  };
1968
- process.stdout.write((handlers[sub] ?? (() => "{}"))());
2053
+ var jobArgs = process.argv.slice(3);
2054
+ function scanWalkthroughsJob() {
2055
+ const scannedSessionId = jobArgs[0] ?? "unknown";
2056
+ const state = readState(scannedSessionId);
2057
+ const scan = scanForOwedWalkthroughs(state);
2058
+ writeWalkthroughScan(scannedSessionId, { prsHandled: state.prsHandled, owed: scan.owed, verified: scan.verified });
2059
+ return "{}";
2060
+ }
2061
+ function reserveWalkthroughCommentJob() {
2062
+ const [prUrl] = jobArgs;
2063
+ if (prUrl) reserveWalkthroughComment(prUrl);
2064
+ return "{}";
2065
+ }
2066
+ function settleWalkthroughSkippedJob() {
2067
+ const [prUrl, codeArg, detail] = jobArgs;
2068
+ const code = E2E_SKIP_CODES.find((skipCode) => skipCode === codeArg);
2069
+ if (prUrl && code) settleWalkthroughCommentAsSkipped(prUrl, code, detail ?? "");
2070
+ return "{}";
2071
+ }
2072
+ function settleWalkthroughUnreasonedJob() {
2073
+ const [prUrl] = jobArgs;
2074
+ if (prUrl) settleWalkthroughCommentAsUnreasoned(prUrl);
2075
+ return "{}";
2076
+ }
2077
+ var backgroundJobs = {
2078
+ ["scan-walkthroughs" /* ScanWalkthroughs */]: scanWalkthroughsJob,
2079
+ ["reserve-walkthrough-comment" /* ReserveWalkthroughComment */]: reserveWalkthroughCommentJob,
2080
+ ["settle-walkthrough-skipped" /* SettleWalkthroughSkipped */]: settleWalkthroughSkippedJob,
2081
+ ["settle-walkthrough-unreasoned" /* SettleWalkthroughUnreasoned */]: settleWalkthroughUnreasonedJob
2082
+ };
2083
+ var runSubcommand = isBackgroundJob(sub) ? backgroundJobs[sub] : handlers[sub] ?? (() => "{}");
2084
+ process.stdout.write(runSubcommand());
@@ -0,0 +1,98 @@
1
+ #!/usr/bin/env bash
2
+
3
+ set -uo pipefail
4
+
5
+ # The slow session-start upkeep, launched detached by ensure-electron-app.sh at most
6
+ # once a day so no hook waits on it: state GC and the Electron runner install daily,
7
+ # and the npm version lookup every three days. The due stamp and the install's marker
8
+ # are claimed before the work starts, so sessions opening together run it once rather
9
+ # than once each. The hook payload arrives on stdin and is handed on to gc-state.sh.
10
+
11
+ # Epoch mtime of a file, or 0 if unreadable. GNU coreutils (Linux/WSL/Git Bash)
12
+ # need `stat -c %Y`; BSD/macOS need `stat -f %m`. The wrong form doesn't fail
13
+ # cleanly — GNU `stat -f` prints filesystem info to stdout and exits non-zero —
14
+ # so each form is tried alone and accepted only when all-digits, keeping stray
15
+ # text like `File:` out of the caller's arithmetic.
16
+ file_mtime() {
17
+ local f="$1" m
18
+ m=$(stat -c %Y "$f" 2>/dev/null) || m=""
19
+ case "$m" in ''|*[!0-9]*) ;; *) printf '%s\n' "$m"; return 0 ;; esac
20
+ m=$(stat -f %m "$f" 2>/dev/null) || m=""
21
+ case "$m" in ''|*[!0-9]*) ;; *) printf '%s\n' "$m"; return 0 ;; esac
22
+ printf '0\n'
23
+ }
24
+
25
+ # Sourcing with MUGGLE_SESSION_MAINTENANCE_LIB_ONLY=1 exposes the helper above
26
+ # without running the upkeep — used by the unit test.
27
+ if [ -n "${MUGGLE_SESSION_MAINTENANCE_LIB_ONLY:-}" ]; then
28
+ return 0 2>/dev/null || exit 0
29
+ fi
30
+
31
+ maintenance_dir="${BASH_SOURCE[0]%/*}"
32
+ [ "$maintenance_dir" = "${BASH_SOURCE[0]}" ] && maintenance_dir=.
33
+ cache_dir="${HOME}/.cache/muggle"
34
+ electron_marker="${cache_dir}/electron-app-checked"
35
+ electron_ttl=$((24 * 60 * 60))
36
+ version_cache="${cache_dir}/version-check"
37
+ version_ttl=$((3 * 24 * 60 * 60))
38
+ upgrade_available="${cache_dir}/upgrade-available"
39
+
40
+ maintenance_stamp="${cache_dir}/session-maintenance-due"
41
+ # Matches the shortest TTL below, so the stamp never holds back work that is due.
42
+ maintenance_interval=$((24 * 60 * 60))
43
+
44
+ mkdir -p "$cache_dir" 2>/dev/null || true
45
+ now=$(date +%s)
46
+ printf '%s\n' "$((now + maintenance_interval))" > "$maintenance_stamp" 2>/dev/null || true
47
+
48
+ # Lets the other session-start hooks answer first: on Windows a burst of process
49
+ # starts here would slow theirs.
50
+ sleep 2
51
+
52
+ bash "${maintenance_dir}/gc-state.sh" || true
53
+
54
+ is_due() {
55
+ local marker="$1" ttl="$2"
56
+ [ ! -f "$marker" ] && return 0
57
+ [ $((now - $(file_mtime "$marker"))) -ge "$ttl" ]
58
+ }
59
+
60
+ # A hung `muggle setup` (e.g. one blocked by host security policy on Windows)
61
+ # must not leak a ~100 MB orphan per session start, so the attempt is capped.
62
+ if is_due "$electron_marker" "$electron_ttl"; then
63
+ touch "$electron_marker" 2>/dev/null || true
64
+ setup_timeout=""
65
+ command -v timeout >/dev/null 2>&1 && setup_timeout="timeout -k 5 60"
66
+ if command -v muggle >/dev/null 2>&1; then
67
+ ${setup_timeout} muggle setup >/dev/null 2>&1 || true
68
+ else
69
+ ${setup_timeout} npx -y @muggleai/works setup >/dev/null 2>&1 || true
70
+ fi
71
+ fi
72
+
73
+ # The cache holds "installed|latest". It is not claimed up front: a failed lookup
74
+ # leaves it due, so the next start retries rather than waiting out the TTL.
75
+ if is_due "$version_cache" "$version_ttl"; then
76
+ installed=$(muggle --version 2>/dev/null | tr -d '[:space:]' || true)
77
+ latest=$(npm view @muggleai/works version 2>/dev/null | tr -d '[:space:]' || true)
78
+ if [ -n "$installed" ] && [ -n "$latest" ]; then
79
+ printf '%s|%s' "$installed" "$latest" > "$version_cache" 2>/dev/null || true
80
+ fi
81
+ fi
82
+
83
+ # ensure-electron-app.sh announces an upgrade only while this file exists, so the
84
+ # version comparison (sort -V) never runs on the hook's own path.
85
+ cached_versions=$(cat "$version_cache" 2>/dev/null || true)
86
+ installed="${cached_versions%%|*}"
87
+ latest="${cached_versions##*|}"
88
+ newest=""
89
+ if [ -n "$installed" ] && [ -n "$latest" ] && [ "$installed" != "$latest" ]; then
90
+ newest=$(printf '%s\n%s\n' "$installed" "$latest" | sort -V | tail -n1)
91
+ fi
92
+ if [ -n "$newest" ] && [ "$newest" = "$latest" ]; then
93
+ printf '%s|%s' "$installed" "$latest" > "$upgrade_available" 2>/dev/null || true
94
+ else
95
+ rm -f "$upgrade_available" 2>/dev/null || true
96
+ fi
97
+
98
+ exit 0
@@ -7,4 +7,5 @@ Map a red CI check to the local command that reproduces and fixes it. Repo-agnos
7
7
  | lint / format | Run the repo's lint `--fix` / formatter; restage. |
8
8
  | typecheck | Run the typecheck script; read the errors; edit the types. |
9
9
  | unit / test | Run the suite; read the failures; fix the code or the test. |
10
- | out of scope — E2E-in-CI, build/deploy infra, flaky / non-deterministic, or unknown | Do **not** attempt; record for escalation. |
10
+ | `muggle-walkthrough` — the Muggle E2E walkthrough check | In scope. Its check-run summary names each failed or inconclusive case with the failing step and a link to the run; the walkthrough comment's hidden `muggle-e2e-result` record carries the same cases with their test case ids. Repair each, re-run the **whole** E2E suite, and settle the walkthrough comment with the new result — editing the comment re-runs the check. A summary saying the comment is still empty means no run was ever posted: run the suite and post it. |
11
+ | out of scope — any other E2E-in-CI, build/deploy infra, flaky / non-deterministic, or unknown | Do **not** attempt; record for escalation. |
@@ -20,3 +20,12 @@ Classify for the watcher:
20
20
  - **green** — every row `pass` / `skipping`, or no rows at all.
21
21
 
22
22
  The fix-ci dispatch carries the `name`s of the red rows. `gh pr checks` exits non-zero when any check fails — capture output regardless of exit code.
23
+
24
+ A check that publishes its own verdict (the `muggle-walkthrough` check run) says why it failed in its output, not in a job log. Read the newest one on the head SHA:
25
+
26
+ ```bash
27
+ gh api "repos/<owner>/<repo>/commits/<head-sha>/check-runs?check_name=<name>" \
28
+ --jq '.check_runs | sort_by(.completed_at) | last | {conclusion, completed_at, summary: .output.summary}'
29
+ ```
30
+
31
+ `completed_at` is how a caller tells a fresh verdict from the one it is repairing.
@@ -1,6 +1,6 @@
1
1
  # Fix-CI (watcher-dispatched)
2
2
 
3
- Resolve red CI on a PR's head — lint/format, typecheck, and failing unit tests — verifying green before re-push. A dumb-pipe dispatch like address-reviews: the executor receives a PR URL, slug, and the failing check names, and fixes them — it owns the fix, not the decision to dispatch.
3
+ Resolve red CI on a PR's head — lint/format, typecheck, failing unit tests, and a red Muggle E2E walkthrough check — verifying green before re-push. A dumb-pipe dispatch like address-reviews: the executor receives a PR URL, slug, and the failing check names, and fixes them — it owns the fix, not the decision to dispatch.
4
4
 
5
5
  ## Turn preamble
6
6
 
@@ -24,12 +24,22 @@ Check out the PR branch in the session's working tree (per `state.md`). Capture
24
24
 
25
25
  ### Step 2 — Map each failing check to a local command
26
26
 
27
- Per [`../_shared/ci-check-to-command.md`](../_shared/ci-check-to-command.md). Fix the in-scope checks in the working tree; record out-of-scope checks for escalation (Step 6).
27
+ Per [`../_shared/ci-check-to-command.md`](../_shared/ci-check-to-command.md). Fix the in-scope checks in the working tree; record out-of-scope checks for escalation (Step 6). A red `muggle-walkthrough` check takes Step 2.5.
28
+
29
+ ### Step 2.5 — Red E2E walkthrough check
30
+
31
+ 1. **Read why.** Fetch the check run's summary per [`../_shared/vcs/github/pr-checks.md`](../_shared/vcs/github/pr-checks.md) and record its `completed_at`. It names every failed or inconclusive case, its failing step, and its run. Take the test case ids from the walkthrough comment's hidden `<!-- muggle-e2e-result:v1 {…} -->` record — the newest comment carrying one.
32
+ 2. **Repair each case** per [`e2e-repair.md`](e2e-repair.md) Steps 1–3: root-cause to a bucket, then retry, regenerate, or repair the code. This stage is unattended, so a case whose disposition is `ask` is out of scope — record it for Step 6 and never open a picker.
33
+ 3. **Re-run the whole suite** through [`e2e-acceptance.md`](e2e-acceptance.md) — every test case the walkthrough listed, passing ones included. The walkthrough is replaced wholesale and the check judges all of it, so a re-run scoped to the failures would post a walkthrough that drops the cases that passed.
34
+ 4. **Order the settle after the push.** If Step 2 changed code, run Steps 3–4 below first, so the new head carries the fix. Then settle the walkthrough comment with the re-run's report via [`../muggle-pr-visual-walkthrough/SKILL.md`](../muggle-pr-visual-walkthrough/SKILL.md) Mode A; editing the comment re-runs the check against the head. With no code change (only retries and regenerations) there is nothing to push — the comment edit alone re-runs the check.
35
+ 5. **Wait for the fresh verdict** before Step 5's respawn: poll the check run until one completes later than the `completed_at` recorded in item 1, for up to 5 minutes. A watcher respawned sooner reads the stale red verdict and spends a fix attempt on a run already repaired. On timeout, respawn anyway — the per-SHA budget still bounds it.
36
+
37
+ An empty-comment failure (no run ever posted) skips items 1–2: run the suite and settle the comment. Under a `unit-only` or `skip` validation in `state.md`, settle it with the verified skip code instead.
28
38
 
29
39
  ### Step 3 — Verify before push
30
40
 
31
41
  - Build (typecheck + lint on the changed surface) + unit suite must pass.
32
- - Run E2E (per [`../muggle-preferences/preference-gates/autoE2ETest.md`](../muggle-preferences/preference-gates/autoE2ETest.md)) only if the fix touched app logic; lint/format-only fixes skip E2E.
42
+ - Run E2E (per [`../muggle-preferences/preference-gates/autoE2ETest.md`](../muggle-preferences/preference-gates/autoE2ETest.md)) only if the fix touched app logic; lint/format-only fixes skip E2E. A Step 2.5 repair always runs the full suite.
33
43
 
34
44
  A fix that can't be made green locally is not pushed → Step 6.
35
45
 
@@ -57,5 +67,5 @@ Emit one `muggle-do:cycle` event ([`../_shared/telemetry-events/muggle-do-cycle.
57
67
 
58
68
  ## Guardrails
59
69
 
60
- - Max 3 fix attempts per SHA; out-of-scope checks escalate immediately rather than churn.
70
+ - Max 3 fix attempts per SHA; out-of-scope checks escalate immediately rather than churn. A walkthrough repair that pushes nothing keeps the head SHA, so the same budget bounds it.
61
71
  - No PR replies; the fix commit is the response.
@@ -20,6 +20,8 @@ Forward pipeline's Stage 7. Invoked by `/muggle-do` after stages 1–6 of a fres
20
20
 
21
21
  1. **Sync with the base:** run [`../../_shared/sync-branch-with-base.md`](../../_shared/sync-branch-with-base.md) with `base` set to the PR target recorded in `state.md` — gated by [`autoRebase`](../../muggle-preferences/preference-gates/autoRebase.md), fires only when `behind > 0`. The branch is not on the remote yet, so the rebase lands without a force-push. Sync here rather than trusting stage 6: a `unit-only` or `skip` run never reaches the E2E stage's sync at all, and on a run that does, the base moves freely while stages 3–6 build and test. If the sync escalates — conflicts under `autoResolveConflicts=never`, or a resolution that fails the verify-or-rollback gate — stop and report; never open a PR on a tree that did not verify.
22
22
 
23
+ 1.5. **CI check:** gate [`autoInstallCiWorkflow`](../../muggle-preferences/preference-gates/autoInstallCiWorkflow.md) — fires only on a GitHub repo whose tree lacks `.github/workflows/muggle-walkthrough.yml`. On `always`, or `CI check: add` recorded by pre-flight, run `muggle ci-install` in the working tree and commit the workflow as `ci: add the Muggle E2E walkthrough check`, so it ships in this PR. On `never` or `CI check: skip`, leave CI alone.
24
+
23
25
  2. **Push:** Execute per [`../../_shared/vcs/common/push-to-branch.md`](../../_shared/vcs/common/push-to-branch.md) — the tool-agnostic instruction for pushing commits (handles the signing gate and directs to provider-specific recipes).
24
26
 
25
27
  3. **Title** (under 70 chars):
@@ -36,6 +36,7 @@ Before asking anything, gather every fact you can resolve without the user:
36
36
  - Is the current checkout already a worktree? `git -C <repo> rev-parse --is-inside-work-tree` plus `git -C <repo> worktree list`.
37
37
  - How many commits behind `origin/<default>`? `git -C <repo> fetch origin && git -C <repo> rev-list --count "HEAD..origin/$(git -C <repo> symbolic-ref refs/remotes/origin/HEAD --short | sed 's|origin/||')"`.
38
38
  10. **`autoE2ETest` preference.** Read the session-context preferences line. Unset → treat as `always` (this gate's default — opposite of the system-wide `ask` default). `ask` → surface in Q13. `always` → no question; stage 6 runs.
39
+ 11. **CI check present?** For each GitHub repo, whether `.github/workflows/muggle-walkthrough.yml` exists on its default branch. Missing and [`autoInstallCiWorkflow`](../muggle-preferences/preference-gates/autoInstallCiWorkflow.md) resolves to `ask` → surface in Q14.
39
40
 
40
41
  ## The consolidated questionnaire
41
42
 
@@ -58,6 +59,7 @@ Present **one `AskUserQuestion`** (or the platform's structured-selection equiva
58
59
  11. **Worktree for this change?** — gate: [`autoUseWorktree`](../muggle-preferences/preference-gates/autoUseWorktree.md). Options: create a dedicated worktree (per [`../_shared/use-worktrees.md`](../_shared/use-worktrees.md)), or work in the current checkout.
59
60
  12. **Sync onto the base branch first?** — gate: [`autoRebase`](../muggle-preferences/preference-gates/autoRebase.md), only if `behind > 0`. The answer governs every sync this cycle, not just one: before the dev server / E2E, and again immediately before stage 7 pushes. Options: sync with the base, or run as-is.
60
61
  13. **Run E2E at the end of every cycle?** — gate: [`autoE2ETest`](../muggle-preferences/preference-gates/autoE2ETest.md), only if step 10's silent detection resolved to `ask`. Options: always run stage 6, or ask each cycle.
62
+ 14. **Add the Muggle E2E check to this repo's CI?** — gate: [`autoInstallCiWorkflow`](../muggle-preferences/preference-gates/autoInstallCiWorkflow.md), only if step 11 found the workflow missing and the gate resolved to `ask`. Record the answer in `state.md` as `CI check: add | skip`; stage 7 acts on it.
61
63
 
62
64
  If fewer than two of the above need the user, still gather them in a single turn — never open a second round.
63
65
 
@@ -67,6 +67,7 @@ When invoked with the directive (PR URL + slug + review ids), routes to [`../do/
67
67
  | `autoE2ETest` | Stage 6 — run E2E every cycle (default `always`), or fold into pre-flight |
68
68
  | `autoResolveConflicts` | On rebase conflict — `always` resolves autonomously behind a verify-or-rollback gate, `never` aborts + escalates; resolve from the configured preference (don't assume a default) |
69
69
  | `autoRouteBuildToMuggleDo` | Front-door guardrail — route build/implement/fix requests through this pipeline (build delegated to superpowers); fired by the UserPromptSubmit guardrail, default `ask` |
70
+ | `autoInstallCiWorkflow` | Stage 7 — add the `muggle-walkthrough` CI check to a GitHub repo that lacks it, shipped in the PR; `ask` folds into pre-flight, default `ask` |
70
71
 
71
72
  `autoUseWorktree`, `autoRebase`, `autoResolveConflicts`, `autoCreatePR`, `autoCleanup`, `postPRVisualWalkthrough` fire from per-stage files.
72
73
 
@@ -31,6 +31,7 @@ For each option: label = key name, description = first paragraph of `preference-
31
31
  - `multiSelect: true`, `header: "Suggestions"` — `suggestRelatedUseCases`, `suggestRelatedTestCases`
32
32
  - `multiSelect: true`, `header: "PR"` — `postPRVisualWalkthrough`, `autoCreatePR`, `autoWatchPR`, `autoRouteBuildToMuggleDo`
33
33
  - `multiSelect: true`, `header: "Branch hygiene"` — `autoUseWorktree`, `autoRebase`, `autoCleanup`, `autoResolveConflicts`
34
+ - `multiSelect: false`, `header: "CI check"` — `autoInstallCiWorkflow`. Options: `Always — add it to every repo Muggle works in` (`always`), `Ask in each repo` (`ask` — default), `Never` (`never`).
34
35
  - `multiSelect: false`, `header: "E2E acceptance"` — `autoE2ETest`. Options: `Always run Stage 6 at the end` (`always` — default), `Ask each cycle` (`ask`). No `never` option.
35
36
  - `multiSelect: false`, `header: "Default mode"` — `defaultExecutionMode`. Options: `Local — run on my computer` (`local`), `Remote — run in the Muggle Test cloud` (`remote`), `Ask each time` (don't change).
36
37
  - `multiSelect: false`, `header: "PR watcher"` — `watcherLifetime`. Options: `Retire after 1 day` (`1d`), `Retire after 7 days` (`7d` — default), `Never retire` (`never`).
@@ -0,0 +1,13 @@
1
+ # `autoInstallCiWorkflow`
2
+
3
+ Controls whether Muggle adds `.github/workflows/muggle-walkthrough.yml` — the CI check that fails a pull request whose E2E walkthrough is missing or reports a failed or inconclusive test case — to a GitHub repository that lacks it. Fires when `muggle init` runs inside such a repository, and when `/muggle-do` is about to open a PR from one. Never fires where the workflow already exists or the repository is not on GitHub. Substitute `{repo}`.
4
+
5
+ **Picker 1** — header `CI check`, question `"Add the Muggle E2E check to {repo}'s CI? Pull requests then fail while their walkthrough is missing or reports a failed test."`
6
+ - `Add it` — `Run muggle ci-install and ship the workflow with this change.` → `always`
7
+ - `Ask me next time` — `Decide per repository.` → `ask`
8
+ - `Skip — leave CI alone` — `Don't add the workflow; muggle ci-install adds it later.` → `never`
9
+
10
+ **Silent action**
11
+ - `always` → `Adding the Muggle E2E check to {repo}'s CI`
12
+ - `ask` → `Asking about the Muggle E2E check for {repo}`
13
+ - `never` → `Leaving {repo}'s CI without the Muggle E2E check`