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

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.
@@ -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
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "release": "5.18.0",
3
- "buildId": "run-157-1",
4
- "commitSha": "981415e27e3c996535a0249c6a20dd74a9860c9d",
5
- "buildTime": "2026-10-21T08:31:54Z",
3
+ "buildId": "run-158-1",
4
+ "commitSha": "63161b4754c1a27b33ccac64c90168d2f8bb17ae",
5
+ "buildTime": "2026-10-21T08:46:44Z",
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.22.0-staging.157",
4
+ "version": "5.22.0-staging.158",
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",
@@ -50,6 +50,7 @@
50
50
  "test": "vitest run",
51
51
  "test:watch": "vitest",
52
52
  "test:codex": "vitest run src/test/codex",
53
+ "test:hook-runtime": "vitest run --config vitest.hook-runtime.config.ts",
53
54
  "test:gates:behavioral": "tsx internal/skill-gate-eval/src/run.ts",
54
55
  "test:agents:behavioral": "tsx internal/agent-gate-eval/src/run.ts",
55
56
  "eval:studio-gen": "tsx internal/studio-gen-eval/src/run.ts",
@@ -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.22.0-staging.157",
4
+ "version": "5.22.0-staging.158",
5
5
  "author": {
6
6
  "name": "Muggle AI",
7
7
  "email": "support@muggle-ai.com"
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "muggle",
3
- "version": "5.22.0-staging.157",
3
+ "version": "5.22.0-staging.158",
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.22.0-staging.157",
5
+ "version": "5.22.0-staging.158",
6
6
  "author": {
7
7
  "name": "Muggle AI",
8
8
  "email": "support@muggle-ai.com"
@@ -28,7 +28,7 @@ A recorder that *clears* an obligation — a walkthrough posted, a failure diagn
28
28
 
29
29
  Each guardrail is a bash gate script in `../scripts/` holding a `guardrail_wants` pre-filter and the `guardrails.mjs` subcommand it feeds; the bundled `../scripts/guardrails.mjs` holds the decision logic (built from `src/guardrails/`, vitest-covered). The busy events — a shell command before and after it runs, and every turn end — register one `guardrail-dispatch.sh` command listing their gates, which reads the payload once, asks every gate's pre-filter in that one process, and starts Node once (`guardrails.mjs run <gates...>`) for just the gates that could fire, merging their responses. Rarer events call a gate script directly. Per-session state in `~/.muggle-ai/guardrails/<session_id>.json` tracks what fired. Any *failure* degrades to `{}` (allow) — a gate blocks only by an explicit, tested decision, never by accident; `guardrail-lib.sh` is the one place that falls back, and `run` isolates gates from each other.
30
30
 
31
- Pre-filters are bash builtins only (`guardrail-lib.sh`), so an irrelevant event starts no process at all. A gate that has spent its block budget stamps a `<gate>Released` flag, which its wrapper then pre-filters on — without it a released gate keeps cold-starting Node on every remaining turn end to answer `{}`, and the walkthrough gate keeps making provider calls to do it. That pre-filter is a second, looser copy of what `guardrails.mjs` matches, and it is the one place a guardrail can fail *silently*: a payload it drops — a skip marker, a reopen line, a comment edit — reaches no recorder, and the gate keeps demanding an action the user already took. Over-matching is free; under-matching is a dead escape hatch. `src/test/guardrails/hook-prefilter.test.ts` pins every payload each subcommand acts on against the wrapper guarding it, and derives the skip-marker tokens from source so a new marker is covered the moment it exists.
31
+ Pre-filters are bash builtins only (`guardrail-lib.sh`), so an irrelevant event starts no process at all. A gate that has spent its block budget stamps a `<gate>Released` flag, which its wrapper then pre-filters on — without it a released gate keeps cold-starting Node on every remaining turn end to answer `{}`, and the walkthrough gate keeps queuing provider scans to do it. That pre-filter is a second, looser copy of what `guardrails.mjs` matches, and it is the one place a guardrail can fail *silently*: a payload it drops — a skip marker, a reopen line, a comment edit — reaches no recorder, and the gate keeps demanding an action the user already took. Over-matching is free; under-matching is a dead escape hatch. `src/test/guardrails/hook-prefilter.test.ts` pins every payload each subcommand acts on against the wrapper guarding it, and derives the skip-marker tokens from source so a new marker is covered the moment it exists.
32
32
 
33
33
  ## Guardrails
34
34
 
@@ -47,7 +47,7 @@ Pre-filters are bash builtins only (`guardrail-lib.sh`), so an irrelevant event
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
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) |
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) |
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) |
53
53
  | `Stop` | `guardrail-comment-reply-gate.sh` | **enforce** | this session claimed a review thread and left one of its comments uncovered | — | **block** the turn until each comment gets its threaded reply per `do/per-comment-replies.md` or a `MUGGLE_REPLY_SKIP: <comment-id> <reason>` marker defers it (releases after 3 blocks). The claim is the signal, not a push, so a round that answers a question with no code change is caught too; a thread another session claimed never blocks this one |
@@ -74,14 +74,18 @@ Codex runs a plugin's hooks only once the user trusts them: it asks at startup (
74
74
 
75
75
  The nudge counts only slots **this session owns**, and reports the rest as orphans it will not act on — ownership and the recovery rules it gates are defined in [`reconcile`](../skills/muggle-pr-followup/reconcile.md). Nothing owned and nothing orphaned → it emits nothing. A pure directory scan (no `gh`, no writes), so it's cheap enough for every session start.
76
76
 
77
+ ## Session-start upkeep
78
+
79
+ `SessionStart` (`scripts/ensure-electron-app.sh`) injects the session context and nothing slower: it reads the caches the upkeep leaves and resolves preferences in one Node process. The upkeep itself — the Electron runner install (`muggle setup`, capped at 60 s), the npm version lookup behind the upgrade notice, and the state GC below — runs in `scripts/session-maintenance.sh`, which the hook launches detached at most once a day. Its `~/.cache/muggle/session-maintenance-due` stamp holds the epoch second it next comes due, so every other start launches nothing; the stamp is written before the work starts, so sessions opening together run it once.
80
+
77
81
  ## Session-start state GC
78
82
 
79
- `SessionStart` (`scripts/gc-state.sh`) — prunes ephemeral state that nothing else garbage-collects, so it doesn't grow without bound (the per-session guardrails files and finalized watcher slots otherwise accumulate one-per-session forever). Collection is keyed on **inactivity, never creation age**, so state a long-lived session still relies on is never deleted out from under it:
83
+ `scripts/gc-state.sh`, run by the upkeep — prunes ephemeral state that nothing else garbage-collects, so it doesn't grow without bound (the per-session guardrails files and finalized watcher slots otherwise accumulate one-per-session forever). Collection is keyed on **inactivity, never creation age**, so state a long-lived session still relies on is never deleted out from under it:
80
84
 
81
- - `~/.muggle-ai/guardrails/*.json` (one per session) is pruned only after 14 days of **no activity**. An in-use session keeps rewriting its file (`guardrails.mjs` on every guarded tool call) and this hook refreshes it on every resume, so its mtime tracks last activity — a session that runs for months stays live indefinitely, and only one that has genuinely gone quiet for the whole window (i.e. ended) is collected.
85
+ - `~/.muggle-ai/guardrails/*.json` (one per session, plus its walkthrough-scan sidecar) is pruned only after 14 days of **no activity**. An in-use session keeps rewriting its file (`guardrails.mjs` on every guarded tool call) and `ensure-electron-app.sh` refreshes it on every resume, so its mtime tracks last activity — a session that runs for months stays live indefinitely, and only one that has genuinely gone quiet for the whole window (i.e. ended) is collected.
82
86
  - Finalized watcher slots (`result.md` present) are pruned 30 days after finalize; their `followup.log` is forensic-only. An **open** slot — a PR watched for any length of time — has no `result.md` and is never touched.
83
87
 
84
- Both windows are overridable (`MUGGLE_GUARDRAILS_TTL_DAYS`, `MUGGLE_SLOT_TTL_DAYS`). TTL-gated to once per day via a `~/.cache/muggle/state-gc-checked` marker (the current-session refresh runs every start regardless); silent and best-effort, never blocks session start. Never touches an open slot or the current session's own state.
88
+ Both windows are overridable (`MUGGLE_GUARDRAILS_TTL_DAYS`, `MUGGLE_SLOT_TTL_DAYS`). TTL-gated to once per day via a `~/.cache/muggle/state-gc-checked` marker; silent and best-effort. It refreshes the current session's own state before sweeping, so never collects it, and never touches an open slot.
85
89
 
86
90
  ## Footprint caps
87
91
 
@@ -93,7 +97,11 @@ Every hook here fires on every tool call, prompt or turn end in every open sessi
93
97
  | Programs started beyond each hook's own launch on an irrelevant event | 0 (Stop: 1, a transcript `tail` until the capability-claim gate has nudged; bash cannot seek) |
94
98
  | `node`, `gh`, `python` on that path | 0 |
95
99
  | Median wall time of one irrelevant firing, Linux/macOS | 100 ms |
96
- | Hook commands in the whole manifest | 15 |
97
- | Hook timeout | declared on every hook; 30 s, SessionStart 120 s |
100
+ | Hook commands in the whole manifest | 14 |
101
+ | Hook timeout | declared on every hook; 1 s each, 2 s summed over the hooks one firing launches |
102
+ | Median wall time of each hook, on every scenario in `HOOK_RUNTIME_SCENARIOS`, every platform | 1 s |
103
+ | Summed median wall time of the hooks one firing launches | 2 s |
98
104
 
99
105
  Counts are exec counts, so they are identical on every runner. Every count is exact: CI fails when a change exceeds a limit, and also when it beats one until `footprint/constants.ts` is lowered to match, so a gain cannot be given back later.
106
+
107
+ The harness kills a hook at its timeout, so the 1 s timeout is the hard cap; the runtime scenarios hold each hook inside it. They fire every `hooks.json` group — a group no scenario fires fails CI — on its irrelevant path and on the payloads that make its gates do real work, with `gh`, `muggle`, `npm`, `npx`, `curl` and `wget` replaced by stand-ins that stall for 5 s, so a hook that waits on the network or an install fails there rather than on a user's machine. Work that has to wait on the network leaves the hook path: the walkthrough comment's reserve and settle writes and the walkthrough gate's provider scan run as detached `guardrails.mjs` background jobs, and every other child a gate starts (`git`, the dev-server probe) is cut to what is left of a 600 ms allowance (`src/hook-budget/`).
@@ -9,7 +9,7 @@
9
9
  "type": "command",
10
10
  "command": "env MUGGLE_HOOK_HOST=codex bash \"${CLAUDE_PLUGIN_ROOT}/scripts/ensure-electron-app.sh\"",
11
11
  "async": false,
12
- "timeout": 120,
12
+ "timeout": 10,
13
13
  "commandWindows": "node \"${CLAUDE_PLUGIN_ROOT}\\scripts\\codex-hook-windows.mjs\" \"${CLAUDE_PLUGIN_ROOT}/scripts/ensure-electron-app.sh\""
14
14
  },
15
15
  {
@@ -18,13 +18,6 @@
18
18
  "async": false,
19
19
  "timeout": 10,
20
20
  "commandWindows": "node \"${CLAUDE_PLUGIN_ROOT}\\scripts\\codex-hook-windows.mjs\" \"${CLAUDE_PLUGIN_ROOT}/scripts/reconcile-stale-watchers.sh\""
21
- },
22
- {
23
- "type": "command",
24
- "command": "env MUGGLE_HOOK_HOST=codex bash \"${CLAUDE_PLUGIN_ROOT}/scripts/gc-state.sh\"",
25
- "async": false,
26
- "timeout": 10,
27
- "commandWindows": "node \"${CLAUDE_PLUGIN_ROOT}\\scripts\\codex-hook-windows.mjs\" \"${CLAUDE_PLUGIN_ROOT}/scripts/gc-state.sh\""
28
21
  }
29
22
  ]
30
23
  }
@@ -63,7 +56,7 @@
63
56
  "type": "command",
64
57
  "command": "env MUGGLE_HOOK_HOST=codex bash \"${CLAUDE_PLUGIN_ROOT}/scripts/guardrail-dispatch.sh\" guardrail-pr-opened.sh guardrail-record-tests.sh guardrail-pr-terminal.sh guardrail-record-stage-signals.sh guardrail-record-comment-replies.sh guardrail-record-stage-read.sh",
65
58
  "async": false,
66
- "timeout": 25,
59
+ "timeout": 10,
67
60
  "commandWindows": "node \"${CLAUDE_PLUGIN_ROOT}\\scripts\\codex-hook-windows.mjs\" \"${CLAUDE_PLUGIN_ROOT}/scripts/guardrail-dispatch.sh\" guardrail-pr-opened.sh guardrail-record-tests.sh guardrail-pr-terminal.sh guardrail-record-stage-signals.sh guardrail-record-comment-replies.sh guardrail-record-stage-read.sh"
68
61
  }
69
62
  ]
@@ -124,7 +117,7 @@
124
117
  "type": "command",
125
118
  "command": "env MUGGLE_HOOK_HOST=codex bash \"${CLAUDE_PLUGIN_ROOT}/scripts/guardrail-dispatch.sh\" guardrail-e2e-gate.sh guardrail-terminal-gate.sh guardrail-watch-gate.sh guardrail-build-followthrough-gate.sh guardrail-walkthrough-gate.sh guardrail-comment-reply-gate.sh guardrail-stage-gate.sh guardrail-debug-path-gate.sh guardrail-capability-claim.sh",
126
119
  "async": false,
127
- "timeout": 30,
120
+ "timeout": 10,
128
121
  "commandWindows": "node \"${CLAUDE_PLUGIN_ROOT}\\scripts\\codex-hook-windows.mjs\" \"${CLAUDE_PLUGIN_ROOT}/scripts/guardrail-dispatch.sh\" guardrail-e2e-gate.sh guardrail-terminal-gate.sh guardrail-watch-gate.sh guardrail-build-followthrough-gate.sh guardrail-walkthrough-gate.sh guardrail-comment-reply-gate.sh guardrail-stage-gate.sh guardrail-debug-path-gate.sh guardrail-capability-claim.sh"
129
122
  }
130
123
  ]