@muggleai/works 5.27.0-staging.235 → 5.27.0-staging.237

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,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.27.0-staging.235",
4
+ "version": "5.27.0-staging.237",
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.27.0-staging.235",
7
+ "@muggleai/works@5.27.0-staging.237",
8
8
  "serve"
9
9
  ],
10
10
  "env": {
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "muggle",
3
- "version": "5.27.0-staging.235",
3
+ "version": "5.27.0-staging.237",
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.27.0-staging.235",
5
+ "version": "5.27.0-staging.237",
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.27.0-staging.235",
7
+ "@muggleai/works@5.27.0-staging.237",
8
8
  "serve"
9
9
  ]
10
10
  }
@@ -30,7 +30,7 @@ Each guardrail is a bash gate script in `../scripts/` holding a `guardrail_wants
30
30
 
31
31
  Every `hooks.json` command enters through `../scripts/hook-entry.sh`, with the hook's script and arguments set as positional parameters first: `set -- guardrail-dispatch.sh guardrail-e2e-gate.sh …; . "${CLAUDE_PLUGIN_ROOT}/scripts/hook-entry.sh"`. Claude Code runs a hook command through Git Bash on Windows and through `/bin/sh` elsewhere. Inside Git Bash the entry sources the script into that same shell, so a hook costs the one Git Bash start Claude Code makes rather than a second `bash` with its own MSYS runtime init — measured at 0.3–1.2 s per firing on a loaded box. Anywhere else `/bin/sh` may be dash, so the entry is POSIX sh and hands the script to a bash of its own, as `bash "<script>"` did. A gate script tells it is the hook's own script — not one `guardrail-dispatch.sh` sourced for its pre-filter — through `guardrail_is_hook_script`, which reads the script path the entry records, or `$0` when bash ran the script.
32
32
 
33
- Pre-filters are bash builtins only (`guardrail-lib.sh`), so an irrelevant event starts no process at all. A pre-filter reads only the payload fields its subcommand judges (`guardrail_fields_match`: the command, the tool's name, the path read, the prompt), never the whole payload — a tool's output or a read file's contents would otherwise start Node whenever they merely mention a trigger. The PreToolUse deny gates go one step further: Claude Code's `if` rules (`Bash(*gh *)`, `Bash(*glab *)` and their `PowerShell` twins) launch them only for a command naming `gh` or `glab`, so every other shell call starts no hook process. A rule's leading `*` is load-bearing: it is what reaches a `gh` inside `bash -c "…"`. 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.
33
+ Pre-filters are bash builtins only (`guardrail-lib.sh`), so an irrelevant event starts no process at all. A pre-filter reads only the payload fields its subcommand judges (`guardrail_fields_match`: the command, the tool's name, the path read, the prompt), never the whole payload — a tool's output or a read file's contents would otherwise start Node whenever they merely mention a trigger. The PreToolUse deny gates go one step further: Claude Code's `if` rules (`Bash(*gh *)`, `Bash(*glab *)` and their `PowerShell` twins) launch them only for a command naming `gh` or `glab`, so every other shell call starts no hook process. A rule's leading `*` is load-bearing: it is what reaches a `gh` inside `bash -c "…"`. The shell recorders after a `PowerShell` call are gated the same way, one rule per trigger a recorder acts on (`*gh pr *`, `*gh api *`, `*glab *`, `*pr-watch-*`, the test runners, `*MUGGLE_*`, `*.md*`, and the thread and reply paths a non-`gh` client names); Claude Code matches PowerShell commands ignoring case and sees into script blocks. After a `Bash` call they run on every command (`if: "Bash"`): Claude Code's Bash parser gives up on a command it cannot read statically — an unresolved `$VAR`, a `$(…)` argument, a loop over one, about a sixth of real commands — and then launches every `if` variant, so a rule per trigger would start more processes than it saves. Since one call can launch several variants at once, the dispatcher claims the call by its `tool_use_id` (a noclobber file under `~/.muggle-ai/guardrails/claims/`) before Node starts, and only the launch holding the claim runs it; the rest answer `{}` in-shell. 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.
34
34
 
35
35
  ## Guardrails
36
36
 
@@ -66,7 +66,7 @@ Codex runs Claude Code-format plugin hooks, from `codex-hooks.json` rather than
66
66
  - **Host stamp.** Codex exports `CLAUDE_PLUGIN_ROOT` to plugin hooks for compatibility, so nothing in the environment tells a guardrail it is not in Claude Code. Every command runs under `env MUGGLE_HOOK_HOST=codex`, and the guardrails word their instructions for Codex (`$muggle:muggle-test`, not `/muggle:muggle-test`).
67
67
  - **Tool names.** A matcher naming a Claude Code tool becomes the Codex tool that plays its part — `AskUserQuestion` → `request_user_input` — and a group whose tools Codex lacks is dropped: Codex reports every shell call as `Bash`, opens files and skills through the shell, and delivers a background command's output as that command's own `Bash` event, so `PowerShell`, `Read`, `Skill` and `Monitor` never fire. An MCP tool reaches a Codex hook as `mcp__muggle__<tool>` with every character outside `[A-Za-z0-9_]` turned into `_` (`mcp__muggle__muggle_local_execute_replay`), so the MCP matchers are respelled; the wrappers' pre-filters and the guardrails' own tool checks accept either spelling.
68
68
  - **Windows.** Codex runs `commandWindows` through the session shell — PowerShell, or cmd.exe as a fallback — so every hook also gets one that starts with a bare `node` (both shells parse it alike; a quoted path there is a PowerShell syntax error) and hands the same script to Git Bash through `../scripts/codex-hook-windows.mjs`. It looks for Git Bash beside `git.exe`, then in the default install paths; `MUGGLE_HOOK_BASH` names one it would not find. With no Git Bash the launcher prints `{}` and succeeds — the same allow-by-default every guardrail falls back to.
69
- - **No `if` rules.** Codex has no counterpart to Claude Code's `if`, so the rule is dropped and the identical commands its variants leave collapse into one: under Codex the deny gates run on every shell call and their in-shell pre-filters decide.
69
+ - **No `if` rules.** Codex has no counterpart to Claude Code's `if`, so the rule is dropped and the identical commands its variants leave collapse into one: under Codex the deny gates and the shell recorders each run once on every shell call and their in-shell pre-filters decide.
70
70
  - **No hook entry.** Codex starts every command as a process — `env` stamps the host, and on Windows the `node` launcher hands the script to Git Bash — so there is no shell to source into, and each Codex command names its script directly: `bash "<script>" <args>`.
71
71
 
72
72
  What Codex sends differs too, and the guardrails read either shape: a shell result arrives as the bare output string (normalized to `tool_response.output` in `hookInput.ts`), with no exit code; the Stop payload carries the closing message as `last_assistant_message`, which the capability-claim gate judges in place of the transcript, whose format is not Claude Code's; and a stage file opened with `cat` or `sed -n` counts as read, since there is no `Read` tool. With no structured question in Codex's default mode, a turn that closes on a question to the user is the post-merge offer there — under Codex only.
@@ -90,6 +90,7 @@ The nudge counts only slots **this session owns**, and reports the rest as orpha
90
90
  `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:
91
91
 
92
92
  - `~/.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.
93
+ - `~/.muggle-ai/guardrails/claims/*`, the dispatcher's one-per-call claims, are pruned an hour after the call: only the launches Claude Code starts together for that call ever read one.
93
94
  - 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.
94
95
 
95
96
  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.
@@ -100,13 +101,13 @@ Every hook here fires on every tool call, prompt or turn end in every open sessi
100
101
 
101
102
  | Cap | Limit |
102
103
  | :-- | :-- |
103
- | Hook commands an irrelevant event launches per busy slot (PostToolUse on `Bash` and `Read`, Stop, UserPromptSubmit) | 1 (PreToolUse on `Bash`: 0, its `if` rules launch nothing for a command naming neither `gh` nor `glab`) |
104
+ | Hook commands an irrelevant event launches per busy slot (PostToolUse on `Bash` and `Read`, Stop, UserPromptSubmit) | 1 (PreToolUse on `Bash` and PostToolUse on `PowerShell`: 0, their `if` rules launch nothing for a command naming no trigger) |
104
105
  | A hook's own `bash` launch inside Git Bash, where `hook-entry.sh` runs the script in place | 0 (elsewhere 1 per command) |
105
106
  | 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) |
106
107
  | `node`, `gh`, `python` on that path | 0 |
107
108
  | Median wall time of one irrelevant firing, Linux/macOS | 100 ms |
108
109
  | Distinct hook commands in the whole manifest (a command's `if` variants count once) | 13 |
109
- | Hook timeout | declared on every hook; 1 s each, 2 s summed over the hooks one firing launches; SessionStart 5 s each, 10 s summed |
110
+ | Hook timeout | declared on every hook; 1 s each, 2 s summed over the hooks one firing launches, a command's `if` variants counted once since they start together and one claims the call; SessionStart 5 s each, 10 s summed |
110
111
  | Median wall time of each hook, on every scenario in `HOOK_RUNTIME_SCENARIOS`, every platform | 1 s |
111
112
  | Summed median wall time of the hooks one firing launches | 2 s |
112
113
 
@@ -71,6 +71,98 @@
71
71
  "hooks": [
72
72
  {
73
73
  "type": "command",
74
+ "if": "Bash",
75
+ "command": "set -- 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; . \"${CLAUDE_PLUGIN_ROOT}/scripts/hook-entry.sh\"",
76
+ "async": false,
77
+ "timeout": 1
78
+ },
79
+ {
80
+ "type": "command",
81
+ "if": "PowerShell(*gh pr *)",
82
+ "command": "set -- 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; . \"${CLAUDE_PLUGIN_ROOT}/scripts/hook-entry.sh\"",
83
+ "async": false,
84
+ "timeout": 1
85
+ },
86
+ {
87
+ "type": "command",
88
+ "if": "PowerShell(*gh api *)",
89
+ "command": "set -- 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; . \"${CLAUDE_PLUGIN_ROOT}/scripts/hook-entry.sh\"",
90
+ "async": false,
91
+ "timeout": 1
92
+ },
93
+ {
94
+ "type": "command",
95
+ "if": "PowerShell(*glab *)",
96
+ "command": "set -- 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; . \"${CLAUDE_PLUGIN_ROOT}/scripts/hook-entry.sh\"",
97
+ "async": false,
98
+ "timeout": 1
99
+ },
100
+ {
101
+ "type": "command",
102
+ "if": "PowerShell(*pr-watch-*)",
103
+ "command": "set -- 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; . \"${CLAUDE_PLUGIN_ROOT}/scripts/hook-entry.sh\"",
104
+ "async": false,
105
+ "timeout": 1
106
+ },
107
+ {
108
+ "type": "command",
109
+ "if": "PowerShell(* test*)",
110
+ "command": "set -- 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; . \"${CLAUDE_PLUGIN_ROOT}/scripts/hook-entry.sh\"",
111
+ "async": false,
112
+ "timeout": 1
113
+ },
114
+ {
115
+ "type": "command",
116
+ "if": "PowerShell(*jest*)",
117
+ "command": "set -- 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; . \"${CLAUDE_PLUGIN_ROOT}/scripts/hook-entry.sh\"",
118
+ "async": false,
119
+ "timeout": 1
120
+ },
121
+ {
122
+ "type": "command",
123
+ "if": "PowerShell(*vitest*)",
124
+ "command": "set -- 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; . \"${CLAUDE_PLUGIN_ROOT}/scripts/hook-entry.sh\"",
125
+ "async": false,
126
+ "timeout": 1
127
+ },
128
+ {
129
+ "type": "command",
130
+ "if": "PowerShell(*pytest*)",
131
+ "command": "set -- 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; . \"${CLAUDE_PLUGIN_ROOT}/scripts/hook-entry.sh\"",
132
+ "async": false,
133
+ "timeout": 1
134
+ },
135
+ {
136
+ "type": "command",
137
+ "if": "PowerShell(*MUGGLE_*)",
138
+ "command": "set -- 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; . \"${CLAUDE_PLUGIN_ROOT}/scripts/hook-entry.sh\"",
139
+ "async": false,
140
+ "timeout": 1
141
+ },
142
+ {
143
+ "type": "command",
144
+ "if": "PowerShell(*.md*)",
145
+ "command": "set -- 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; . \"${CLAUDE_PLUGIN_ROOT}/scripts/hook-entry.sh\"",
146
+ "async": false,
147
+ "timeout": 1
148
+ },
149
+ {
150
+ "type": "command",
151
+ "if": "PowerShell(*reviewThreads*)",
152
+ "command": "set -- 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; . \"${CLAUDE_PLUGIN_ROOT}/scripts/hook-entry.sh\"",
153
+ "async": false,
154
+ "timeout": 1
155
+ },
156
+ {
157
+ "type": "command",
158
+ "if": "PowerShell(*discussions*)",
159
+ "command": "set -- 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; . \"${CLAUDE_PLUGIN_ROOT}/scripts/hook-entry.sh\"",
160
+ "async": false,
161
+ "timeout": 1
162
+ },
163
+ {
164
+ "type": "command",
165
+ "if": "PowerShell(*/replies*)",
74
166
  "command": "set -- 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; . \"${CLAUDE_PLUGIN_ROOT}/scripts/hook-entry.sh\"",
75
167
  "async": false,
76
168
  "timeout": 1
@@ -14,6 +14,9 @@ set -uo pipefail
14
14
  # rewriting it (guardrails.mjs on every guarded tool call) and refreshes it
15
15
  # on resume (below), so its mtime tracks last activity — only a session gone
16
16
  # quiet for the whole window is collected, and by then it has ended.
17
+ # guardrails/claims/<event>-<tool call> one per guarded tool call that started
18
+ # Node. Only the launches Claude Code starts together for that one call ever
19
+ # read it, so a claim an hour old is dead.
17
20
  # muggle-do/sessions/<slug>/ a PR-follow-up slot. Pruned only once finalized
18
21
  # (result.md present — the terminal marker); an OPEN slot, a PR watched for
19
22
  # any length of time, has no result.md and is never touched.
@@ -23,6 +26,7 @@ set -uo pipefail
23
26
 
24
27
  home="${HOME}"
25
28
  guardrails_dir="${home}/.muggle-ai/guardrails"
29
+ claims_dir="${guardrails_dir}/claims"
26
30
  sessions_dir="${home}/.muggle-ai/muggle-do/sessions"
27
31
  marker_dir="${home}/.cache/muggle"
28
32
  marker="${marker_dir}/state-gc-checked"
@@ -51,6 +55,10 @@ if [ -d "$guardrails_dir" ]; then
51
55
  -mtime "+${guardrails_ttl_days}" -delete 2>/dev/null || true
52
56
  fi
53
57
 
58
+ if [ -d "$claims_dir" ]; then
59
+ find "$claims_dir" -maxdepth 1 -type f -mmin +60 -delete 2>/dev/null || true
60
+ fi
61
+
54
62
  if [ -d "$sessions_dir" ]; then
55
63
  for slot in "$sessions_dir"/*/; do
56
64
  [ -d "$slot" ] || continue
@@ -10,7 +10,9 @@ set -uo pipefail
10
10
  # GUARDRAIL_SUBCOMMAND without running it), and asks every pre-filter in this one process.
11
11
  # Irrelevant events — nearly all of them — end here with {} and no process started. When any
12
12
  # gate could fire, Node runs once for all of them (`guardrails.mjs run <gates...>`), merging
13
- # their outputs the way the harness merged separate hooks.
13
+ # their outputs the way the harness merged separate hooks. A tool event's `if` variants can launch
14
+ # this several times for one call, so before Node starts the launch claims the call, and only the
15
+ # launch holding the claim runs it.
14
16
 
15
17
  guardrail_script_dir="${BASH_SOURCE[0]%/*}"
16
18
  [[ $guardrail_script_dir == "${BASH_SOURCE[0]}" ]] && guardrail_script_dir=.
@@ -27,7 +29,7 @@ for gate_script in "$@"; do
27
29
  fi
28
30
  done
29
31
 
30
- if [[ ${#firing_subcommands[@]} -eq 0 ]]; then
32
+ if [[ ${#firing_subcommands[@]} -eq 0 ]] || ! guardrail_claim_tool_call; then
31
33
  printf '{}'
32
34
  exit 0
33
35
  fi
@@ -114,6 +114,33 @@ guardrail_is_hook_script() {
114
114
  [[ ${BASH_SOURCE[1]} == "${MUGGLE_HOOK_SCRIPT:-$0}" ]]
115
115
  }
116
116
 
117
+ # Claims this event's tool call for the calling launch; returns 1 when a sibling launch already holds it.
118
+ # Claude Code starts a hook once per `if` variant whose rule matches the call — every variant when it cannot
119
+ # parse the command — all at once and with the same payload, so without a claim one `gh pr create --body-file
120
+ # notes.md` would record and announce itself twice. The claim is a file created under noclobber, which bash
121
+ # opens O_EXCL, so exactly one concurrent launch wins it. A payload with no tool_use_id (a turn end, a host
122
+ # that sends none) has no sibling to race, and a claim that cannot be written leaves the call unclaimed:
123
+ # recording a call twice beats not recording it. Noclobber is put back as found, since hook-entry.sh may have
124
+ # sourced this into the shell Claude Code started.
125
+ guardrail_claim_tool_call() {
126
+ local tool_use_id_pattern='"tool_use_id"[[:space:]]*:[[:space:]]*"([^"]+)"'
127
+ [[ $GUARDRAIL_PAYLOAD =~ $tool_use_id_pattern ]] || return 0
128
+ local claim_name="${BASH_REMATCH[1]//[^A-Za-z0-9_-]/_}"
129
+ guardrail_payload_field hook_event_name && claim_name="${GUARDRAIL_FIELD_VALUE//[^A-Za-z0-9_-]/_}-$claim_name"
130
+ guardrail_resolve_home
131
+ local claims_dir="$GUARDRAIL_HOME/.muggle-ai/guardrails/claims"
132
+ [[ -d $claims_dir ]] || mkdir -p "$claims_dir" 2>/dev/null
133
+ local claim_file="$claims_dir/$claim_name"
134
+ local is_create_failed=""
135
+ local was_noclobber=""
136
+ [[ -o noclobber ]] && was_noclobber=1
137
+ set -C
138
+ { : >"$claim_file"; } 2>/dev/null || is_create_failed=1
139
+ [[ -n $was_noclobber ]] || set +C
140
+ [[ -n $is_create_failed && -e $claim_file ]] && return 1
141
+ return 0
142
+ }
143
+
117
144
  # Runs guardrails.mjs on the payload. Never blocks a turn: any failure degrades to {}.
118
145
  # A here-string rather than a pipe, so the fallback hears only Node's exit status: a pipe's writer dies of SIGPIPE
119
146
  # when Node exits before reading all of its stdin, and pipefail would count that as Node failing and print a second
@@ -667,6 +667,35 @@ function readPrHeadSha(pr, run) {
667
667
  return null;
668
668
  }
669
669
  }
670
+ function readPrDiffPaths(pr, run) {
671
+ try {
672
+ const refs = JSON.parse(
673
+ run([
674
+ "api",
675
+ `repos/${pr.repo}/pulls/${pr.prNumber}`,
676
+ "--jq",
677
+ "{base: .base.sha, head: .head.sha, changedFiles: .changed_files}"
678
+ ]) ?? "null"
679
+ );
680
+ if (!refs?.base || !refs.head) return null;
681
+ const diff = JSON.parse(
682
+ run([
683
+ "api",
684
+ `repos/${pr.repo}/compare/${refs.base}...${refs.head}`,
685
+ "--jq",
686
+ "{mergeBase: .merge_base_commit.sha, files: [.files[] | {path: .filename, previousPath: .previous_filename}]}"
687
+ ]) ?? "null"
688
+ );
689
+ if (!diff?.mergeBase || !Array.isArray(diff.files) || diff.files.length !== refs.changedFiles) return null;
690
+ return {
691
+ mergeBaseSha: diff.mergeBase,
692
+ headSha: refs.head,
693
+ changedPaths: diff.files.flatMap((file) => file.previousPath ? [file.path, file.previousPath] : [file.path])
694
+ };
695
+ } catch {
696
+ return null;
697
+ }
698
+ }
670
699
  function writeJson(args, payload, run) {
671
700
  try {
672
701
  return run(args, JSON.stringify(payload)) !== null;
@@ -1876,16 +1905,28 @@ function commentWithStatus(comments, status) {
1876
1905
  function designatedComment(comments) {
1877
1906
  return comments.find((comment) => classifyComment(comment.body) !== "not-designated" /* NotDesignated */);
1878
1907
  }
1908
+ function openingCommentBody(pr, run) {
1909
+ const diff = readPrDiffPaths(pr, run);
1910
+ if (!diff || diff.changedPaths.length === 0 || !diff.changedPaths.every(isNonAppPath)) {
1911
+ return renderReservedComment();
1912
+ }
1913
+ return renderNoAppLogicChangeComment(
1914
+ { preCycleSha: diff.mergeBaseSha, baseTipSha: null, reason: "" },
1915
+ diff.headSha,
1916
+ null
1917
+ );
1918
+ }
1879
1919
  function reserveComment(pr, comments, run) {
1880
- if (designatedComment(comments)) return false;
1881
- return postPrComment(pr, renderReservedComment(), run);
1920
+ if (designatedComment(comments)) return null;
1921
+ const body = openingCommentBody(pr, run);
1922
+ return postPrComment(pr, body, run) ? body : null;
1882
1923
  }
1883
1924
  function reserveWalkthroughComment(prUrl, run = defaultGhRunner) {
1884
1925
  const pr = parsePrUrl(prUrl);
1885
1926
  if (!pr) return false;
1886
1927
  const comments = listPrComments(pr, run);
1887
1928
  if (comments === null) return false;
1888
- return reserveComment(pr, comments, run);
1929
+ return reserveComment(pr, comments, run) !== null;
1889
1930
  }
1890
1931
  function isWalkthroughSettledOnPr(prUrl, run = defaultGhRunner) {
1891
1932
  const pr = parsePrUrl(prUrl);
@@ -2537,7 +2578,7 @@ function prOpened() {
2537
2578
  startBackgroundJob("scan-walkthroughs" /* ScanWalkthroughs */, [sessionId], input.cwd);
2538
2579
  }
2539
2580
  const slotNote = declaredSkip ? `Its Muggle AI visual-walkthrough comment is being settled with the E2E skip already recorded this session (${declaredSkip.code}); the turn cannot end until the PR shows it.
2540
- ` : `Its Muggle AI visual-walkthrough comment is reserved and empty \u2014 settle it with the E2E run of this PR's own change (a wave's PRs share one run; any other PR gets its own), or by recording why E2E does not apply from this PR's working tree.
2581
+ ` : `Its Muggle AI visual-walkthrough comment is being reserved. When every path the PR changes is ${NON_APP_PATH_SUMMARY}, it opens already settled as skipped (${"NO_APP_LOGIC_CHANGE" /* NoAppLogicChange */}) and needs nothing more. Otherwise settle it with the E2E run of this PR's own change (a wave's PRs share one run; any other PR gets its own), or by recording why E2E does not apply from this PR's working tree.
2541
2582
  `;
2542
2583
  const ctx = `A pull request was just opened: ${url}
2543
2584
  ` + slotNote + `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.`;
@@ -4,7 +4,7 @@
4
4
  */
5
5
  const BARE_DIRECTORY_RELEASE_STREAM = "production";
6
6
 
7
- const BARE_VERSION_DIRECTORY_PATTERN = /^\d+\.\d+\.\d+$/;
7
+ const RELEASE_VERSION_PATTERN = /^\d+\.\d+\.\d+$/;
8
8
 
9
9
  /**
10
10
  * Build the directory name, under `~/.muggle-ai/electron-app`, that a studio
@@ -23,27 +23,78 @@ export function buildElectronAppDirName({ version, releaseStream }) {
23
23
  return `${version}-${releaseStream}`;
24
24
  }
25
25
 
26
+ function readStreamInstallVersion({ directoryName, releaseStream }) {
27
+ if (releaseStream === BARE_DIRECTORY_RELEASE_STREAM) {
28
+ return RELEASE_VERSION_PATTERN.test(directoryName) ? directoryName : null;
29
+ }
30
+ const streamSuffix = `-${releaseStream}`;
31
+ if (!directoryName.endsWith(streamSuffix)) {
32
+ return null;
33
+ }
34
+ const version = directoryName.slice(0, -streamSuffix.length);
35
+ return RELEASE_VERSION_PATTERN.test(version) ? version : null;
36
+ }
37
+
38
+ function compareReleaseVersions(leftVersion, rightVersion) {
39
+ const leftParts = leftVersion.split(".").map(Number);
40
+ const rightParts = rightVersion.split(".").map(Number);
41
+ for (let partIndex = 0; partIndex < leftParts.length; partIndex++) {
42
+ if (leftParts[partIndex] !== rightParts[partIndex]) {
43
+ return leftParts[partIndex] - rightParts[partIndex];
44
+ }
45
+ }
46
+ return 0;
47
+ }
48
+
26
49
  /**
27
- * Whether a directory under `~/.muggle-ai/electron-app` is an outdated install
28
- * of the given stream. Each install lane prunes only its own stream's
50
+ * Whether a directory under `~/.muggle-ai/electron-app` is a studio install of
51
+ * the given stream. Each install lane only ever touches its own stream's
29
52
  * directories, so a staging install never deletes the production studio and a
30
53
  * production install never deletes the staging one.
31
54
  * @param {object} params - Check parameters.
32
55
  * @param {string} params.directoryName - Directory to classify.
33
56
  * @param {string} params.releaseStream - Stream the current install belongs to.
57
+ * @returns {boolean} True when the directory holds a release of that stream.
58
+ */
59
+ export function isStreamInstall({ directoryName, releaseStream }) {
60
+ return readStreamInstallVersion({ directoryName: directoryName, releaseStream: releaseStream }) !== null;
61
+ }
62
+
63
+ /**
64
+ * Whether a stream install is older than the current one and so safe to prune.
65
+ * A newer install — a dev build or a later release someone chose on purpose —
66
+ * is never outdated, whatever the bundled pin says.
67
+ * @param {object} params - Check parameters.
68
+ * @param {string} params.directoryName - Directory to classify.
69
+ * @param {string} params.releaseStream - Stream the current install belongs to.
34
70
  * @param {string} params.currentDirectoryName - Directory the current install uses.
35
- * @returns {boolean} True when the directory belongs to the stream and is not the current install.
71
+ * @returns {boolean} True when the directory holds an older release of the same stream.
36
72
  */
37
73
  export function isOutdatedStreamInstall({ directoryName, releaseStream, currentDirectoryName }) {
38
- if (directoryName === currentDirectoryName) {
74
+ const installVersion = readStreamInstallVersion({ directoryName: directoryName, releaseStream: releaseStream });
75
+ const currentVersion = readStreamInstallVersion({
76
+ directoryName: currentDirectoryName,
77
+ releaseStream: releaseStream,
78
+ });
79
+ if (installVersion === null || currentVersion === null) {
39
80
  return false;
40
81
  }
41
- if (releaseStream === BARE_DIRECTORY_RELEASE_STREAM) {
42
- return BARE_VERSION_DIRECTORY_PATTERN.test(directoryName);
82
+ return compareReleaseVersions(installVersion, currentVersion) < 0;
83
+ }
84
+
85
+ /**
86
+ * Whether an install keeps the user's studio version override. An override
87
+ * naming a release newer than the bundled pin was chosen on purpose and stays;
88
+ * one the pin has caught up with, or one naming a non-release build, resets so
89
+ * nobody stays silently pinned to an old or dev studio.
90
+ * @param {object} params - Check parameters.
91
+ * @param {string} params.overrideVersion - Version the override file names.
92
+ * @param {string} params.bundledVersion - Version this works install pins.
93
+ * @returns {boolean} True when the override names a newer release than the pin.
94
+ */
95
+ export function shouldKeepVersionOverride({ overrideVersion, bundledVersion }) {
96
+ if (!RELEASE_VERSION_PATTERN.test(overrideVersion) || !RELEASE_VERSION_PATTERN.test(bundledVersion)) {
97
+ return false;
43
98
  }
44
- const streamSuffix = `-${releaseStream}`;
45
- return (
46
- directoryName.endsWith(streamSuffix) &&
47
- BARE_VERSION_DIRECTORY_PATTERN.test(directoryName.slice(0, -streamSuffix.length))
48
- );
99
+ return compareReleaseVersions(overrideVersion, bundledVersion) > 0;
49
100
  }
@@ -26,8 +26,13 @@ import { pipeline } from "stream/promises";
26
26
  import { createRequire } from "module";
27
27
  import { fileURLToPath } from "url";
28
28
  import { pointClaudeMarketplaceAtPackage } from "./claude-marketplace-sync.mjs";
29
- import { buildElectronAppDirName, isOutdatedStreamInstall } from "./electron-app-install-dir.mjs";
29
+ import {
30
+ buildElectronAppDirName,
31
+ isOutdatedStreamInstall,
32
+ shouldKeepVersionOverride,
33
+ } from "./electron-app-install-dir.mjs";
30
34
  import { backfillOnboardingStamp } from "./onboarding-backfill.mjs";
35
+ import { listRunningInstallDirectoryNames, normalizeInstallDirectoryName } from "./running-studio-installs.mjs";
31
36
  import {
32
37
  SIGNATURE_BUNDLE_SUFFIX,
33
38
  resolveIntegrityPolicy,
@@ -114,20 +119,54 @@ function logError(...args) {
114
119
  }
115
120
 
116
121
  /**
117
- * Remove the electron-app version override file if it exists.
118
- * Each new install should use the bundled version from package.json.
119
- * Users can still override manually after install, but it resets on next install.
122
+ * Get the Electron app version this package pins.
123
+ * @returns {string} Bundled version from package.json
120
124
  */
121
- function removeVersionOverrideFile() {
122
- const overridePath = join(homedir(), ".muggle-ai", VERSION_OVERRIDE_FILE_NAME);
125
+ function getBundledElectronAppVersion() {
126
+ return (require("../package.json").muggleConfig || {}).electronAppVersion || "1.0.0";
127
+ }
123
128
 
124
- if (existsSync(overridePath)) {
125
- try {
126
- rmSync(overridePath, { force: true });
127
- log(`Removed version override file: ${overridePath}`);
128
- } catch (error) {
129
- logError(`Failed to remove version override file: ${error.message}`);
130
- }
129
+ function getVersionOverridePath() {
130
+ return join(getDataDir(), VERSION_OVERRIDE_FILE_NAME);
131
+ }
132
+
133
+ /**
134
+ * Read the version the electron-app override file names.
135
+ * @returns {string | null} Override version, or null when the file is missing or unreadable
136
+ */
137
+ function readVersionOverrideVersion() {
138
+ try {
139
+ const overrideContent = JSON.parse(readFileSync(getVersionOverridePath(), "utf-8"));
140
+ return typeof overrideContent.version === "string" && overrideContent.version ? overrideContent.version : null;
141
+ } catch {
142
+ return null;
143
+ }
144
+ }
145
+
146
+ /**
147
+ * Remove the electron-app version override file unless it names a release newer
148
+ * than the bundled one. A newer pick was made on purpose and outlives the
149
+ * install; an override the pin has caught up with would hold users on an old
150
+ * studio, so it resets to the bundled version.
151
+ */
152
+ function resetStaleVersionOverrideFile() {
153
+ const overridePath = getVersionOverridePath();
154
+ if (!existsSync(overridePath)) {
155
+ return;
156
+ }
157
+
158
+ const overrideVersion = readVersionOverrideVersion();
159
+ const bundledVersion = getBundledElectronAppVersion();
160
+ if (overrideVersion && shouldKeepVersionOverride({ overrideVersion: overrideVersion, bundledVersion: bundledVersion })) {
161
+ log(`Kept version override v${overrideVersion}: newer than the bundled v${bundledVersion}`);
162
+ return;
163
+ }
164
+
165
+ try {
166
+ rmSync(overridePath, { force: true });
167
+ log(`Removed version override file: ${overridePath}`);
168
+ } catch (error) {
169
+ logError(`Failed to remove version override file: ${error.message}`);
131
170
  }
132
171
  }
133
172
 
@@ -374,7 +413,10 @@ async function verifyFileChecksum(filePath, expectedChecksum) {
374
413
  }
375
414
 
376
415
  /**
377
- * Remove this release stream's Electron app directories other than the current install.
416
+ * Remove this release stream's Electron app directories older than the current
417
+ * install. A directory the version override names, or one a running process
418
+ * executes from, is another session's runner and stays; when running processes
419
+ * cannot be listed, nothing is removed.
378
420
  * @param {object} params - Cleanup parameters
379
421
  * @param {string} params.appDir - Base Electron app directory
380
422
  * @param {string} params.releaseStream - Stream the current install belongs to
@@ -385,32 +427,49 @@ function cleanupOutdatedStreamInstalls({ appDir, releaseStream, currentDirectory
385
427
  return;
386
428
  }
387
429
 
388
- const appEntries = readdirSync(appDir, { withFileTypes: true });
430
+ const outdatedDirectoryNames = readdirSync(appDir, { withFileTypes: true })
431
+ .filter((appEntry) => appEntry.isDirectory())
432
+ .map((appEntry) => appEntry.name)
433
+ .filter((directoryName) =>
434
+ isOutdatedStreamInstall({
435
+ directoryName: directoryName,
436
+ releaseStream: releaseStream,
437
+ currentDirectoryName: currentDirectoryName,
438
+ }),
439
+ );
440
+ if (outdatedDirectoryNames.length === 0) {
441
+ return;
442
+ }
389
443
 
390
- for (const appEntry of appEntries) {
391
- if (!appEntry.isDirectory()) {
444
+ const runningDirectoryNames = listRunningInstallDirectoryNames({ appDir: appDir });
445
+ if (runningDirectoryNames === null) {
446
+ log("Could not list running processes; keeping outdated Electron app versions until the next install.");
447
+ return;
448
+ }
449
+ const overrideVersion = readVersionOverrideVersion();
450
+ const overrideDirectoryName = overrideVersion
451
+ ? buildElectronAppDirName({ version: overrideVersion, releaseStream: releaseStream })
452
+ : null;
453
+
454
+ for (const directoryName of outdatedDirectoryNames) {
455
+ if (directoryName === overrideDirectoryName) {
456
+ log(`Keeping Electron app version ${directoryName}: the version override names it`);
392
457
  continue;
393
458
  }
394
-
395
- if (
396
- !isOutdatedStreamInstall({
397
- directoryName: appEntry.name,
398
- releaseStream: releaseStream,
399
- currentDirectoryName: currentDirectoryName,
400
- })
401
- ) {
459
+ if (runningDirectoryNames.has(normalizeInstallDirectoryName(directoryName))) {
460
+ log(`Keeping Electron app version ${directoryName}: a running process uses it`);
402
461
  continue;
403
462
  }
404
463
 
405
- const staleVersionDir = join(appDir, appEntry.name);
464
+ const staleVersionDir = join(appDir, directoryName);
406
465
  try {
407
- log(`Removing stale Electron app version: ${appEntry.name}`);
466
+ log(`Removing stale Electron app version: ${directoryName}`);
408
467
  rmSync(staleVersionDir, { recursive: true, force: true });
409
468
  } catch (error) {
410
469
  logError("\n========================================");
411
470
  logError("ERROR: Failed to remove stale Electron app version");
412
471
  logError("========================================\n");
413
- logError("Version:", appEntry.name);
472
+ logError("Version:", directoryName);
414
473
  logError("Path:", staleVersionDir);
415
474
  logError("\nFull error details:");
416
475
  logError(error instanceof Error ? error.stack || error : error);
@@ -639,7 +698,7 @@ async function downloadElectronApp() {
639
698
  // Read config from package.json
640
699
  const packageJson = require("../package.json");
641
700
  const config = packageJson.muggleConfig || {};
642
- const version = config.electronAppVersion || "1.0.0";
701
+ const version = getBundledElectronAppVersion();
643
702
  const baseUrl = config.downloadBaseUrl || "https://github.com/multiplex-ai/muggle-ai-works/releases/download";
644
703
 
645
704
  const runtimeTarget = resolveRuntimeTarget(config);
@@ -990,7 +1049,7 @@ function logOnboardingBackfill() {
990
1049
  // Windows) keeps the event loop alive — see issue #167.
991
1050
  initLogFile();
992
1051
  logOnboardingBackfill();
993
- removeVersionOverrideFile();
1052
+ resetStaleVersionOverrideFile();
994
1053
  syncCursorSkills();
995
1054
  syncClaudeMarketplace();
996
1055
  applyWatchServicePreference();