@codewizard-dt/bootstrap 2.14.0 → 2.15.0

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 (38) hide show
  1. package/lib/hooks/README.md +592 -12
  2. package/lib/hooks/absolute-path-guard.js +142 -0
  3. package/lib/hooks/claude-settings-guard.js +235 -0
  4. package/lib/hooks/env-content-read-guard.js +367 -0
  5. package/lib/hooks/git-protected-ops-block.js +12 -7
  6. package/lib/hooks/interpreter-indirection-guard.js +576 -0
  7. package/lib/hooks/lib/command-parse.js +63 -0
  8. package/lib/hooks/package-install-consent.js +151 -0
  9. package/lib/hooks/protected-write-guard.js +237 -0
  10. package/lib/scripts/README.md +62 -5
  11. package/lib/scripts/build-mcp-guide.sh +9 -1
  12. package/lib/scripts/install-global.sh +25 -2
  13. package/lib/scripts/install-mcps.sh +140 -36
  14. package/lib/scripts/lib.sh +10 -6
  15. package/lib/scripts/merge-gitignore.sh +163 -27
  16. package/lib/scripts/merge-settings-deny.js +112 -39
  17. package/lib/scripts/templates/file-suggestion.sh +142 -0
  18. package/lib/scripts/templates/gitignore +8 -0
  19. package/lib/scripts/templates/guides/stubs/playwright.md +2 -0
  20. package/lib/scripts/templates/settings-deny.json +81 -1
  21. package/lib/skills/debug-logs/SKILL.md +1 -1
  22. package/lib/skills/git-commit/SKILL.md +8 -0
  23. package/package.json +5 -2
  24. package/raw/research/brave-mcp-single-docker-container/index.md +0 -94
  25. package/raw/research/brave-mcp-single-docker-container/sources.md +0 -70
  26. package/raw/research/dark-mode-theme/index.md +0 -85
  27. package/raw/research/dark-mode-theme/sources.md +0 -49
  28. package/raw/research/mcp-add-scope-writes/index.md +0 -46
  29. package/raw/research/mcp-add-scope-writes/sources.md +0 -38
  30. package/raw/research/mcp-one-process-per-user/index.md +0 -75
  31. package/raw/research/mcp-one-process-per-user/sources.md +0 -66
  32. package/raw/research/mcp-scope-conflict-handling/index.md +0 -61
  33. package/raw/research/mcp-scope-conflict-handling/sources.md +0 -32
  34. package/raw/research/serena-mcp-disconnect/index.md +0 -81
  35. package/raw/research/serena-mcp-disconnect/sources.md +0 -87
  36. package/raw/research/wiki-tooling-improvements/index.md +0 -126
  37. package/raw/research/wiki-tooling-improvements/sources.md +0 -73
  38. package/raw/software-factory-case-study.pdf +0 -0
@@ -11,12 +11,22 @@ scripts sit on disk and never run.
11
11
 
12
12
  ## Why hooks (vs. allow/deny permission rules)
13
13
 
14
- The permissions `deny` list is **not consulted** when an agent runs in
15
- `bypassPermissions` mode (`--dangerously-skip-permissions`, power-mode teammates,
16
- or any subagent spawned with `mode: bypassPermissions`). `PreToolUse` hooks, by
17
- contrast, fire in **every** permission mode and for **subagent** tool calls. So a
18
- hook is the only reliable enforcement point for "this must never run, even under
19
- bypass." Keep a matching `deny` entry too — belt-and-suspenders for normal modes.
14
+ The permissions `deny` list **is** enforced in every permission mode, including
15
+ `bypassPermissions` (`--dangerously-skip-permissions`, power-mode teammates, or
16
+ any subagent spawned with `mode: bypassPermissions`), and for subagent tool calls
17
+ as well as main-session ones. Hooks are not here to cover a gap under bypass —
18
+ there isn't one.
19
+
20
+ Hooks exist because **a `deny` rule matches a literal command spelling, while a
21
+ hook parses the command.** `Bash(rm -rf ~*)` does not stop `/bin/rm -rf ~`, and
22
+ no pattern can see inside `bash -c`, `python -c`, or an absolute-path fetcher.
23
+ A hook reads the actual command string, so it catches the variants a pattern
24
+ cannot enumerate — and it can return a **message** explaining the block, which a
25
+ `deny` rule cannot. Both reasons hold in every mode.
26
+
27
+ `PreToolUse` hooks also fire *before* permission rules are evaluated, so a hook
28
+ exiting 2 stops a call the rules would never see. Keep a matching `deny` entry
29
+ too — defence in depth, and the rules keep working if a hook ever fails to fire.
20
30
 
21
31
  ---
22
32
 
@@ -30,6 +40,486 @@ bypass." Keep a matching `deny` entry too — belt-and-suspenders for normal mod
30
40
  | `mv-absolute-path-block.js` | `Bash` (`if: Bash(mv *)`) | `mv` to an absolute path outside the project root |
31
41
  | `git-protected-ops-block.js` | `Bash` (no `if:`) | `git stash` / `git restore` / `git checkout` in any command segment |
32
42
 
43
+ ### Command-class guards
44
+
45
+ The hooks above gate a named tool or a named command. The six files below gate a
46
+ *class* of invocation that a `deny` rule provably cannot reach, because the
47
+ dangerous part of the command is not where a pattern can look: inside a quoted
48
+ `-c` payload, behind an absolute path, after a redirect operator, in an
49
+ environment assignment, or on the far side of an MCP tool boundary.
50
+
51
+ | Script | Matcher | Blocks |
52
+ |--------|---------|--------|
53
+ | `interpreter-indirection-guard.js` | `Bash` | Extracts the inline program from `bash -c`, `node -e`, `python3 -c`, … and re-judges it as if typed directly; denies a command substitution outright |
54
+ | `package-install-consent.js` | `Bash` | Every package-manager install, with one allowlisted source (Serena) |
55
+ | `absolute-path-guard.js` | `Bash` | Evasive *spellings* of destructive commands (`/bin/rm`, `\rm`, `env rm`) |
56
+ | `protected-write-guard.js` | `Bash` | `>`/`>>` into shell/git/Claude config, `DYLD_*`/`LD_*` injection, `git -c` RCE config keys |
57
+ | `claude-settings-guard.js` | `Edit\|Write\|NotebookEdit\|MultiEdit` | File-tool writes to `~/.claude/settings*.json` (with a bootstrap-claude exception) and `~/.claude/hooks/**` (no exception) |
58
+ | `env-content-read-guard.js` | `Bash\|mcp__serena__.*\|mcp__plugin_[^_]+_serena__.*` | `.env` *contents* reaching the transcript, on both the Bash and Serena surfaces |
59
+
60
+ They share `lib/command-parse.js` (stdin read, segment split, tokenize, deny
61
+ envelope). `git-protected-ops-block.js` deliberately still carries its own copies
62
+ of those four helpers — see [Shared library](#shared-library).
63
+
64
+ #### `interpreter-indirection-guard.js`
65
+
66
+ **The rule: you may not use `bash -c` to do something you could not do without
67
+ it.** The guard detects `bash|sh|zsh|python|python3 -c`, `node -e|--eval`,
68
+ `ruby|perl -e` in any segment, *extracts the inline program*, strips the one
69
+ layer of quoting the shell already consumed, and re-judges that program as if it
70
+ had been typed at the prompt. It allows unless something objects. The interpreter
71
+ token is matched on its *basename* after stripping leading `\`, so `/bin/bash
72
+ -c`, `env bash -c`, and `\bash -c` are all caught; the flag comparison takes the
73
+ longest `startsWith` match, so `-c'echo hi'` and `--eval=code` are reached
74
+ alongside the spaced form.
75
+
76
+ **Why a hook.** The entire point of `-c` is that the real program lives inside a
77
+ quoted string, where no permission pattern can reach it. One approved `bash -c`
78
+ can carry a redirect into `~/.zshrc`, an absolute-path `rm`, or an `rm -rf ~`
79
+ that the deny list would have caught the moment it was typed plainly. A hook
80
+ receives the raw, undecomposed string and can parse the invocation form itself.
81
+
82
+ **Why re-evaluation and not blanket deny.** This guard originally denied every
83
+ inline-program invocation outright (TASK-027), on the grounds that inspecting the
84
+ payload is defeated by one line of obfuscation — `bash -c 'c=cur;l=l;$c$l
85
+ http://x'`. That reasoning is correct but bounded: it only bites against an
86
+ *adversary*, and against an adversary this hook already fails, by its own
87
+ documented escape hatch. The deny message said *write the script to a file and
88
+ run the file* — which is also the complete bypass. `printf '…' > /tmp/x.sh &&
89
+ bash /tmp/x.sh` runs the identical program and never touches this guard. A
90
+ control whose published alternative is its own bypass was never an adversarial
91
+ control and cannot become one; it is a guardrail against a careless one-liner.
92
+
93
+ So blanket deny bought nothing extra against the threat it cannot stop, while
94
+ charging real friction against the mistake it actually catches: `node -e` and
95
+ `python3 -c` one-liners are routine and were simply unavailable.
96
+
97
+ **Why re-evaluation and not a payload blocklist.** A fixed danger list (`.env`,
98
+ `~/.zshrc`, `rm -rf`, …) is a *second matching vocabulary* that drifts out of
99
+ sync with the guards it duplicates. Re-running the payload through the existing
100
+ checks is exactly as strong as the direct-command path by construction, needs no
101
+ new vocabulary, has near-zero false positives (anything permitted directly is
102
+ permitted inside `-c`), and fails only where the direct path already fails — a
103
+ consistency, not a new hole.
104
+
105
+ **What the payload is checked against — four deny sources.** They are consulted
106
+ in this order, and the first objection wins:
107
+
108
+ 1. **The permission deny list.** No hook in this directory objects to a bare `rm
109
+ -rf ~`, `sudo …`, `crontab -r`, or `git push --force` — the deny list does,
110
+ and Claude Code applies it to the literal command string, so it never sees
111
+ inside `-c`. Re-evaluating through the hooks *alone* would have opened a hole
112
+ blanket deny had closed. Each `Bash(...)` entry compiles to a RegExp matched
113
+ segment-by-segment, reproducing the four semantics the shipped list depends
114
+ on: a trailing ` *` is a word boundary (`dd *` matches `dd` and `dd if=…`, not
115
+ `ddrescue`), `:*` is that same boundary as a suffix, no wildcard is an exact
116
+ match (`sh` must not catch `shellcheck`), and `*` is an ordinary wildcard at
117
+ any position (`git * --force*`).
118
+ 2. **The five sibling guards**, spawned as subprocesses against a synthesized
119
+ PreToolUse payload: `absolute-path-guard.js`, `protected-write-guard.js`,
120
+ `env-content-read-guard.js`, `package-install-consent.js`,
121
+ `git-protected-ops-block.js`. The original `cwd` is carried through, because
122
+ `protected-write-guard.js` resolves relative redirect targets against it.
123
+ 3. **Unparseable payload** — flag last (`bash -c`), unbalanced quoting (`bash -c
124
+ 'oops`), or shell concatenation (`bash -c 'echo '"$X"`). The whole basis for
125
+ permitting `-c` is that its program can be read; when extraction fails there
126
+ is nothing to evaluate, and an unreadable program is not an approved one.
127
+ 4. **Command substitution** — `bash -c "$(curl …)"` and the backtick form are
128
+ denied unconditionally and never re-evaluated. The program does not exist
129
+ until execution time, so there is genuinely nothing in the command being
130
+ approved to inspect.
131
+
132
+ Plus a depth cap: `bash -c "bash -c '…'"` is allowed (one nesting, for the
133
+ occasional real `ssh host bash -c` idiom), a third layer is not. Each layer of
134
+ quoting is another chance for what executes to differ from what was read.
135
+
136
+ **The deny reason is the objecting check's own**, merely prefixed with ``Blocked
137
+ inside `bash -c` — ``. A generic "blocked" tells the caller something was wrong
138
+ without telling them what, which is how a block gets worked around instead of
139
+ fixed. Note that the reason differs by source: a deny-list match names the rule
140
+ (``matches the permission deny rule `Bash(rm -rf ~*)` ``), a sibling deny carries
141
+ that guard's text.
142
+
143
+ **It reads `~/.claude/settings.json` at runtime**, not a copy baked in at install
144
+ time. A user who edits their own deny list gets that change honored *inside* `bash
145
+ -c` immediately, with no re-install. The lookup resolves from `__dirname`, so one
146
+ code path serves both locations this file lives in: `../settings.json` in the
147
+ installed layout (the live list), falling back to
148
+ `../scripts/templates/settings-deny.json` in the repo. Exactly one exists per
149
+ machine, so this is a fallback, not a precedence question.
150
+
151
+ **Everything that cannot be checked denies.** A missing sibling file, a spawn
152
+ error, a timeout (2s), non-JSON output, a non-zero exit, an unreadable deny list —
153
+ all block, with a message saying the check *could not be completed* rather than
154
+ that the command was refused. A guard that silently degrades to permissive under
155
+ load or after a botched install is worse than one that occasionally over-blocks,
156
+ because from the outside it is indistinguishable from a guard that approved.
157
+
158
+ **`node -e` and `python3 -c` payloads are re-evaluated as Bash** even though they
159
+ are JavaScript and Python. This is a deliberate over-approximation: a JS payload
160
+ judged by shell rules can only ever match *more* than it should, never less, so
161
+ the error direction is over-blocking. Writing per-language analyzers would be a
162
+ third and fourth matching vocabulary for a guardrail that a file redirect already
163
+ bypasses.
164
+
165
+ **Cost.** ~46 ms for a command with no interpreter — the common path, where the
166
+ deny list is never even read (loading is lazy and memoized per process) and
167
+ nothing is spawned. ~270 ms once a segment genuinely contains an interpreter plus
168
+ an eval flag, which is five short-lived subprocesses plus ~6 ms of regex
169
+ compilation.
170
+
171
+ **Why subprocesses rather than shared functions.** The siblings are shipped,
172
+ globally-installed controls. Spawning them requires zero changes to them, uses
173
+ them exactly as Claude Code does, and stays in sync automatically. Extracting
174
+ their decision logic into shared pure functions in `lib/` would remove the spawns
175
+ and is the better *eventual* refactor — see [Follow-up](#follow-up-shared-decision-functions).
176
+
177
+ **Not covered, deliberately:**
178
+
179
+ - Other POSIX shells (`dash`, `ksh`) are not in the interpreter set; bundled short
180
+ flags (`sh -ec '…'`) are not decomposed.
181
+ - `permissions.allow` / `ask` and their precedence. This is a deny-only check —
182
+ which matches Claude Code in the direction that matters, but does mean a payload
183
+ the user explicitly allowed is still denied here.
184
+ - Project-scoped `.claude/settings.json` and `.claude/settings.local.json`. Only
185
+ the user-scope list is consulted.
186
+ - `Edit(…)` / `Read(…)` deny entries. They are file-tool rules and cannot match a
187
+ command string, so they are skipped rather than mis-applied.
188
+ - Quote-aware decomposition. Segments come from the shared `splitSegments`, which
189
+ splits on `;`/`&&`/`||`/`|` without regard for quoting, so `bash -c "git commit
190
+ -m 'a; sudo b'"` over-blocks. That errs toward blocking, never toward allowing.
191
+ - An interpreter mentioned inside a quoted string (`echo "bash -c foo"`) is not
192
+ detected at all — the opening `"` is part of the token, so the basename lookup
193
+ misses.
194
+
195
+ **Measured cost in this repo: zero.** Every `bash -c` / `sh -c` / `node -e` under
196
+ `lib/` lives *inside* a shell script (`setup-runner.sh:73`, `startup.sh:25`/`:37`,
197
+ `install-mcps.sh:321`), which runs as a subprocess of an already-approved
198
+ `bash <script>.sh` call and is never seen by a PreToolUse hook. `bash -n
199
+ script.sh` — the static gate `/tackle` mandates — uses `-n`, not `-c`.
200
+
201
+ #### `package-install-consent.js`
202
+
203
+ **Blocks** `npm install|i|add`, `pnpm add|install`, `yarn add`, `pip|pip3
204
+ install`, `uv pip install`, `pipx install`, `gem install`, `cargo install`,
205
+ `go install`, `brew install`, and `uvx --from <anything>`. Leading `VAR=…`,
206
+ `env`, and `sudo` are stripped and the manager is matched on its basename, so
207
+ `FOO=1 sudo /usr/local/bin/npm install` gates identically to `npm install`.
208
+ `--dry-run`, `--help`, and `-h` fall through — an install that resolves nothing
209
+ and writes nothing is not a package addition.
210
+
211
+ Read-only and lockfile-driven subcommands are not gated because they are *absent
212
+ from the map*, not because of a negative list: `npm ci`, `npm test`, `npm run *`,
213
+ `npm ls`, `pip list`, `cargo build`, `go build`, `brew list`. `yarn install` is
214
+ omitted for the same reason as `npm ci` — it installs what the lockfile already
215
+ records, adding nothing the repo has not already consented to.
216
+
217
+ **The one allowlisted source** is `uvx --from
218
+ git+https://github.com/oraios/serena` (an optional `.git` suffix and an optional
219
+ `@ref` pin are accepted as ordinary spellings of the same repo). It is matched on
220
+ the *source URL*, not on `uvx --from` generally, so every other `--from` target
221
+ still gates.
222
+
223
+ **Why a hook.** That exception is the reason. A deny rule cannot carry one: deny
224
+ beats allow at every scope, and a hook returning `allow` cannot loosen a deny
225
+ rule either — but a hook can simply decline to deny.
226
+
227
+ **Why not `permissions.ask`.** `ask` is the natural fit for consent and works
228
+ correctly in an interactive session. This repo routinely runs headless (`claude
229
+ -p` under `/uat-auto-plus` and power-mode), where nobody can answer the prompt and
230
+ the call becomes a block or a hang. A consent gate that hangs an unattended run is
231
+ worse than one that denies with instructions. *(That headless-`ask` behavior is
232
+ recorded as inference, not primary source, in
233
+ `raw/research/bypass-mode-enforcement/index.md`.)*
234
+
235
+ **The deny reason echoes the segment verbatim**, never a re-join of tokens —
236
+ re-joining silently drops quoting (`npm install "@scope/pkg@^1.0"`), and the
237
+ entire value of this gate over a deny rule is that the user can copy the exact
238
+ string back out and run it. In a chain (`npm test && npm install foo`) the
239
+ *segment* is echoed, which is the install part alone.
240
+
241
+ **Not gated by construction:** installs inside shell scripts. PreToolUse sees only
242
+ the command Claude asks to run; when that is `bash lib/scripts/install-mcps.sh`,
243
+ everything the script executes is a subprocess of an already-approved call.
244
+ `install-mcps.sh:197`/`:297` and `bootstrap-serena.sh:35`/`:51` therefore run
245
+ unaffected, while the same `npm install -g @playwright/mcp@latest` typed at the
246
+ prompt IS gated. Both are correct: consent was given once for the setup script as
247
+ a whole; an ad-hoc install carries no such consent.
248
+
249
+ **Known friction, real and expected.**
250
+ `lib/skills/frontend-taste/SKILL.md:29` instructs Claude to run
251
+ `cd ~/code/house-style/preview && npm i && npm run dev`. That command *is*
252
+ hook-visible and will be gated. It is the one genuine friction point this gate
253
+ introduces in-repo — not a bug. Approve it by running it yourself.
254
+
255
+ **Not covered, deliberately:** bare `uvx <pkg>` with no `--from`; `npx`; and a
256
+ manager that is not the segment's first token, so `claude mcp add … -- uvx --from
257
+ …` does not match.
258
+
259
+ #### `absolute-path-guard.js`
260
+
261
+ **Blocks evasive spellings** — not commands — of eleven names: `rm`, `dd`,
262
+ `mkfs`, `sudo`, `diskutil`, `chmod`, `chown`, `shutdown`, `launchctl`, `crontab`,
263
+ `osascript`. Three evasion kinds fire it: a leading `\` (`\rm`, which also skips
264
+ alias and shell-function lookup), a `/` anywhere in the token (`/bin/rm`, `./rm`),
265
+ or having skipped a wrapper or env-assignment prefix to reach it (`env rm`,
266
+ `FOO=1 rm`, `command`/`exec`/`nohup`).
267
+
268
+ **Why a hook.** A deny rule matches a literal spelling anchored at the start of
269
+ the string. `Bash(rm -rf ~*)` blocks `rm -rf ~` and nothing else — `/bin/rm -rf
270
+ ~`, `\rm -rf ~`, and `env rm -rf ~` run the identical program and none match.
271
+ Enumerating path prefixes is unbounded (`/bin`, `/usr/bin`, `/usr/sbin`,
272
+ `/opt/homebrew/bin`, any relative path), so the class only closes by parsing.
273
+
274
+ **It fires on the spelling, never on the command — and this is load-bearing.**
275
+ The deny entries for these names are deliberately *narrow*: `rm` is denied only
276
+ for catastrophic targets (`rm -rf ~*`, `rm -rf /Users*`), `chmod` only for
277
+ `777`/`a+rwx`/`+s`, `chown` only for `-R`, `diskutil` only for the erase verbs,
278
+ `launchctl` only for `load`/`bootstrap`/`submit`. An unconditional block on the
279
+ name would break routine `rm build/out.js`, `chmod +x script.sh`, `chown me
280
+ file`, `diskutil list`, and `launchctl list` — a regression far worse than the gap
281
+ being closed. A plainly-spelled invocation therefore falls straight through to the
282
+ permission engine, which decides it on its own merits.
283
+
284
+ **Argument-blind is deliberate.** The hook grants nothing; it only forces a
285
+ command back into the form the deny list can inspect. Inspecting arguments to
286
+ decide whether to fire would be literal-spelling matching again.
287
+
288
+ **Accepted consequence, stated plainly:** `/bin/rm file.txt` is blocked even
289
+ though `rm file.txt` is allowed. The escape hatch is to retype it with the plain
290
+ name — which is not a workaround, it re-exposes the command to the deny rules,
291
+ which will permit it if it is safe.
292
+
293
+ **The list is intentionally partial** — eleven names, not a mirror of the ~116
294
+ deny entries. Each addition costs a class of false positives, so names are added
295
+ only when the consequence of an ungated run is destructive and irreversible.
296
+
297
+ **Not covered, deliberately:** `xargs rm` and `find -exec rm` (the command is not
298
+ a first token); `env -i rm` (the `-i` flag halts the wrapper walk); `sh -c
299
+ '/bin/rm …'` (covered by `interpreter-indirection-guard.js`).
300
+
301
+ #### `protected-write-guard.js`
302
+
303
+ Three rules that look unrelated but share one property: each is a **write to
304
+ something that executes later**, expressed in a form the permission engine does
305
+ not recognise as a write at all.
306
+
307
+ 1. **Redirects into files that execute later.** `>`/`>>` targeting `~/.zshrc`,
308
+ `~/.zshenv`, `~/.zprofile`, `~/.bashrc`, `~/.bash_profile`, `~/.profile`,
309
+ `~/.gitconfig`, `~/.claude/settings.json`, `~/.claude/settings.local.json`,
310
+ anything under `~/.claude/hooks/`, or `~/Library/LaunchAgents/`. `~`, `$HOME`,
311
+ and `${HOME}` are expanded and relative targets resolve against the session's
312
+ `cwd`, so `echo x > .zshrc` run from `$HOME` is caught. This is the documented
313
+ gap in the deny list's protected-dotfile group: `Edit(~/.zshrc)` covers the
314
+ Edit tool and the Bash writers the engine recognises, but `echo … >> ~/.zshrc`
315
+ is an `echo`, and the file it lands in is a redirect target the matcher never
316
+ inspects. The deny list has no vocabulary for "wherever this command's stdout
317
+ ends up".
318
+ 2. **Dynamic-linker injection** — `DYLD_INSERT_LIBRARIES=`, `DYLD_LIBRARY_PATH=`,
319
+ `LD_PRELOAD=`, `LD_LIBRARY_PATH=` anywhere in a segment. This is not a command
320
+ at all: `DYLD_INSERT_LIBRARIES=/tmp/x.dylib git log` is, to a literal matcher,
321
+ a read-only `git log`. The code that runs is a library loaded before `main()`.
322
+ 3. **`git -c` config keys git executes itself** — `core.fsmonitor=<non-empty>`
323
+ and `alias.x=!…`, in both the spaced (`-c key=value`) and fused
324
+ (`-ckey=value`) forms. Git runs its own config on ordinary commands, so this
325
+ is remote code execution that is neither a fetch nor a write nor a watched
326
+ subcommand: `Bash(git status:*)` — an entry most people would call obviously
327
+ safe — matches it (GHSA-9ccr-r5hg-74gf, TALOS-2025-2243). An **empty**
328
+ `core.fsmonitor=` is the CVE *remediation* and is allowed; `git -c
329
+ alias.foo=status` and `git -c user.name=…` are unaffected, since only a
330
+ `!`-prefixed alias body is executed as a shell command.
331
+
332
+ **Why the rules match differently.** Rule 1 is a whole-segment *regex* scan: a
333
+ redirect operator can appear anywhere, and `>>~/.zshrc` is one whitespace token
334
+ while `>> ~/.zshrc` is two, so tokenizing first would split the operator from its
335
+ target in one form and not the other. (`(?![&>])` is what keeps `2>&1` from being
336
+ read as a redirect to a file named `&1`.) Rules 2 and 3 are whole-segment *token*
337
+ scans, because an assignment can appear as a bare prefix, an argument to `env`, or
338
+ an argument to `export`, and `-c` can sit anywhere before a git subcommand.
339
+
340
+ **Not covered, deliberately:** `tee ~/.zshrc` and `cp x ~/.zshrc` write the same
341
+ files without a redirect (worth a follow-up); redirect targets resolve
342
+ *lexically* rather than through `realpath()`, because the target usually does not
343
+ exist yet, so a pre-existing symlink with an unremarkable name pointing into
344
+ `~/.claude/` is missed; `git --config-env=alias.x=VAR` reads the payload from an
345
+ environment variable, so the dangerous string never appears in the command.
346
+
347
+ #### `claude-settings-guard.js`
348
+
349
+ **The only new guard that matches file tools rather than Bash** —
350
+ `env-file-guard.js` is the structural precedent. The Bash side of the same
351
+ protected paths (`echo … >> ~/.claude/settings.json`) is
352
+ `protected-write-guard.js` rule 1.
353
+
354
+ **Blocks** `Edit`/`Write`/`NotebookEdit`/`MultiEdit` targeting
355
+ `~/.claude/settings.json` and `~/.claude/settings.local.json` — **except** when
356
+ the session's working directory sits inside a genuine bootstrap-claude checkout —
357
+ and anything under `~/.claude/hooks/` with **no exception at all**.
358
+
359
+ **A checkout is identified by marker file, not by path substring.**
360
+ `cwd.includes('bootstrap-claude')` is spoofed by `mkdir bootstrap-claude`, so
361
+ both of these must hold at a candidate root: `lib/scripts/templates/settings-deny.json`
362
+ exists, **and** `package.json` at that root parses with
363
+ `name === "@codewizard-dt/bootstrap"`. The walk up from the session cwd is lexical
364
+ (`path.dirname`, so it cannot follow a symlink into a cycle), capped at 64
365
+ iterations, and lazy — a MultiEdit batch touching no protected path never hits the
366
+ filesystem. No marker root found means no exception.
367
+
368
+ **Why the exception has to live in a hook.** `Edit(~/.claude/settings.json)` and
369
+ `Edit(~/.claude/settings.local.json)` were deny entries and had to be *removed*
370
+ for the carve-out to be expressible at all: deny beats allow at every scope, and a
371
+ hook returning `allow` cannot loosen a deny rule. While the entries existed the
372
+ exception was unsayable — and this repo legitimately manages those files (that is
373
+ exactly what `install-global.sh` and `merge-settings-deny.js` do), so a blanket
374
+ deny made the repo unable to work on itself. A hook is the only layer that can
375
+ carry a conditional. The shipped deny list carries zero `.claude/settings`
376
+ entries today and `test/settings-deny.test.js` locks that in, so the carve-out is
377
+ live rather than dead on arrival.
378
+
379
+ **Why the `~/.claude/hooks/` tree is also checked here, and is not duplication.** The
380
+ `Edit(~/.claude/hooks/**)` and `Edit(**/.claude/hooks/**)` deny entries remain in
381
+ place and are the primary control. But file permission checks consult only
382
+ `Edit(path)` and `Read(path)`: `Write(...)` rules are accepted by the settings
383
+ parser and then never consulted, while the Write *tool* still works. So
384
+ `Write(~/.claude/hooks/evil.js)` had no deny coverage whatsoever, and neither did
385
+ the MultiEdit or NotebookEdit surface. That is the deny list proving insufficient,
386
+ not the hook restating it.
387
+
388
+ **Path resolution handles targets that do not exist yet.** `realpathSync()` throws
389
+ on an uncreated path — the normal case for a `Write` — so the hook walks up to the
390
+ nearest ancestor that *does* resolve, resolves that, and re-attaches the
391
+ components below it. A new file inside a symlinked directory therefore still
392
+ resolves through the symlink into `~/.claude/`. `os.homedir()` goes through the
393
+ same function so both sides of the comparison are real paths, and a literal `~` in
394
+ `tool_input` is expanded first — the shell never sees it, it arrives raw in JSON.
395
+ `NotebookEdit` names its target `notebook_path`; `MultiEdit` is checked per
396
+ `edits[].file_path`, so a protected target cannot ride along in a batch.
397
+
398
+ **Residual risk, accepted deliberately.** An agent working inside a genuine
399
+ bootstrap-claude checkout can still self-grant permissions by writing
400
+ `~/.claude/settings.json`. This hook does not prevent that and is not trying to:
401
+ managing those settings is this repo's entire purpose, so the exception *is* the
402
+ feature. The containment for a compromised agent inside this repo is OS-level
403
+ sandboxing, not this hook. **Do not "harden" this by removing the exception** —
404
+ it breaks the repo and still would not contain a Bash-capable agent.
405
+
406
+ **Not covered, deliberately:** project-level `.claude/settings.json` files (this
407
+ hook is scoped to the user-global `~/.claude/` tree); and writing a script
408
+ elsewhere and executing it, which is a Bash concern.
409
+
410
+ #### `env-content-read-guard.js`
411
+
412
+ > **Wiring warning:** the matcher must be
413
+ > `Bash|mcp__serena__.*|mcp__plugin_[^_]+_serena__.*`. Under a `Bash`-only matcher
414
+ > the entire Serena half of this hook is silently inert.
415
+
416
+ **Stops `.env` *contents* reaching the transcript** on the two surfaces that can
417
+ emit them. This closed a hole that was live, not hypothetical: `cat .env` printed
418
+ secrets into the conversation, because three controls each assumed one of the
419
+ others covered it. `Read(**/.env)` is a *file-tool* rule that a Bash command never
420
+ reaches; `env-file-guard.js` matches only `Read|Write|Edit|MultiEdit`, never Bash
421
+ and never an MCP tool; and `serena-bash-grep-block.js` intercepts
422
+ `cat`/`head`/`tail`/`less`/`more`/`bat` only when the target is `.md` or a code
423
+ extension, which `.env` is neither.
424
+
425
+ **Relationship to `serena-bash-grep-block.js`.** That hook's grep phase goes
426
+ further and *explicitly allows* `.env` targets as a "non-code extension"
427
+ (`:126`, `:160`, `:189`). That is correct for its purpose — Serena-first
428
+ navigation does not care about non-code files — and wrong for this one, and it is
429
+ why `grep KEY .env` leaked. The two are complementary: the navigation hook decides
430
+ where you should look for *code*, this one decides what may be *displayed*.
431
+
432
+ **Bash side.** Content-emitting readers pointed at a `.env`: whole-file dumpers
433
+ (`cat tac nl head tail less more most bat od xxd hexdump strings rev`), the grep
434
+ family (`grep egrep fgrep rg ag ack` — a grep against a credentials file prints
435
+ the payload), and stream processors used as readers (`sed awk gawk cut sort uniq
436
+ paste column`). Also copiers (`cp scp rsync ditto install`) with a `.env` as the
437
+ *source*, and an input redirect `< .env` regardless of verb (which catches
438
+ `tee /tmp/x < .env`). `.env.example` is always allowed, matching the standing
439
+ exception in `env-file-guard.js` and the shipped gitignore
440
+ (`templates/gitignore:23-25`) — so the guard and the thing that keeps secrets out
441
+ of git define "secret" identically.
442
+
443
+ **Direction is load-bearing.** `cat .env.example > .env` is ordinary scaffolding
444
+ and passes; `cat .env > /tmp/x` is exfiltration and is blocked. The only thing
445
+ separating them is which side of the operator the non-example path sits on, so
446
+ output-redirect destinations are dropped from the input-path set while
447
+ input-redirect sources are kept. Likewise `cp .env.example .env` passes because
448
+ only a `.env` used as a *source* fires the copier rule.
449
+
450
+ **Serena side.** Tools that return file contents — `read_file`,
451
+ `search_for_pattern`, `find_symbol` (`include_body=true`),
452
+ `find_referencing_symbols`, `get_symbols_overview` — plus the mutating tools
453
+ `create_text_file`, `replace_content`, `replace_in_files`, `replace_lines`,
454
+ `delete_lines`, `insert_at_line`, whenever a `relative_path`, `file_path`, `path`,
455
+ or `paths_include_glob` names a `.env`. The mutating half is parity, not leak
456
+ prevention: `env-file-guard.js` says a `.env` can be neither read nor written, and
457
+ these tools reach the file without passing through it. `find_file` and `list_dir`
458
+ return paths only — knowing a `.env` exists is not a leak — so they are
459
+ deliberately absent.
460
+
461
+ Closing only Bash would have moved the leak rather than sealed it:
462
+ `serena-bash-grep-block.js` actively redirects Bash greps toward Serena, so
463
+ `search_for_pattern` is the first thing reached for after a Bash block, and it
464
+ returns exactly the same lines.
465
+
466
+ **`source .env` and `. .env` remain permitted. This is deliberate — do not "close
467
+ the gap" later.** `CLAUDE.md` grants it and `env-file-guard.js:39` says so in its
468
+ own deny message. Sourcing loads values into the environment and prints *nothing*;
469
+ the leak is sourcing **plus emission** (`source .env && echo $KEY`), and the
470
+ emission half can be written without `source` at all. Blocking `source` would
471
+ block the safe case and miss the unsafe one. This hook governs **display and
472
+ duplication, not use** — every deny message says so and names `source .env &&
473
+ ./script.sh` as the alternative, along with reading `.env.example` to learn which
474
+ keys exist.
475
+
476
+ **Not covered, deliberately:** a `search_for_pattern` with no `relative_path`
477
+ (denying every unscoped search would make the tool unusable, and Serena's project
478
+ scan honours gitignore, where `.env` always sits); the same for a `relative_path`
479
+ naming a *directory* that contains a `.env`; `find . -name .env -exec cat {} +`
480
+ and `xargs cat` (the reader is not at the front of a segment); `git show
481
+ HEAD:.env`; `docker exec … cat .env`.
482
+
483
+ **Follow-up.** `isBlockedEnvFile` is byte-identical to `env-file-guard.js:6-13`
484
+ and is annotated "change it in both places or in neither". It should be extracted
485
+ into `lib/` so the two cannot drift; that was left undone here because it means
486
+ editing a live shipped control for a refactor.
487
+
488
+ #### Known divergence: how much of a segment each guard inspects
489
+
490
+ `absolute-path-guard.js` inspects only the **first token** of each segment, so
491
+ `echo "use /bin/rm"` and `ls /bin/rm` pass cleanly. The other three Bash guards
492
+ scan the **whole segment**, so a command that merely quotes a guarded form can
493
+ fire on text it is only talking about — `grep -rn "cat .env" docs/` does.
494
+ (`git-protected-ops-block.js` has always behaved this way too.)
495
+
496
+ **How far the quoting actually protects you is inconsistent, and it is worth
497
+ knowing which way.** Where the guard matches a *token* against a fixed name, an
498
+ adjacent quote character defeats the match and the command passes: `echo "bash -c
499
+ foo"` **allows** (the opening `"` is part of the token, so the basename lookup
500
+ misses) while unquoted `echo bash -c foo` **denies**. Same for `echo "add it with
501
+ >> ~/.zshrc"`, which **allows** because the trailing `"` attaches to the redirect
502
+ target and resolves to `~/.zshrc"`. Where the guard matches a *substring* instead,
503
+ the quote does not help. So the false-positive class is real, but a quoted example
504
+ is often not an instance of it — do not reason from one to the other. All four
505
+ spellings above are pinned in `test/command-class-hooks.test.js` so this stays
506
+ true.
507
+
508
+ This is a real inconsistency and it is left in place on purpose. Unifying it means
509
+ one of two bad trades:
510
+
511
+ - Narrow the whole-segment guards to first-token-only, which destroys them. An
512
+ interpreter's `-c` flag, a redirect operator, a `DYLD_` assignment, a `git -c`
513
+ config pair, and a reader's `.env` operand never sit at the front of a command.
514
+ - Teach all four to parse shell quoting well enough to tell a mention from an
515
+ invocation — i.e. reimplement the shell inside a hook.
516
+
517
+ The split is not arbitrary: first-token-only is right for a guard asking *"what
518
+ program is this segment running?"*, whole-segment is right for a guard asking
519
+ *"does this segment contain this construct?"*. The cost of the divergence is that
520
+ a quoted mention triggers a block. The remedy is one rephrase, and every deny
521
+ message names it — cheap enough that neither trade above is worth making.
522
+
33
523
  ### Serena-first enforcement hooks (ported from `claude-code-lsp-enforcement-kit`)
34
524
 
35
525
  These hooks enforce Serena as the primary tool for code navigation and editing.
@@ -53,6 +543,12 @@ does its own matching in JS (splitting on `;`, `&&`, `||`, `|` and handling
53
543
  `git -C …`, `--no-pager`, etc.), so enforcement never depends on the same
54
544
  permission-matcher path that lets compound/piped commands slip past a `deny` rule.
55
545
 
546
+ It also still carries its own inline copies of the four `lib/command-parse.js`
547
+ helpers rather than requiring them. The refactor is behaviour-identical on
548
+ inspection, but it is a working shipped control and `command-parse.js` has so far
549
+ only been exercised statically — migrating one onto the other trades zero risk for
550
+ nonzero risk to save about ten lines. Revisit once UAT has exercised the helper.
551
+
56
552
  ### Health tracking & fail-open enforcement
57
553
 
58
554
  The Serena guards block Grep/Read/Edit/Write/Bash and demand Serena tools. If the
@@ -125,9 +621,31 @@ as a last resort) is the only guaranteed path back to a working session.
125
621
 
126
622
  | File | Used by |
127
623
  |------|---------|
624
+ | `lib/command-parse.js` | All six [command-class guards](#command-class-guards) — `readHookInput(handler)` (stdin accumulate + `JSON.parse`; unparseable input exits 0 silently), `splitSegments(cmd)` (the `/;\|&&\|\|\|\|\|/` split, lifted verbatim from `git-protected-ops-block.js`), `tokenize(segment)`, and `deny(reason)` (the `permissionDecision: 'deny'` envelope). Every helper is fail-open: a hook that exits non-zero breaks a call it was never meant to gate. `readHookInput` carries **no** `tool_name` guard by design — `claude-settings-guard.js` matches file tools, not Bash — so each hook does its own |
128
625
  | `lib/serena.js` | All Serena hooks — intent→tool mapping, `isAllowedPath`, block-message builders, per-project state file (`getStateFilePath`/`readStateFile`/`writeStateFile`/`shouldEnforceSerena`/`defaultFlag`/`defaultHealth`), an advisory lock + atomic read-modify-write helper (`acquireLock`/`releaseLock`/`updateStateFile`) used by every hook that writes the state file, failure classification + process health (`classifySerenaFailure`/`isSerenaProcessAlive` — diagnostic only, never terminates the process), and consolidated symbol detection (`isCodeSymbol`/`extractSymbolsFromPattern`) |
129
626
  | `lib/serena-languages.js` | `lib/serena.js` — reads `.serena/project.yml` to scope enforcement to configured languages |
130
627
 
628
+ #### Follow-up: shared decision functions
629
+
630
+ `interpreter-indirection-guard.js` re-evaluates an extracted payload by
631
+ **spawning** five sibling guards as subprocesses — a ~270 ms cost whenever a
632
+ command contains an interpreter plus an eval flag, and five `node` starts to
633
+ answer a question that is pure computation.
634
+
635
+ The better eventual shape is to extract each guard's decision logic into shared
636
+ pure functions here in `lib/` — `decide(command, cwd) → {deny, reason} | null` —
637
+ leaving each hook file as a thin stdin/stdout wrapper around its own function.
638
+ The interpreter guard would then call five functions instead of spawning five
639
+ processes, and the spawn-failure handling (timeouts, missing files, non-JSON
640
+ output, non-zero exits) would disappear along with the processes.
641
+
642
+ It is **deliberately not done**, for the reason recorded in TASK-027 step 7: a
643
+ working control should not be migrated onto newer code to save a few lines. These
644
+ are five shipped, globally-installed controls; subprocess re-evaluation requires
645
+ zero changes to them, uses them exactly as Claude Code does, and stays in sync
646
+ automatically. The refactor trades that guarantee for latency, and the latency is
647
+ only paid on commands that already contain an interpreter.
648
+
131
649
  ### State file JSON schema
132
650
 
133
651
  One file per project cwd, `~/.claude/state/lsp-ready-<md5(cwd).slice(0,12)>`,
@@ -191,6 +709,24 @@ hook objects to its existing `hooks` array rather than creating a second block.
191
709
  }
192
710
  ]
193
711
  },
712
+ {
713
+ "matcher": "Edit|Write|NotebookEdit|MultiEdit",
714
+ "hooks": [
715
+ {
716
+ "type": "command",
717
+ "command": "node ~/.claude/hooks/claude-settings-guard.js"
718
+ }
719
+ ]
720
+ },
721
+ {
722
+ "matcher": "Bash|mcp__serena__.*|mcp__plugin_[^_]+_serena__.*",
723
+ "hooks": [
724
+ {
725
+ "type": "command",
726
+ "command": "node ~/.claude/hooks/env-content-read-guard.js"
727
+ }
728
+ ]
729
+ },
194
730
  {
195
731
  "matcher": "Read",
196
732
  "hooks": [
@@ -260,6 +796,22 @@ hook objects to its existing `hooks` array rather than creating a second block.
260
796
  {
261
797
  "type": "command",
262
798
  "command": "node ~/.claude/hooks/git-protected-ops-block.js"
799
+ },
800
+ {
801
+ "type": "command",
802
+ "command": "node ~/.claude/hooks/interpreter-indirection-guard.js"
803
+ },
804
+ {
805
+ "type": "command",
806
+ "command": "node ~/.claude/hooks/package-install-consent.js"
807
+ },
808
+ {
809
+ "type": "command",
810
+ "command": "node ~/.claude/hooks/absolute-path-guard.js"
811
+ },
812
+ {
813
+ "type": "command",
814
+ "command": "node ~/.claude/hooks/protected-write-guard.js"
263
815
  }
264
816
  ]
265
817
  }
@@ -290,6 +842,32 @@ hook objects to its existing `hooks` array rather than creating a second block.
290
842
  }
291
843
  ```
292
844
 
845
+ Three notes on the command-class guard matchers, each of which makes a hook
846
+ silently inert if it is wrong:
847
+
848
+ - **`env-content-read-guard.js` gets its own block**, matcher
849
+ `Bash|mcp__serena__.*|mcp__plugin_[^_]+_serena__.*`. Do **not** move it into the
850
+ `Bash` block to tidy things up: the guard handles two surfaces, and under a
851
+ `Bash`-only matcher its whole Serena half never receives a call. Multiple
852
+ `PreToolUse` blocks may match the same tool and every matching hook runs, so a
853
+ Bash command legitimately passes through both this block and the `Bash` one.
854
+ - **`claude-settings-guard.js` is a file-tool hook**, matcher
855
+ `Edit|Write|NotebookEdit|MultiEdit` — it is the one command-class guard that
856
+ never sees a Bash call. Note this is *not* the same matcher as
857
+ `env-file-guard.js`'s `Read|Write|Edit|MultiEdit`: this guard adds
858
+ `NotebookEdit` and drops `Read`, because a read of a settings file is harmless
859
+ and a notebook write is not.
860
+ - The other four are `Bash`-matched and are appended to the existing `Bash` block.
861
+ None of them takes an `if:` filter — like `git-protected-ops-block.js` they do
862
+ their own matching in JS, so enforcement never depends on the same
863
+ permission-matcher path that lets compound and piped commands slip past a `deny`
864
+ rule.
865
+
866
+ Reminder: `install-global.sh` rsyncs these scripts to `~/.claude/hooks/` on every
867
+ run, but it never touches the `hooks` section of `~/.claude/settings.json`.
868
+ Registration is the one-time manual step above; until it is done every script
869
+ here sits on disk and does nothing.
870
+
293
871
  The `PostToolUse` matcher is broadened from the six navigation tools to **all**
294
872
  Serena tools so every call feeds health tracking; the tracker gates the read-guard
295
873
  nav counters internally (only the six nav/exploration tools advance the gate, as
@@ -299,7 +877,7 @@ for why both events are wired. If your Claude Code build does not support
299
877
  `PostToolUseFailure`, that block is simply ignored and the `PostToolUse` error
300
878
  path still catches failures.
301
879
 
302
- The companion `deny` entries (belt-and-suspenders for normal modes) no longer
880
+ The companion `deny` entries (defence in depth alongside these hooks) no longer
303
881
  need manual wiring: the full canonical deny list lives in
304
882
  [`lib/scripts/templates/settings-deny.json`](../scripts/templates/settings-deny.json)
305
883
  and is merged into `~/.claude/settings.json` automatically by
@@ -308,10 +886,12 @@ merge is additive-only — your own entries are never removed or reordered.
308
886
 
309
887
  Two documented caveats on those deny rules:
310
888
 
311
- - Deny rules are **not enforced** in `bypassPermissions` mode — that is exactly
312
- why these hooks exist (see above). The deny list covers normal modes.
313
- - `Bash(git push --force *)` / `Bash(git push -f *)` are prefix matches, so a
314
- command like `git push origin main --force` slips past them — partial
315
- protection only.
889
+ - Deny rules match a **literal command spelling**, not a capability — that is
890
+ exactly why these hooks exist (see above). They are enforced in every mode,
891
+ `bypassPermissions` included; what they cannot do is see through `/bin/rm`,
892
+ `bash -c`, or `python -c`.
893
+ - Deny rules cannot carry allowlist exceptions: a broad deny blocks every
894
+ matching call even when a narrower `allow` rule also matches. So
895
+ `Bash(git stash:*)` also blocks read-only `git stash list`.
316
896
 
317
897
  Hooks load at session start, so restart any running session after wiring.