@codewizard-dt/bootstrap 2.10.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/.github/workflows/build.yml +88 -0
- package/.github/workflows/security.yml +24 -0
- package/.gitleaks.toml +15 -0
- package/README.md +472 -0
- package/bin/cli.js +47 -0
- package/lib/README.md +27 -0
- package/lib/hooks/README.md +316 -0
- package/lib/hooks/env-file-guard.js +45 -0
- package/lib/hooks/git-protected-ops-block.js +77 -0
- package/lib/hooks/lib/serena-languages.js +158 -0
- package/lib/hooks/lib/serena.js +787 -0
- package/lib/hooks/mv-absolute-path-block.js +53 -0
- package/lib/hooks/serena-bash-grep-block.js +501 -0
- package/lib/hooks/serena-edit-guard.js +74 -0
- package/lib/hooks/serena-first-glob-guard.js +94 -0
- package/lib/hooks/serena-first-guard.js +74 -0
- package/lib/hooks/serena-first-read-guard.js +167 -0
- package/lib/hooks/serena-pre-delegation.js +117 -0
- package/lib/hooks/serena-session-reset.js +45 -0
- package/lib/hooks/serena-usage-tracker.js +186 -0
- package/lib/hooks/serena-write-guard.js +58 -0
- package/lib/prompts/README.md +16 -0
- package/lib/prompts/migrate-wiki.md +111 -0
- package/lib/prompts/setup-deployment.md +322 -0
- package/lib/prompts/setup-design-system.md +162 -0
- package/lib/prompts/setup-strict-typechecks.md +139 -0
- package/lib/scripts/README.md +49 -0
- package/lib/scripts/bootstrap-serena.sh +145 -0
- package/lib/scripts/build-mcp-guide.sh +108 -0
- package/lib/scripts/install-global.sh +78 -0
- package/lib/scripts/install-mcps.sh +131 -0
- package/lib/scripts/lib.sh +154 -0
- package/lib/scripts/merge-gitignore.sh +65 -0
- package/lib/scripts/migrate-project.sh +273 -0
- package/lib/scripts/setup-deployment.sh +104 -0
- package/lib/scripts/setup-project.sh +55 -0
- package/lib/scripts/setup-runner.sh +99 -0
- package/lib/scripts/setup-strict-typechecks.sh +29 -0
- package/lib/scripts/startup.sh +42 -0
- package/lib/scripts/sync-wiki-scaffold.sh +104 -0
- package/lib/scripts/templates/CLAUDE-env-safety.md +3 -0
- package/lib/scripts/templates/CLAUDE-wiki.md +60 -0
- package/lib/scripts/templates/gitignore +136 -0
- package/lib/scripts/templates/guides/stubs/00-header.md +15 -0
- package/lib/scripts/templates/guides/stubs/brave-search.md +20 -0
- package/lib/scripts/templates/guides/stubs/context7.md +26 -0
- package/lib/scripts/templates/guides/stubs/playwright.md +26 -0
- package/lib/scripts/templates/guides/stubs/serena.md +219 -0
- package/lib/scripts/templates/wiki/conventions.md +100 -0
- package/lib/scripts/templates/wiki/dashboard.html +1733 -0
- package/lib/scripts/templates/wiki/hot.md +21 -0
- package/lib/scripts/templates/wiki/index.md +46 -0
- package/lib/scripts/templates/wiki/knowledge/concepts/.gitkeep +0 -0
- package/lib/scripts/templates/wiki/knowledge/entities/components/.gitkeep +0 -0
- package/lib/scripts/templates/wiki/knowledge/entities/organisations/.gitkeep +0 -0
- package/lib/scripts/templates/wiki/knowledge/entities/people/.gitkeep +0 -0
- package/lib/scripts/templates/wiki/knowledge/entities/tools/.gitkeep +0 -0
- package/lib/scripts/templates/wiki/knowledge/sources/.gitkeep +0 -0
- package/lib/scripts/templates/wiki/log.md +14 -0
- package/lib/scripts/templates/wiki/work/bugs/.gitkeep +0 -0
- package/lib/scripts/templates/wiki/work/bugs/archive/index.md +6 -0
- package/lib/scripts/templates/wiki/work/bugs/index.md +12 -0
- package/lib/scripts/templates/wiki/work/bugs/lifecycle.md +39 -0
- package/lib/scripts/templates/wiki/work/decisions/.gitkeep +0 -0
- package/lib/scripts/templates/wiki/work/decisions/archive/index.md +6 -0
- package/lib/scripts/templates/wiki/work/decisions/index.md +12 -0
- package/lib/scripts/templates/wiki/work/decisions/lifecycle.md +42 -0
- package/lib/scripts/templates/wiki/work/requirements/.gitkeep +0 -0
- package/lib/scripts/templates/wiki/work/requirements/archive/index.md +6 -0
- package/lib/scripts/templates/wiki/work/requirements/index.md +12 -0
- package/lib/scripts/templates/wiki/work/requirements/lifecycle.md +34 -0
- package/lib/scripts/templates/wiki/work/roadmaps/.gitkeep +0 -0
- package/lib/scripts/templates/wiki/work/roadmaps/archive/index.md +6 -0
- package/lib/scripts/templates/wiki/work/roadmaps/index.md +12 -0
- package/lib/scripts/templates/wiki/work/roadmaps/lifecycle.md +32 -0
- package/lib/scripts/templates/wiki/work/tasks/.gitkeep +0 -0
- package/lib/scripts/templates/wiki/work/tasks/archive/index.md +6 -0
- package/lib/scripts/templates/wiki/work/tasks/index.md +12 -0
- package/lib/scripts/templates/wiki/work/tasks/lifecycle.md +39 -0
- package/lib/scripts/templates/wiki/work/uat/.gitkeep +0 -0
- package/lib/scripts/templates/wiki/work/uat/archive/index.md +6 -0
- package/lib/scripts/templates/wiki/work/uat/index.md +12 -0
- package/lib/scripts/templates/wiki/work/uat/lifecycle.md +48 -0
- package/lib/scripts/templates/wiki/work/uat/screenshots/.gitkeep +0 -0
- package/lib/scripts/update-project.sh +75 -0
- package/lib/scripts/wiki-dashboard-server.js +146 -0
- package/lib/skills/README.md +146 -0
- package/lib/skills/anti-slop/SKILL.md +183 -0
- package/lib/skills/bug-close/SKILL.md +136 -0
- package/lib/skills/bug-file/SKILL.md +114 -0
- package/lib/skills/bug-triage/SKILL.md +140 -0
- package/lib/skills/company-align/SKILL.md +203 -0
- package/lib/skills/debug-logs/SKILL.md +129 -0
- package/lib/skills/decision-create/SKILL.md +220 -0
- package/lib/skills/decision-finalize/SKILL.md +181 -0
- package/lib/skills/decision-next/SKILL.md +129 -0
- package/lib/skills/decision-walkthrough/SKILL.md +169 -0
- package/lib/skills/demo/SKILL.md +183 -0
- package/lib/skills/elevator-pitch/SKILL.md +125 -0
- package/lib/skills/eval-create/SKILL.md +344 -0
- package/lib/skills/eval-gap/SKILL.md +150 -0
- package/lib/skills/eval-run/SKILL.md +214 -0
- package/lib/skills/extract-feature/SKILL.md +344 -0
- package/lib/skills/flashcard/SKILL.md +513 -0
- package/lib/skills/frontend-taste/SKILL.md +184 -0
- package/lib/skills/gap-assess/SKILL.md +97 -0
- package/lib/skills/git-commit/SKILL.md +164 -0
- package/lib/skills/lint/SKILL.md +99 -0
- package/lib/skills/marp-slideshow/SKILL.md +212 -0
- package/lib/skills/mermaid-flowchart/SKILL.md +194 -0
- package/lib/skills/now/SKILL.md +36 -0
- package/lib/skills/port-feature/SKILL.md +315 -0
- package/lib/skills/power-mode/SKILL.md +184 -0
- package/lib/skills/primer/SKILL.md +84 -0
- package/lib/skills/project-readme/SKILL.md +166 -0
- package/lib/skills/req-compile/SKILL.md +131 -0
- package/lib/skills/req-create/SKILL.md +124 -0
- package/lib/skills/req-extract-decisions/SKILL.md +241 -0
- package/lib/skills/req-finalize/SKILL.md +251 -0
- package/lib/skills/req-retire/SKILL.md +185 -0
- package/lib/skills/req-update/SKILL.md +265 -0
- package/lib/skills/research/SKILL.md +250 -0
- package/lib/skills/research-company/SKILL.md +345 -0
- package/lib/skills/roadmap-add/SKILL.md +238 -0
- package/lib/skills/roadmap-create/SKILL.md +223 -0
- package/lib/skills/roadmap-next/SKILL.md +132 -0
- package/lib/skills/security-audit/SKILL.md +246 -0
- package/lib/skills/serena-config/SKILL.md +92 -0
- package/lib/skills/simplify/SKILL.md +227 -0
- package/lib/skills/tackle/SKILL.md +156 -0
- package/lib/skills/task-add/SKILL.md +208 -0
- package/lib/skills/task-audit/SKILL.md +294 -0
- package/lib/skills/task-trash/SKILL.md +115 -0
- package/lib/skills/task-update/SKILL.md +136 -0
- package/lib/skills/uat-auto/SKILL.md +69 -0
- package/lib/skills/uat-auto-plus/SKILL.md +115 -0
- package/lib/skills/uat-generate/SKILL.md +289 -0
- package/lib/skills/uat-skip/SKILL.md +169 -0
- package/lib/skills/uat-walk/SKILL.md +164 -0
- package/lib/skills/uat-walk/UAT-CORE.md +140 -0
- package/lib/skills/update-docs/SKILL.md +75 -0
- package/lib/skills/wiki-archive/SKILL.md +96 -0
- package/lib/skills/wiki-ingest/SKILL.md +139 -0
- package/lib/skills/wiki-lint/SKILL.md +131 -0
- package/lib/skills/wiki-query/SKILL.md +71 -0
- package/lib/skills/wiki-rotate-log/SKILL.md +90 -0
- package/lib/skills/wiki-tidy/SKILL.md +107 -0
- package/package.json +32 -0
- package/raw/.gitkeep +0 -0
- package/raw/design-principles.md +65 -0
- package/raw/guides/command-anti-patterns.md +79 -0
- package/raw/guides/deployment-strategy.md +448 -0
- package/raw/guides/evals-framework.md +452 -0
- package/raw/guides/mcp-tools.md +335 -0
- package/raw/guides/task-spec.md +79 -0
- package/raw/guides/type-checking-templates/README.md +112 -0
- package/raw/guides/type-checking-templates/eslint/eslint.config.ts +105 -0
- package/raw/guides/type-checking-templates/python/mypy.ini +69 -0
- package/raw/guides/type-checking-templates/python/pyproject.toml +164 -0
- package/raw/guides/type-checking-templates/python/pyrightconfig.json +67 -0
- package/raw/guides/type-checking-templates/tsconfig/tsconfig.app.jsonc +45 -0
- package/raw/guides/type-checking-templates/tsconfig/tsconfig.lib.jsonc +44 -0
- package/raw/guides/type-checking-templates/tsconfig/tsconfig.node-esm.jsonc +40 -0
- package/raw/guides/type-checking-templates/tsconfig/tsconfig.node.jsonc +34 -0
- package/raw/guides/type-checking-templates/tsconfig/tsconfig.vite-root.json +8 -0
- package/raw/harness-notes.md +20 -0
- package/raw/house-style/components/Badge.tsx +16 -0
- package/raw/house-style/components/Button.tsx +32 -0
- package/raw/house-style/components/Card.tsx +26 -0
- package/raw/house-style/components/Chip.tsx +57 -0
- package/raw/house-style/components/IconButton.tsx +67 -0
- package/raw/house-style/components/Modal.tsx +18 -0
- package/raw/house-style/components/Stepper.tsx +141 -0
- package/raw/house-style/components/icons.tsx +128 -0
- package/raw/house-style/preview/src/index.css +46 -0
- package/raw/house-style/tokens/tailwind.preset.ts +49 -0
- package/raw/house-style/tokens/tokens.json +62 -0
- package/raw/llm-wiki-2.md +162 -0
- package/raw/llm-wiki.md +75 -0
- package/raw/research/dark-mode-theme/index.md +85 -0
- package/raw/research/dark-mode-theme/sources.md +49 -0
- package/raw/research/serena-mcp-disconnect/index.md +81 -0
- package/raw/research/serena-mcp-disconnect/sources.md +87 -0
- package/raw/research/wiki-tooling-improvements/index.md +126 -0
- package/raw/research/wiki-tooling-improvements/sources.md +73 -0
- package/raw/software-factory-case-study.pdf +0 -0
|
@@ -0,0 +1,787 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* serena.js — shared helper for Serena-first enforcement hooks
|
|
5
|
+
*
|
|
6
|
+
* Single-provider helper that maps high-level intents to Serena MCP tool
|
|
7
|
+
* names and produces block-message copy that consumers render verbatim.
|
|
8
|
+
*
|
|
9
|
+
* Supported intents (see TOOLS map):
|
|
10
|
+
* Navigation: definition, references, symbol_search, implementation,
|
|
11
|
+
* incoming_calls, overview
|
|
12
|
+
* Symbolic edit: symbol_edit_body, insert_before, insert_after, rename,
|
|
13
|
+
* safe_delete
|
|
14
|
+
* Line-based edit: line_edit, line_range_edit, line_insert, line_delete
|
|
15
|
+
* Filesystem: create_file, list_dir, find_file
|
|
16
|
+
* Unmapped: hover, diagnostics, outgoing_calls (Serena has no direct
|
|
17
|
+
* equivalent — consumers fall back to symbol_search)
|
|
18
|
+
*
|
|
19
|
+
* Serena (https://github.com/oraios/serena — MIT) provides high-level
|
|
20
|
+
* symbolic tools with multi-language support via solidlsp.
|
|
21
|
+
*
|
|
22
|
+
* Claude Code MCP tool naming has two forms:
|
|
23
|
+
* mcp__serena__<tool> — standalone server
|
|
24
|
+
* mcp__plugin_<plugin>_serena__<tool> — plugin-bundled server
|
|
25
|
+
*
|
|
26
|
+
* Both forms are recognised by isLspProviderTool / getTrackerToolNameRegex.
|
|
27
|
+
*
|
|
28
|
+
* This module also centralises the allowlist policy (file extensions,
|
|
29
|
+
* config filenames, path patterns, test patterns) used to decide whether
|
|
30
|
+
* a path should bypass code-enforcement. `isAllowedPath(filePath)` is the
|
|
31
|
+
* single source of truth; edit-guard, write-guard and bash-grep-block all
|
|
32
|
+
* import from here.
|
|
33
|
+
*
|
|
34
|
+
* No network, no MCP runtime introspection, no dependency on Serena being
|
|
35
|
+
* installed — detection (if used) reads user-level Claude Code config.
|
|
36
|
+
*/
|
|
37
|
+
|
|
38
|
+
const fs = require('fs');
|
|
39
|
+
const path = require('path');
|
|
40
|
+
const os = require('os');
|
|
41
|
+
const crypto = require('crypto');
|
|
42
|
+
const { execSync } = require('child_process');
|
|
43
|
+
const { getEnabledExtensionsSet } = require('./serena-languages');
|
|
44
|
+
|
|
45
|
+
const HOME = os.homedir();
|
|
46
|
+
|
|
47
|
+
// ── Serena constants ───────────────────────────────────────────────────────
|
|
48
|
+
const SERENA_PREFIX = 'mcp__serena__';
|
|
49
|
+
const SERENA_LABEL = 'Serena';
|
|
50
|
+
const SERENA_TOKEN = 'serena';
|
|
51
|
+
|
|
52
|
+
// First tool to call when understanding a file. Doubles as Gate 1 warmup.
|
|
53
|
+
const WARMUP_TOOL = 'get_symbols_overview';
|
|
54
|
+
const WARMUP_NOTE = "Serena's 'first tool to understand a file'";
|
|
55
|
+
|
|
56
|
+
// Abstract navigation intent → Serena tool name.
|
|
57
|
+
// Intents with no direct Serena equivalent fall back to find_symbol.
|
|
58
|
+
const TOOLS = {
|
|
59
|
+
// Navigation / read-side intents
|
|
60
|
+
definition: 'find_symbol',
|
|
61
|
+
references: 'find_referencing_symbols',
|
|
62
|
+
symbol_search: 'find_symbol',
|
|
63
|
+
implementation: 'find_symbol',
|
|
64
|
+
incoming_calls: 'find_referencing_symbols',
|
|
65
|
+
overview: 'get_symbols_overview',
|
|
66
|
+
// Symbolic edit intents
|
|
67
|
+
symbol_edit_body: 'replace_symbol_body',
|
|
68
|
+
insert_before: 'insert_before_symbol',
|
|
69
|
+
insert_after: 'insert_after_symbol',
|
|
70
|
+
rename: 'rename_symbol',
|
|
71
|
+
safe_delete: 'safe_delete_symbol',
|
|
72
|
+
// Line-based edit intents
|
|
73
|
+
line_edit: 'replace_content',
|
|
74
|
+
line_range_edit: 'replace_lines',
|
|
75
|
+
line_insert: 'insert_at_line',
|
|
76
|
+
line_delete: 'delete_lines',
|
|
77
|
+
// File / filesystem intents
|
|
78
|
+
create_file: 'create_text_file',
|
|
79
|
+
list_dir: 'list_dir',
|
|
80
|
+
find_file: 'find_file',
|
|
81
|
+
// Intents Serena does not expose directly — consumers should fall back
|
|
82
|
+
// to symbol_search when these are null.
|
|
83
|
+
hover: null,
|
|
84
|
+
diagnostics: null,
|
|
85
|
+
outgoing_calls: null,
|
|
86
|
+
};
|
|
87
|
+
|
|
88
|
+
// Plugin-wrapped form (compiled once at module load).
|
|
89
|
+
const PLUGIN_WRAPPED_RE = new RegExp(`^mcp__plugin_[^_]+_${SERENA_TOKEN}__`);
|
|
90
|
+
|
|
91
|
+
// ── Allowlist policy (centralised) ─────────────────────────────────────────
|
|
92
|
+
// Single source of truth used by edit-guard, write-guard, bash-grep-block and
|
|
93
|
+
// serena-first-read-guard (via isAllowedPath). No hook keeps its own copy.
|
|
94
|
+
const CODE_EXTENSIONS = /\.(ts|tsx|js|jsx|mjs|cjs|py|go|rs|java|kt|swift|vue|svelte|cpp|c|h|hpp)$/i;
|
|
95
|
+
const ALLOW_NON_CODE_EXT = /\.(md|txt|log|json|jsonc|yaml|yml|env|csv|toml|xml|sql|sh|css|scss|html|lock|ini|conf|cfg)$/i;
|
|
96
|
+
const ALLOW_CONFIG_PATTERNS = /(\.config\.|tsconfig|next\.config|vite\.config|webpack\.config|rollup\.config|babel\.config|jest\.config|vitest\.config|tailwind\.config|postcss\.config|eslint|prettier|package\.json|pnpm-lock|yarn\.lock)/i;
|
|
97
|
+
const ALLOW_PATH_PATTERNS = /(^|\/)(\.task|\.claude|\.git|node_modules|build|dist|out|public|scripts|docs?|knowledge-vault|supabase\/migrations|coverage|\.next|\.turbo|__tests__|__mocks__)(\/|$)/i;
|
|
98
|
+
const ALLOW_TEST_PATTERNS = /\.(test|spec)\.(ts|tsx|js|jsx|mjs|cjs|py)$/i;
|
|
99
|
+
|
|
100
|
+
/**
|
|
101
|
+
* Returns true if the given path should bypass code-enforcement hooks.
|
|
102
|
+
*
|
|
103
|
+
* A path is allowed when it either:
|
|
104
|
+
* - has a non-code extension (.md, .json, .yaml, .env, .sql, .css, .html …)
|
|
105
|
+
* - matches a known config filename (tsconfig.json, package.json, next.config.*)
|
|
106
|
+
* - lives under a reserved path (.task/, .claude/, node_modules/, __tests__/ …)
|
|
107
|
+
* - is a test file (*.test.*, *.spec.*)
|
|
108
|
+
* - has no recognised code extension at all
|
|
109
|
+
*
|
|
110
|
+
* Options:
|
|
111
|
+
* - enforceMarkdown: when true, `.md` / `.mdx` files are NOT exempt by extension
|
|
112
|
+
* (path-pattern exemptions still apply). Used by the read guard so markdown
|
|
113
|
+
* reads must go through Serena warmup.
|
|
114
|
+
* - allowMarkdown: when true, `.md` / `.mdx` files are ALWAYS exempt, overriding
|
|
115
|
+
* language-aware enforcement. Used by the edit and write guards so markdown
|
|
116
|
+
* edits go through native tools regardless of Serena language config.
|
|
117
|
+
*
|
|
118
|
+
* Empty / non-string input returns true (fail-open for hooks that should
|
|
119
|
+
* not block absent input — callers are expected to guard earlier).
|
|
120
|
+
*/
|
|
121
|
+
function isAllowedPath(filePath, opts = {}) {
|
|
122
|
+
if (!filePath || typeof filePath !== 'string') return true;
|
|
123
|
+
|
|
124
|
+
const enforceMarkdown = opts.enforceMarkdown === true;
|
|
125
|
+
const allowMarkdown = opts.allowMarkdown === true;
|
|
126
|
+
const isMarkdown = /\.(md|mdx)$/i.test(filePath);
|
|
127
|
+
|
|
128
|
+
// Edit/write callers pass `allowMarkdown: true` → always exempt .md / .mdx,
|
|
129
|
+
// overriding any language-aware enforcement.
|
|
130
|
+
if (isMarkdown && allowMarkdown) return true;
|
|
131
|
+
|
|
132
|
+
if (!(isMarkdown && enforceMarkdown)) {
|
|
133
|
+
const enabledExts = getEnabledExtensionsSet();
|
|
134
|
+
if (enabledExts.size > 0) {
|
|
135
|
+
// Language-aware: only enforce files whose extension belongs to an enabled language
|
|
136
|
+
const ext = path.extname(filePath).slice(1).toLowerCase();
|
|
137
|
+
if (!ext || !enabledExts.has(ext)) return true;
|
|
138
|
+
} else {
|
|
139
|
+
// Fallback (no languages configured): use static extension list
|
|
140
|
+
if (ALLOW_NON_CODE_EXT.test(filePath)) return true;
|
|
141
|
+
if (!CODE_EXTENSIONS.test(filePath)) return true;
|
|
142
|
+
}
|
|
143
|
+
}
|
|
144
|
+
|
|
145
|
+
if (ALLOW_CONFIG_PATTERNS.test(path.basename(filePath))) return true;
|
|
146
|
+
if (ALLOW_PATH_PATTERNS.test(filePath)) return true;
|
|
147
|
+
if (ALLOW_TEST_PATTERNS.test(filePath)) return true;
|
|
148
|
+
return false;
|
|
149
|
+
}
|
|
150
|
+
|
|
151
|
+
// ── Config-file readers ────────────────────────────────────────────────────
|
|
152
|
+
function readJsonSilent(filePath) {
|
|
153
|
+
try {
|
|
154
|
+
if (!fs.existsSync(filePath)) return null;
|
|
155
|
+
return JSON.parse(fs.readFileSync(filePath, 'utf8'));
|
|
156
|
+
} catch {
|
|
157
|
+
return null;
|
|
158
|
+
}
|
|
159
|
+
}
|
|
160
|
+
|
|
161
|
+
/**
|
|
162
|
+
* Minimal presence check: scans ~/.claude.json mcpServers for a `serena` key.
|
|
163
|
+
* Returns true if Serena is registered as an MCP server.
|
|
164
|
+
*/
|
|
165
|
+
function hasSerena() {
|
|
166
|
+
const candidates = [
|
|
167
|
+
path.join(HOME, '.claude.json'),
|
|
168
|
+
path.join(HOME, '.claude', 'settings.json'),
|
|
169
|
+
path.join(HOME, '.claude', 'mcp.json'),
|
|
170
|
+
path.join(HOME, '.mcp.json'),
|
|
171
|
+
path.join(process.cwd(), '.mcp.json'),
|
|
172
|
+
];
|
|
173
|
+
for (const p of candidates) {
|
|
174
|
+
const data = readJsonSilent(p);
|
|
175
|
+
const servers = data?.mcpServers;
|
|
176
|
+
if (servers && typeof servers === 'object') {
|
|
177
|
+
for (const name of Object.keys(servers)) {
|
|
178
|
+
if (String(name).toLowerCase() === SERENA_TOKEN) return true;
|
|
179
|
+
}
|
|
180
|
+
}
|
|
181
|
+
}
|
|
182
|
+
return false;
|
|
183
|
+
}
|
|
184
|
+
|
|
185
|
+
// ── Public API ─────────────────────────────────────────────────────────────
|
|
186
|
+
|
|
187
|
+
/**
|
|
188
|
+
* Returns the list of active providers. Kept for backward compatibility
|
|
189
|
+
* with existing consumers; in Serena-only mode this is always ['serena'].
|
|
190
|
+
*/
|
|
191
|
+
function detectProviders() {
|
|
192
|
+
return ['serena'];
|
|
193
|
+
}
|
|
194
|
+
|
|
195
|
+
function resolveTool(intent) {
|
|
196
|
+
return TOOLS[intent] || TOOLS.symbol_search;
|
|
197
|
+
}
|
|
198
|
+
|
|
199
|
+
/**
|
|
200
|
+
* Build a single-line Serena suggestion for a symbol and navigation intent.
|
|
201
|
+
*/
|
|
202
|
+
function buildSuggestion(symbol, intent, indent = ' ') {
|
|
203
|
+
const tool = resolveTool(intent);
|
|
204
|
+
const safeSym = String(symbol).replace(/"/g, '\\"');
|
|
205
|
+
return `${indent}${SERENA_PREFIX}${tool}("${safeSym}")`;
|
|
206
|
+
}
|
|
207
|
+
|
|
208
|
+
/**
|
|
209
|
+
* Warmup instructions for Gate 1 in serena-first-read-guard.js.
|
|
210
|
+
* Returns an array of human-readable lines.
|
|
211
|
+
*/
|
|
212
|
+
function buildWarmupInstructions(indent = ' ') {
|
|
213
|
+
return [
|
|
214
|
+
`${indent}${SERENA_PREFIX}${WARMUP_TOOL}(<any project file>)`,
|
|
215
|
+
`${indent} → ${WARMUP_NOTE}`,
|
|
216
|
+
];
|
|
217
|
+
}
|
|
218
|
+
|
|
219
|
+
/**
|
|
220
|
+
* Build a copy-pasteable Serena warmup call parametrized by the actual file.
|
|
221
|
+
*/
|
|
222
|
+
function buildFileWarmupCall(filePath, indent = ' ') {
|
|
223
|
+
if (!filePath) return '';
|
|
224
|
+
const safeFile = String(filePath).replace(/"/g, '\\"');
|
|
225
|
+
return `${indent}${SERENA_PREFIX}${WARMUP_TOOL}("${safeFile}")`;
|
|
226
|
+
}
|
|
227
|
+
|
|
228
|
+
/**
|
|
229
|
+
* Build a two-line edit suggestion (symbolic + line-based).
|
|
230
|
+
*/
|
|
231
|
+
function buildEditSuggestion(filePath, symbolHint, indent = ' ') {
|
|
232
|
+
const safeFile = String(filePath ?? '').replace(/"/g, '\\"');
|
|
233
|
+
const lineBased =
|
|
234
|
+
`${indent}${SERENA_PREFIX}replace_content("${safeFile}", mode="literal", needle=..., repl=...)`;
|
|
235
|
+
if (symbolHint) {
|
|
236
|
+
const safeSym = String(symbolHint).replace(/"/g, '\\"');
|
|
237
|
+
const symbolic =
|
|
238
|
+
`${indent}${SERENA_PREFIX}replace_symbol_body("${safeSym}", "${safeFile}")`;
|
|
239
|
+
return `${symbolic}\n${lineBased}`;
|
|
240
|
+
}
|
|
241
|
+
return lineBased;
|
|
242
|
+
}
|
|
243
|
+
|
|
244
|
+
/**
|
|
245
|
+
* Build a create_text_file suggestion for new code files.
|
|
246
|
+
*/
|
|
247
|
+
function buildWriteSuggestion(filePath, indent = ' ') {
|
|
248
|
+
const safeFile = String(filePath ?? '').replace(/"/g, '\\"');
|
|
249
|
+
return `${indent}${SERENA_PREFIX}create_text_file("${safeFile}", ...)`;
|
|
250
|
+
}
|
|
251
|
+
|
|
252
|
+
/**
|
|
253
|
+
* Map a detected bash command to its Serena equivalent(s).
|
|
254
|
+
*/
|
|
255
|
+
function buildBashFsSuggestion(command, indent = ' ') {
|
|
256
|
+
const cmd = String(command ?? '');
|
|
257
|
+
const lines = [];
|
|
258
|
+
const push = (line) => lines.push(`${indent}${line}`);
|
|
259
|
+
|
|
260
|
+
// ls / tree / find -type d → list_dir
|
|
261
|
+
const lsMatch = /\b(?:ls|tree)\b(?:\s+(?:-[A-Za-z]+\s+)*)*([^\s|;&<>]+)?/.exec(cmd);
|
|
262
|
+
const findDirMatch = /\bfind\b\s+([^\s|;&<>]+)[^|;&<>]*-type\s+d\b/.exec(cmd);
|
|
263
|
+
if (/\b(?:ls|tree)\b/.test(cmd) || findDirMatch) {
|
|
264
|
+
const dir = (findDirMatch && findDirMatch[1]) || (lsMatch && lsMatch[1]) || '.';
|
|
265
|
+
const safeDir = String(dir).replace(/"/g, '\\"');
|
|
266
|
+
push(`${SERENA_PREFIX}list_dir("${safeDir}")`);
|
|
267
|
+
}
|
|
268
|
+
|
|
269
|
+
// find -name "<pattern>" → find_file
|
|
270
|
+
const findNameMatch = /\bfind\b\s+([^\s|;&<>]+)[^|;&<>]*-name\s+(['"]?)([^'"\s|;&<>]+)\2/.exec(cmd);
|
|
271
|
+
if (findNameMatch) {
|
|
272
|
+
const dir = findNameMatch[1] || '.';
|
|
273
|
+
const pattern = findNameMatch[3];
|
|
274
|
+
const safeDir = String(dir).replace(/"/g, '\\"');
|
|
275
|
+
const safePat = String(pattern).replace(/"/g, '\\"');
|
|
276
|
+
push(`${SERENA_PREFIX}find_file("${safePat}", "${safeDir}")`);
|
|
277
|
+
}
|
|
278
|
+
|
|
279
|
+
// cat / head / tail → get_symbols_overview (code) or Read (md/config)
|
|
280
|
+
const catMatch = /\b(?:cat|head|tail)\b(?:\s+(?:-[A-Za-z0-9]+\s*\S*\s*))*\s*([^\s|;&<>]+)/.exec(cmd);
|
|
281
|
+
if (catMatch) {
|
|
282
|
+
const file = catMatch[1];
|
|
283
|
+
const safeFile = String(file).replace(/"/g, '\\"');
|
|
284
|
+
if (isAllowedPath(file)) {
|
|
285
|
+
push(`Read("${safeFile}") # markdown/config — native Read is fine`);
|
|
286
|
+
} else {
|
|
287
|
+
push(`${SERENA_PREFIX}get_symbols_overview("${safeFile}")`);
|
|
288
|
+
}
|
|
289
|
+
}
|
|
290
|
+
|
|
291
|
+
// sed -i / awk -i inplace / perl -i → replace_content
|
|
292
|
+
const sedMatch = /\bsed\b\s+[^\n]*-i\b[^\n]*?\s(['"]?)([^'"\s|;&<>]+)\1\s*$/m.exec(cmd);
|
|
293
|
+
const awkMatch = /\bawk\b\s+[^\n]*-i\s+inplace\b[^\n]*?\s(['"]?)([^'"\s|;&<>]+)\1\s*$/m.exec(cmd);
|
|
294
|
+
const perlMatch = /\bperl\b\s+[^\n]*-i\b[^\n]*?\s(['"]?)([^'"\s|;&<>]+)\1\s*$/m.exec(cmd);
|
|
295
|
+
const inplaceMatch = sedMatch || awkMatch || perlMatch;
|
|
296
|
+
if (inplaceMatch || /\bsed\b[^\n]*-i\b/.test(cmd) || /\bawk\b[^\n]*-i\s+inplace\b/.test(cmd) || /\bperl\b[^\n]*-i\b/.test(cmd)) {
|
|
297
|
+
const file = inplaceMatch ? inplaceMatch[2] : '<path>';
|
|
298
|
+
const safeFile = String(file).replace(/"/g, '\\"');
|
|
299
|
+
const modeHint = /\bsed\b/.test(cmd) || /\bperl\b/.test(cmd) ? 'regex' : 'literal';
|
|
300
|
+
push(`${SERENA_PREFIX}replace_content("${safeFile}", mode="${modeHint}", needle=..., repl=...)`);
|
|
301
|
+
}
|
|
302
|
+
|
|
303
|
+
// echo ... >> <file> → insert_at_line or Edit
|
|
304
|
+
const echoMatch = /\becho\b[^\n]*?>>\s*([^\s|;&<>]+)/.exec(cmd);
|
|
305
|
+
if (echoMatch) {
|
|
306
|
+
const file = echoMatch[1];
|
|
307
|
+
const safeFile = String(file).replace(/"/g, '\\"');
|
|
308
|
+
if (isAllowedPath(file)) {
|
|
309
|
+
push(`Edit("${safeFile}", ...) # markdown/config — native Edit is fine`);
|
|
310
|
+
} else {
|
|
311
|
+
push(`${SERENA_PREFIX}insert_at_line("${safeFile}", line, content)`);
|
|
312
|
+
}
|
|
313
|
+
}
|
|
314
|
+
|
|
315
|
+
if (lines.length === 0) return '';
|
|
316
|
+
return lines.join('\n');
|
|
317
|
+
}
|
|
318
|
+
|
|
319
|
+
/**
|
|
320
|
+
* Returns a regex fragment that matches Serena tool_name strings.
|
|
321
|
+
*/
|
|
322
|
+
function getTrackerToolNameRegex() {
|
|
323
|
+
return `mcp__(?:plugin_[^_]+_)?${SERENA_TOKEN}__`;
|
|
324
|
+
}
|
|
325
|
+
|
|
326
|
+
/**
|
|
327
|
+
* Check whether a tool_name string is a Serena tool call.
|
|
328
|
+
*/
|
|
329
|
+
function isLspProviderTool(toolName) {
|
|
330
|
+
if (!toolName || typeof toolName !== 'string') return false;
|
|
331
|
+
if (!toolName.startsWith('mcp__')) return false;
|
|
332
|
+
if (toolName.startsWith(SERENA_PREFIX)) return true;
|
|
333
|
+
if (PLUGIN_WRAPPED_RE.test(toolName)) return true;
|
|
334
|
+
return false;
|
|
335
|
+
}
|
|
336
|
+
|
|
337
|
+
/**
|
|
338
|
+
* Structured suggestion list for programmatic consumers.
|
|
339
|
+
*/
|
|
340
|
+
function buildStructuredSuggestions(symbol, intent) {
|
|
341
|
+
const tool = resolveTool(intent);
|
|
342
|
+
const safeSym = String(symbol).replace(/"/g, '\\"');
|
|
343
|
+
return [{
|
|
344
|
+
provider: 'serena',
|
|
345
|
+
label: SERENA_LABEL,
|
|
346
|
+
tool: `${SERENA_PREFIX}${tool}`,
|
|
347
|
+
args: { query: String(symbol) },
|
|
348
|
+
displayTool: `${SERENA_PREFIX}${tool}("${safeSym}")`,
|
|
349
|
+
}];
|
|
350
|
+
}
|
|
351
|
+
|
|
352
|
+
/**
|
|
353
|
+
* Assemble a structured block response for blocking hooks.
|
|
354
|
+
*/
|
|
355
|
+
function buildStructuredBlockResponse({ hook, symbols, intent, reason }) {
|
|
356
|
+
const providers = detectProviders();
|
|
357
|
+
const suggestions = [];
|
|
358
|
+
const symbolList = Array.isArray(symbols) ? symbols : [];
|
|
359
|
+
for (const sym of symbolList) {
|
|
360
|
+
for (const s of buildStructuredSuggestions(sym, intent)) {
|
|
361
|
+
suggestions.push({ symbol: String(sym), ...s });
|
|
362
|
+
}
|
|
363
|
+
}
|
|
364
|
+
return {
|
|
365
|
+
decision: 'block',
|
|
366
|
+
reason: String(reason ?? ''),
|
|
367
|
+
hook: String(hook ?? ''),
|
|
368
|
+
symbols: symbolList.map(String),
|
|
369
|
+
intent: String(intent ?? ''),
|
|
370
|
+
providers,
|
|
371
|
+
suggestions,
|
|
372
|
+
};
|
|
373
|
+
}
|
|
374
|
+
|
|
375
|
+
// ── Per-project state file (Serena readiness + health) ──────────────────────
|
|
376
|
+
// One file per project cwd: ~/.claude/state/lsp-ready-<md5(cwd).slice(0,12)>.
|
|
377
|
+
// Holds warmup/nav counters (read-guard gate) and a `health` sub-object
|
|
378
|
+
// (fail-open enforcement). Single source of truth for the three hooks that
|
|
379
|
+
// touch it: serena-first-read-guard, serena-usage-tracker, serena-session-reset.
|
|
380
|
+
const STATE_DIR = path.join(HOME, '.claude', 'state');
|
|
381
|
+
const FLAG_EXPIRY_MS = 24 * 60 * 60 * 1000;
|
|
382
|
+
|
|
383
|
+
function getStateFilePath(cwd = process.cwd()) {
|
|
384
|
+
const hash = crypto.createHash('md5').update(String(cwd)).digest('hex').slice(0, 12);
|
|
385
|
+
return path.join(STATE_DIR, `lsp-ready-${hash}`);
|
|
386
|
+
}
|
|
387
|
+
|
|
388
|
+
/** Read + parse the state file. Returns null on missing, expired, or parse error. */
|
|
389
|
+
function readStateFile(fp) {
|
|
390
|
+
try {
|
|
391
|
+
if (!fs.existsSync(fp)) return null;
|
|
392
|
+
const d = JSON.parse(fs.readFileSync(fp, 'utf8'));
|
|
393
|
+
if (Date.now() - (d.timestamp || 0) > FLAG_EXPIRY_MS) return null;
|
|
394
|
+
return d;
|
|
395
|
+
} catch { return null; }
|
|
396
|
+
}
|
|
397
|
+
|
|
398
|
+
/**
|
|
399
|
+
* Write the state file atomically (temp file + rename, same directory so the
|
|
400
|
+
* rename is same-filesystem) — a torn write can never leave invalid JSON on
|
|
401
|
+
* disk. mkdir -p, silent failure — hooks must never throw.
|
|
402
|
+
*/
|
|
403
|
+
function writeStateFile(fp, data) {
|
|
404
|
+
try {
|
|
405
|
+
if (!fs.existsSync(STATE_DIR)) fs.mkdirSync(STATE_DIR, { recursive: true });
|
|
406
|
+
const tmp = `${fp}.tmp.${process.pid}.${crypto.randomBytes(4).toString('hex')}`;
|
|
407
|
+
fs.writeFileSync(tmp, JSON.stringify(data));
|
|
408
|
+
fs.renameSync(tmp, fp);
|
|
409
|
+
} catch { /* silent */ }
|
|
410
|
+
}
|
|
411
|
+
|
|
412
|
+
/** Default shape of the per-project state file before any hook has written it. */
|
|
413
|
+
function defaultFlag() {
|
|
414
|
+
return {
|
|
415
|
+
cwd: process.cwd(), warmup_done: false, nav_count: 0, read_count: 0,
|
|
416
|
+
read_files: [], warmup_block_count: 0,
|
|
417
|
+
};
|
|
418
|
+
}
|
|
419
|
+
|
|
420
|
+
/** Default shape of the state file's `health` sub-object. */
|
|
421
|
+
function defaultHealth() {
|
|
422
|
+
return { should_enforce: true, healthy: true, error_count: 0, last_error: null, last_check: 0, notified: false };
|
|
423
|
+
}
|
|
424
|
+
|
|
425
|
+
// ── Advisory locking (dependency-free) ──────────────────────────────────────
|
|
426
|
+
// The state file is written by two independent hook scripts
|
|
427
|
+
// (serena-usage-tracker.js and serena-first-read-guard.js) on the same path
|
|
428
|
+
// with no other coordination between them. acquireLock/releaseLock/
|
|
429
|
+
// updateStateFile give both callers a short-lived, self-healing mutex around
|
|
430
|
+
// the full read-modify-write cycle, so concurrent writers can no longer lose
|
|
431
|
+
// each other's updates. This fails open by design — a hook that can't get
|
|
432
|
+
// the lock within budget proceeds unlocked rather than hanging; hooks must
|
|
433
|
+
// never block indefinitely.
|
|
434
|
+
const LOCK_STALE_MS = 750;
|
|
435
|
+
const LOCK_RETRY_BUDGET_MS = 250;
|
|
436
|
+
const LOCK_BACKOFF_MS = [10, 20, 40, 80];
|
|
437
|
+
|
|
438
|
+
/** Block the current thread for `ms` ms without spawning a process (no execSync). */
|
|
439
|
+
function blockingSleep(ms) {
|
|
440
|
+
try {
|
|
441
|
+
Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, ms);
|
|
442
|
+
} catch {
|
|
443
|
+
const until = Date.now() + ms;
|
|
444
|
+
while (Date.now() < until) { /* busy-wait fallback */ }
|
|
445
|
+
}
|
|
446
|
+
}
|
|
447
|
+
|
|
448
|
+
/**
|
|
449
|
+
* Acquire an exclusive lock at `${fp}.lock`. Returns the lock path on
|
|
450
|
+
* success, or null if the retry budget was exhausted (caller proceeds
|
|
451
|
+
* unlocked, best-effort). Self-heals a lock orphaned by a crashed hook
|
|
452
|
+
* process — nothing auto-releases a plain marker file, so a lock older than
|
|
453
|
+
* LOCK_STALE_MS is forcibly cleared and retried immediately.
|
|
454
|
+
*/
|
|
455
|
+
function acquireLock(fp) {
|
|
456
|
+
const lockPath = `${fp}.lock`;
|
|
457
|
+
const deadline = Date.now() + LOCK_RETRY_BUDGET_MS;
|
|
458
|
+
let attempt = 0;
|
|
459
|
+
while (true) {
|
|
460
|
+
try {
|
|
461
|
+
fs.closeSync(fs.openSync(lockPath, 'wx'));
|
|
462
|
+
return lockPath;
|
|
463
|
+
} catch (err) {
|
|
464
|
+
if (err && err.code !== 'EEXIST') return null;
|
|
465
|
+
}
|
|
466
|
+
try {
|
|
467
|
+
const age = Date.now() - fs.statSync(lockPath).mtimeMs;
|
|
468
|
+
if (age > LOCK_STALE_MS) {
|
|
469
|
+
try { fs.unlinkSync(lockPath); } catch {}
|
|
470
|
+
continue; // retry immediately after clearing a stale lock
|
|
471
|
+
}
|
|
472
|
+
} catch { /* lock disappeared between attempts — retry */ }
|
|
473
|
+
if (Date.now() >= deadline) return null;
|
|
474
|
+
blockingSleep(LOCK_BACKOFF_MS[Math.min(attempt, LOCK_BACKOFF_MS.length - 1)]);
|
|
475
|
+
attempt++;
|
|
476
|
+
}
|
|
477
|
+
}
|
|
478
|
+
|
|
479
|
+
/** Best-effort lock release. Never throws. */
|
|
480
|
+
function releaseLock(lockPath) {
|
|
481
|
+
if (!lockPath) return;
|
|
482
|
+
try { fs.unlinkSync(lockPath); } catch { /* silent */ }
|
|
483
|
+
}
|
|
484
|
+
|
|
485
|
+
/**
|
|
486
|
+
* Locked read-modify-write cycle for the state file. `mutatorFn(data)`
|
|
487
|
+
* mutates `data` in place and/or returns a replacement object; the result is
|
|
488
|
+
* written atomically. `defaultFactory()` supplies the initial object when no
|
|
489
|
+
* state file exists yet. Callers must derive their field updates from `data`
|
|
490
|
+
* as passed to `mutatorFn` (the freshly-locked read) — never from a snapshot
|
|
491
|
+
* read before the lock was acquired, or a concurrent writer's update can
|
|
492
|
+
* still be lost even though the write itself is now atomic.
|
|
493
|
+
*/
|
|
494
|
+
function updateStateFile(fp, defaultFactory, mutatorFn) {
|
|
495
|
+
const lockPath = acquireLock(fp);
|
|
496
|
+
try {
|
|
497
|
+
const data = readStateFile(fp) || defaultFactory();
|
|
498
|
+
const result = mutatorFn(data) || data;
|
|
499
|
+
writeStateFile(fp, result);
|
|
500
|
+
return result;
|
|
501
|
+
} finally {
|
|
502
|
+
releaseLock(lockPath);
|
|
503
|
+
}
|
|
504
|
+
}
|
|
505
|
+
|
|
506
|
+
/**
|
|
507
|
+
* Enforcement gate for all guards. Enforce (return true) unless the state
|
|
508
|
+
* file explicitly recorded the provider as unhealthy for this project.
|
|
509
|
+
* false ONLY when flag.health.should_enforce === false; null/missing/legacy
|
|
510
|
+
* state ⇒ true (assume healthy).
|
|
511
|
+
*/
|
|
512
|
+
function shouldEnforceSerena(flag) {
|
|
513
|
+
return !(flag && flag.health && flag.health.should_enforce === false);
|
|
514
|
+
}
|
|
515
|
+
|
|
516
|
+
/**
|
|
517
|
+
* True when `p` resolves to a location OUTSIDE the project root. Serena is
|
|
518
|
+
* registered per-project and can only operate on files inside it, so any tool
|
|
519
|
+
* call targeting a path outside the root must pass through untouched.
|
|
520
|
+
*
|
|
521
|
+
* Resolution: `~` / `~/…` expand to the home dir; relative paths resolve
|
|
522
|
+
* against `projectRoot` (hooks run with cwd = project root). The containment
|
|
523
|
+
* test uses a trailing-separator guard so `/foo/barbaz` is NOT treated as
|
|
524
|
+
* inside `/foo/bar`. The root itself counts as inside.
|
|
525
|
+
*
|
|
526
|
+
* Indeterminate input (empty / non-string) returns false (⇒ enforce): callers
|
|
527
|
+
* decide separately how to treat unresolvable shell-variable paths.
|
|
528
|
+
*/
|
|
529
|
+
function isOutsideProject(p, projectRoot = process.cwd()) {
|
|
530
|
+
if (!p || typeof p !== 'string') return false;
|
|
531
|
+
let s = p.trim();
|
|
532
|
+
if (!s) return false;
|
|
533
|
+
if (s === '~') s = HOME;
|
|
534
|
+
else if (s.startsWith('~/') || s.startsWith('~\\')) s = path.join(HOME, s.slice(2));
|
|
535
|
+
const root = path.resolve(String(projectRoot));
|
|
536
|
+
const resolved = path.resolve(root, s);
|
|
537
|
+
if (resolved === root) return false;
|
|
538
|
+
return !resolved.startsWith(root + path.sep);
|
|
539
|
+
}
|
|
540
|
+
|
|
541
|
+
// ── Failure classification & process health ─────────────────────────────────
|
|
542
|
+
|
|
543
|
+
/**
|
|
544
|
+
* Classify a Serena failure payload as a 'tool'-level failure (server alive,
|
|
545
|
+
* bad query / no matches / benign config-related decline — keep enforcing)
|
|
546
|
+
* or a 'transport'-level failure (process down/unreachable — assess health).
|
|
547
|
+
* A null/empty payload (no content to classify at all) defaults to
|
|
548
|
+
* 'transport' so health still gets assessed in that genuinely ambiguous
|
|
549
|
+
* case. Any other UNRECOGNIZED payload defaults to 'tool': receiving one at
|
|
550
|
+
* all already proves the round-trip completed, which is proof of life, not
|
|
551
|
+
* evidence of a dead transport.
|
|
552
|
+
*/
|
|
553
|
+
function classifySerenaFailure(errorPayload) {
|
|
554
|
+
if (errorPayload == null) return 'transport';
|
|
555
|
+
let s;
|
|
556
|
+
if (typeof errorPayload === 'string') {
|
|
557
|
+
s = errorPayload;
|
|
558
|
+
} else if (typeof errorPayload === 'object' && !Array.isArray(errorPayload)
|
|
559
|
+
&& Object.keys(errorPayload).length === 0) {
|
|
560
|
+
return 'transport'; // empty object payload
|
|
561
|
+
} else {
|
|
562
|
+
try { s = JSON.stringify(errorPayload); } catch { s = String(errorPayload); }
|
|
563
|
+
}
|
|
564
|
+
if (!s || !s.trim()) return 'transport';
|
|
565
|
+
|
|
566
|
+
// Tool-level: the server answered, the query just didn't resolve, or it
|
|
567
|
+
// declined for a benign/config reason (e.g. the file's language isn't
|
|
568
|
+
// enabled in .serena/project.yml — a normal, expected response).
|
|
569
|
+
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)) {
|
|
570
|
+
return 'tool';
|
|
571
|
+
}
|
|
572
|
+
// Transport-level: the server is unreachable / the pipe broke.
|
|
573
|
+
if (/timeout|timed out|connection|refused|econnrefused|socket|epipe|closed|disconnect|not connected|unreachable|reset|broken pipe|hang/i.test(s)) {
|
|
574
|
+
return 'transport';
|
|
575
|
+
}
|
|
576
|
+
// Unknown ⇒ tool-level. This hook only runs because the MCP round-trip
|
|
577
|
+
// completed with a payload to classify, which already proves the server
|
|
578
|
+
// responded — never proof of a dead transport. A missed real transport
|
|
579
|
+
// failure just delays detection to the next failed call; defaulting to
|
|
580
|
+
// 'transport' instead risked treating an ordinary, unanticipated tool
|
|
581
|
+
// error as grounds to assess (and previously, kill) a live process. See
|
|
582
|
+
// raw/research/serena-mcp-disconnect/index.md for the incident this fixes.
|
|
583
|
+
return 'tool';
|
|
584
|
+
}
|
|
585
|
+
|
|
586
|
+
/** Build a pgrep pattern matching a Serena server bound to `projectDir`. */
|
|
587
|
+
function serenaProcPattern(projectDir) {
|
|
588
|
+
// Escape regex metacharacters (pgrep uses extended regex), then escape
|
|
589
|
+
// single quotes for safe single-quote shell wrapping.
|
|
590
|
+
const escaped = String(projectDir).replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
|
|
591
|
+
return `serena start-mcp-server.*${escaped}`.replace(/'/g, `'\\''`);
|
|
592
|
+
}
|
|
593
|
+
|
|
594
|
+
/**
|
|
595
|
+
* True if a Serena MCP server process for `projectDir` is currently running.
|
|
596
|
+
* Diagnostic only — this is never used to decide whether to terminate the
|
|
597
|
+
* process. A process that just answered a tool call (even with an error) has
|
|
598
|
+
* already proven it is alive and responsive, not hung; there is also no
|
|
599
|
+
* documented way to reconnect a stdio MCP server mid-session, so killing one
|
|
600
|
+
* has no realistic upside and a confirmed, irreversible downside. See
|
|
601
|
+
* raw/research/serena-mcp-disconnect/index.md.
|
|
602
|
+
*/
|
|
603
|
+
function isSerenaProcessAlive(projectDir) {
|
|
604
|
+
try {
|
|
605
|
+
execSync(`pgrep -f '${serenaProcPattern(projectDir)}'`, { stdio: 'pipe' });
|
|
606
|
+
return true;
|
|
607
|
+
} catch {
|
|
608
|
+
return false;
|
|
609
|
+
}
|
|
610
|
+
}
|
|
611
|
+
|
|
612
|
+
// ── Symbol detection (consolidated) ─────────────────────────────────────────
|
|
613
|
+
// Single classification core shared by serena-first-guard (Grep),
|
|
614
|
+
// serena-first-glob-guard (Glob) and serena-bash-grep-block (Bash). The three
|
|
615
|
+
// call sites tokenize differently (their pattern syntaxes differ) and carry
|
|
616
|
+
// slightly different allowlists — those genuine differences are expressed via
|
|
617
|
+
// `opts`, so identical inputs yield identical block/allow decisions.
|
|
618
|
+
|
|
619
|
+
const SYMBOL_ZERO_WIDTH = /[--]/g;
|
|
620
|
+
|
|
621
|
+
// Glob guard's exact-match skip set: extensions, common dirs/stems, framework
|
|
622
|
+
// config names, directives. Checked case-insensitively.
|
|
623
|
+
const GLOB_SKIP_EXACT = new Set([
|
|
624
|
+
// extensions
|
|
625
|
+
'ts', 'tsx', 'js', 'jsx', 'mjs', 'cjs', 'py', 'go', 'rs', 'java',
|
|
626
|
+
'vue', 'svelte', 'md', 'mdx', 'json', 'jsonc', 'yaml', 'yml', 'sql',
|
|
627
|
+
'sh', 'bash', 'css', 'scss', 'sass', 'less', 'html', 'htm', 'xml',
|
|
628
|
+
'toml', 'ini', 'env', 'lock', 'log', 'txt', 'csv',
|
|
629
|
+
// common dirs / file stems
|
|
630
|
+
'src', 'app', 'lib', 'libs', 'hooks', 'utils', 'util', 'types',
|
|
631
|
+
'components', 'pages', 'api', 'server', 'client', 'public', 'docs',
|
|
632
|
+
'tests', 'test', 'spec', 'specs', 'dist', 'build', 'out', 'next',
|
|
633
|
+
'turbo', 'cache', 'node_modules', 'coverage', 'scripts', 'config',
|
|
634
|
+
'assets', 'styles', 'fonts', 'images', 'icons', 'locales', 'i18n',
|
|
635
|
+
'middleware', 'services', 'service', 'models', 'model', 'schemas',
|
|
636
|
+
'schema', 'routes', 'route', 'views', 'view', 'store', 'stores',
|
|
637
|
+
'actions', 'action', 'reducers', 'slices', 'providers', 'contexts',
|
|
638
|
+
'layouts', 'layout', 'templates', 'template', 'helpers', 'helper',
|
|
639
|
+
'constants', 'const', 'configs', 'fixtures', 'mocks', 'mock',
|
|
640
|
+
'validations', 'validators', 'transformers',
|
|
641
|
+
// common filenames
|
|
642
|
+
'index', 'main', 'page', 'error', 'loading', 'not-found', 'global',
|
|
643
|
+
'root', 'readme', 'license', 'changelog', 'dockerfile', 'makefile',
|
|
644
|
+
'tsconfig', 'jsconfig', 'package', 'pnpm-lock', 'yarn', 'npm-lock',
|
|
645
|
+
// framework / tool config stems
|
|
646
|
+
'next', 'vite', 'webpack', 'rollup', 'babel', 'jest', 'vitest',
|
|
647
|
+
'tailwind', 'postcss', 'eslint', 'prettier', 'playwright', 'cypress',
|
|
648
|
+
'drizzle', 'prisma', 'supabase', 'turbo', 'nx', 'bun', 'deno',
|
|
649
|
+
// directives / keywords
|
|
650
|
+
'todo', 'fixme', 'hack', 'xxx', 'note', 'import', 'export', 'from',
|
|
651
|
+
'require', 'http', 'https',
|
|
652
|
+
]);
|
|
653
|
+
|
|
654
|
+
// Guard's tailwind-utility prefixes — kebab tokens starting with these are
|
|
655
|
+
// styling classes, never symbols.
|
|
656
|
+
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-)/;
|
|
657
|
+
const KEBAB_COMPONENT_SUFFIX = /-(modal|form|dialog|sidebar|popover|tab|list|card|button|widget|table|page|layout|header|footer|section|panel|gallery|grid|menu|nav|banner|badge|skeleton|spinner|tooltip|dropdown|select|input|textarea|checkbox|radio|switch|slider|avatar|icon|chip|toast|alert|bar|row|cell|item|field|wrapper|container|provider|context|hook|view|screen|chart|editor|builder|filler|picker|uploader|timeline|breadcrumb|steward|runner|tester|checker|resolver|reviewer|optimizer|detector|guard|enforcer)s?$/;
|
|
658
|
+
const KEBAB_DOMAIN_PREFIX = /^(actions?|helpers?|utils?|hooks?|types?|constants?|validations?|services?)-/;
|
|
659
|
+
|
|
660
|
+
/**
|
|
661
|
+
* Decide whether a single token names a code symbol. Options select the
|
|
662
|
+
* dialect a given call site needs (all default off):
|
|
663
|
+
* - allowlist: 'guard' | 'bash' | 'glob' — which prefix/skip rules to apply
|
|
664
|
+
* - rejectRegexSpecials: true — reject tokens containing regex metachars
|
|
665
|
+
* (Grep guard, whose tokens are raw and unsplit)
|
|
666
|
+
* - kebabComponents: true — apply the component-suffix carve-out so some
|
|
667
|
+
* kebab tokens (e.g. user-modal, actions-foo) count as symbols (Grep guard)
|
|
668
|
+
* - dottedSymbol: true — also accept dotted symbols like `mcp.Tool` (Grep guard)
|
|
669
|
+
* - stripZeroWidth: true — strip zero-width chars first (Glob guard)
|
|
670
|
+
*/
|
|
671
|
+
function isCodeSymbol(raw, opts = {}) {
|
|
672
|
+
if (raw == null) return false;
|
|
673
|
+
let s = String(raw);
|
|
674
|
+
if (opts.stripZeroWidth) s = s.replace(SYMBOL_ZERO_WIDTH, '');
|
|
675
|
+
if (s.length < 4) return false;
|
|
676
|
+
if (/\s/.test(s)) return false;
|
|
677
|
+
|
|
678
|
+
if (opts.rejectRegexSpecials && /[&?+[\]{}()\\^$*]/.test(s)) return false;
|
|
679
|
+
|
|
680
|
+
if (opts.allowlist === 'guard') {
|
|
681
|
+
const allow = [
|
|
682
|
+
/^(TODO|FIXME|HACK|XXX|NOTE)/i,
|
|
683
|
+
/^console\./, /^import\b/, /^require\(/, /^from\b/, /^export\b/,
|
|
684
|
+
/^\/\//, /^#/, /^\./, /^http/i, /^\d/,
|
|
685
|
+
/^[A-Z_]{3,}$/,
|
|
686
|
+
/^[a-z]{1,8}$/,
|
|
687
|
+
/^['"`]/,
|
|
688
|
+
/^use (client|server)/,
|
|
689
|
+
];
|
|
690
|
+
if (allow.some(rx => rx.test(s))) return false;
|
|
691
|
+
} else if (opts.allowlist === 'bash') {
|
|
692
|
+
const skip = [
|
|
693
|
+
/^(TODO|FIXME|HACK|XXX|NOTE)/i,
|
|
694
|
+
/^console\b/, /^import\b/, /^export\b/, /^http/i, /^\d/,
|
|
695
|
+
/^[A-Z_]{3,}$/, /^[a-z]{1,8}$/, /^[a-z]+-[a-z]+/,
|
|
696
|
+
];
|
|
697
|
+
if (skip.some(rx => rx.test(s))) return false;
|
|
698
|
+
} else if (opts.allowlist === 'glob') {
|
|
699
|
+
if (GLOB_SKIP_EXACT.has(s.toLowerCase())) return false;
|
|
700
|
+
if (/^[a-z]{1,8}$/.test(s)) return false;
|
|
701
|
+
if (/^[A-Z_]{3,}$/.test(s)) return false;
|
|
702
|
+
if (/^[a-z][a-z0-9]*(-[a-z0-9]+)+$/.test(s)) return false; // kebab filenames
|
|
703
|
+
}
|
|
704
|
+
|
|
705
|
+
// Guard's kebab carve-out: some kebab tokens ARE symbols.
|
|
706
|
+
if (opts.kebabComponents && /^[a-z]+-[a-z]/.test(s)) {
|
|
707
|
+
if (KEBAB_TAILWIND_PREFIX.test(s)) return false;
|
|
708
|
+
if (KEBAB_COMPONENT_SUFFIX.test(s)) return true;
|
|
709
|
+
if (KEBAB_DOMAIN_PREFIX.test(s)) return true;
|
|
710
|
+
return false;
|
|
711
|
+
}
|
|
712
|
+
|
|
713
|
+
const isCamelCase = /^[a-z][a-zA-Z0-9]{3,}$/.test(s) && /[A-Z]/.test(s);
|
|
714
|
+
const isPascalCase = /^[A-Z][a-zA-Z][a-zA-Z0-9]{2,}$/.test(s);
|
|
715
|
+
const isSnakeCaseFn = /^[a-z]+(_[a-z]+){2,}$/.test(s) && s.length >= 9;
|
|
716
|
+
const isDotted = opts.dottedSymbol && /^[a-z][a-zA-Z]*\.[a-z][a-zA-Z]*$/i.test(s);
|
|
717
|
+
|
|
718
|
+
return isCamelCase || isPascalCase || isSnakeCaseFn || !!isDotted;
|
|
719
|
+
}
|
|
720
|
+
|
|
721
|
+
/**
|
|
722
|
+
* Split a search pattern into tokens and return those that name code symbols.
|
|
723
|
+
* `opts.splitRe` selects the tokenizer (per call site); `opts.clean(token)`
|
|
724
|
+
* optionally cleans each token before trimming. Remaining opts are forwarded
|
|
725
|
+
* to isCodeSymbol.
|
|
726
|
+
*/
|
|
727
|
+
function extractSymbolsFromPattern(pattern, opts = {}) {
|
|
728
|
+
const p = String(pattern ?? '');
|
|
729
|
+
const splitRe = opts.splitRe || '|';
|
|
730
|
+
const tokens = p.split(splitRe).map(t => {
|
|
731
|
+
if (opts.clean) t = opts.clean(t);
|
|
732
|
+
return t.trim();
|
|
733
|
+
}).filter(Boolean);
|
|
734
|
+
return tokens.filter(t => isCodeSymbol(t, opts));
|
|
735
|
+
}
|
|
736
|
+
|
|
737
|
+
module.exports = {
|
|
738
|
+
// Constants
|
|
739
|
+
SERENA_PREFIX,
|
|
740
|
+
WARMUP_TOOL,
|
|
741
|
+
TOOLS,
|
|
742
|
+
STATE_DIR,
|
|
743
|
+
FLAG_EXPIRY_MS,
|
|
744
|
+
// State file
|
|
745
|
+
getStateFilePath,
|
|
746
|
+
readStateFile,
|
|
747
|
+
writeStateFile,
|
|
748
|
+
acquireLock,
|
|
749
|
+
releaseLock,
|
|
750
|
+
updateStateFile,
|
|
751
|
+
defaultFlag,
|
|
752
|
+
defaultHealth,
|
|
753
|
+
shouldEnforceSerena,
|
|
754
|
+
isOutsideProject,
|
|
755
|
+
// Health / failure handling
|
|
756
|
+
classifySerenaFailure,
|
|
757
|
+
isSerenaProcessAlive,
|
|
758
|
+
// Symbol detection
|
|
759
|
+
isCodeSymbol,
|
|
760
|
+
extractSymbolsFromPattern,
|
|
761
|
+
SYMBOL_ZERO_WIDTH,
|
|
762
|
+
// Allowlist policy (centralised — single source of truth)
|
|
763
|
+
CODE_EXTENSIONS,
|
|
764
|
+
ALLOW_NON_CODE_EXT,
|
|
765
|
+
ALLOW_CONFIG_PATTERNS,
|
|
766
|
+
ALLOW_PATH_PATTERNS,
|
|
767
|
+
ALLOW_TEST_PATTERNS,
|
|
768
|
+
isAllowedPath,
|
|
769
|
+
getEnabledExtensionsSet,
|
|
770
|
+
// Presence detection
|
|
771
|
+
hasSerena,
|
|
772
|
+
detectProviders,
|
|
773
|
+
// Intent resolution
|
|
774
|
+
resolveTool,
|
|
775
|
+
// Message builders
|
|
776
|
+
buildSuggestion,
|
|
777
|
+
buildWarmupInstructions,
|
|
778
|
+
buildFileWarmupCall,
|
|
779
|
+
buildEditSuggestion,
|
|
780
|
+
buildWriteSuggestion,
|
|
781
|
+
buildBashFsSuggestion,
|
|
782
|
+
buildStructuredSuggestions,
|
|
783
|
+
buildStructuredBlockResponse,
|
|
784
|
+
// Tool-name matchers
|
|
785
|
+
getTrackerToolNameRegex,
|
|
786
|
+
isLspProviderTool,
|
|
787
|
+
};
|