@codewizard-dt/bootstrap 2.17.0 → 2.19.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.
- package/lib/hooks/README.md +94 -3
- package/lib/hooks/absolute-path-guard.js +5 -0
- package/lib/hooks/claude-settings-guard.js +5 -0
- package/lib/hooks/env-content-read-guard.js +13 -3
- package/lib/hooks/env-file-guard.js +42 -0
- package/lib/hooks/interpreter-indirection-guard.js +7 -0
- package/lib/hooks/lib/command-parse.js +8 -0
- package/lib/hooks/lib/serena-languages.js +94 -1
- package/lib/hooks/lib/serena.js +228 -0
- package/lib/hooks/mv-absolute-path-block.js +84 -3
- package/lib/hooks/package-install-consent.js +11 -0
- package/lib/hooks/protected-write-guard.js +7 -0
- package/lib/hooks/serena-bash-grep-block.js +507 -44
- package/lib/hooks/serena-first-glob-guard.js +65 -20
- package/lib/hooks/serena-first-guard.js +98 -2
- package/lib/hooks/serena-first-read-guard.js +92 -2
- package/lib/hooks/serena-pre-delegation.js +123 -0
- package/lib/hooks/serena-write-guard.js +56 -3
- package/lib/scripts/README.md +306 -1
- package/lib/scripts/bootstrap-prefs.js +734 -0
- package/lib/scripts/install-global.sh +188 -18
- package/lib/scripts/install-mcps.sh +102 -14
- package/lib/scripts/lib.sh +581 -11
- package/lib/scripts/merge-gitignore.sh +201 -15
- package/lib/scripts/sync-wiki-scaffold.sh +33 -4
- package/lib/scripts/templates/CLAUDE-wiki.md +1 -1
- package/lib/scripts/templates/bootstrap-prefs-schema.json +175 -0
- package/lib/scripts/update-project.sh +42 -9
- package/lib/skills/README.md +2 -1
- package/lib/skills/bootstrap-config/SKILL.md +154 -0
- package/lib/skills/git-commit/SKILL.md +89 -6
- package/lib/skills/research/SKILL.md +34 -3
- package/lib/skills/simplify/SKILL.md +1 -1
- package/lib/skills/uat-auto/SKILL.md +9 -4
- package/lib/skills/uat-auto-plus/SKILL.md +6 -6
- package/lib/skills/uat-generate/SKILL.md +47 -7
- package/lib/skills/uat-walk/UAT-CORE.md +41 -6
- package/lib/skills/wiki-query/SKILL.md +48 -8
- package/package.json +1 -1
|
@@ -1,13 +1,40 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
2
|
'use strict';
|
|
3
3
|
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
|
|
4
|
+
/**
|
|
5
|
+
* serena-bash-grep-block.js — PreToolUse / Bash
|
|
6
|
+
*
|
|
7
|
+
* Blocks: shell commands that navigate or edit code the way Serena should — the grep
|
|
8
|
+
* family aimed at code symbols, cat/head/tail/sed/awk reads of code and markdown
|
|
9
|
+
* files, ls/tree/find over source directories, and in-place edits of code files
|
|
10
|
+
* (sed -i, awk -i inplace, perl -i, and redirect writes).
|
|
11
|
+
* Why a hook: a deny rule matches a literal command spelling; the verdict here depends
|
|
12
|
+
* on the command's *pattern argument* and its *target's extension*. `grep UserService
|
|
13
|
+
* src/` must block while `grep -c error app.log` must not — same verb, same flags.
|
|
14
|
+
* No settings.json pattern can read a quoted regex, classify its tokens as code
|
|
15
|
+
* symbols, and then check what file the operand names.
|
|
16
|
+
* Fails: open — every failure path exits 0 and allows. Unparseable stdin, a non-Bash
|
|
17
|
+
* payload, `CLAUDE_MIGRATION=1`, and an unhealthy Serena (`shouldEnforceSerena()`
|
|
18
|
+
* false) all pass straight through, so a crashed or hung MCP server cannot trap the
|
|
19
|
+
* agent between broken Serena calls and blocked shell fallbacks.
|
|
20
|
+
* False positives: a command that merely *mentions* a guarded form fires the rule that
|
|
21
|
+
* owns it, because nothing here parses shell quoting. The load-bearing case in this
|
|
22
|
+
* repo is an arrow function followed by a `.js` string — `x => require("a.js")` reads
|
|
23
|
+
* as `>` redirecting into a code file. Escape hatch: write `function () {}` instead
|
|
24
|
+
* of `=>` (pinned in UAT-033 and UAT-034, whose inline scripts are deliberately
|
|
25
|
+
* arrow-free). Second known case: this file's own name. `git log -- lib/hooks/
|
|
26
|
+
* serena-bash-grep-block.js` blocks because `-grep-` satisfies `\bgrep\b`; escape
|
|
27
|
+
* hatch is a glob that omits the word, e.g. `'lib/hooks/serena-bash-*.js'`.
|
|
28
|
+
* See README.md § "Serena-first enforcement hooks (ported from
|
|
29
|
+
* `claude-code-lsp-enforcement-kit`)" for this hook's row, and § "Health tracking &
|
|
30
|
+
* fail-open enforcement" for the fail-open contract every Serena guard shares.
|
|
31
|
+
*
|
|
32
|
+
* Structure: three ordered phases inside checkSegment() — see the PHASE banners there.
|
|
33
|
+
*/
|
|
10
34
|
|
|
35
|
+
// NOTE: `path` is imported but never referenced anywhere in this file. Harmless, but it
|
|
36
|
+
// is dead — do not take its presence as evidence that path resolution happens here; the
|
|
37
|
+
// real resolution lives in lib/serena.js (`isAllowedPath`, `isOutsideProject`).
|
|
11
38
|
const path = require('path');
|
|
12
39
|
const {
|
|
13
40
|
buildSuggestion, buildStructuredBlockResponse, buildBashFsSuggestion, isAllowedPath,
|
|
@@ -17,6 +44,17 @@ const {
|
|
|
17
44
|
|
|
18
45
|
// Zero-width / formatting chars that would split tokens invisibly and
|
|
19
46
|
// bypass ASCII regex symbol detection.
|
|
47
|
+
//
|
|
48
|
+
// Why these specific ranges: a security audit of the upstream kit (CHANGELOG 2.1.0,
|
|
49
|
+
// "Unicode zero-width character bypass") found that a pattern with a ZWSP spliced into
|
|
50
|
+
// it tokenized as one non-ASCII blob, matched none of the PascalCase/camelCase regexes,
|
|
51
|
+
// and sailed through. The set is the soft hyphen plus the three formatting blocks that
|
|
52
|
+
// render as nothing: ZWSP/ZWNJ/ZWJ/LRM/RLM, the word-joiner and invisible-operator
|
|
53
|
+
// range, and the BOM.
|
|
54
|
+
//
|
|
55
|
+
// Stripping rather than rejecting is deliberate: a stripped command is still judged on
|
|
56
|
+
// its real symbols, whereas rejecting outright would deny commands that picked up a BOM
|
|
57
|
+
// by accident. This is a guardrail against evasion, not a security boundary.
|
|
20
58
|
const ZERO_WIDTH = /[\u00AD\u200B-\u200F\u2060-\u2064\uFEFF]/g;
|
|
21
59
|
|
|
22
60
|
let raw = '';
|
|
@@ -24,11 +62,24 @@ process.stdin.setEncoding('utf8');
|
|
|
24
62
|
process.stdin.on('data', d => { raw += d; });
|
|
25
63
|
process.stdin.on('end', () => {
|
|
26
64
|
let data;
|
|
65
|
+
// Fail-open #1: malformed stdin. A hook that exits non-zero on garbage input would
|
|
66
|
+
// break every Bash call rather than the ones it means to gate.
|
|
27
67
|
try { data = JSON.parse(raw); } catch { process.exit(0); }
|
|
28
68
|
if (data.tool_name !== 'Bash') process.exit(0);
|
|
69
|
+
// Set only by `lib/scripts/migrate-project.sh:228`, which runs Claude headless to
|
|
70
|
+
// bulk-move a legacy .docs/ tree. That work is inherently filesystem-shaped (git mv,
|
|
71
|
+
// find, sed over paths that are about to stop existing) and Serena has nothing to
|
|
72
|
+
// offer it, so the whole run opts out via one env flag rather than by teaching every
|
|
73
|
+
// rule below a migration-specific exception. `serena-first-read-guard.js:64` honours
|
|
74
|
+
// the same flag. Note it is an ordinary env var: it is a convenience for a trusted
|
|
75
|
+
// local script, not a control an untrusted caller is prevented from setting.
|
|
29
76
|
if (process.env.CLAUDE_MIGRATION === '1') process.exit(0);
|
|
30
77
|
|
|
31
|
-
// Fail-open: skip enforcement when Serena is unhealthy for this project.
|
|
78
|
+
// Fail-open #2: skip enforcement when Serena is unhealthy for this project.
|
|
79
|
+
// A missing, legacy, or 24h-expired state file all mean "assume healthy, enforce" —
|
|
80
|
+
// only an explicit `health.should_enforce === false`, written by the usage tracker
|
|
81
|
+
// after a transport-level failure with no live Serena process, disables the guard.
|
|
82
|
+
// See README § "Health tracking & fail-open enforcement".
|
|
32
83
|
if (!shouldEnforceSerena(readStateFile(getStateFilePath()))) process.exit(0);
|
|
33
84
|
|
|
34
85
|
// String coercion: non-string command would throw on .trim() and fail-open.
|
|
@@ -37,25 +88,63 @@ process.stdin.on('end', () => {
|
|
|
37
88
|
|
|
38
89
|
// Container bypass: `docker exec`, `docker compose exec`, `docker-compose exec`.
|
|
39
90
|
// Serena cannot reach into a container's filesystem, so the FS-exploration and
|
|
40
|
-
// in-place-editing rules
|
|
41
|
-
//
|
|
42
|
-
//
|
|
91
|
+
// in-place-editing rules have nothing to redirect such a command *to*.
|
|
92
|
+
//
|
|
93
|
+
// ORDERING (load-bearing): this runs on `fullCmd`, BEFORE the segment split below.
|
|
94
|
+
// Reversing it breaks the real case that motivated the current shape (upstream
|
|
95
|
+
// CHANGELOG 3.1.5): `ssh host 'docker exec ctr sh -c "ls /path; ls /path2"'` splits on
|
|
96
|
+
// the inner `;` into two bare `ls /path` segments, and the `docker exec` context that
|
|
97
|
+
// justified them is gone from both. Split first and the bypass can never fire.
|
|
98
|
+
//
|
|
99
|
+
// Intentionally NOT anchored at `^` — the docker invocation is frequently nested
|
|
100
|
+
// inside another command (`ssh host '...'`, `sudo`), which an anchored match misses.
|
|
101
|
+
// The `(?:\s+-{1,2}[\w-]+(?:[ =]\S+)?)*` run skips flags between the manager and
|
|
102
|
+
// `exec` so `docker --context prod compose -f x.yml exec` still matches.
|
|
103
|
+
//
|
|
104
|
+
// Accepted cost: this is a whole-command substring test, so a command that merely
|
|
105
|
+
// quotes the phrase (`echo "run docker exec first"`) disables the guard for that call.
|
|
106
|
+
// Serena-first is agent guidance rather than a security boundary, so an occasional
|
|
107
|
+
// over-permissive read is the cheaper error direction here than blocking real
|
|
108
|
+
// container work.
|
|
43
109
|
if (/(?:^|[\s'"])(?:sudo\s+)?(?:docker-compose|docker(?:\s+compose)?)(?:\s+-{1,2}[\w-]+(?:[ =]\S+)?)*\s+exec\b/i.test(fullCmd)) {
|
|
44
110
|
process.exit(0);
|
|
45
111
|
}
|
|
46
112
|
|
|
47
113
|
// SSH bypass: any ssh-to-remote-host invocation skips all Serena-first checks.
|
|
48
|
-
// Serena's LSP
|
|
49
|
-
//
|
|
50
|
-
//
|
|
51
|
-
//
|
|
52
|
-
//
|
|
114
|
+
// Same rationale as the container bypass — Serena's LSP is bound to this project's
|
|
115
|
+
// local root, so it cannot answer a question about a remote filesystem, and blocking
|
|
116
|
+
// `ssh host 'grep foo /etc/x'` would leave the agent with no way to do the work.
|
|
117
|
+
//
|
|
118
|
+
// ORDERING: also on `fullCmd`, also before the split, for the same reason — the
|
|
119
|
+
// remote command usually arrives as a quoted payload full of `;` and `&&`.
|
|
120
|
+
//
|
|
121
|
+
// Two deliberate narrowings in the regex:
|
|
122
|
+
// - the leading `(?:^|[\s'"|;&])` class means `\bssh\b` cannot match inside a longer
|
|
123
|
+
// word, so `sshpass -p … ssh host` still matches on its second token while a
|
|
124
|
+
// hypothetical `myssh` does not;
|
|
125
|
+
// - the trailing `\s+\S` requires ssh to have at least one argument, so the bare
|
|
126
|
+
// word "ssh" in prose or a variable name does not switch the whole guard off.
|
|
127
|
+
//
|
|
128
|
+
// NOTE: the narrowings reduce accidental matches; they do not make this tamper-proof.
|
|
129
|
+
// `echo 'ssh host'` still disables the guard for that command. Accepted for the same
|
|
130
|
+
// reason as above: guidance, not a boundary.
|
|
53
131
|
if (/(?:^|[\s'"|;&])ssh\s+\S/i.test(fullCmd)) {
|
|
54
132
|
process.exit(0);
|
|
55
133
|
}
|
|
56
134
|
|
|
57
135
|
// Split the command on `;`, `&&`, `||` and evaluate each segment independently.
|
|
58
|
-
// This catches cases like `ls src/ && cat src/index.ts` where only one segment is bad
|
|
136
|
+
// This catches cases like `ls src/ && cat src/index.ts` where only one segment is bad;
|
|
137
|
+
// judging the whole string at once would let a bad half hide behind a good half.
|
|
138
|
+
//
|
|
139
|
+
// `|` is deliberately NOT a separator here. Phase 1 needs to see a pipeline whole in
|
|
140
|
+
// order to decide whether a grep is filtering another tool's output (allowed) or
|
|
141
|
+
// searching the codebase (blocked) — splitting on `|` would destroy exactly the
|
|
142
|
+
// context that decision rests on. Phase 1 does its own `|` split internally.
|
|
143
|
+
//
|
|
144
|
+
// The split is quoting-unaware, like `lib/command-parse.js#splitSegments`: a `;` or
|
|
145
|
+
// `&&` inside a quoted string splits anyway. That errs toward evaluating more, smaller
|
|
146
|
+
// fragments, i.e. toward blocking — the safe direction for a guard whose failure mode
|
|
147
|
+
// is over-permissiveness. Teaching it real quoting means reimplementing the shell.
|
|
59
148
|
const segments = fullCmd.split(/;|&&|\|\|/).map(s => s.trim()).filter(Boolean);
|
|
60
149
|
|
|
61
150
|
for (const cmd of segments) {
|
|
@@ -73,65 +162,180 @@ process.stdin.on('end', () => {
|
|
|
73
162
|
/**
|
|
74
163
|
* Inspect a single command segment for violations.
|
|
75
164
|
* Returns { stderr, json } if the segment should be blocked, or null to allow.
|
|
165
|
+
*
|
|
166
|
+
* Three phases run in a fixed order. The order is not stylistic — see the ORDERING
|
|
167
|
+
* notes on each PHASE banner for what breaks if they are swapped. In short:
|
|
168
|
+
*
|
|
169
|
+
* PHASE 1 (grep family) must be first, because it is the only phase that inspects the
|
|
170
|
+
* *pattern* rather than the target, and it owns the pipeline-shape decision. Phases
|
|
171
|
+
* 2 and 3 would otherwise claim commands (`cat x.ts | grep Foo`) on the strength of
|
|
172
|
+
* the target alone and emit the wrong suggestion.
|
|
173
|
+
* PHASE 2 (reads) must precede PHASE 3 (writes), because the read rules carry negative
|
|
174
|
+
* lookaheads for `-i` that hand the editing variants down to phase 3. Reverse them
|
|
175
|
+
* and the redirect rules in phase 3 would claim `sed -n '1,5p' a.ts > /dev/null`.
|
|
176
|
+
*
|
|
177
|
+
* Every phase returns on first match, so within a phase the earlier rule wins.
|
|
76
178
|
*/
|
|
77
179
|
function checkSegment(cmd, fullCmd) {
|
|
78
|
-
// Strip transparent rtk proxy prefix so
|
|
79
|
-
//
|
|
180
|
+
// Strip the transparent `rtk` proxy prefix so the bypasses below match the real
|
|
181
|
+
// command. `rtk` wraps another command without changing its semantics, so
|
|
182
|
+
// `rtk git diff HEAD -- file.md` must be judged as `git diff HEAD -- file.md`;
|
|
183
|
+
// without the strip, the VCS bypass's `^(?:sudo\s+)?(?:git|gh|…)` anchor misses and
|
|
184
|
+
// an ordinary `git diff` on a markdown file gets blocked.
|
|
185
|
+
//
|
|
186
|
+
// Anchored at `^` and applied per-segment: only a leading `rtk` is a proxy prefix,
|
|
187
|
+
// whereas `rtk` appearing later is an argument and must stay visible to the rules.
|
|
188
|
+
// NOTE: `sudo` is stripped inline by the individual regexes rather than here, so
|
|
189
|
+
// `sudo rtk git …` (prefixes in that order) is not handled. Not known to occur.
|
|
80
190
|
cmd = cmd.replace(/^rtk\s+/, '');
|
|
81
191
|
|
|
82
192
|
// Out-of-project scoping: Serena is per-project and can't reach outside the
|
|
83
193
|
// root, so a segment whose every path target escapes the project passes
|
|
84
194
|
// through. Read-exploration commands additionally allow variable-led paths
|
|
85
195
|
// (e.g. `ls "$SDIR"`) that can't be proven in-project; in-place edits do not.
|
|
196
|
+
//
|
|
197
|
+
// ORDERING: this precedes all three phases because it is a scope question, not a
|
|
198
|
+
// policy question — if Serena cannot reach the target, no phase below has a valid
|
|
199
|
+
// suggestion to offer, and blocking would leave the agent with no route at all.
|
|
200
|
+
// "EVERY target escapes" rather than "any" is what keeps `cat /etc/hosts src/a.ts`
|
|
201
|
+
// blocked; see segmentEscapesProject().
|
|
86
202
|
if (segmentEscapesProject(cmd)) return null;
|
|
87
203
|
|
|
88
204
|
// VCS bypass: `git`, `gh`, `hg`, `jj`, `svn` may legitimately reference any
|
|
89
205
|
// path (e.g. `git diff HEAD -- foo.md`, `gh pr view`). They don't read file
|
|
90
206
|
// contents in the way `cat`/`sed`/`grep` do — the diff/show output is VCS
|
|
91
|
-
// metadata,
|
|
92
|
-
//
|
|
207
|
+
// metadata (revisions, hunks, blame) that Serena cannot produce at all, so there is
|
|
208
|
+
// no Serena call to redirect the user to. Skip all Phase 2/3 checks for them.
|
|
209
|
+
//
|
|
210
|
+
// Anchored at `^` on purpose: this asks "what program is this segment running?", not
|
|
211
|
+
// "does this segment mention git?". `cat src/a.ts && echo git` must not get a pass.
|
|
212
|
+
//
|
|
213
|
+
// `git grep` specifically is NOT exempted, and that is a reversal worth knowing about:
|
|
214
|
+
// upstream 3.1.1 added a `git grep`/`git show` substring bypass, and 3.1.2 removed it
|
|
215
|
+
// because `git grep` is a codebase search that bypasses Serena's LSP index — exactly
|
|
216
|
+
// the thing this hook exists to redirect. `git … | grep` stays allowed via Phase 1's
|
|
217
|
+
// pipe bypass, which is the legitimate case (filtering VCS output, not searching code).
|
|
93
218
|
if (/^(?:sudo\s+)?(?:git|gh|hg|jj|svn)\b/.test(cmd)) {
|
|
94
219
|
// Still run Phase 1 in case of `git log | grep MySymbol` patterns within a single segment.
|
|
95
220
|
// (Phase 1 has its own allowlist for git-piped grep, so this is safe.)
|
|
221
|
+
//
|
|
222
|
+
// KNOWN FALSE POSITIVE: this test is a whole-segment substring scan, so a VCS command
|
|
223
|
+
// whose *pathspec* contains the word grep is dragged into Phase 1 — e.g.
|
|
224
|
+
// `git log -- lib/hooks/serena-bash-grep-block.js` (the `-` delimiters make `-grep-`
|
|
225
|
+
// satisfy `\bgrep\b`), which then blocks on Phase 1's `lib/` fallback. Escape hatch:
|
|
226
|
+
// a pathspec glob that omits the word, e.g. `git log -- 'lib/hooks/serena-bash-*.js'`.
|
|
227
|
+
// Narrowing this to "grep is an actual command token" would need quote-aware parsing.
|
|
96
228
|
if (!/\b(grep|rg|ag|ack)\b/i.test(cmd)) return null;
|
|
97
229
|
}
|
|
98
230
|
|
|
99
231
|
// ── PHASE 1: grep-family detection ────────────────────────────────────────
|
|
100
|
-
|
|
232
|
+
//
|
|
233
|
+
// ORDERING: first, and it must stay first. This is the only phase that judges the
|
|
234
|
+
// *pattern* rather than the target, and the only one that reasons about pipeline
|
|
235
|
+
// shape. Run Phase 2 first and `cat src/a.ts | grep UserService` would be claimed by
|
|
236
|
+
// the cat rule on the strength of its target, producing a `get_symbols_overview`
|
|
237
|
+
// suggestion for what is really a symbol search — the wrong tool, and the pipe bypass
|
|
238
|
+
// that decides whether the grep was legitimate never gets consulted at all.
|
|
239
|
+
//
|
|
240
|
+
// The `/i` flag is not cosmetic: upstream CHANGELOG 2.1.0 records `GREP` and `RG` in
|
|
241
|
+
// caps evading a case-sensitive test.
|
|
101
242
|
if (/\b(grep|rg|ag|ack)\b/i.test(cmd)) {
|
|
102
243
|
// Markdown exploration: grep/rg on .md files must go through Serena
|
|
103
244
|
// (search_for_pattern / read_file). Markdown writing stays on native Edit/Write,
|
|
104
245
|
// but reading & searching are Serena's job — the symbol-pattern heuristic below
|
|
105
246
|
// misses lowercase prose queries like "addendum|amend|update", which would
|
|
106
247
|
// otherwise slip past on a markdown target.
|
|
248
|
+
//
|
|
249
|
+
// ORDERING within Phase 1: this deliberately precedes the pipe bypass. A markdown
|
|
250
|
+
// target is decided by *what file is named*, and that is true regardless of how many
|
|
251
|
+
// pipes the command has; letting the pipe bypass run first would let
|
|
252
|
+
// `find . | grep -f pat wiki/index.md` through on pipeline shape alone.
|
|
253
|
+
//
|
|
254
|
+
// Accepted cost of that choice: a `.md` path anywhere in a piped command blocks it,
|
|
255
|
+
// including when the file is incidental (`npm test | grep -c "README.md"`). The
|
|
256
|
+
// escape hatch is the suggested Serena call itself, which does the same job.
|
|
107
257
|
const mdTargetMatch = cmd.match(/(?:^|\s)((?:[~./\w-]+\/)?[\w.-]+\.md)\b/i);
|
|
108
258
|
if (mdTargetMatch) {
|
|
109
259
|
return buildMarkdownBlockResult(cmd, fullCmd, 'grep', mdTargetMatch[1]);
|
|
110
260
|
}
|
|
111
261
|
|
|
112
|
-
// Pipe-bypass (
|
|
262
|
+
// Pipe-bypass (INVERSE denylist): allow grep after any pipe unless the first pipe segment
|
|
113
263
|
// itself runs grep/rg/ag/ack, or reads a code file directly (cat/head/tail <code-ext>,
|
|
114
|
-
// find <code-dir>).
|
|
115
|
-
//
|
|
264
|
+
// find <code-dir>).
|
|
265
|
+
//
|
|
266
|
+
// Why inverted. The upstream original was a positive allowlist of trusted first-stage
|
|
267
|
+
// tools, which started at `git|gh|hg` (3.1.1) and immediately had to grow to add
|
|
268
|
+
// `docker|docker-compose|podman|kubectl|oc|nerdctl` (3.1.3). Every build tool, test
|
|
269
|
+
// runner, and linter in existence is a legitimate thing to pipe into grep — composer,
|
|
270
|
+
// cargo, mvn, make, npm test, ruff — so the allowlist could only ever be incomplete,
|
|
271
|
+
// and each gap presented as a spurious block. 3.1.4 inverted it: the *unsafe* first
|
|
272
|
+
// stages are the short, closed, and stable list, because "grep the codebase" only has
|
|
273
|
+
// a few spellings. Do not convert this back to an allowlist.
|
|
274
|
+
//
|
|
275
|
+
// The principle: `X | grep Foo` filters X's output; only when X is itself a codebase
|
|
276
|
+
// search or a code-file read is the pipeline a disguised codebase search.
|
|
116
277
|
const _pipeSegs = cmd.split('|').map(s => s.trim());
|
|
117
278
|
if (_pipeSegs.length >= 2) {
|
|
118
279
|
const _firstSeg = _pipeSegs[0];
|
|
280
|
+
// Guards against the naive split above: `|` is a regex alternation as often as it is
|
|
281
|
+
// a pipe. `git grep -nrE "smart_launch|llm_audit_sink"` splits into two fragments,
|
|
282
|
+
// making a plain `git grep` look like a two-stage pipeline and bypassing the check —
|
|
283
|
+
// a real hole fixed in 3.1.2. Testing the first fragment for a grep token closes it,
|
|
284
|
+
// since the verb stays in fragment one however the quoted pattern is chopped up.
|
|
119
285
|
const _firstSegIsGrep = /\b(grep|rg|ag|ack)\b/i.test(_firstSeg);
|
|
286
|
+
// The other disguised-search shape: pipe a code file's contents into grep and the
|
|
287
|
+
// search is over code, not over tool output. Two spellings are covered —
|
|
288
|
+
// 1. a reader with a code-extension operand (`cat src/app.ts | grep Foo`);
|
|
289
|
+
// 2. `find` rooted at a conventional source directory (`find src -name '*.ts' |
|
|
290
|
+
// grep Handler`) — matched by directory name because find's output is paths,
|
|
291
|
+
// which carry no extension to test until after the pipe.
|
|
292
|
+
// The `\S*` before the directory alternation lets `./src`, `../lib`, and `app/lib`
|
|
293
|
+
// match. Both lists are conventional-name heuristics, so a project using
|
|
294
|
+
// non-standard directory names (e.g. `source/`) is simply not covered — accepted,
|
|
295
|
+
// since the failure direction is a missed block rather than a spurious one.
|
|
120
296
|
const _firstSegReadsCode =
|
|
121
297
|
/\b(?:cat|head|tail|less|more|bat)\s+\S+\.(ts|tsx|js|jsx|mjs|cjs|py|go|rs|java|kt|swift|vue|svelte|cpp|c|h|hpp)\b/i.test(_firstSeg) ||
|
|
122
298
|
/\bfind\s+\S*(?:src|app|components|lib|hooks|utils|services|actions)\b/i.test(_firstSeg);
|
|
123
299
|
if (!_firstSegIsGrep && !_firstSegReadsCode) return null;
|
|
124
300
|
}
|
|
301
|
+
// Path-based exemptions — directories Serena's index does not usefully cover, so a
|
|
302
|
+
// grep is the only tool available: generated SQL migrations, agent scratch/config
|
|
303
|
+
// trees (`.task`, `.claude`), vendored dependencies, and the knowledge-vault notes
|
|
304
|
+
// directory. Each side of the name is anchored to a separator or a string boundary;
|
|
305
|
+
// upstream 2.1.0 recorded a bare substring match letting `myknowledge-vaultxxx`
|
|
306
|
+
// through, and the same shape would let any of these be spoofed by a longer name.
|
|
125
307
|
if (/(?:^|[\/\\])(?:supabase[\/\\]migrations|\.task|\.claude|node_modules|knowledge-vault)(?:[\/\\]|$)/i.test(cmd)) return null;
|
|
308
|
+
// An explicit `--include`/`--include=` restricted to a non-code extension is the user
|
|
309
|
+
// stating the search scope outright: nothing Serena indexes can match, so there is no
|
|
310
|
+
// symbol search to redirect to. Note `env` in this list — see the deliberate division
|
|
311
|
+
// of labour with `env-content-read-guard.js` at the `hasNonCodeTarget` rules below.
|
|
126
312
|
if (/--include=?\S*\.(sql|json|txt|env|sh|css|scss|log)\b/i.test(cmd)) return null;
|
|
127
313
|
|
|
314
|
+
// Un-escape `\"` first: the command often arrives already quoted once (from a JSON
|
|
315
|
+
// payload or a nested shell), and without this the double-quoted alternative below
|
|
316
|
+
// fails to find its closing quote and silently falls through to the weaker forms.
|
|
128
317
|
const cleaned = cmd.replace(/\\"/g, '"');
|
|
318
|
+
// Three alternatives, tried in descending confidence. Order matters only in that the
|
|
319
|
+
// quoted forms must precede the bare form: an unquoted match inside an already-quoted
|
|
320
|
+
// pattern would capture a fragment rather than the whole expression.
|
|
321
|
+
// 1/2. double- then single-quoted pattern — the operand is unambiguous.
|
|
322
|
+
// 3. bare pattern with no quotes. Deliberately restricted to `[A-Z][a-zA-Z]\w+`:
|
|
323
|
+
// an unquoted operand cannot be told apart from a path or a flag argument in
|
|
324
|
+
// general, so this only fires on the one shape that is almost always a symbol
|
|
325
|
+
// (initial capital, at least three chars). The `(?:-\w+\s+(?:[a-z]+\s+)?)*?`
|
|
326
|
+
// run skips leading flags and their lowercase arguments (`-t ts`, `-m 5`)
|
|
327
|
+
// without swallowing the pattern itself.
|
|
129
328
|
const patternMatch =
|
|
130
329
|
cleaned.match(/\b(?:grep|rg|ag|ack)\s+(?:-\S+\s+)*"([^"]+)"/i) ||
|
|
131
330
|
cleaned.match(/\b(?:grep|rg|ag|ack)\s+(?:-\S+\s+)*'([^']+)'/i) ||
|
|
132
331
|
cleaned.match(/\b(?:grep|rg|ag|ack)\s+(?:(?:-\w+\s+(?:[a-z]+\s+)?)*?)([A-Z][a-zA-Z]\w+)/);
|
|
133
332
|
|
|
134
333
|
if (!patternMatch) {
|
|
334
|
+
// No readable pattern (e.g. `-e` forms, `-f patfile`, heavy shell quoting). The
|
|
335
|
+
// pattern is what normally decides this phase, so fall back to the target: a grep
|
|
336
|
+
// aimed at a conventional source directory or a TS/JS file is a codebase search
|
|
337
|
+
// whatever its pattern turns out to be. The suggestion says `<code file>` because
|
|
338
|
+
// there is no symbol to name.
|
|
135
339
|
const fallbackTargetsCode =
|
|
136
340
|
/\bsrc[\\/]|\bapp[\\/]|components[\\/]|lib[\\/]|hooks[\\/]|utils[\\/]|services[\\/]|actions[\\/]/i.test(cmd) ||
|
|
137
341
|
/\.tsx?\b|\.jsx?\b/i.test(cmd);
|
|
@@ -144,8 +348,21 @@ function checkSegment(cmd, fullCmd) {
|
|
|
144
348
|
const fullPattern = patternMatch[1];
|
|
145
349
|
// NOTE: split on BOTH `|` and `.` — splitting on dots avoids merging
|
|
146
350
|
// dotted expressions like `mcp.Tool` into `mcpTool` (camelCase false positive).
|
|
147
|
-
//
|
|
148
|
-
//
|
|
351
|
+
// That exact false positive is recorded in upstream CHANGELOG 2.2.0: stripping the
|
|
352
|
+
// dot as a regex metacharacter fused the two halves into something that looked like
|
|
353
|
+
// a camelCase identifier, so an ordinary `grep "mcp.Tool"` was blocked. Splitting on
|
|
354
|
+
// the dot before metachar-stripping means each half is classified on its own.
|
|
355
|
+
// `\\?\|` accepts both the bare `|` alternation and the escaped `\|` that basic
|
|
356
|
+
// (non-extended) grep requires.
|
|
357
|
+
//
|
|
358
|
+
// Order inside `clean` is load-bearing: zero-width chars are stripped BEFORE regex
|
|
359
|
+
// metacharacters, because a metachar-strip on a token containing an invisible
|
|
360
|
+
// separator would leave the separator in place and hide the symbol.
|
|
361
|
+
//
|
|
362
|
+
// `allowlist: 'bash'` selects one of the three call-site dialects in lib/serena.js —
|
|
363
|
+
// the one tuned for shell patterns, which is more permissive about common lowercase
|
|
364
|
+
// words than the Grep-tool dialect. Classification itself lives in
|
|
365
|
+
// `isCodeSymbol` there; this file only decides what to feed it.
|
|
149
366
|
const symbols = extractSymbolsFromPattern(fullPattern, {
|
|
150
367
|
splitRe: /\\?\||\./,
|
|
151
368
|
clean: p => p.replace(ZERO_WIDTH, '').replace(/[*+?^${}()[\]\\]/g, ''),
|
|
@@ -153,18 +370,49 @@ function checkSegment(cmd, fullCmd) {
|
|
|
153
370
|
});
|
|
154
371
|
|
|
155
372
|
// SECURITY: only allow the safe-prefix pipe bypass AFTER confirming no code symbols.
|
|
373
|
+
// This branch ordering *is* the fix for a reported bypass (upstream 2.1.0,
|
|
374
|
+
// "Pipe-ordering bypass"): the safe-prefix exemption originally ran before symbol
|
|
375
|
+
// detection, so `echo x | grep SomeCamelFunc` was allowed on pipeline shape alone.
|
|
376
|
+
// Hoisting the exemption back out of this `symbols.length === 0` guard — a tempting
|
|
377
|
+
// simplification, since it would flatten a level of nesting — reopens it exactly.
|
|
156
378
|
if (symbols.length === 0) {
|
|
157
379
|
const targetsCodeEarly =
|
|
158
380
|
/\bsrc[\\/]|\bapp[\\/]|components[\\/]|lib[\\/]|hooks[\\/]|utils[\\/]|services[\\/]|actions[\\/]/i.test(cmd) ||
|
|
159
381
|
/\.tsx?\b|\.jsx?\b/i.test(cmd);
|
|
382
|
+
// A non-code extension in the command means the search is scoped to something
|
|
383
|
+
// Serena does not index, so there is no Serena call to redirect to. The
|
|
384
|
+
// `&& !targetsCodeEarly` conjunct keeps a mixed command (`grep X src/a.ts b.json`)
|
|
385
|
+
// blocked — a code target anywhere outranks a non-code one.
|
|
386
|
+
//
|
|
387
|
+
// ⚠️ `env` is in this list on purpose (navigation does not care about .env files),
|
|
388
|
+
// and that is precisely why `grep KEY .env` once leaked secrets to the transcript.
|
|
389
|
+
// Secrets are NOT this hook's job — `env-content-read-guard.js` owns display of
|
|
390
|
+
// .env contents, and both hooks are wired on Bash so both see the call. Do not
|
|
391
|
+
// "fix" the leak by removing `env` here; that would block legitimate navigation
|
|
392
|
+
// and still miss the Serena-side path. See README § `env-content-read-guard.js`.
|
|
160
393
|
const hasNonCodeTargetEarly = /\.(sql|json|txt|env|sh|css|scss|log|xml)\b/i.test(cmd) && !targetsCodeEarly;
|
|
161
394
|
if (hasNonCodeTargetEarly) return null;
|
|
162
395
|
|
|
396
|
+
// Narrow safe-prefix exemption, distinct from the inverse-denylist pipe bypass
|
|
397
|
+
// above. That one has already declined to exempt this command (the first stage
|
|
398
|
+
// was a grep or a code read); this one re-admits a short list of first stages
|
|
399
|
+
// whose output is plainly not source code. It is reachable only with zero code
|
|
400
|
+
// symbols in the pattern, which is what makes the extra permissiveness safe.
|
|
401
|
+
//
|
|
402
|
+
// `xargs`/`exec` disqualify the command because both turn the first stage's output
|
|
403
|
+
// back into arguments for a second command — `find src | xargs grep Foo` is a
|
|
404
|
+
// codebase search wearing a pipe, not a filter over output.
|
|
405
|
+
// The `pipePos < grepPos` test enforces that the grep is genuinely downstream:
|
|
406
|
+
// `grep Foo src/ | head` has a pipe but the grep is the source, not the sink.
|
|
163
407
|
const isSimplePipe = /\|/.test(cmd) && !/xargs|exec/.test(cmd);
|
|
164
408
|
const grepPos = cmd.search(/\b(grep|rg|ag|ack)\b/i);
|
|
165
409
|
const pipePos = cmd.indexOf('|');
|
|
166
410
|
if (isSimplePipe && pipePos !== -1 && pipePos < grepPos) {
|
|
167
411
|
const beforePipe = cmd.substring(0, pipePos).trim();
|
|
412
|
+
// Two anchored groups: package managers / runtimes / `echo` / a `cat` of an
|
|
413
|
+
// explicitly non-code file, plus plain text utilities. `cat` is admitted only
|
|
414
|
+
// with a non-code extension spelled out — a bare `cat` would readmit the
|
|
415
|
+
// `cat src/a.ts | grep Foo` case the inverse denylist exists to catch.
|
|
168
416
|
if (/^(git|npm|npx|pnpm|node|echo|cat\s+\S+\.(?:json|md|txt|log|ya?ml))/i.test(beforePipe) ||
|
|
169
417
|
/^(ls|wc|head|tail|sort|uniq)\b/i.test(beforePipe)) {
|
|
170
418
|
return null;
|
|
@@ -176,6 +424,23 @@ function checkSegment(cmd, fullCmd) {
|
|
|
176
424
|
return null;
|
|
177
425
|
}
|
|
178
426
|
|
|
427
|
+
// ── On the duplication with targetsCodeEarly / hasNonCodeTargetEarly above ──
|
|
428
|
+
//
|
|
429
|
+
// These are NOT copies: this pair is a strict superset. The `Early` pair tests two
|
|
430
|
+
// clauses (source-directory path, TS/JS extension); this one adds five — ripgrep's
|
|
431
|
+
// `-t ts` and `--type=ts` type filters, `find` rooted at a source directory, and the
|
|
432
|
+
// two argument-passing shapes `xargs grep` and `find -exec grep`.
|
|
433
|
+
//
|
|
434
|
+
// Extracting one shared helper therefore cannot be a pure refactor: it needs a
|
|
435
|
+
// parameter that switches those five clauses off, which trades a visible difference
|
|
436
|
+
// for a hidden one in a security guard. That is the argument against doing it.
|
|
437
|
+
//
|
|
438
|
+
// NOTE: whether the *narrower* test on the zero-symbol path is deliberate is not
|
|
439
|
+
// recoverable from the code, the README, or the upstream changelog. The effect is
|
|
440
|
+
// that `rg -t ts "some phrase"` (type-scoped, no code symbols) is allowed here while
|
|
441
|
+
// the same flags with a symbol present are blocked — defensible as "no symbol, no
|
|
442
|
+
// symbol search", but equally consistent with the extra clauses simply having been
|
|
443
|
+
// added to one site and not the other. Verify intent before unifying them.
|
|
179
444
|
const targetsCode =
|
|
180
445
|
/\bsrc[\\/]|\bapp[\\/]|components[\\/]|lib[\\/]|hooks[\\/]|utils[\\/]|services[\\/]|actions[\\/]/i.test(cmd) ||
|
|
181
446
|
/\.tsx?\b|\.jsx?\b/i.test(cmd) ||
|
|
@@ -189,14 +454,30 @@ function checkSegment(cmd, fullCmd) {
|
|
|
189
454
|
/\.(sql|json|txt|env|sh|css|scss|log|xml)\b/i.test(cmd) &&
|
|
190
455
|
!targetsCode;
|
|
191
456
|
|
|
457
|
+
// The `&& !targetsCode` conjunct is already baked into hasNonCodeTarget, so the
|
|
458
|
+
// second test here is redundant. Harmless, but do not read it as a second condition.
|
|
192
459
|
if (hasNonCodeTarget && !targetsCode) return null;
|
|
193
460
|
|
|
461
|
+
// Intent per symbol, from its first character: an initial capital reads as a type or
|
|
462
|
+
// component name, so the useful next call is a symbol lookup; a lowercase identifier
|
|
463
|
+
// is usually a function or variable already known to exist, so the useful call is a
|
|
464
|
+
// reference search. A cheap heuristic, but it only picks *which* Serena tool to
|
|
465
|
+
// suggest — getting it wrong costs a suboptimal suggestion, never a wrong verdict.
|
|
194
466
|
const suggestions = symbols.map(sym => {
|
|
195
467
|
const intent = /^[A-Z]/.test(sym) ? 'symbol_search' : 'references';
|
|
196
468
|
return ` ${sym}:\n${buildSuggestion(sym, intent, ' ')}`;
|
|
197
469
|
}).join('\n');
|
|
198
470
|
|
|
471
|
+
// 200 chars keeps a long pipeline from burying the suggestion it is paired with;
|
|
472
|
+
// the agent already has the full command it just tried, so echoing all of it adds
|
|
473
|
+
// nothing. `fullCmd` not `cmd`, so the echo matches what the user actually typed
|
|
474
|
+
// rather than the post-split, post-rtk-strip fragment being judged.
|
|
199
475
|
const displayCmd = fullCmd.length > 200 ? fullCmd.slice(0, 200) + '…' : fullCmd;
|
|
476
|
+
// DEFECT (comments-only pass — deliberately not fixed): `serenaCall` is computed
|
|
477
|
+
// here and never read. The reason/stderr strings below both use `suggestions`
|
|
478
|
+
// instead. Dead as written; deleting it changes no behaviour, but the alternative
|
|
479
|
+
// reading — that one of the two messages was meant to use the FS-style suggestion —
|
|
480
|
+
// needs a decision rather than a silent tidy-up.
|
|
200
481
|
const serenaCall = buildBashFsSuggestion(cmd, ' ') ||
|
|
201
482
|
symbols.map(sym => {
|
|
202
483
|
const intent = /^[A-Z]/.test(sym) ? 'symbol_search' : 'references';
|
|
@@ -217,14 +498,32 @@ function checkSegment(cmd, fullCmd) {
|
|
|
217
498
|
}
|
|
218
499
|
|
|
219
500
|
// ── PHASE 2: filesystem exploration detection ──────────────────────────────
|
|
220
|
-
|
|
221
|
-
//
|
|
501
|
+
//
|
|
502
|
+
// Reads: listing directories and dumping file contents. Reached only when Phase 1
|
|
503
|
+
// found no grep-family verb, or found one it declined to block.
|
|
504
|
+
//
|
|
505
|
+
// ORDERING vs PHASE 3: reads must be judged before writes. The sed/awk read rules below
|
|
506
|
+
// carry `(?!…-i…)` negative lookaheads that deliberately hand the editing variants down
|
|
507
|
+
// to Phase 3; run Phase 3 first and its redirect rules would claim read commands that
|
|
508
|
+
// merely happen to redirect (`sed -n '1,5p' a.ts > /dev/null`), reporting an in-place
|
|
509
|
+
// edit that never happened and naming the wrong Serena replacement tool.
|
|
510
|
+
|
|
511
|
+
// `ls` on a directory is `list_dir`'s job. `ls -d` is excluded because it prints the
|
|
512
|
+
// directory entry itself rather than its contents — a stat, not an exploration, and
|
|
513
|
+
// Serena has no equivalent.
|
|
222
514
|
const lsMatch = /\bls\b(?!\s+-d\b)(?:\s+[^\s|;&<>]+)/.exec(cmd);
|
|
223
515
|
if (lsMatch) {
|
|
224
516
|
// Extract directory argument (skip flags)
|
|
517
|
+
// NOTE: `cmd.indexOf('ls')` finds the first literal "ls" anywhere in the string, not
|
|
518
|
+
// the position the regex matched. On a segment where "ls" first appears inside another
|
|
519
|
+
// word (e.g. a path containing "tools"), the slice starts mid-token and the extracted
|
|
520
|
+
// target is garbage — which yields a confusing target in the block message, though the
|
|
521
|
+
// block/allow verdict still comes from isExemptDir on whatever was extracted.
|
|
225
522
|
const afterLs = cmd.slice(cmd.indexOf('ls') + 2).trim();
|
|
226
523
|
const lsTarget = afterLs.replace(/^(?:-\S+\s+)*/, '').split(/\s/)[0] || '';
|
|
227
|
-
// Block only when the target is not in the always-exempt list
|
|
524
|
+
// Block only when the target is not in the always-exempt list.
|
|
525
|
+
// A bare `ls` with no operand extracts to '' and falls through — listing the cwd is
|
|
526
|
+
// the single most common orientation command and blocking it is pure friction.
|
|
228
527
|
if (lsTarget && !isExemptDir(lsTarget)) {
|
|
229
528
|
return buildFsBlockResult(cmd, fullCmd, 'ls', lsTarget || '.');
|
|
230
529
|
}
|
|
@@ -246,7 +545,12 @@ function checkSegment(cmd, fullCmd) {
|
|
|
246
545
|
}
|
|
247
546
|
}
|
|
248
547
|
|
|
249
|
-
// find
|
|
548
|
+
// `find` is only claimed when it carries a predicate — `-name`/`-path`/`-iname`/`-type`.
|
|
549
|
+
// That is what makes it a *search* (Serena's `find_file`) rather than a bare recursive
|
|
550
|
+
// listing, and it keeps `find` used as a plumbing primitive (piped into another tool,
|
|
551
|
+
// or with `-delete`/`-exec` doing non-navigational work) out of scope.
|
|
552
|
+
// `[^|;&<>]*` stops the scan at a shell operator so a predicate belonging to a later
|
|
553
|
+
// command in the pipeline is not attributed to this `find`.
|
|
250
554
|
const findMatch = /\bfind\s+(\S+)\s+[^|;&<>]*-(?:name|path|iname|type)\b/.exec(cmd);
|
|
251
555
|
if (findMatch) {
|
|
252
556
|
const findTarget = findMatch[1];
|
|
@@ -256,19 +560,34 @@ function checkSegment(cmd, fullCmd) {
|
|
|
256
560
|
}
|
|
257
561
|
|
|
258
562
|
// cat/head/tail/less/more/bat on markdown — Serena owns markdown reading too.
|
|
563
|
+
// Checked before the code-extension rule below purely so the message is right: both
|
|
564
|
+
// would fire, but this one names `read_file` rather than `get_symbols_overview`, and a
|
|
565
|
+
// markdown file has no symbol overview to give.
|
|
566
|
+
// The lazy `[^|;&<>]*?\s` (rather than the code rule's `\s+`) lets the operand sit
|
|
567
|
+
// after flags — `head -n 20 wiki/index.md` — while still stopping at a shell operator.
|
|
259
568
|
const catMdMatch = /\b(?:cat|head|tail|less|more|bat)\b[^|;&<>]*?\s(\S+\.md)\b/i.exec(cmd);
|
|
260
569
|
if (catMdMatch) {
|
|
261
570
|
return buildMarkdownBlockResult(cmd, fullCmd, 'cat', catMdMatch[1]);
|
|
262
571
|
}
|
|
263
572
|
|
|
264
|
-
// cat/head/tail/less/more/bat on code-extension files
|
|
573
|
+
// cat/head/tail/less/more/bat on code-extension files.
|
|
574
|
+
// The extension list is the same one used by the pipe bypass and the redirect rules in
|
|
575
|
+
// Phase 3; they are kept literal at each site rather than hoisted to a shared constant,
|
|
576
|
+
// which means adding a language requires touching every copy. Flagged, not changed.
|
|
265
577
|
const catMatch = /\b(?:cat|head|tail|less|more|bat)\s+\S+\.(ts|tsx|js|jsx|mjs|cjs|py|go|rs|java|kt|swift|vue|svelte|cpp|c|h|hpp)\b/.exec(cmd);
|
|
266
578
|
if (catMatch) {
|
|
579
|
+
// Re-extracting via extractFileArg rather than reusing catMatch: the regex above
|
|
580
|
+
// proves *a* code file is being read, but its `\S+` may have captured a token that is
|
|
581
|
+
// not the operand. isAllowedPath then gets the final say, since it applies the
|
|
582
|
+
// language-aware and test/config allowlists that this regex knows nothing about.
|
|
267
583
|
const fileArg = extractFileArg(cmd, /\b(?:cat|head|tail|less|more|bat)\b/);
|
|
268
584
|
if (fileArg && !isAllowedPath(fileArg)) {
|
|
269
585
|
return buildFsBlockResult(cmd, fullCmd, 'cat', fileArg);
|
|
270
586
|
}
|
|
271
|
-
// Even if extraction failed, pattern already confirmed code extension
|
|
587
|
+
// Even if extraction failed, pattern already confirmed code extension.
|
|
588
|
+
// Fail toward blocking here — unlike the top-level fail-open paths, this is a case
|
|
589
|
+
// where the read is known to be of code and only the operand is uncertain, so the
|
|
590
|
+
// allowlist cannot be consulted and the conservative verdict is the correct one.
|
|
272
591
|
if (!fileArg) {
|
|
273
592
|
return buildFsBlockResult(cmd, fullCmd, 'cat', catMatch[0]);
|
|
274
593
|
}
|
|
@@ -276,6 +595,12 @@ function checkSegment(cmd, fullCmd) {
|
|
|
276
595
|
|
|
277
596
|
// Fallback: head/tail/cat with flags put the file last (e.g. `head -85 file.ts`, `tail -f file.ts`).
|
|
278
597
|
// The catMatch regex above requires the file to be the first argument, so it misses these.
|
|
598
|
+
// Guarded by `!catMatch` so the two rules cannot both fire and double-report.
|
|
599
|
+
//
|
|
600
|
+
// Last-token-only is deliberately crude: it cannot tell an operand from a trailing
|
|
601
|
+
// argument, so it will miss `head -n 20 a.ts | wc -l` (last token is `-l`). Accepted —
|
|
602
|
+
// this is a backstop for the common spelling, and widening it to scan every token would
|
|
603
|
+
// start claiming code paths that appear as flag values elsewhere in the command.
|
|
279
604
|
if (!catMatch && /\b(?:cat|head|tail|less|more|bat)\b/.test(cmd)) {
|
|
280
605
|
const lastToken = cmd.trim().split(/\s+/).pop() || '';
|
|
281
606
|
if (/\.(ts|tsx|js|jsx|mjs|cjs|py|go|rs|java|kt|swift|vue|svelte|cpp|c|h|hpp)$/i.test(lastToken) &&
|
|
@@ -287,8 +612,21 @@ function checkSegment(cmd, fullCmd) {
|
|
|
287
612
|
|
|
288
613
|
// sed/awk used as readers (no in-place flag) on code-extension files.
|
|
289
614
|
// Phase 3 catches the editing variants (sed -i, awk -i inplace); this rule
|
|
290
|
-
// covers `sed -n '8,14p' foo.py`, `awk '/x/' foo.py`, etc.
|
|
291
|
-
//
|
|
615
|
+
// covers `sed -n '8,14p' foo.py`, `awk '/x/' foo.py`, etc.
|
|
616
|
+
//
|
|
617
|
+
// The `(?![^\n]*?\s-i(?:\s|$|nplace))` lookahead is the read/write divider, and it is
|
|
618
|
+
// why Phase 2 must run before Phase 3 rather than the two being merged. It makes this
|
|
619
|
+
// rule decline any segment carrying an in-place flag so that segment falls through to
|
|
620
|
+
// Phase 3, which reports it as an *edit* and suggests `replace_content` instead of a
|
|
621
|
+
// read tool. Delete the lookahead and every `sed -i` gets claimed here first, with a
|
|
622
|
+
// message telling the user to read a file they were trying to write.
|
|
623
|
+
//
|
|
624
|
+
// The three alternatives after `-i` are what keep it from firing on unrelated flags:
|
|
625
|
+
// `\s` for `sed -i -E …`, `$` for a trailing `-i`, and `nplace` for awk's `-i inplace`.
|
|
626
|
+
// A short flag that merely starts with i (`-in`) is therefore not mistaken for it.
|
|
627
|
+
// Known gap: the fused GNU spelling `sed -i.bak` matches none of the three, so it is
|
|
628
|
+
// treated as a read here rather than falling through to Phase 3. It still blocks (the
|
|
629
|
+
// target is a code file) but under the wrong verb and with the wrong suggestion.
|
|
292
630
|
const sedAwkReadMatch = /\b(sed|awk)\b(?![^\n]*?\s-i(?:\s|$|nplace))[^\n]*?\s(\S+\.(?:ts|tsx|js|jsx|mjs|cjs|py|go|rs|java|kt|swift|vue|svelte|cpp|c|h|hpp))\b/.exec(cmd);
|
|
293
631
|
if (sedAwkReadMatch) {
|
|
294
632
|
const verb = sedAwkReadMatch[1];
|
|
@@ -305,8 +643,21 @@ function checkSegment(cmd, fullCmd) {
|
|
|
305
643
|
}
|
|
306
644
|
|
|
307
645
|
// ── PHASE 3: in-place editing detection ───────────────────────────────────
|
|
308
|
-
|
|
309
|
-
//
|
|
646
|
+
//
|
|
647
|
+
// Writes. Serena's structural editors (`replace_symbol_body`, `replace_content`) know
|
|
648
|
+
// the symbol boundaries a stream editor cannot see, so an in-place `sed` over code is
|
|
649
|
+
// both the riskiest and the least reviewable way to change a file.
|
|
650
|
+
//
|
|
651
|
+
// ORDERING: last. Every rule here matches on a write *operator* rather than a verb, and
|
|
652
|
+
// operators appear in read commands too (`sed -n 1p a.ts > out`). Running this phase
|
|
653
|
+
// earlier would claim those reads. Phases 2 and 3 are mutually exclusive by
|
|
654
|
+
// construction, via the `-i` lookaheads in Phase 2 — that is a contract between the two
|
|
655
|
+
// phases, not a local detail of either.
|
|
656
|
+
|
|
657
|
+
// sed -i, both flag orders. Two alternatives rather than one flexible pattern because
|
|
658
|
+
// `-E` is the only other flag commonly fused into this idiom and the pair covers both
|
|
659
|
+
// spellings exactly; a general "any flags" pattern would start matching `-i` appearing
|
|
660
|
+
// as another flag's value.
|
|
310
661
|
if (/\bsed\s+(?:-E\s+)?-i\b|\bsed\s+-i(?:\s+-E)?\b/.test(cmd)) {
|
|
311
662
|
const fileArg = extractLastPathArg(cmd);
|
|
312
663
|
if (!fileArg || !isAllowedPath(fileArg)) {
|
|
@@ -322,7 +673,10 @@ function checkSegment(cmd, fullCmd) {
|
|
|
322
673
|
}
|
|
323
674
|
}
|
|
324
675
|
|
|
325
|
-
// perl -i (any combination of n/p/i flags)
|
|
676
|
+
// perl -i (any combination of n/p/i flags). Perl bundles its short flags, so the
|
|
677
|
+
// in-place flag legitimately appears as `-i`, `-pi`, `-ni`, `-pie`, `-ine`, … — the
|
|
678
|
+
// character classes on both sides accept any bundling with an `i` somewhere in it,
|
|
679
|
+
// which is why this one rule replaces the enumerated alternatives used for sed.
|
|
326
680
|
if (/\bperl\s+-[npi]*i[npe]*\b/.test(cmd)) {
|
|
327
681
|
const fileArg = extractLastPathArg(cmd);
|
|
328
682
|
if (!fileArg || !isAllowedPath(fileArg)) {
|
|
@@ -330,7 +684,9 @@ function checkSegment(cmd, fullCmd) {
|
|
|
330
684
|
}
|
|
331
685
|
}
|
|
332
686
|
|
|
333
|
-
// >> <code-file> (append redirect)
|
|
687
|
+
// >> <code-file> (append redirect). Appending to a source file writes code without any
|
|
688
|
+
// editor involved, so neither the Edit-tool guards nor the sed/awk rules above see it.
|
|
689
|
+
// Checked before the `>` rule so the two-character operator is consumed first.
|
|
334
690
|
const appendMatch = />>\s*(\S+\.(ts|tsx|js|jsx|mjs|cjs|py|go|rs|java|kt|swift|vue|svelte|cpp|c|h|hpp))\b/.exec(cmd);
|
|
335
691
|
if (appendMatch) {
|
|
336
692
|
const fileArg = appendMatch[1];
|
|
@@ -339,7 +695,26 @@ function checkSegment(cmd, fullCmd) {
|
|
|
339
695
|
}
|
|
340
696
|
}
|
|
341
697
|
|
|
342
|
-
// > <code-file> (overwrite redirect — not preceded by `2>`)
|
|
698
|
+
// > <code-file> (overwrite redirect — not preceded by `2>`).
|
|
699
|
+
//
|
|
700
|
+
// The `(?<!2)` lookbehind exists to spare stderr redirection: `node build.js 2> err.js`
|
|
701
|
+
// redirects a stream, and treating it as an overwrite of a source file would block an
|
|
702
|
+
// ordinary command. It is a single-character lookbehind, so only the `2` descriptor is
|
|
703
|
+
// covered — `1>` and `3>` are not, which is fine for `1>` (that genuinely is an
|
|
704
|
+
// overwrite) and untested territory for higher descriptors.
|
|
705
|
+
//
|
|
706
|
+
// ⚠️ THIS IS THE HOOK'S MOST-HIT FALSE POSITIVE, and it is worth knowing before editing
|
|
707
|
+
// anything nearby. A JS arrow function whose body mentions a `.js` file —
|
|
708
|
+
// `x => require("a.js")` — presents as `>` followed by a code-extension token, so the
|
|
709
|
+
// rule reads it as a redirect into source. Every inline `node -e` script in this repo's
|
|
710
|
+
// UAT files is therefore written with classic `function () {}` expressions; UAT-033 and
|
|
711
|
+
// UAT-034 both record this as a standing constraint. Escape hatch: avoid `=>`, or move
|
|
712
|
+
// the script into a file.
|
|
713
|
+
//
|
|
714
|
+
// Fixing it properly means requiring whitespace or a non-`=` character before the `>`,
|
|
715
|
+
// which is a behaviour change and so out of scope for a comments-only pass. Note that
|
|
716
|
+
// the naive version of that fix — extending the lookbehind to `(?<![2=])` — would also
|
|
717
|
+
// silently stop catching `x=>foo.ts` style redirects if any exist.
|
|
343
718
|
const overwriteMatch = /(?<!2)>\s*(\S+\.(ts|tsx|js|jsx|mjs|cjs|py|go|rs|java|kt|swift|vue|svelte|cpp|c|h|hpp))\b/.exec(cmd);
|
|
344
719
|
if (overwriteMatch) {
|
|
345
720
|
const fileArg = overwriteMatch[1];
|
|
@@ -358,21 +733,43 @@ function stripQuotes(t) {
|
|
|
358
733
|
return String(t).replace(/^['"]+/, '').replace(/['"]+$/, '');
|
|
359
734
|
}
|
|
360
735
|
|
|
361
|
-
/**
|
|
736
|
+
/**
|
|
737
|
+
* True if a segment performs an in-place edit / file-write (not a pure read).
|
|
738
|
+
*
|
|
739
|
+
* Used only by segmentEscapesProject() to decide whether unresolvable `$VAR` paths get
|
|
740
|
+
* the benefit of the doubt. It is intentionally broader than the Phase 3 rules — it fires
|
|
741
|
+
* on ANY redirect target, not just code extensions — because the question here is "could
|
|
742
|
+
* this write something?", not "does this write code?". A false positive costs a variable-
|
|
743
|
+
* path edit an out-of-project pass it might have deserved; a false negative would let an
|
|
744
|
+
* unprovable write through.
|
|
745
|
+
*/
|
|
362
746
|
function segmentIsInPlaceEdit(cmd) {
|
|
363
747
|
return /\bsed\s+(?:-E\s+)?-i\b|\bsed\s+-i(?:\s+-E)?\b/.test(cmd) ||
|
|
364
748
|
/\bawk\s+-i\s+inplace\b/.test(cmd) ||
|
|
365
749
|
/\bperl\s+-[npi]*i[npe]*\b/.test(cmd) ||
|
|
750
|
+
// `[^0-9&]` before the operator excludes both `2>` (a descriptor redirect) and `&>`;
|
|
751
|
+
// `[^\s&|;]` after it requires a real destination token, so the `>` in `2>&1` — whose
|
|
752
|
+
// next char is `&` — does not read as a write to a file.
|
|
366
753
|
/(?:^|[^0-9&])>>?\s*[^\s&|;]/.test(cmd); // > file / >> file (not 2>&1)
|
|
367
754
|
}
|
|
368
755
|
|
|
369
|
-
/**
|
|
756
|
+
/**
|
|
757
|
+
* Extract path-looking argument tokens from a command segment.
|
|
758
|
+
*
|
|
759
|
+
* "Path-looking" requires a slash, a leading `~`, or a leading `$VAR`. A bare `foo.ts`
|
|
760
|
+
* is deliberately NOT a path token: the sole consumer is the out-of-project check, and a
|
|
761
|
+
* relative filename with no separator is in-project by definition, so admitting it could
|
|
762
|
+
* only ever produce a wrong "escapes the project" verdict.
|
|
763
|
+
*/
|
|
370
764
|
function extractPathTokens(cmd) {
|
|
371
765
|
const paths = [];
|
|
372
766
|
for (let t of String(cmd).split(/\s+/)) {
|
|
373
767
|
t = stripQuotes(t);
|
|
374
768
|
if (!t || t.startsWith('-')) continue; // empty or flag
|
|
375
769
|
if (/^[|&;<>]+$/.test(t)) continue; // shell operator
|
|
770
|
+
// sed/awk scripts contain slashes as delimiters, not as path separators —
|
|
771
|
+
// `s/a/b/` and `y/abc/xyz/` would otherwise be read as relative paths and, since
|
|
772
|
+
// they resolve inside the project, would drag the whole segment back into scope.
|
|
376
773
|
if (/^[sy][/|#,]/.test(t)) continue; // sed/awk script (s/a/b/, y/a/b/)
|
|
377
774
|
// Path-looking: contains a slash, or begins with ~ / $VAR.
|
|
378
775
|
if (/\//.test(t) || /^~/.test(t) || /^\$\{?\w/.test(t)) paths.push(t);
|
|
@@ -397,15 +794,47 @@ function targetEscapesProject(t, opts = {}) {
|
|
|
397
794
|
* True when EVERY path target in a segment escapes the project root, so Serena
|
|
398
795
|
* can't operate on it and the segment should pass through. Read-exploration
|
|
399
796
|
* segments also permit unresolvable variable-led paths; in-place edits do not.
|
|
797
|
+
*
|
|
798
|
+
* EVERY, not ANY, and that is the whole safety property: `cat /etc/hosts src/app.ts`
|
|
799
|
+
* has an escaping target but is still a code read, so an `.some()` here would hand out a
|
|
800
|
+
* bypass to any command with one out-of-project argument tacked on.
|
|
400
801
|
*/
|
|
401
802
|
function segmentEscapesProject(cmd) {
|
|
402
803
|
const tokens = extractPathTokens(cmd);
|
|
804
|
+
// No path tokens at all means "not scoped out" rather than "vacuously outside" — the
|
|
805
|
+
// `every()` below is true for an empty array, so returning early is required to stop a
|
|
806
|
+
// path-free command (`ls`, `tree`) from being waved through as out-of-project.
|
|
403
807
|
if (tokens.length === 0) return false;
|
|
404
808
|
const allowVar = !segmentIsInPlaceEdit(cmd);
|
|
405
809
|
return tokens.every(t => targetEscapesProject(t, { allowVar }));
|
|
406
810
|
}
|
|
407
811
|
|
|
408
|
-
/**
|
|
812
|
+
/**
|
|
813
|
+
* Directories that are always exempt from ls/tree/find blocking.
|
|
814
|
+
*
|
|
815
|
+
* The allowlist splits into two justifications, and both are about Serena's index rather
|
|
816
|
+
* than about safety:
|
|
817
|
+
*
|
|
818
|
+
* - Not indexed, so Serena genuinely cannot answer: `node_modules` (vendored deps,
|
|
819
|
+
* excluded from the project scan), `dist` and `build` (generated output — listing
|
|
820
|
+
* build artifacts is a build question, not a navigation question), and `.git`
|
|
821
|
+
* (object storage, not source).
|
|
822
|
+
* - Agent-infrastructure trees the agent must be able to inspect *in order to* diagnose
|
|
823
|
+
* Serena itself: `.claude` (hooks, settings, skills), `.serena` (project.yml and
|
|
824
|
+
* memories), `.task` (scratch state). Blocking these creates a bootstrapping problem —
|
|
825
|
+
* you would need a working Serena to investigate a broken one.
|
|
826
|
+
*
|
|
827
|
+
* `dir === '.'` returns false (not exempt) so that listing the project root is still
|
|
828
|
+
* redirected to Serena; the root is the case the guard most wants to catch.
|
|
829
|
+
*
|
|
830
|
+
* Three tests rather than one because they answer different questions: the first is an
|
|
831
|
+
* anchored path-component match (`src/node_modules`, `./dist/`) written so a longer name
|
|
832
|
+
* cannot spoof it — the bare-substring version of this shape is what let
|
|
833
|
+
* `myknowledge-vaultxxx` through upstream. The second catches a bare prefix with no
|
|
834
|
+
* trailing separator (`.claude`, `.serena-backup`) — note it is deliberately looser and
|
|
835
|
+
* WILL match a sibling directory whose name merely starts with `.task`. The third is a
|
|
836
|
+
* plain equality shortcut for the two names most often typed with no path at all.
|
|
837
|
+
*/
|
|
409
838
|
function isExemptDir(dir) {
|
|
410
839
|
if (!dir || dir === '.') return false;
|
|
411
840
|
return /(?:^|[/\\])(?:\.claude|\.serena|\.task|node_modules|dist|build|\.git)(?:[/\\]|$)/i.test(dir) ||
|
|
@@ -423,7 +852,19 @@ function extractFileArg(cmd, verbRe) {
|
|
|
423
852
|
return token || null;
|
|
424
853
|
}
|
|
425
854
|
|
|
426
|
-
/**
|
|
855
|
+
/**
|
|
856
|
+
* Extract the last path-looking argument in a command (for sed/awk/perl).
|
|
857
|
+
*
|
|
858
|
+
* Last-token-first because these three all take their target as the final operand, after
|
|
859
|
+
* a script argument that is itself full of slashes and dots. Scanning forward would
|
|
860
|
+
* return the script (`s/foo/bar/`) instead of the file.
|
|
861
|
+
*
|
|
862
|
+
* The rejections encode that: a leading `-` is a flag, a leading quote is the script, and
|
|
863
|
+
* `^[sg]/` catches an unquoted sed substitution or a `g`-suffixed one. Requiring `[./]`
|
|
864
|
+
* keeps bare words (`inplace`, a command name) out. Returning null when nothing qualifies
|
|
865
|
+
* is meaningful to the callers — Phase 3 treats "in-place edit, unidentifiable target" as
|
|
866
|
+
* a block with `<path>` in the message, not as a pass.
|
|
867
|
+
*/
|
|
427
868
|
function extractLastPathArg(cmd) {
|
|
428
869
|
// Match last whitespace-delimited token that looks like a path (not a flag or substitution)
|
|
429
870
|
const tokens = cmd.split(/\s+/);
|
|
@@ -437,10 +878,25 @@ function extractLastPathArg(cmd) {
|
|
|
437
878
|
return null;
|
|
438
879
|
}
|
|
439
880
|
|
|
881
|
+
// ── Block-message builders ──────────────────────────────────────────────────
|
|
882
|
+
//
|
|
883
|
+
// Three builders rather than one parameterised one because each names a different Serena
|
|
884
|
+
// replacement and carries a different allowlist note — the message is the entire remedy
|
|
885
|
+
// the agent gets, and a generic "blocked" is how a block gets worked around instead of
|
|
886
|
+
// followed. All three emit the same two channels: stderr (short, human-facing) and a
|
|
887
|
+
// structured JSON envelope on stdout (for programmatic consumers). Exit code 2 is what
|
|
888
|
+
// actually blocks; the JSON alone would not.
|
|
889
|
+
//
|
|
890
|
+
// Each falls back to a hand-built suggestion string when buildBashFsSuggestion() cannot
|
|
891
|
+
// parse the command, so the message is never empty of a next step.
|
|
892
|
+
|
|
440
893
|
/** Build block result for filesystem exploration commands. */
|
|
441
894
|
function buildFsBlockResult(cmd, fullCmd, verb, targetPath) {
|
|
442
895
|
const displayCmd = fullCmd.length > 200 ? fullCmd.slice(0, 200) + '…' : fullCmd;
|
|
443
896
|
const serenaCall = buildBashFsSuggestion(cmd, ' ');
|
|
897
|
+
// NOTE: this note drifts from isExemptDir() — it advertises `.docs/`, which the function
|
|
898
|
+
// does not exempt, and omits `.task/`, `dist/`, and `build/`, which it does. Message-only
|
|
899
|
+
// (no verdict depends on this string), so it is recorded rather than corrected here.
|
|
444
900
|
const allowNote = 'Allowlist: .docs/, .claude/, .serena/, node_modules/, .git/.';
|
|
445
901
|
const reason = `SERENA-FIRST: Filesystem exploration via '${verb}' on '${targetPath}' blocked.\n` +
|
|
446
902
|
`Command (truncated): ${displayCmd}\n` +
|
|
@@ -477,7 +933,14 @@ function buildInplaceBlockResult(cmd, fullCmd, verb, targetPath) {
|
|
|
477
933
|
};
|
|
478
934
|
}
|
|
479
935
|
|
|
480
|
-
/**
|
|
936
|
+
/**
|
|
937
|
+
* Build block result for markdown exploration (grep/cat/head/tail on .md).
|
|
938
|
+
*
|
|
939
|
+
* The one builder that picks its suggestion from the verb rather than the target: a grep
|
|
940
|
+
* maps to `search_for_pattern`, everything else to `read_file`. It also states the
|
|
941
|
+
* read/write asymmetry explicitly, because it is the surprising part of the policy —
|
|
942
|
+
* markdown *reading* is Serena's, markdown *writing* stays on native Edit/Write.
|
|
943
|
+
*/
|
|
481
944
|
function buildMarkdownBlockResult(cmd, fullCmd, verb, targetPath) {
|
|
482
945
|
const displayCmd = fullCmd.length > 200 ? fullCmd.slice(0, 200) + '…' : fullCmd;
|
|
483
946
|
const serenaCall =
|