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