@codewizard-dt/bootstrap 2.15.0 → 2.18.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 (41) hide show
  1. package/lib/hooks/README.md +192 -184
  2. package/lib/hooks/absolute-path-guard.js +5 -0
  3. package/lib/hooks/claude-settings-guard.js +43 -73
  4. package/lib/hooks/env-content-read-guard.js +13 -3
  5. package/lib/hooks/env-file-guard.js +42 -0
  6. package/lib/hooks/interpreter-indirection-guard.js +7 -0
  7. package/lib/hooks/lib/command-parse.js +8 -0
  8. package/lib/hooks/lib/serena-languages.js +94 -1
  9. package/lib/hooks/lib/serena.js +228 -0
  10. package/lib/hooks/mv-absolute-path-block.js +84 -3
  11. package/lib/hooks/package-install-consent.js +11 -0
  12. package/lib/hooks/protected-write-guard.js +7 -0
  13. package/lib/hooks/serena-bash-grep-block.js +507 -44
  14. package/lib/hooks/serena-first-glob-guard.js +65 -20
  15. package/lib/hooks/serena-first-guard.js +98 -2
  16. package/lib/hooks/serena-first-read-guard.js +92 -2
  17. package/lib/hooks/serena-pre-delegation.js +123 -0
  18. package/lib/hooks/serena-write-guard.js +56 -3
  19. package/lib/scripts/README.md +319 -16
  20. package/lib/scripts/bootstrap-prefs.js +734 -0
  21. package/lib/scripts/install-global.sh +182 -25
  22. package/lib/scripts/install-mcps.sh +102 -14
  23. package/lib/scripts/lib.sh +595 -20
  24. package/lib/scripts/merge-gitignore.sh +254 -16
  25. package/lib/scripts/merge-settings-hooks.js +374 -0
  26. package/lib/scripts/sync-wiki-scaffold.sh +33 -4
  27. package/lib/scripts/templates/CLAUDE-wiki.md +1 -1
  28. package/lib/scripts/templates/bootstrap-prefs-schema.json +175 -0
  29. package/lib/scripts/templates/settings-hooks.json +151 -0
  30. package/lib/scripts/update-project.sh +42 -9
  31. package/lib/skills/README.md +2 -1
  32. package/lib/skills/bootstrap-config/SKILL.md +154 -0
  33. package/lib/skills/git-commit/SKILL.md +54 -1
  34. package/lib/skills/research/SKILL.md +34 -3
  35. package/lib/skills/simplify/SKILL.md +1 -1
  36. package/lib/skills/uat-auto/SKILL.md +9 -4
  37. package/lib/skills/uat-auto-plus/SKILL.md +6 -6
  38. package/lib/skills/uat-generate/SKILL.md +30 -3
  39. package/lib/skills/uat-walk/UAT-CORE.md +41 -6
  40. package/lib/skills/wiki-query/SKILL.md +48 -8
  41. package/package.json +1 -1
@@ -32,7 +32,7 @@
32
32
  //
33
33
  // Do not "close this gap" later — it is not a gap. CLAUDE.md grants it
34
34
  // ("You are, however, allowed to source an .env file to use the variables in
35
- // the command line") and env-file-guard.js:39 says so in its own deny message.
35
+ // the command line") and env-file-guard.js:81 says so in its own deny message.
36
36
  //
37
37
  // The reasoning, so it does not have to be rediscovered: sourcing loads values
38
38
  // into the shell's environment and prints NOTHING. Nothing enters the
@@ -74,15 +74,25 @@
74
74
  // fires. Accepted for the same reason as protected-write-guard.js:50 —
75
75
  // narrowing it means inspecting quoting well enough to reimplement the
76
76
  // shell, and the cost of over-firing is one rephrase.
77
+ //
78
+ // Fails: open — a payload shape this hook does not expect falls through to allow
79
+ // (the try/catch wrapping the dispatch at the bottom of this file, and
80
+ // lib/command-parse.js's own handler catch). Ambiguous MATCHES go the other way
81
+ // and block, which is why a segment that merely quotes a blocked form fires.
77
82
 
78
83
  const path = require('path');
79
84
  const { readHookInput, splitSegments, tokenize, deny } = require('./lib/command-parse');
80
85
 
81
- // KEPT BYTE-IDENTICAL WITH env-file-guard.js:6-13. If the allow-list changes,
86
+ // KEPT BYTE-IDENTICAL WITH env-file-guard.js:48-55. If the allow-list changes,
82
87
  // change it in both places or in neither — two .env controls that disagree
83
88
  // about which files are secret is worse than one control. It also matches the
84
89
  // gitignore this repo ships (`.env`, `.env.*`, `!.env.example`), so "secret" is
85
90
  // defined the same way by the guard and by the thing that keeps it out of git.
91
+ //
92
+ // BUG-0007 tracks extracting this into lib/ so the two copies cannot drift. The
93
+ // twin now carries the same warning (env-file-guard.js:36-47), so both sides of
94
+ // the duplication point at each other and at the bug; README.md:522-525 records
95
+ // why the extraction was deferred.
86
96
  function isBlockedEnvFile(filePath) {
87
97
  if (!filePath) return false;
88
98
  const basename = path.basename(String(filePath));
@@ -262,7 +272,7 @@ function checkBash(data) {
262
272
 
263
273
  // Each `;`/`&&`/`||`/`|` segment gets its own turn, so a reader hidden after
264
274
  // a separator is still judged as a first token — the same reasoning as
265
- // absolute-path-guard.js:118.
275
+ // absolute-path-guard.js:123.
266
276
  for (const segment of splitSegments(fullCmd)) checkScope(segment, segment);
267
277
 
268
278
  // …and then, in one narrow case, the whole command as a single scope.
@@ -1,8 +1,50 @@
1
1
  #!/usr/bin/env node
2
2
  'use strict';
3
3
 
4
+ /**
5
+ * env-file-guard.js — PreToolUse / Read|Write|Edit|MultiEdit
6
+ *
7
+ * Blocks: file-tool reads and writes of any .env file, at any path in the tree.
8
+ * Why a hook: a deny rule matches one literal spelling. settings-deny.json
9
+ * carries Read entries for `.env` and `.env.local` only (:58-59), so
10
+ * `.env.production` and every future suffix would each need their own line,
11
+ * and Write/Edit/MultiEdit are not covered by them at all. The harder half is
12
+ * the `.env.example` carve-out: it is a hole INSIDE the pattern, and a deny
13
+ * list has no "except" — an allow entry does not override a deny entry. "Every
14
+ * `.env.` variant but one" is only expressible in code. A hook also returns a
15
+ * reason, and the reason is what points at the permitted alternative
16
+ * (`source .env`) — the difference between a policy and a wall people route
17
+ * around.
18
+ * Fails: open — unparseable stdin exits 0 silently at the JSON.parse catch
19
+ * below. A payload that parses but is not an object (`null`, a number) throws
20
+ * out of the `const { tool_name, tool_input } = data` destructure and exits
21
+ * non-zero, which Claude Code treats as a NON-blocking hook error: stderr is
22
+ * surfaced to the user but the tool call still proceeds. So both failure paths
23
+ * allow — one quietly, one loudly. This file predates lib/command-parse.js and
24
+ * does not use its readHookInput, so it has no handler-level catch to make the
25
+ * second path silent the way the command-class guards do.
26
+ * False positives: the test is a basename prefix, so `.env.template`,
27
+ * `.env.sample`, and even a doc named `.env.local.md` are all treated as live
28
+ * secrets — escape hatch: name the file so its basename does not begin with
29
+ * `.env.` (`env.template` and `example.env` both pass cleanly), or use the one
30
+ * permitted spelling, `.env.example`.
31
+ * See README.md § Safety / policy hooks for the full rationale.
32
+ */
33
+
4
34
  const path = require('path');
5
35
 
36
+ // KEPT BYTE-IDENTICAL WITH env-content-read-guard.js:86-98. If the allow-list
37
+ // changes, change it in both places or in neither — two .env controls that
38
+ // disagree about which files are secret is worse than one control. It also
39
+ // matches the gitignore this repo ships (`.env`, `.env.*`, `!.env.example`), so
40
+ // "secret" is defined the same way by the guard and by the thing that keeps the
41
+ // file out of git.
42
+ //
43
+ // BUG-0007 tracks extracting this into lib/ so the two copies cannot drift.
44
+ // Until it lands the duplication is load-bearing and this warning is the only
45
+ // thing holding it together — README.md:522-525 records why it was deferred
46
+ // (extraction means editing two live shipped controls for a pure refactor).
47
+ // Until now only the twin carried the warning; both sides do from here on.
6
48
  function isBlockedEnvFile(filePath) {
7
49
  if (!filePath) return false;
8
50
  const basename = path.basename(String(filePath));
@@ -20,6 +20,13 @@
20
20
  // The interpreter token is matched on its BASENAME with leading backslashes
21
21
  // stripped, so `/bin/bash -c`, `env bash -c`, and `\bash -c` are all caught
22
22
  // where a literal `bash -c` deny pattern is not.
23
+ //
24
+ // Fails: closed — every uncertain outcome denies. A sibling guard that is
25
+ // missing, times out, crashes, or answers with something that is not a decision
26
+ // envelope blocks; a deny list that cannot be read blocks; a payload that cannot
27
+ // be isolated blocks. The one exception sits upstream of this file: a hook
28
+ // payload that is not parseable JSON exits 0 in lib/command-parse.js, which is
29
+ // fail-OPEN by design there.
23
30
 
24
31
  // ---------------------------------------------------------------------------
25
32
  // RECURSIVE RE-EVALUATION, not blanket deny (TASK-028). The rule this hook now
@@ -35,6 +35,14 @@ function readHookInput(handler) {
35
35
  * Split a command into independently-inspectable segments. Pipes are included
36
36
  * alongside the separators so a blocked command cannot hide behind
37
37
  * `&&`, `;`, `||`, or `| tail -20`.
38
+ *
39
+ * QUOTING-UNAWARE, and every caller inherits it: the split is a plain regex, so
40
+ * a separator inside quotes still splits (`grep "A|B" .env` becomes `grep "A`
41
+ * and `B" .env`). That direction errs toward more segments and therefore toward
42
+ * blocking, never toward allowing — but a rule that inspects only the FIRST
43
+ * token of a segment can lose its match when a token is torn in half, which is
44
+ * why env-content-read-guard.js re-runs its check over the whole command when
45
+ * it sees both a quote and a pipe.
38
46
  */
39
47
  function splitSegments(cmd) {
40
48
  return String(cmd ?? '').split(/;|&&|\|\||\|/).map(s => s.trim()).filter(Boolean);
@@ -4,6 +4,24 @@
4
4
  * serena-languages.js — reads project/global Serena config for enabled languages
5
5
  * and maps them to file extensions for use in enforcement hooks.
6
6
  *
7
+ * ── This is a library, not a hook ─────────────────────────────────────────
8
+ * It is never wired in lib/scripts/templates/settings-hooks.json, has no
9
+ * stdin/stdout contract, and must never call process.exit or throw. It is loaded
10
+ * at require-time by hooks that are all fail-open, so an exit or an uncaught
11
+ * throw here would take down a tool call the hook was never meant to gate. That
12
+ * is why readFileSafe swallows its catch and why every lookup degrades to "not
13
+ * configured" instead of erroring.
14
+ *
15
+ * Who depends on it:
16
+ * lib/serena.js — getEnabledExtensionsSet, inside isAllowedPath, to decide
17
+ * whether a path's extension belongs to an enabled language. serena.js
18
+ * re-exports the function, so every Serena hook that calls isAllowedPath
19
+ * (edit-guard, write-guard, read-guard, bash-grep-block, …) depends on this
20
+ * file transitively; serena-first-glob-guard.js calls the re-export directly
21
+ * to decide whether a non-code glob is worth enforcing.
22
+ * LANG_EXTS, getEnabledLanguages and buildCodeExtensionsRegex are exported but
23
+ * have no in-repo consumer today — public surface, not dead code.
24
+ *
7
25
  * Resolution order (mirrors Serena itself):
8
26
  * 1. ~/.serena/serena_config.yml — global defaults
9
27
  * 2. {cwd}/.serena/project.yml — project override (wins when languages: present)
@@ -22,9 +40,18 @@ const os = require('os');
22
40
 
23
41
  const GLOBAL_CONFIG = path.join(os.homedir(), '.serena', 'serena_config.yml');
24
42
 
25
- // Serena language name → file extensions (lowercase, no leading dot)
43
+ // Serena language name → file extensions (lowercase, no leading dot).
44
+ // Keys are the exact strings Serena accepts in `languages:`; an unknown key
45
+ // contributes nothing (getEnabledExtensionsSet's `|| []`) rather than throwing,
46
+ // so a typo degrades to narrower scoping, never to a crash.
47
+ // typescript carries js/jsx/mjs/cjs because Serena's TypeScript server also
48
+ // serves plain JavaScript — a JS-only project still writes `typescript`.
26
49
  const LANG_EXTS = {
27
50
  typescript: ['ts', 'tsx', 'js', 'jsx', 'mjs', 'cjs'],
51
+ // The *_jedi / *_ty / *_ccls / *_omnisharp / *_solargraph / *_phpactor keys are
52
+ // not extra languages — they are Serena's alternate language-server backends,
53
+ // and each is a distinct value a user may write in `languages:`. Both spellings
54
+ // must map, or a project on the alternate backend loses language scoping.
28
55
  python: ['py'],
29
56
  python_jedi: ['py'],
30
57
  python_ty: ['py'],
@@ -75,10 +102,16 @@ const LANG_EXTS = {
75
102
  al: ['al'],
76
103
  hlsl: ['hlsl'],
77
104
  msl: ['metal'],
105
+ // FALSE POSITIVE: '.m' is also Objective-C (and Mathematica). A project with
106
+ // matlab enabled will see Objective-C files treated as enabled-language code.
107
+ // Escape hatch: drop matlab from `languages:` in .serena/project.yml.
78
108
  matlab: ['m'],
79
109
  rego: ['rego'],
80
110
  systemverilog: ['sv', 'svh'],
81
111
  haxe: ['hx'],
112
+ // The three CSS-family names deliberately share one extension set, so whichever
113
+ // one a project names in `languages:` covers .css/.scss/.sass — `languages:
114
+ // [css]` on a .scss codebase would otherwise fall out of enforcement entirely.
82
115
  scss: ['scss', 'sass', 'css'],
83
116
  sass: ['scss', 'sass', 'css'],
84
117
  css: ['css', 'scss', 'sass'],
@@ -90,6 +123,26 @@ const LANG_EXTS = {
90
123
  * Returns null when the key is absent.
91
124
  * Returns [] when the key is present but the list is empty.
92
125
  * Returns [...] for a populated list (inline or block form).
126
+ *
127
+ * The null/[] split is load-bearing, not stylistic — getEnabledLanguages uses it
128
+ * to decide whether project.yml overrides the global config. Do not normalise
129
+ * null to [].
130
+ *
131
+ * Hand-rolled instead of js-yaml because the hooks must run with zero
132
+ * dependencies: package.json declares no `dependencies` or `devDependencies` at
133
+ * all, and install-global.sh rsyncs lib/hooks/ into ~/.claude/hooks/, where the
134
+ * scripts execute standalone with no node_modules anywhere on the resolution
135
+ * path. A require('js-yaml') there would throw MODULE_NOT_FOUND on every tool
136
+ * call that triggers a Serena hook. The price is that only the two forms below
137
+ * parse — anchors, flow maps, and multi-line quoted scalars all read as "key
138
+ * absent", which degrades to the caller's static fallback rather than erroring.
139
+ *
140
+ * Accepted forms (block items may sit at any indentation, including column 0):
141
+ * languages: [] → []
142
+ * languages: [typescript, python] → ['typescript', 'python']
143
+ * languages: → ['typescript', 'python']
144
+ * - typescript
145
+ * - python
93
146
  */
94
147
  function parseLanguagesFromYaml(content) {
95
148
  if (!content) return null;
@@ -106,17 +159,33 @@ function parseLanguagesFromYaml(content) {
106
159
  const keyMatch = content.match(/^languages\s*:/m);
107
160
  if (!keyMatch) return null;
108
161
 
162
+ // KNOWN DEFECT, left unfixed (this pass is comments-only): the regex above is
163
+ // ^-anchored, but indexOf is not — it searches from position 0 for the literal
164
+ // matched text ("languages:"). An earlier occurrence of that substring, e.g.
165
+ // inside a comment or as the tail of a key such as `default_languages:`, makes
166
+ // the slice start in the wrong place and the block items are read from the
167
+ // wrong region of the file. Inline form returns before reaching this line, so
168
+ // only block form is affected.
109
169
  const afterKey = content.slice(content.indexOf(keyMatch[0]) + keyMatch[0].length);
110
170
  const items = [];
111
171
  for (const line of afterKey.split('\n')) {
112
172
  if (/^\s*#/.test(line)) continue; // skip comment lines
173
+ // A block item always starts with '-' (at any indentation), so a line
174
+ // beginning with a letter at column 0 is the next top-level key and the list
175
+ // has ended. Without this the loop swallows the rest of the file.
113
176
  if (/^[a-zA-Z]/.test(line)) break; // next top-level key — stop
177
+ // \S+ stops at the first space, so a quoted value containing whitespace
178
+ // parses as its first word. No Serena language name contains a space, so this
179
+ // has no real-world false positive today.
114
180
  const m = line.match(/^\s*-\s*(['"]?)(\S+)\1/);
115
181
  if (m) items.push(m[2]);
116
182
  }
117
183
  return items;
118
184
  }
119
185
 
186
+ // Missing file, unreadable file, and permission denied all mean the same thing
187
+ // here: "not configured". This module is required by fail-open hooks, so it must
188
+ // never throw — see the library note at the top of the file.
120
189
  function readFileSafe(filePath) {
121
190
  try { return fs.readFileSync(filePath, 'utf8'); } catch { return null; }
122
191
  }
@@ -125,11 +194,26 @@ function readFileSafe(filePath) {
125
194
  * Returns the list of enabled language names for the current working directory.
126
195
  * Project config ({cwd}/.serena/project.yml) overrides the global config when
127
196
  * it provides a non-null languages list (even an empty one).
197
+ *
198
+ * "Even an empty one" is the entire reason parseLanguagesFromYaml distinguishes
199
+ * null from []: `languages: []` in project.yml is an authoritative "this project
200
+ * scopes to nothing", and it has to outrank a populated global list. Collapse
201
+ * the two and such a project silently inherits whatever the user happens to have
202
+ * in ~/.serena/serena_config.yml.
203
+ *
204
+ * process.cwd() is the project root only because Claude Code runs hooks from it.
205
+ * This module does no repo-root discovery, so a caller that has chdir'd
206
+ * elsewhere resolves the wrong project.yml and gets the global list instead.
128
207
  */
129
208
  function getEnabledLanguages() {
130
209
  const globalLangs = parseLanguagesFromYaml(readFileSafe(GLOBAL_CONFIG));
131
210
  const projectYml = path.join(process.cwd(), '.serena', 'project.yml');
132
211
  const projectLangs = parseLanguagesFromYaml(readFileSafe(projectYml));
212
+ // The trailing `|| []` deliberately collapses null/[] for callers — downstream
213
+ // only cares about the resulting set. Consequence worth knowing: "no languages
214
+ // configured" reaches serena.js's isAllowedPath as an empty set, and that
215
+ // branch falls back to the static CODE_EXTENSIONS list. An empty result
216
+ // therefore widens enforcement to the built-in defaults; it does not disable it.
133
217
  return (projectLangs !== null ? projectLangs : globalLangs) || [];
134
218
  }
135
219
 
@@ -148,6 +232,15 @@ function getEnabledExtensionsSet() {
148
232
  /**
149
233
  * Returns a RegExp matching file paths whose extension belongs to an enabled
150
234
  * language, or null when no languages are configured.
235
+ *
236
+ * Callers must read null as "no language scoping available" and fall back to
237
+ * their own static list — null is not "matches nothing". No in-repo caller today
238
+ * (see the consumer list at the top); this is public surface, not dead code.
239
+ *
240
+ * Extensions are interpolated unescaped. That is safe only because every value
241
+ * in LANG_EXTS is [a-z0-9]+ — an extension containing a regex metacharacter
242
+ * ('.', '+', '*') would silently corrupt the alternation rather than fail, so
243
+ * keep LANG_EXTS values alphanumeric.
151
244
  */
152
245
  function buildCodeExtensionsRegex() {
153
246
  const exts = getEnabledExtensionsSet();
@@ -33,6 +33,28 @@
33
33
  *
34
34
  * No network, no MCP runtime introspection, no dependency on Serena being
35
35
  * installed — detection (if used) reads user-level Claude Code config.
36
+ *
37
+ * ── This is a library, not a hook ─────────────────────────────────────────
38
+ * It is never wired in lib/scripts/templates/settings-hooks.json, has no
39
+ * stdin/stdout contract, and must never call process.exit — every consumer is
40
+ * fail-open, and an uncaught throw here would take down a tool call the hook
41
+ * was never meant to gate. Hence the swallowed catches throughout: silent
42
+ * degradation is the correct failure mode for this file specifically.
43
+ *
44
+ * Nine hooks require it (all siblings in ../, installed to ~/.claude/hooks/):
45
+ * serena-first-guard.js Grep symbol detection
46
+ * serena-first-glob-guard.js Glob symbol detection ('glob' dialect)
47
+ * serena-bash-grep-block.js Bash symbol detection ('bash') + paths
48
+ * serena-first-read-guard.js Read state file, gates, isAllowedPath
49
+ * serena-edit-guard.js Edit|MultiEdit isAllowedPath + block copy
50
+ * serena-write-guard.js Write isAllowedPath + block copy
51
+ * serena-usage-tracker.js PostToolUse(+Failure) state file, health
52
+ * serena-session-reset.js SessionStart state file path
53
+ * serena-pre-delegation.js Agent fail-open gate only
54
+ * A behaviour change here lands in all nine at once and there is no way to roll
55
+ * one back independently — which is why the call-site differences are expressed
56
+ * as explicit `opts` (see isCodeSymbol's dialect table) rather than as branches
57
+ * on who is calling.
36
58
  */
37
59
 
38
60
  const fs = require('fs');
@@ -445,6 +467,26 @@ function defaultHealth() {
445
467
  // each other's updates. This fails open by design — a hook that can't get
446
468
  // the lock within budget proceeds unlocked rather than hanging; hooks must
447
469
  // never block indefinitely.
470
+ // Why these three numbers. The critical section is a read, a JSON.parse, an
471
+ // in-memory mutate and an atomic rename — sub-millisecond in practice. A lock
472
+ // still held after LOCK_STALE_MS (750ms) is therefore not contended, it is
473
+ // orphaned by a hook process that died mid-cycle; nothing auto-releases a plain
474
+ // marker file, so without a staleness rule one crash wedges every later state
475
+ // write for the rest of the session. 750ms sits far enough above the real cost
476
+ // that clearing a genuinely live holder takes a pathological stall.
477
+ //
478
+ // LOCK_RETRY_BUDGET_MS (250ms) is the other side of the trade: it caps what a
479
+ // *waiting* hook adds to a tool call it was never meant to slow down. On
480
+ // exhaustion the caller proceeds unlocked and best-effort — a lost counter
481
+ // update is cheap, a PreToolUse hook that hangs is not. Being well under
482
+ // LOCK_STALE_MS means a waiter normally gives up rather than clearing a lock
483
+ // whose holder is merely slow. (Staleness is judged from the lock file's own
484
+ // mtime, not from how long this waiter has waited, so a waiter that arrives late
485
+ // in a stale lock's life still clears it immediately — that is the self-heal
486
+ // working, not a violation of the budget.)
487
+ //
488
+ // The backoff ladder tops out at 80ms, so the budget covers about five wakeups:
489
+ // enough to yield to a real holder, few enough that waiting is never the cost.
448
490
  const LOCK_STALE_MS = 750;
449
491
  const LOCK_RETRY_BUDGET_MS = 250;
450
492
  const LOCK_BACKOFF_MS = [10, 20, 40, 80];
@@ -580,10 +622,30 @@ function classifySerenaFailure(errorPayload) {
580
622
  // Tool-level: the server answered, the query just didn't resolve, or it
581
623
  // declined for a benign/config reason (e.g. the file's language isn't
582
624
  // enabled in .serena/project.yml — a normal, expected response).
625
+ // The alternation is grouped by what Serena's error strings actually say, not
626
+ // by an error taxonomy: query misses ("not found", "no results", "no matching",
627
+ // "no symbol", "could not find"), path misses ("does not exist", "no such
628
+ // file/symbol/path/directory"), the "error at <location>" form emitted for a
629
+ // bad location, and — the group that matters most — the language-config
630
+ // declines ("cannot extract symbols", "active languages", "unsupported
631
+ // language", "no language server"). A file whose language is not enabled in
632
+ // .serena/project.yml fails on EVERY call, so misfiling that group as
633
+ // transport would shell out to pgrep on each one and, the first time the probe
634
+ // came back empty, disable Serena-first enforcement for the whole project on
635
+ // the strength of a perfectly healthy server declining a file type.
583
636
  if (/not found|no results|no matching|no symbol|could not find|error searching|error finding|does not exist|no such (?:file|symbol|path|directory)|error at |cannot extract symbols|active languages|unsupported language|no language server/i.test(s)) {
584
637
  return 'tool';
585
638
  }
586
639
  // Transport-level: the server is unreachable / the pipe broke.
640
+ // Transport-level: nothing in this alternation describes a query, only a pipe.
641
+ // `closed`, `reset` and `connection` are bare because they arrive with no
642
+ // stable prefix ("connection closed", "transport closed", "socket reset").
643
+ //
644
+ // Ordering is load-bearing: a single error string can match both lists
645
+ // ("connection to the language server closed: symbol not found"), and first
646
+ // match wins, so the narrower tool-level test must run first. Swapping the two
647
+ // blocks would route ordinary query misses that merely mention a connection
648
+ // into the health-assessment path.
587
649
  if (/timeout|timed out|connection|refused|econnrefused|socket|epipe|closed|disconnect|not connected|unreachable|reset|broken pipe|hang/i.test(s)) {
588
650
  return 'transport';
589
651
  }
@@ -630,8 +692,43 @@ function isSerenaProcessAlive(projectDir) {
630
692
  // slightly different allowlists — those genuine differences are expressed via
631
693
  // `opts`, so identical inputs yield identical block/allow decisions.
632
694
 
695
+ // Zero-width and bidi formatting characters. They render as nothing, so
696
+ // `create<ZWSP>Order` is visually identical to `createOrder` while every ASCII
697
+ // shape regex below fails to match it — a single pasted character is enough to
698
+ // walk a symbol search past the guards. Stripping is opt-in (`stripZeroWidth`)
699
+ // because the three call sites handle it differently: the Glob guard sets the
700
+ // flag, the Bash guard strips them in its own `clean` callback before tokens
701
+ // ever reach here, and the Grep guard (serena-first-guard.js) does NEITHER.
702
+ //
703
+ // SUSPECTED DEFECT — annotated, deliberately not fixed in this comments-only
704
+ // pass. That third case leaves the exact bypass this constant exists to close
705
+ // still open on the Grep surface: a zero-width character inside a Grep pattern
706
+ // token is neither stripped nor rejected (it is not a regex metacharacter, so
707
+ // rejectRegexSpecials does not catch it). The fix is one option at that call
708
+ // site, but it needs its own regression test rather than riding along here.
633
709
  const SYMBOL_ZERO_WIDTH = /[­​-‏⁠-⁤]/g;
634
710
 
711
+ // Why this list is ~150 entries long, and what earns a place on it. The Glob
712
+ // guard hands over a pattern already shredded into fragments — `src/**/*Modal.tsx`
713
+ // becomes `src`, `Modal`, `tsx` — and by the time a fragment reaches
714
+ // isCodeSymbol there is no context left to distinguish "this was the extension"
715
+ // from "this was a symbol". So every fragment a legitimate file-discovery glob
716
+ // routinely produces has to be named here, or the guard blocks ordinary work:
717
+ // extensions, directory names, file stems, framework/tool config stems, and the
718
+ // directive words people search for. The length is the cost of exact matching;
719
+ // each entry is one word that would otherwise be judged on its shape alone.
720
+ //
721
+ // The bar for adding an entry: the token shows up in globs people write to find
722
+ // files by location or kind, and nobody writes it meaning a symbol. `Modal`
723
+ // fails that test (it is a real component name) and is deliberately absent;
724
+ // `middleware`, `providers`, and `transformers` pass it and are present even
725
+ // though each is also a plausible identifier — because here a false block costs
726
+ // a real search while a false allow costs only a slower route to the same files.
727
+ //
728
+ // Matched lowercased and EXACTLY. Substring matching would exempt `UserService`
729
+ // for containing `service`, which is the entire class of token this guard exists
730
+ // to catch. (`next` and `turbo` appear under two group headings; Set membership
731
+ // makes the duplicate inert.)
635
732
  // Glob guard's exact-match skip set: extensions, common dirs/stems, framework
636
733
  // config names, directives. Checked case-insensitively.
637
734
  const GLOB_SKIP_EXACT = new Set([
@@ -665,6 +762,37 @@ const GLOB_SKIP_EXACT = new Set([
665
762
  'require', 'http', 'https',
666
763
  ]);
667
764
 
765
+ // ── The kebab carve-out (Grep dialect only) ────────────────────────────────
766
+ // A kebab token is normally a filename, not a symbol, and the Glob dialect
767
+ // rejects the shape outright for exactly that reason. The Grep dialect cannot
768
+ // afford to: in a React/Next codebase the component and its file share a name,
769
+ // so a developer greps `user-modal` meaning the component. These three regexes
770
+ // triage that, and they are tested in the order they are declared.
771
+ //
772
+ // KEBAB_TAILWIND_PREFIX — the dominant false positive by volume, and the reason
773
+ // the carve-out needs a reject list at all. A Tailwind project's markup is
774
+ // wall-to-wall `text-sm`, `bg-white`, `hover:bg-gray-100`, `max-w-md`,
775
+ // `data-state` — every one a kebab token of symbol-ish length. Grepping a
776
+ // utility class is a styling search over markup, never a symbol lookup, and
777
+ // Serena has nothing better to offer for it, so these must fall through to Grep
778
+ // or the guard makes CSS work impossible. The list is the Tailwind utility
779
+ // prefix set (spacing, sizing, colour, layout, typography, transition, and the
780
+ // `hover:`/`focus:`/`active:`/`group-` state variants); it is not exhaustive,
781
+ // it stops where class attributes stop.
782
+ //
783
+ // KEBAB_COMPONENT_SUFFIX — the inverse judgement. A kebab token ending in a
784
+ // UI-part noun (`user-modal`, `date-picker`, `nav-bar`, `error-boundary`) names
785
+ // something that exists as a symbol, so Serena can answer for it. The trailing
786
+ // `s?` covers the plural filename convention (`user-cards`). The agent-role tail
787
+ // (`-runner`, `-reviewer`, `-checker`, `-resolver`, `-guard`, `-enforcer`) is
788
+ // not decoration: this repo and the kit it was ported from name their own
789
+ // subagents and hook scripts that way, so it is the local vocabulary and the
790
+ // tokens actually get searched for.
791
+ //
792
+ // KEBAB_DOMAIN_PREFIX — the same call from the other end. A token whose FIRST
793
+ // segment is a code-layer word (`actions-`, `helpers-`, `utils-`, `hooks-`,
794
+ // `types-`, `constants-`, `validations-`, `services-`) is naming code whatever
795
+ // follows it, so the suffix never has to be enumerated.
668
796
  // Guard's tailwind-utility prefixes — kebab tokens starting with these are
669
797
  // styling classes, never symbols.
670
798
  const KEBAB_TAILWIND_PREFIX = /^(text-|bg-|border-|font-|hover:|focus:|active:|group-|ring-|shadow-|rounded-|flex-|grid-|gap-|space-|divide-|overflow-|whitespace-|break-|leading-|tracking-|align-|justify-|items-|self-|order-|col-|row-|transition-|duration-|ease-|animate-|scale-|rotate-|translate-|origin-|cursor-|select-|resize-|appearance-|outline-|decoration-|underline-|line-|placeholder-|caret-|accent-|sr-|z-|opacity-|w-|h-|p-|m-|px-|py-|pt-|pb-|pl-|pr-|mx-|my-|mt-|mb-|ml-|mr-|max-|min-|inset-|top-|right-|bottom-|left-|float-|data-)/;
@@ -685,12 +813,63 @@ const KEBAB_DOMAIN_PREFIX = /^(actions?|helpers?|utils?|hooks?|types?|constants?
685
813
  function isCodeSymbol(raw, opts = {}) {
686
814
  if (raw == null) return false;
687
815
  let s = String(raw);
816
+ // Ordering: strip zero-width first, then measure. Measuring first would let a
817
+ // padded 3-character name clear the floor and then fail every shape test below
818
+ // — allowed, but for the wrong reason, and silently.
819
+ //
820
+ // The 4-character floor and the whitespace reject are the two rules every
821
+ // dialect shares. Below 4 characters the shape tests stop discriminating (`ab`,
822
+ // `x1`, `Foo` are as likely to be prose as code) and find_symbol is not the
823
+ // better tool for such a name anyway. Whitespace means the token is a phrase,
824
+ // and a phrase is a text search — which is precisely what Grep is for.
688
825
  if (opts.stripZeroWidth) s = s.replace(SYMBOL_ZERO_WIDTH, '');
689
826
  if (s.length < 4) return false;
690
827
  if (/\s/.test(s)) return false;
691
828
 
829
+ // Grep dialect only. Its tokens arrive raw, so one still carrying `(`, `[`,
830
+ // `\`, `^`, `$`, `*`, `+`, `?` or `&` is a regex fragment, not a name — and
831
+ // Serena's find_symbol takes a name, not a pattern. Blocking there would trade
832
+ // a working regex search for a tool that cannot express it. The other two
833
+ // dialects never need this: the Bash call site strips the same metacharacters
834
+ // in `clean`, and the Glob splitRe consumes them as delimiters.
692
835
  if (opts.rejectRegexSpecials && /[&?+[\]{}()\\^$*]/.test(s)) return false;
693
836
 
837
+ // ── The three allowlist dialects ─────────────────────────────────────────
838
+ // This is the entire false-positive surface of three hooks, so the differences
839
+ // below are deliberate rather than drift. Every dialect answers one question —
840
+ // "would blocking this token cost the caller a search Serena cannot do?" — for
841
+ // a different input shape:
842
+ //
843
+ // 'guard' serena-first-guard.js (Grep). Tokens are raw pattern fragments,
844
+ // split on `|` and nothing else, so they can still be comment
845
+ // markers, quoted strings, JS keywords, or call syntax. Hence the
846
+ // widest reject list (`^//`, `^#`, `^.`, `^['"` + backtick`]`,
847
+ // `require(`, `console.`, `use client|server`): every one of those
848
+ // is a thing people grep for, and none of them is a symbol name.
849
+ // 'bash' serena-bash-grep-block.js (a grep/rg command line). The call site
850
+ // has already stripped regex metacharacters in its `clean`
851
+ // callback, so the list is shorter — but it adds
852
+ // `^[a-z]+-[a-z]+`, rejecting kebab outright. A shell grep for
853
+ // `user-modal` is usually hunting a filename or a CSS class, and
854
+ // this dialect never sets kebabComponents, so the two agree.
855
+ // 'glob' serena-first-glob-guard.js (a file glob). Tokens are path
856
+ // fragments, so prefix rules do not apply; it uses GLOB_SKIP_EXACT
857
+ // — an exact-match vocabulary of everything a legitimate glob
858
+ // produces — plus a full kebab-filename reject, because inside a
859
+ // glob a kebab token IS a filename.
860
+ //
861
+ // Passing no allowlist (the default) applies none of this: only the shared
862
+ // floors above and the shape tests below. Nothing in this repo calls it that
863
+ // way. It is the honest default for a new call site that has not yet decided
864
+ // what its tokens look like, and it is also the STRICTEST — with no rejects it
865
+ // calls more things symbols and therefore blocks more.
866
+ //
867
+ // Two rules recur in all three lists and carry most of the weight:
868
+ // `^[A-Z_]{3,}$` (SCREAMING_SNAKE is a constant or an env var — grep is the
869
+ // right tool, find_symbol is not) and `^[a-z]{1,8}$` (a short all-lowercase
870
+ // word is too generic to be worth a symbol lookup). `^\d` and `^http` appear
871
+ // in the two prefix-based dialects; the glob dialect covers the same ground by
872
+ // exact match (`http`, `https` are in GLOB_SKIP_EXACT).
694
873
  if (opts.allowlist === 'guard') {
695
874
  const allow = [
696
875
  /^(TODO|FIXME|HACK|XXX|NOTE)/i,
@@ -710,6 +889,12 @@ function isCodeSymbol(raw, opts = {}) {
710
889
  ];
711
890
  if (skip.some(rx => rx.test(s))) return false;
712
891
  } else if (opts.allowlist === 'glob') {
892
+ // Ordering trap: the kebab-filename reject below sits ABOVE the
893
+ // kebabComponents carve-out further down, so a caller passing both
894
+ // `allowlist: 'glob'` and `kebabComponents: true` would never reach the
895
+ // carve-out and every kebab component name would be allowed. No call site
896
+ // does that today — the two options are mutually exclusive by intent, and
897
+ // nothing here enforces it.
713
898
  if (GLOB_SKIP_EXACT.has(s.toLowerCase())) return false;
714
899
  if (/^[a-z]{1,8}$/.test(s)) return false;
715
900
  if (/^[A-Z_]{3,}$/.test(s)) return false;
@@ -717,6 +902,18 @@ function isCodeSymbol(raw, opts = {}) {
717
902
  }
718
903
 
719
904
  // Guard's kebab carve-out: some kebab tokens ARE symbols.
905
+ // Reached only from the Grep dialect — it is the sole call site that sets
906
+ // kebabComponents. The `^[a-z]+-[a-z]/` test scopes the block to lowercase
907
+ // kebab; anything else falls straight through to the shape tests below.
908
+ //
909
+ // Overlaps resolve top-down, and there are real ones: `grid-item` and
910
+ // `text-field` carry a Tailwind prefix *and* a component suffix, and the
911
+ // prefix wins, so they are treated as styling and the Grep is allowed. That
912
+ // error direction is the cheap one — a permitted Grep costs a slower route to
913
+ // the same lines, while a wrong block costs a search Serena cannot perform.
914
+ //
915
+ // The trailing `return false` is the actual policy of this block: an
916
+ // unrecognised kebab token is a filename until proven otherwise.
720
917
  if (opts.kebabComponents && /^[a-z]+-[a-z]/.test(s)) {
721
918
  if (KEBAB_TAILWIND_PREFIX.test(s)) return false;
722
919
  if (KEBAB_COMPONENT_SUFFIX.test(s)) return true;
@@ -724,6 +921,22 @@ function isCodeSymbol(raw, opts = {}) {
724
921
  return false;
725
922
  }
726
923
 
924
+ // The shapes that mean "this is an identifier". What each one is really doing:
925
+ // camelCase requires an interior capital; the `{3,}` bound only restates
926
+ // the shared 4-character floor above.
927
+ // PascalCase requires the *second* character to be a letter, so `S3Client`
928
+ // and `X11Server` are not recognised. That miss is real; no
929
+ // rationale for excluding a digit there is recoverable from the
930
+ // code or the README — verify before relying on it either way.
931
+ // snake_case demands three or more segments AND 9+ characters, because
932
+ // two-segment snake (`user_id`, `my_var`, `is_open`) is far more
933
+ // often a column, a flag, or a variable than a function anyone
934
+ // would navigate to — and blocking those would break routine
935
+ // grepping of SQL and config text.
936
+ // dotted Grep-only (`mcp.Tool`, `router.push`): a module-qualified name.
937
+ // The Bash dialect splits on `.` and the Glob dialect treats it
938
+ // as a path separator, so the raw-token dialect is the only one
939
+ // that can ever see one intact.
727
940
  const isCamelCase = /^[a-z][a-zA-Z0-9]{3,}$/.test(s) && /[A-Z]/.test(s);
728
941
  const isPascalCase = /^[A-Z][a-zA-Z][a-zA-Z0-9]{2,}$/.test(s);
729
942
  const isSnakeCaseFn = /^[a-z]+(_[a-z]+){2,}$/.test(s) && s.length >= 9;
@@ -738,6 +951,21 @@ function isCodeSymbol(raw, opts = {}) {
738
951
  * optionally cleans each token before trimming. Remaining opts are forwarded
739
952
  * to isCodeSymbol.
740
953
  */
954
+ // The tokenizer belongs to the call site, not to this function, because the
955
+ // three pattern syntaxes disagree about what a delimiter is:
956
+ // Grep splitRe '|' regex alternation and nothing else; a dot
957
+ // stays inside the token (see dottedSymbol).
958
+ // Bash splitRe /\\?\||\./ alternation plus dots — a shell grep pattern
959
+ // keeps `mcp.Tool` as one token, and the
960
+ // call site's `clean` strips the dot, which
961
+ // would manufacture `mcpTool`, a camelCase
962
+ // false positive out of thin air.
963
+ // Glob splitRe /[*/.\\{}...]+/ all punctuation — a glob is a path, and its
964
+ // punctuation is structure, not content.
965
+ // Choosing wrong does not fail loudly: it silently changes which tokens exist,
966
+ // and therefore which searches get blocked. `opts` is forwarded whole to
967
+ // isCodeSymbol, so a call site's splitRe and its dialect must be picked together
968
+ // — see the dialect table in isCodeSymbol.
741
969
  function extractSymbolsFromPattern(pattern, opts = {}) {
742
970
  const p = String(pattern ?? '');
743
971
  const splitRe = opts.splitRe || '|';