@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
@@ -2,29 +2,40 @@
2
2
  'use strict';
3
3
 
4
4
  /**
5
- * serena-first-glob-guard.js — PreToolUse hook (matcher: Glob)
5
+ * serena-first-glob-guard.js — PreToolUse / Glob
6
6
  *
7
- * HARD BLOCK: Glob patterns that search for code symbols by filename.
8
- * Closes the gap where an agent bypasses serena-first-guard (Grep matcher)
9
- * and serena-first-read-guard (Read matcher) by using Glob to locate files
10
- * containing a symbol name.
11
- *
12
- * Allowed:
13
- * - Extension patterns: src/**\/*.ts, *.tsx, **\/*.json
14
- * - Concept patterns: *subdomain*, *auth*, **\/middleware*
15
- * - Short / all-lowercase: *modal*, *form*, auth/**
16
- * - Config / framework files: tsconfig.json, next.config.ts
17
- *
18
- * Blocked:
19
- * - PascalCase symbol: *UserService*, **\/*Modal.tsx, *TabsClient*
20
- * - camelCase symbol: *createOrder*, *handleSubmit*
21
- * - snake_case function (3+): *get_user_sessions*, *write_audit_log*
22
- *
23
- * Philosophy: if you know the symbol name, use Serena's find_symbol. Glob
24
- * is for broad file discovery by extension or concept, not for
25
- * symbol-based search.
7
+ * Blocks: Glob patterns that encode a code symbol in a filename. This closes
8
+ * the gap where an agent blocked from grepping for a symbol
9
+ * (serena-first-guard) and from Reading the file (serena-first-read-guard)
10
+ * reaches the same place by globbing for the symbol's *filename* instead.
11
+ * Why a hook: the verdict is a classification of the `pattern` argument —
12
+ * settings.json can match the Glob tool or a path, never "this glob spells
13
+ * an identifier". The block also names the find_symbol call to use instead.
14
+ * Fails: open — unparseable stdin, an empty or non-string pattern, an
15
+ * out-of-project `path`, or `health.should_enforce === false` all pass the
16
+ * Glob through untouched.
17
+ * False positives: a file you want to OPEN rather than navigate, whose name is
18
+ * legitimately PascalCase (`*Dockerfile*`, `**\/*Modal.tsx`) — escape hatch:
19
+ * search by extension or concept in lowercase (`*modal*`, `src/**\/*.tsx`),
20
+ * which the 'glob' dialect below always allows.
21
+ * Philosophy: if you know the symbol name, use Serena's find_symbol. Glob is
22
+ * for broad file discovery by extension or concept, not symbol lookup.
23
+ * See README.md § "Serena-first enforcement hooks (ported from
24
+ * `claude-code-lsp-enforcement-kit`)" for the full rationale.
26
25
  */
27
26
 
27
+ // Worked examples of the line the 'glob' dialect draws, kept as the
28
+ // regression cases to reason from when changing GLOB_SKIP_EXACT:
29
+ // Allowed:
30
+ // - Extension patterns: src/**/*.ts, *.tsx, **/*.json
31
+ // - Concept patterns: *subdomain*, *auth*, **/middleware*
32
+ // - Short / all-lowercase: *modal*, *form*, auth/**
33
+ // - Config / framework files: tsconfig.json, next.config.ts
34
+ // Blocked:
35
+ // - PascalCase symbol: *UserService*, **/*Modal.tsx, *TabsClient*
36
+ // - camelCase symbol: *createOrder*, *handleSubmit*
37
+ // - snake_case function (3+): *get_user_sessions*, *write_audit_log*
38
+
28
39
  const {
29
40
  buildSuggestion, buildStructuredBlockResponse,
30
41
  extractSymbolsFromPattern,
@@ -55,12 +66,46 @@ process.stdin.on('end', () => {
55
66
 
56
67
  // ── Allow: non-code paths (anchored — bare substring would let
57
68
  // "myknowledge-vaultxxx" bypass detection) ──────────────────────────
69
+ // Tested against BOTH the `path` param and the pattern itself, because a
70
+ // glob routinely carries its own root (`node_modules/**/*.js`) with no path
71
+ // param at all — checking only `path` would miss every such call.
72
+ // The equivalent list in serena-first-guard.js is unanchored and sees only
73
+ // the path; that divergence is flagged as a known defect on that side.
58
74
  const NON_CODE_PATH = /(?:^|[\/\\])(?:knowledge-vault|\.task|\.claude|node_modules|supabase[\/\\]migrations|\.git)(?:[\/\\]|$)/i;
59
75
  if (NON_CODE_PATH.test(searchPath)) process.exit(0);
60
76
  if (NON_CODE_PATH.test(pattern)) process.exit(0);
61
77
 
62
78
  // Extract alphabetic tokens from the pattern (strip *, /, ., brackets, etc.)
63
79
  // and keep those that name code symbols.
80
+ //
81
+ // Call-site dialect — the counterpart to serena-first-guard.js's Grep
82
+ // dialect. The differences below are the whole point, not drift:
83
+ // splitRe: /[*/.\\{}\[\]()!?,\s|+-]+/ — a glob is punctuation-dense and
84
+ // every one of those characters is a separator here rather than part of
85
+ // a name, so splitting on all of them leaves bare identifier candidates:
86
+ // `src/**/*UserService*.tsx` → ['src', 'UserService', 'tsx']. Because the
87
+ // tokenizer has already removed the metacharacters, this call site does
88
+ // not need `rejectRegexSpecials`; the Grep guard splits only on '|',
89
+ // keeps them, and therefore does.
90
+ // allowlist: 'glob' — after that split an ordinary glob sheds tokens that
91
+ // look symbol-ish in isolation (`src`, `ts`, `tsconfig`, `middleware`,
92
+ // `playwright`), so this dialect adds GLOB_SKIP_EXACT: an exact-match set
93
+ // of extensions, directory stems, framework config names and directives.
94
+ // The Grep dialect needs no such set — its tokens are whole patterns, so
95
+ // prefix rules suffice. This dialect also rejects EVERY kebab token,
96
+ // precisely inverting the Grep dialect's kebabComponents carve-out: in a
97
+ // glob, `user-modal` is a filename convention; in a Grep pattern it is
98
+ // the component's name.
99
+ // dottedSymbol is likewise not passed: `.` is an extension separator here
100
+ // and splitRe consumes it before any classification can see it.
101
+ // stripZeroWidth: true — strips zero-width and soft-hyphen characters
102
+ // first, so an invisible character cannot break a name out of the
103
+ // camelCase / PascalCase shapes isCodeSymbol tests for. Only this guard
104
+ // passes it. NOTE: the reason for the asymmetry is not recoverable from
105
+ // the code or the README — a zero-width char in a glob matches no real
106
+ // filename, so this reads as classifier hardening rather than a
107
+ // Glob-specific need. Verify before copying it to, or removing it from,
108
+ // the other guards.
64
109
  const symbolTokens = extractSymbolsFromPattern(pattern, {
65
110
  splitRe: /[*/.\\{}\[\]()!?,\s|+-]+/, allowlist: 'glob', stripZeroWidth: true,
66
111
  });
@@ -1,8 +1,29 @@
1
1
  #!/usr/bin/env node
2
2
  'use strict';
3
3
 
4
- // serena-first-guard.js — PreToolUse hook (matcher: Grep)
5
- // Blocks Grep on code symbols. Suggests the equivalent Serena tool call.
4
+ /**
5
+ * serena-first-guard.js — PreToolUse / Grep
6
+ *
7
+ * Blocks: the built-in Grep tool when its pattern names a code symbol
8
+ * (camelCase, PascalCase, 3+-part snake_case, dotted member access, or a
9
+ * kebab component name) and the search is rooted inside the project.
10
+ * Suggests the equivalent Serena call for each symbol found.
11
+ * Why a hook: the verdict depends on *classifying an argument string* — a
12
+ * settings.json rule can match a tool name or a path, never "this pattern
13
+ * looks like an identifier". A hook can also answer with the exact
14
+ * find_symbol / find_referencing_symbols call to make instead, which a deny
15
+ * rule has no channel for.
16
+ * Fails: open — unparseable stdin, a non-string pattern, an out-of-project
17
+ * `path`, or `health.should_enforce === false` all pass the Grep through.
18
+ * False positives: grepping for a *string literal* shaped like an identifier —
19
+ * a log message, a JSON key, a CSS-in-JS class — escape hatch: scope the
20
+ * search with `glob` to a non-enforced extension or `path` to one of the
21
+ * exempt directories below, or loosen the pattern into something that reads
22
+ * as a regex (`handleSubmit` → `handle.*Submit`; the `*` trips
23
+ * rejectRegexSpecials and the token stops counting as a symbol).
24
+ * See README.md § "Serena-first enforcement hooks (ported from
25
+ * `claude-code-lsp-enforcement-kit`)" for the full rationale.
26
+ */
6
27
 
7
28
  const {
8
29
  buildSuggestion, buildStructuredBlockResponse, getEnabledExtensionsSet,
@@ -33,18 +54,87 @@ process.stdin.on('end', () => {
33
54
  // passes through regardless of pattern (Serena can't reach outside).
34
55
  if (searchPath && isOutsideProject(searchPath)) process.exit(0);
35
56
 
57
+ // Directories where an identifier-shaped match is not code, so redirecting to
58
+ // Serena would be useless: the knowledge vault and docs (prose that *quotes*
59
+ // symbol names), .task / .claude (agent scratch), node_modules (Serena
60
+ // indexes the project, not its dependencies), logs (identifiers appear in
61
+ // every stack trace), and generated SQL migrations.
62
+ //
63
+ // This is a near-duplicate of ALLOW_PATH_PATTERNS in lib/serena.js but NOT
64
+ // the same set — it adds `logs?/` and `knowledge-vault`, and drops
65
+ // build/dist/out/public/scripts/coverage/__tests__ — so swapping in the
66
+ // shared constant would silently change this hook's behaviour in both
67
+ // directions. That is why the tempting de-duplication has not been made.
68
+ //
69
+ // KNOWN DEFECT, left in place: unlike NON_CODE_PATH in
70
+ // serena-first-glob-guard.js this regex is unanchored, so `myknowledge-vault/`
71
+ // and `mydocs/` also match and skip enforcement. The glob guard carries a
72
+ // comment about fixing exactly this bug on its side; this side was missed.
36
73
  if (/knowledge-vault|\.task[\\/]|\.claude[\\/]|node_modules|logs?[\\/]|docs?[\\/]|supabase[\\/]migrations/i.test(searchPath)) {
37
74
  process.exit(0);
38
75
  }
39
76
 
77
+ // A search already scoped to a data/config extension needs no symbol
78
+ // enforcement — Serena has no symbol index for those files. The extension
79
+ // list is only a cheap pre-filter; the actual decision is the second step,
80
+ // which pulls the extension back out and defers to the project's *enabled*
81
+ // Serena languages (.serena/project.yml), so a project that really does
82
+ // index e.g. `sh` or `sql` keeps enforcement on those globs.
83
+ //
84
+ // `.md` is absent from the list, so markdown-scoped Greps stay enforced —
85
+ // the same stance as the read guard's `enforceMarkdown: true`. (Whether the
86
+ // two were aligned deliberately is not recorded anywhere; they agree today.)
87
+ //
88
+ // Both regexes are unanchored, and a brace list defeats the second one: for
89
+ // `**/*.{ts,json}` the first regex matches on `.json`, but the second finds
90
+ // no `.<letters><delimiter>` sequence at all, leaving ext '' → exit 0. A
91
+ // mixed code/non-code brace glob is therefore never enforced.
40
92
  if (/\.(txt|log|json|jsonc|yaml|yml|env|csv|toml|xml|sql|sh|css|scss)/i.test(glob)) {
41
93
  const m = glob.match(/\.([a-z0-9]+)(?:[^a-z0-9]|$)/i);
42
94
  const ext = m ? m[1].toLowerCase() : '';
43
95
  if (!ext || !getEnabledExtensionsSet().has(ext)) process.exit(0);
44
96
  }
45
97
 
98
+ // Fast path, not an independent policy: isCodeSymbol already rejects tokens
99
+ // shorter than 4 chars, and no token split out of a <4-char pattern can be
100
+ // >= 4, so this changes no verdict — it only skips the split and allocation
101
+ // for the very common short pattern. Lowering the floor is inert. RAISING it
102
+ // is not: at 8, the 7-char pattern `getUser` would exit here and never be
103
+ // classified at all.
46
104
  if (pattern.length < 4) process.exit(0);
47
105
 
106
+ // Call-site dialect. isCodeSymbol / extractSymbolsFromPattern in
107
+ // lib/serena.js serve three guards whose pattern languages differ; every
108
+ // option below encodes one fact about Grep's syntax specifically.
109
+ //
110
+ // splitRe: '|' — a LITERAL pipe split, not a regex one. A Grep pattern is
111
+ // a regex, and top-level alternation is the only decomposition that is
112
+ // safe without parsing it: `getUser|setUser` is two candidates. Anything
113
+ // else stays glued to its token — which is what forces the next option.
114
+ // allowlist: 'guard' — the skip list tuned for Grep tokens: TODO/FIXME/
115
+ // HACK/XXX/NOTE markers, `console.`, import/export/from/`require(`,
116
+ // comment and shell-comment prefixes, URLs, leading digits,
117
+ // SCREAMING_CASE constants, any short all-lowercase word, a quoted
118
+ // string, and "use client"/"use server". Every one is something you
119
+ // legitimately grep for AS TEXT. The 'bash' and 'glob' dialects carry
120
+ // different lists because their call sites see different token shapes —
121
+ // they are not three copies of one list that drifted.
122
+ // rejectRegexSpecials: true — because tokens arrive raw and unsplit, a
123
+ // token containing regex metacharacters is a regex construct, not an
124
+ // identifier. Without it, `handleSubmit\(` would be reported as the
125
+ // symbol `handleSubmit\(`: a blocked-but-legitimate regex search, plus a
126
+ // suggested Serena call naming a symbol that does not exist. The glob
127
+ // guard does not pass this because its tokenizer already strips those
128
+ // characters, so no token there can contain one.
129
+ // kebabComponents: true — the carve-out saying some kebab tokens ARE
130
+ // symbols: `user-modal`, `actions-order` name components and modules
131
+ // worth finding symbolically, while `text-sm` / `bg-white` are Tailwind
132
+ // classes. Exactly inverted in the glob guard, where a kebab token is a
133
+ // filename convention and is always rejected.
134
+ // dottedSymbol: true — `router.push`, `mcp.Tool`: member access is a
135
+ // natural thing to grep for and does name a real symbol. The glob guard
136
+ // cannot enable it, since a `.` there is an extension separator its
137
+ // tokenizer splits on.
48
138
  const symbolParts = extractSymbolsFromPattern(pattern, {
49
139
  splitRe: '|', allowlist: 'guard', rejectRegexSpecials: true,
50
140
  kebabComponents: true, dottedSymbol: true,
@@ -64,6 +154,12 @@ process.stdin.on('end', () => {
64
154
 
65
155
  // Emit structured JSON for programmatic consumers (monitoring, dashboards, IDE plugins).
66
156
  // `decision` and `reason` fields remain backward compatible.
157
+ //
158
+ // This is also what performs the block: the process ends normally (exit 0)
159
+ // and the `decision: 'block'` envelope is what stops the call. Note the
160
+ // divergence from serena-write-guard.js, which emits the same envelope AND
161
+ // exits 2. Claude Code honours either signal, so both hooks block; nothing in
162
+ // the repo records why the two files chose differently.
67
163
  const intent = /^[A-Z]/.test(symbolParts[0]) ? 'symbol_search' : 'references';
68
164
  console.log(JSON.stringify(buildStructuredBlockResponse({
69
165
  hook: 'serena-first-guard',
@@ -1,6 +1,30 @@
1
1
  #!/usr/bin/env node
2
2
  'use strict';
3
3
 
4
+ /**
5
+ * serena-first-read-guard.js — PreToolUse / Read
6
+ *
7
+ * Blocks: Read on in-project code files until Serena has been used, via a
8
+ * five-gate ladder (warmup → 2 free Reads → warning → 1 nav call → 2 nav
9
+ * calls → unlimited). Gate numbering matches the upstream kit's table; only
10
+ * the blocking rungs (1, 4, 5) appear in messages here — Gates 2 and 3 are
11
+ * the free-Read and warn rungs and emit no block.
12
+ * Why a hook: a deny rule matches a path spelling; every gate here is a
13
+ * decision about session *history* — has warmup happened, how many distinct
14
+ * files have been Read, how many Serena nav calls have succeeded. That state
15
+ * lives in ~/.claude/state/lsp-ready-<md5(cwd)> and settings.json has no way
16
+ * to consult it. A hook also gets to return the exact call to make next.
17
+ * Fails: open — an absent/expired/corrupt state file, an out-of-project path,
18
+ * `health.should_enforce === false`, or any thrown exception all let the Read
19
+ * through. Serena-first is agent guidance, not a security boundary, so the
20
+ * error direction is always "allow the Read".
21
+ * False positives: a legitimately breadth-first pass (auditing many small
22
+ * files, sweeping configs) hits Gate 4/5 despite being the right approach —
23
+ * escape hatch: one mcp__serena__get_symbols_overview or find_symbol call
24
+ * unlocks Reads 4-5, and a second unlocks the session ("surgical mode").
25
+ * See README.md § "Health tracking & fail-open enforcement" for the full rationale.
26
+ */
27
+
4
28
  const {
5
29
  buildWarmupInstructions, buildFileWarmupCall, isAllowedPath,
6
30
  getStateFilePath, readStateFile, updateStateFile, defaultFlag, defaultHealth,
@@ -19,6 +43,30 @@ function buildConcreteCall(filePath) {
19
43
  return `\nCONCRETE CALL FOR THIS FILE (works in any project):\n${call}\n`;
20
44
  }
21
45
 
46
+ // ── The Read ladder ─────────────────────────────────────────────────────────
47
+ // Counted in DISTINCT code files Read this session (see nextReadNum below —
48
+ // re-reading a file already on the list never advances it), and what each
49
+ // count costs:
50
+ //
51
+ // 1-2 free (FREE_READS)
52
+ // 3 allowed, warning emitted (WARN_AT)
53
+ // 4-5 blocked unless nav_count >= 1
54
+ // 6+ blocked unless nav_count >= 2 (REQUIRE_NAV_2_AT)
55
+ //
56
+ // Two invariants the gate branches below depend on without restating:
57
+ // WARN_AT === FREE_READS + 1 — the warn branch tests `=== WARN_AT`, so any
58
+ // other value makes it dead code: the Read it would have warned about gets
59
+ // blocked by Gate 4 instead, with no advance notice. That "you were told
60
+ // once before being blocked" property is the whole point of the warn rung.
61
+ // REQUIRE_NAV_2_AT >= WARN_AT + 2 — otherwise the "1 nav call is enough"
62
+ // window (Reads 4-5) is empty and one nav call buys nothing over zero.
63
+ //
64
+ // NOTE: the specific counts 2 / 3 / 6 are a judgement about how much blind
65
+ // reading is tolerable before Serena navigation pays for itself. No
66
+ // measurement or written rationale for these exact numbers survives in this
67
+ // repo or in the upstream claude-code-lsp-enforcement-kit README (which
68
+ // documents the same ladder, not its derivation). Treat the invariants above
69
+ // as load-bearing and the numbers themselves as tunable.
22
70
  const FREE_READS = 2;
23
71
  const WARN_AT = 3;
24
72
  const REQUIRE_NAV_2_AT = 6;
@@ -30,6 +78,13 @@ const REQUIRE_NAV_2_AT = 6;
30
78
  // instead of blocking forever. Escalating there (not just bypassing Gate 1
31
79
  // locally) matters: a local-only bypass would just relocate the deadlock to
32
80
  // the next guard hook the agent hits.
81
+ //
82
+ // The value trades two costs: too low and one transient hiccup disables
83
+ // enforcement for the session; too high and a real outage costs that many
84
+ // dead-end Reads before the agent is released. 3 is the smallest count that
85
+ // cannot be reached by a single failure plus one retry. NOTE: that reading is
86
+ // reconstructed from the mechanism — no recorded derivation of the number
87
+ // exists in this repo or the upstream kit. Verify before changing.
33
88
  const WARMUP_BLOCK_LIMIT = 3;
34
89
 
35
90
  const GATE1_DEADLOCK_NOTICE =
@@ -75,8 +130,19 @@ process.stdin.on('end', () => {
75
130
  const flag = readStateFile(flagPath);
76
131
 
77
132
  // Fail-open: skip enforcement when Serena is unhealthy for this project.
78
- // Runs BEFORE the Gate-1 null-flag block. readStateFile returns null on 24h
79
- // expiry, which correctly falls through to enforcement (null ⇒ enforce).
133
+ //
134
+ // ORDERING (strict): this MUST stay above the Gate-1 `!flag || !flag.warmup_done`
135
+ // branch. Reverse the two and an unhealthy Serena deadlocks the session:
136
+ // Gate 1 blocks the Read because warmup_done is false, warmup can only be
137
+ // cleared by a *successful* Serena call, and Serena is precisely what is
138
+ // down — so every Read blocks forever while the circuit breaker that would
139
+ // release it (health.should_enforce === false, written either by
140
+ // serena-usage-tracker.js or by this file's own WARMUP_BLOCK_LIMIT
141
+ // escalation) sits unread below the block that never returns.
142
+ //
143
+ // readStateFile returns null on 24h expiry, and null ⇒ enforce. That is the
144
+ // wanted direction: a day-old session re-imposes warmup rather than
145
+ // inheriting a stale unlock.
80
146
  if (!shouldEnforceSerena(flag)) process.exit(0);
81
147
 
82
148
  if (isAllowedPath(filePath, { enforceMarkdown: true })) process.exit(0);
@@ -119,8 +185,27 @@ process.stdin.on('end', () => {
119
185
  const readFiles = Array.isArray(flag.read_files) ? flag.read_files : [];
120
186
  const navCount = flag.nav_count || 0;
121
187
  const alreadyRead = readFiles.includes(filePath);
188
+ // nextReadNum = how many DISTINCT code files this session will have Read once
189
+ // this call goes through. Two consequences worth knowing before touching it:
190
+ // - Re-reading a file already on the list does not advance the ladder, so
191
+ // the gates measure breadth of exploration, not Read volume. Re-reading
192
+ // the same file 50 times is deliberately free.
193
+ // - On the `alreadyRead` path the value is the unchanged total, NOT this
194
+ // file's original position on the ladder. It is only meaningful as a gate
195
+ // ordinal for a *new* file. That is safe only because the `alreadyRead`
196
+ // branch immediately below exits before any gate reads it; move or
197
+ // re-order that branch and the off-by-one becomes live, mis-gating repeat
198
+ // Reads by one rung.
199
+ // Also note the gates read `flag` — the snapshot taken *before* persistRead's
200
+ // lock. Two Reads racing in the same tick can compute the same nextReadNum
201
+ // and both pass a gate. persistRead recomputes inside the lock so no write is
202
+ // lost; only the gate verdict is best-effort, which fail-open policy accepts.
122
203
  const nextReadNum = alreadyRead ? readFiles.length : readFiles.length + 1;
123
204
 
205
+ // Surgical mode: 2 successful nav calls unlock Reads for the rest of the
206
+ // session (the tracker resets nav_count only at SessionStart / 24h expiry).
207
+ // An already-read file is likewise always free — and per the nextReadNum note
208
+ // above, this branch has to stay ahead of every gate for that to be correct.
124
209
  if (navCount >= 2 || alreadyRead) {
125
210
  if (!alreadyRead) persistRead(flagPath, filePath);
126
211
  process.exit(0);
@@ -142,6 +227,11 @@ process.stdin.on('end', () => {
142
227
  process.exit(0);
143
228
  }
144
229
 
230
+ // Gates 4 and 5 are complementary halves of `nextReadNum > WARN_AT`: the
231
+ // `<` / `>=` split around REQUIRE_NAV_2_AT is the only thing that makes Reads
232
+ // 4-5 the one-nav-call window. Move one bound without the other and either a
233
+ // rung becomes unreachable or some Read count falls through both gates
234
+ // ungated, straight to the persistRead at the bottom.
145
235
  if (nextReadNum < REQUIRE_NAV_2_AT && navCount < 1) {
146
236
  emitBlock(
147
237
  `⛔ SERENA-FIRST BLOCK (Gate 4 — Serena Navigation Required)\n\n` +
@@ -1,14 +1,52 @@
1
1
  #!/usr/bin/env node
2
2
  'use strict';
3
3
 
4
+ /**
5
+ * serena-pre-delegation.js — PreToolUse / Agent
6
+ *
7
+ * Blocks: Agent spawns that are about to read code — forced explorers,
8
+ * worktree-isolated runs, and implement-phase delegations — when the prompt
9
+ * carries no pre-resolved "## LSP CONTEXT" block, so the subagent re-derives
10
+ * symbol locations the parent already had cheaper access to.
11
+ * Why a hook: the target is the *content* of one field of tool_input. A
12
+ * settings.json rule matches a tool name and a literal command spelling; it
13
+ * has no vocabulary for "this prompt string is missing a section", and none at
14
+ * all for the filesystem state (.task/ phase, folder mtime) that decides
15
+ * whether the omission is worth mentioning.
16
+ * Fails: open — unparseable stdin, a non-Agent call, an unreadable .task/ tree,
17
+ * or Serena marked unhealthy for this project all exit 0 silently. This is
18
+ * agent guidance, not a security boundary; a broken check must never stop a
19
+ * delegation.
20
+ * False positives: a long implement-phase prompt that genuinely needs no symbol
21
+ * context (a docs rewrite, a dependency bump) — escape hatch: that path only
22
+ * warns, and a one-line "## LSP CONTEXT" heading clears it outright.
23
+ * See README.md § Serena-first enforcement hooks (ported from
24
+ * `claude-code-lsp-enforcement-kit`) for the group's rationale, and
25
+ * § Health tracking & fail-open enforcement for the shouldEnforceSerena gate.
26
+ */
4
27
  const fs = require('fs');
5
28
  const path = require('path');
6
29
  const { getStateFilePath, readStateFile, shouldEnforceSerena } = require('./lib/serena');
7
30
 
31
+ // Explorer subagents whose entire output is code navigation. For these the LSP
32
+ // CONTEXT requirement is unconditional: no .task/ phase evidence is needed, and
33
+ // the exemption list below is not consulted at all (the two lists are disjoint
34
+ // today; if a name ever appeared in both, forcing wins). Spawning one with no
35
+ // resolved symbols guarantees it re-runs searches the parent session could have
36
+ // done once and passed down — which is the entire cost this hook exists to stop.
8
37
  const FORCE_LSP_CONTEXT_AGENTS = [
9
38
  'backend-explorer', 'frontend-explorer', 'db-explorer',
10
39
  ];
11
40
 
41
+ // Subagents whose work does not improve with a pre-resolved symbol map:
42
+ // reviewers and auditors (handed a diff, not a search), runners and checkers
43
+ // (they execute, they do not navigate), planners/architects/doc-updaters (prose
44
+ // in, prose out). `explore` heads the list for a sharper reason — it *is* the
45
+ // search agent, so requiring that it be handed search results first is circular.
46
+ //
47
+ // Membership is judged per agent, which is why the match below is exact rather
48
+ // than by prefix or substring: a name is exempt because someone assessed that
49
+ // specific agent, and a near-miss is a different agent.
12
50
  const EXEMPT_AGENTS = [
13
51
  'explore', 'security-reviewer', 'performance-reviewer', 'conventions-reviewer',
14
52
  'conflict-detector', 'code-auditor', 'lint-types-checker', 'test-runner',
@@ -44,28 +82,73 @@ process.stdin.on('end', () => {
44
82
  if (EXEMPT_AGENTS.some(e => e.toLowerCase() === subType)) process.exit(0);
45
83
  }
46
84
 
85
+ // Length floor: a short prompt is a hand-off ("read X and report"), not a
86
+ // delegation carrying enough work to be worth pre-resolving symbols for.
87
+ // Demanding a symbol map from one would be pure noise — for scale, the block
88
+ // this hook asks for is itself ~110 characters, so a sub-200-character prompt
89
+ // would be mostly boilerplate.
90
+ // NOTE: the 200 figure is not recoverable from the code, the README, or git
91
+ // history. It is a proxy for prompt substance and therefore drifts with prompt
92
+ // style; treat it as a tuning knob, not a boundary.
47
93
  if (prompt.length < 200) process.exit(0);
48
94
 
49
95
  const isolation = String(toolInput.isolation ?? '');
50
96
  const cwd = String(data.cwd ?? process.cwd());
51
97
  const taskDir = path.join(cwd, '.task');
52
98
 
99
+ // An undeclared delegation is only judged in a project that actually carries a
100
+ // .task/ tree to judge it by. No directory ⇒ no phase signal ⇒ no opinion.
101
+ // Without this exit the hook would start warning on every long Agent prompt in
102
+ // every project that has never used the .task/ convention — which is most of
103
+ // them, this repo included.
53
104
  if (!isForcedExplorer && isolation !== 'worktree') {
54
105
  if (!fs.existsSync(taskDir)) process.exit(0);
55
106
  }
56
107
 
108
+ // A forced explorer or a worktree-isolated run needs no phase evidence at all:
109
+ // the first is an agent whose entire job is code navigation, the second is an
110
+ // isolated checkout that exists only because real work is about to happen in
111
+ // it. Both facts are declared in the call itself, so the .task/ scan below is
112
+ // purely the fallback for a delegation that declared neither.
57
113
  let inImplementPhase = isForcedExplorer || isolation === 'worktree';
58
114
 
59
115
  if (!inImplementPhase) {
60
116
  try {
117
+ // The `20` prefix filter: task folders are date-stamped (`2026-08-06-…`),
118
+ // so the year is the cheapest way to separate them from a harness's own
119
+ // bookkeeping entries, and testing it before the statSync keeps the common
120
+ // case off the filesystem. It is a prefix heuristic, not a date parse — it
121
+ // accepts anything beginning "20" and stops working in 2100.
61
122
  const entries = fs.readdirSync(taskDir).filter(e => {
62
123
  return e.startsWith('20') && fs.statSync(path.join(taskDir, e)).isDirectory();
63
124
  });
125
+ // Freshness window: only a task folder touched recently counts as evidence
126
+ // of what is being worked on *now*. Without it, one abandoned folder left
127
+ // in phase=implement arms this hook for every Agent spawn in that project
128
+ // indefinitely, and the only remedy would be deleting files the hook has no
129
+ // business owning.
130
+ // NOTE: the two-hour value itself is not recoverable from the code, the
131
+ // README, or git history — it reads as a working-session length, not a
132
+ // measured figure. Raising it risks acting on finished work; lowering it
133
+ // silently disables the check partway through a long session. Check real
134
+ // .task/ mtimes before changing it.
64
135
  const twoHoursAgo = Date.now() - 2 * 60 * 60 * 1000;
65
136
  for (const entry of entries) {
66
137
  const folderPath = path.join(taskDir, entry);
67
138
  const stat = fs.statSync(folderPath);
68
139
  if (stat.mtimeMs < twoHoursAgo) continue;
140
+ // Two independent phase signals. state.json is the structured form (a
141
+ // harness writing machine state); 00-task.md below is the human one.
142
+ // Both are consulted because different harnesses write one or the other,
143
+ // and each sits in its own try block so a malformed state.json cannot
144
+ // suppress the markdown check.
145
+ //
146
+ // Neither shape is produced by this repo — `.task/` is an external
147
+ // orchestration convention carried over with the hook from
148
+ // claude-code-lsp-enforcement-kit. On a bootstrap-claude checkout this
149
+ // whole branch therefore never fires, and only the forced-explorer and
150
+ // worktree paths are live. Do not read a green run here as evidence the
151
+ // scan works.
69
152
  const statePath = path.join(folderPath, 'state.json');
70
153
  if (fs.existsSync(statePath)) {
71
154
  try {
@@ -73,6 +156,12 @@ process.stdin.on('end', () => {
73
156
  if (state.phase === 'implement') { inImplementPhase = true; break; }
74
157
  } catch {}
75
158
  }
159
+ // Fallback for harnesses that keep the phase in the task's markdown
160
+ // instead of in state.json. The three `\*{0,2}` groups exist because the
161
+ // field renders bold in some task templates and not others: `Phase:
162
+ // implement`, `**Phase**: implement`, and `**Phase:** implement` are the
163
+ // same field, and a guard that only matched the plain form would silently
164
+ // stop firing the moment a template added emphasis.
76
165
  const taskMd = path.join(folderPath, '00-task.md');
77
166
  if (fs.existsSync(taskMd)) {
78
167
  try {
@@ -86,6 +175,22 @@ process.stdin.on('end', () => {
86
175
 
87
176
  if (!inImplementPhase) process.exit(0);
88
177
 
178
+ // Six ways a prompt can prove it already carries resolved symbol locations.
179
+ // The first two match the *heading* the deny message below asks for — the
180
+ // happy path, an agent that followed the instruction verbatim. The other four
181
+ // match the *content* instead, so a prompt that pastes real file:line
182
+ // references under a heading of its own wording is not punished for it. Those
183
+ // four mirror the navigation intents worth pre-resolving: where a symbol is
184
+ // defined, who calls it, where it is used, who imports it.
185
+ //
186
+ // The `\.\w{2,4}:\d+` tail is what turns each of the four into a claim rather
187
+ // than prose — "defined at the top of the file" does not match, "defined at
188
+ // src/a.ts:42" does. Accepting a bare filename instead would let "defined at
189
+ // runtime" through and make the check meaningless.
190
+ //
191
+ // Trivially satisfiable by design: the literal string "## LSP CONTEXT" passes
192
+ // with no symbols behind it. This is agent guidance, not a security boundary,
193
+ // and an agent that games it only wastes its own tokens re-searching.
89
194
  const hasLspContext =
90
195
  /\bLSP CONTEXT\b/i.test(prompt) ||
91
196
  /\bSymbol Map\b/i.test(prompt) ||
@@ -98,6 +203,24 @@ process.stdin.on('end', () => {
98
203
 
99
204
  const agentLabel = isForcedExplorer ? `explorer "${subagentType}"` : 'implement agent';
100
205
 
206
+ // Warn vs. block, and why the split is not arbitrary. `block` is reserved for
207
+ // the two paths where the trigger was read straight out of tool_input — a
208
+ // subagent_type on the forced-explorer list, or isolation === 'worktree'. The
209
+ // caller declared what it was launching, so a false positive is close to
210
+ // impossible and being wrong costs one retry with a heading added. The generic
211
+ // implement path is *inferred* instead, from a .task/ folder's mtime and a
212
+ // phase field that may belong to finished or unrelated work — so it only
213
+ // warns. Blocking a real delegation on filesystem guesswork costs more than
214
+ // the missing symbol map does.
215
+ //
216
+ // SUSPECTED DEFECT — annotated, deliberately not fixed in this comments-only
217
+ // pass. `decision: 'warn'` is not a value Claude Code documents for
218
+ // PreToolUse; `decision: 'block'` is the honored legacy form, and the sibling
219
+ // warn path in serena-first-read-guard.js:40 uses `{ systemMessage: ... }`
220
+ // instead. If 'warn' is simply unrecognized, the entire non-forced implement
221
+ // path emits nothing at all and this hook is effectively
222
+ // forced-explorer/worktree-only. Verify that before touching anything else
223
+ // here — the fix changes which delegations get interrupted.
101
224
  const decision = (isForcedExplorer || isolation === 'worktree') ? 'block' : 'warn';
102
225
  console.log(JSON.stringify({
103
226
  decision,