@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,94 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
'use strict';
|
|
3
|
+
|
|
4
|
+
/**
|
|
5
|
+
* serena-first-glob-guard.js — PreToolUse hook (matcher: Glob)
|
|
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.
|
|
26
|
+
*/
|
|
27
|
+
|
|
28
|
+
const {
|
|
29
|
+
buildSuggestion, buildStructuredBlockResponse,
|
|
30
|
+
extractSymbolsFromPattern,
|
|
31
|
+
getStateFilePath, readStateFile, shouldEnforceSerena, isOutsideProject,
|
|
32
|
+
} = require('./lib/serena');
|
|
33
|
+
|
|
34
|
+
let raw = '';
|
|
35
|
+
process.stdin.setEncoding('utf8');
|
|
36
|
+
process.stdin.on('data', d => { raw += d; });
|
|
37
|
+
process.stdin.on('end', () => {
|
|
38
|
+
let data;
|
|
39
|
+
try { data = JSON.parse(raw); } catch { process.exit(0); }
|
|
40
|
+
|
|
41
|
+
if (data.tool_name !== 'Glob') process.exit(0);
|
|
42
|
+
|
|
43
|
+
// Fail-open: skip enforcement when Serena is unhealthy for this project.
|
|
44
|
+
if (!shouldEnforceSerena(readStateFile(getStateFilePath()))) process.exit(0);
|
|
45
|
+
|
|
46
|
+
// String coercion: non-string input would throw on .trim() and fail-open.
|
|
47
|
+
const pattern = String(data.tool_input?.pattern ?? '').trim();
|
|
48
|
+
if (!pattern) process.exit(0);
|
|
49
|
+
|
|
50
|
+
const searchPath = String(data.tool_input?.path ?? '').trim();
|
|
51
|
+
|
|
52
|
+
// Enforcement is scoped to the project root — a glob rooted outside it
|
|
53
|
+
// passes through regardless of pattern (Serena can't reach outside).
|
|
54
|
+
if (searchPath && isOutsideProject(searchPath)) process.exit(0);
|
|
55
|
+
|
|
56
|
+
// ── Allow: non-code paths (anchored — bare substring would let
|
|
57
|
+
// "myknowledge-vaultxxx" bypass detection) ──────────────────────────
|
|
58
|
+
const NON_CODE_PATH = /(?:^|[\/\\])(?:knowledge-vault|\.task|\.claude|node_modules|supabase[\/\\]migrations|\.git)(?:[\/\\]|$)/i;
|
|
59
|
+
if (NON_CODE_PATH.test(searchPath)) process.exit(0);
|
|
60
|
+
if (NON_CODE_PATH.test(pattern)) process.exit(0);
|
|
61
|
+
|
|
62
|
+
// Extract alphabetic tokens from the pattern (strip *, /, ., brackets, etc.)
|
|
63
|
+
// and keep those that name code symbols.
|
|
64
|
+
const symbolTokens = extractSymbolsFromPattern(pattern, {
|
|
65
|
+
splitRe: /[*/.\\{}\[\]()!?,\s|+-]+/, allowlist: 'glob', stripZeroWidth: true,
|
|
66
|
+
});
|
|
67
|
+
if (symbolTokens.length === 0) process.exit(0);
|
|
68
|
+
|
|
69
|
+
const suggestions = symbolTokens.map(sym => {
|
|
70
|
+
const intent = /^[A-Z]/.test(sym) ? 'symbol_search' : 'references';
|
|
71
|
+
return ` ${sym}:\n${buildSuggestion(sym, intent, ' ')}`;
|
|
72
|
+
}).join('\n');
|
|
73
|
+
|
|
74
|
+
const msg =
|
|
75
|
+
`\n⛔ SERENA-FIRST BLOCK: Glob pattern contains ${symbolTokens.length} code symbol(s)\n` +
|
|
76
|
+
`━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\n` +
|
|
77
|
+
`Pattern: ${pattern}\n` +
|
|
78
|
+
`Symbols: ${symbolTokens.join(', ')}\n\n` +
|
|
79
|
+
`Serena is always connected. Searching files by symbol name is Serena territory:\n` +
|
|
80
|
+
`${suggestions}\n\n` +
|
|
81
|
+
`If you need to find files by extension or concept, use lowercase\n` +
|
|
82
|
+
`(e.g. "*subdomain*", "src/**/*.ts") — those are allowed.\n` +
|
|
83
|
+
`━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\n\n`;
|
|
84
|
+
|
|
85
|
+
process.stderr.write(msg);
|
|
86
|
+
|
|
87
|
+
const intent = /^[A-Z]/.test(symbolTokens[0]) ? 'symbol_search' : 'references';
|
|
88
|
+
console.log(JSON.stringify(buildStructuredBlockResponse({
|
|
89
|
+
hook: 'serena-first-glob-guard',
|
|
90
|
+
symbols: symbolTokens,
|
|
91
|
+
intent,
|
|
92
|
+
reason: `SERENA-FIRST: Glob pattern contains code symbol(s) [${symbolTokens.join(', ')}]. Use Serena tools instead of filename-based symbol search.`,
|
|
93
|
+
})));
|
|
94
|
+
});
|
|
@@ -0,0 +1,74 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
'use strict';
|
|
3
|
+
|
|
4
|
+
// serena-first-guard.js — PreToolUse hook (matcher: Grep)
|
|
5
|
+
// Blocks Grep on code symbols. Suggests the equivalent Serena tool call.
|
|
6
|
+
|
|
7
|
+
const {
|
|
8
|
+
buildSuggestion, buildStructuredBlockResponse, getEnabledExtensionsSet,
|
|
9
|
+
extractSymbolsFromPattern,
|
|
10
|
+
getStateFilePath, readStateFile, shouldEnforceSerena, isOutsideProject,
|
|
11
|
+
} = require('./lib/serena');
|
|
12
|
+
|
|
13
|
+
let raw = '';
|
|
14
|
+
process.stdin.setEncoding('utf8');
|
|
15
|
+
process.stdin.on('data', d => { raw += d; });
|
|
16
|
+
process.stdin.on('end', () => {
|
|
17
|
+
let data;
|
|
18
|
+
try { data = JSON.parse(raw); } catch (e) { process.exit(0); }
|
|
19
|
+
|
|
20
|
+
if (data.tool_name !== 'Grep') process.exit(0);
|
|
21
|
+
|
|
22
|
+
// Fail-open: skip enforcement when Serena is unhealthy for this project.
|
|
23
|
+
if (!shouldEnforceSerena(readStateFile(getStateFilePath()))) process.exit(0);
|
|
24
|
+
|
|
25
|
+
const params = data.tool_input || {};
|
|
26
|
+
// String coercion: non-string pattern (number, array, etc.) would throw on .trim()
|
|
27
|
+
// and fail-open — Claude Code treats crash as passthrough. See security review.
|
|
28
|
+
const pattern = String(params.pattern ?? '').trim();
|
|
29
|
+
const searchPath = String(params.path ?? '');
|
|
30
|
+
const glob = String(params.glob ?? '');
|
|
31
|
+
|
|
32
|
+
// Enforcement is scoped to the project root — a search rooted outside it
|
|
33
|
+
// passes through regardless of pattern (Serena can't reach outside).
|
|
34
|
+
if (searchPath && isOutsideProject(searchPath)) process.exit(0);
|
|
35
|
+
|
|
36
|
+
if (/knowledge-vault|\.task[\\/]|\.claude[\\/]|node_modules|logs?[\\/]|docs?[\\/]|supabase[\\/]migrations/i.test(searchPath)) {
|
|
37
|
+
process.exit(0);
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
if (/\.(txt|log|json|jsonc|yaml|yml|env|csv|toml|xml|sql|sh|css|scss)/i.test(glob)) {
|
|
41
|
+
const m = glob.match(/\.([a-z0-9]+)(?:[^a-z0-9]|$)/i);
|
|
42
|
+
const ext = m ? m[1].toLowerCase() : '';
|
|
43
|
+
if (!ext || !getEnabledExtensionsSet().has(ext)) process.exit(0);
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
if (pattern.length < 4) process.exit(0);
|
|
47
|
+
|
|
48
|
+
const symbolParts = extractSymbolsFromPattern(pattern, {
|
|
49
|
+
splitRe: '|', allowlist: 'guard', rejectRegexSpecials: true,
|
|
50
|
+
kebabComponents: true, dottedSymbol: true,
|
|
51
|
+
});
|
|
52
|
+
|
|
53
|
+
if (symbolParts.length === 0) process.exit(0);
|
|
54
|
+
|
|
55
|
+
const suggestions = symbolParts.map(sym => {
|
|
56
|
+
const intent = /^[A-Z]/.test(sym) ? 'symbol_search' : 'references';
|
|
57
|
+
return ` ${sym}:\n${buildSuggestion(sym, intent, ' ')}`;
|
|
58
|
+
}).join('\n');
|
|
59
|
+
|
|
60
|
+
process.stderr.write(
|
|
61
|
+
`\n⛔ SERENA-FIRST BLOCK: ${symbolParts.length} code symbol(s) in Grep — use Serena instead\n` +
|
|
62
|
+
`Symbols: ${symbolParts.join(', ')}\nSerena tools:\n${suggestions}\n\n`
|
|
63
|
+
);
|
|
64
|
+
|
|
65
|
+
// Emit structured JSON for programmatic consumers (monitoring, dashboards, IDE plugins).
|
|
66
|
+
// `decision` and `reason` fields remain backward compatible.
|
|
67
|
+
const intent = /^[A-Z]/.test(symbolParts[0]) ? 'symbol_search' : 'references';
|
|
68
|
+
console.log(JSON.stringify(buildStructuredBlockResponse({
|
|
69
|
+
hook: 'serena-first-guard',
|
|
70
|
+
symbols: symbolParts,
|
|
71
|
+
intent,
|
|
72
|
+
reason: `SERENA-FIRST: Pattern contains code symbol(s) [${symbolParts.join(', ')}]. Use Serena tools:\n${suggestions}`,
|
|
73
|
+
})));
|
|
74
|
+
});
|
|
@@ -0,0 +1,167 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
'use strict';
|
|
3
|
+
|
|
4
|
+
const {
|
|
5
|
+
buildWarmupInstructions, buildFileWarmupCall, isAllowedPath,
|
|
6
|
+
getStateFilePath, readStateFile, updateStateFile, defaultFlag, defaultHealth,
|
|
7
|
+
shouldEnforceSerena, isOutsideProject,
|
|
8
|
+
} = require('./lib/serena');
|
|
9
|
+
|
|
10
|
+
/**
|
|
11
|
+
* Build a copy-pasteable warmup call parametrized by the exact file the
|
|
12
|
+
* agent is about to Read. This is project-agnostic: it uses the file path
|
|
13
|
+
* from the hook input instead of guessing a symbol name from the filename,
|
|
14
|
+
* so it works in any project regardless of export conventions.
|
|
15
|
+
*/
|
|
16
|
+
function buildConcreteCall(filePath) {
|
|
17
|
+
const call = buildFileWarmupCall(filePath, ' ');
|
|
18
|
+
if (!call) return '';
|
|
19
|
+
return `\nCONCRETE CALL FOR THIS FILE (works in any project):\n${call}\n`;
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
const FREE_READS = 2;
|
|
23
|
+
const WARN_AT = 3;
|
|
24
|
+
const REQUIRE_NAV_2_AT = 6;
|
|
25
|
+
|
|
26
|
+
// Defense-in-depth: if Gate 1 blocks WARMUP_BLOCK_LIMIT times in a row with
|
|
27
|
+
// no successful Serena call in between, warmup can never succeed (Serena is
|
|
28
|
+
// genuinely down, or an unforeseen error type evaded the health-tracking
|
|
29
|
+
// classification) — escalate to the shared should_enforce circuit breaker
|
|
30
|
+
// instead of blocking forever. Escalating there (not just bypassing Gate 1
|
|
31
|
+
// locally) matters: a local-only bypass would just relocate the deadlock to
|
|
32
|
+
// the next guard hook the agent hits.
|
|
33
|
+
const WARMUP_BLOCK_LIMIT = 3;
|
|
34
|
+
|
|
35
|
+
const GATE1_DEADLOCK_NOTICE =
|
|
36
|
+
`⚠️ Serena warmup failed ${WARMUP_BLOCK_LIMIT} times in a row for this project ` +
|
|
37
|
+
'with no successful Serena call in between. Serena-first enforcement is now ' +
|
|
38
|
+
'disabled for this session; standard tools (Read/Grep/Edit) are permitted. ' +
|
|
39
|
+
'It will re-enable automatically when a Serena call succeeds.';
|
|
40
|
+
|
|
41
|
+
function emitWarning(msg) { console.log(JSON.stringify({ systemMessage: msg })); }
|
|
42
|
+
function emitBlock(msg) { process.stderr.write(msg); process.exit(2); }
|
|
43
|
+
|
|
44
|
+
/** Persist that `filePath` was read, recomputing against the freshly-locked state. */
|
|
45
|
+
function persistRead(flagPath, filePath) {
|
|
46
|
+
return updateStateFile(flagPath, defaultFlag, (flag) => {
|
|
47
|
+
const readFiles = Array.isArray(flag.read_files) ? flag.read_files : [];
|
|
48
|
+
if (!readFiles.includes(filePath)) {
|
|
49
|
+
readFiles.push(filePath);
|
|
50
|
+
flag.read_files = readFiles;
|
|
51
|
+
flag.read_count = readFiles.length;
|
|
52
|
+
}
|
|
53
|
+
flag.timestamp = Date.now();
|
|
54
|
+
return flag;
|
|
55
|
+
});
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
let raw = '';
|
|
59
|
+
process.stdin.setEncoding('utf8');
|
|
60
|
+
process.stdin.on('data', d => { raw += d; });
|
|
61
|
+
process.stdin.on('end', () => {
|
|
62
|
+
let data;
|
|
63
|
+
try { data = JSON.parse(raw); } catch { process.exit(0); }
|
|
64
|
+
if (data.tool_name !== 'Read') process.exit(0);
|
|
65
|
+
if (process.env.CLAUDE_MIGRATION === '1') process.exit(0);
|
|
66
|
+
|
|
67
|
+
// String coercion: non-string input would throw on .trim() and fail-open.
|
|
68
|
+
const filePath = String(data.tool_input?.file_path ?? '').trim();
|
|
69
|
+
if (!filePath) process.exit(0);
|
|
70
|
+
|
|
71
|
+
// Enforcement is scoped to the project root — Serena can't reach outside it.
|
|
72
|
+
if (isOutsideProject(filePath)) process.exit(0);
|
|
73
|
+
|
|
74
|
+
const flagPath = getStateFilePath();
|
|
75
|
+
const flag = readStateFile(flagPath);
|
|
76
|
+
|
|
77
|
+
// 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).
|
|
80
|
+
if (!shouldEnforceSerena(flag)) process.exit(0);
|
|
81
|
+
|
|
82
|
+
if (isAllowedPath(filePath, { enforceMarkdown: true })) process.exit(0);
|
|
83
|
+
|
|
84
|
+
if (!flag || !flag.warmup_done) {
|
|
85
|
+
const updated = updateStateFile(flagPath, defaultFlag, (f) => {
|
|
86
|
+
f.warmup_block_count = (f.warmup_block_count || 0) + 1;
|
|
87
|
+
f.timestamp = Date.now();
|
|
88
|
+
return f;
|
|
89
|
+
});
|
|
90
|
+
|
|
91
|
+
if (updated.warmup_block_count >= WARMUP_BLOCK_LIMIT) {
|
|
92
|
+
updateStateFile(flagPath, defaultFlag, (f) => {
|
|
93
|
+
const health = f.health || defaultHealth();
|
|
94
|
+
health.should_enforce = false;
|
|
95
|
+
health.healthy = false;
|
|
96
|
+
health.last_error = `gate1-deadlock-guard: ${WARMUP_BLOCK_LIMIT} consecutive warmup blocks with no successful Serena call`;
|
|
97
|
+
health.last_check = Date.now();
|
|
98
|
+
f.health = health;
|
|
99
|
+
f.timestamp = Date.now();
|
|
100
|
+
return f;
|
|
101
|
+
});
|
|
102
|
+
emitWarning(GATE1_DEADLOCK_NOTICE);
|
|
103
|
+
process.exit(0);
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
const warmupLines = buildWarmupInstructions(' ').join('\n');
|
|
107
|
+
const concrete = buildConcreteCall(filePath);
|
|
108
|
+
emitBlock(
|
|
109
|
+
`⛔ SERENA-FIRST BLOCK (Gate 1 — Warmup Required)\n\n` +
|
|
110
|
+
`Read on code file requires prior Serena warmup.\n\n` +
|
|
111
|
+
`WARMUP PROTOCOL — call one of these first:\n` +
|
|
112
|
+
`${warmupLines}\n` +
|
|
113
|
+
concrete +
|
|
114
|
+
`\nAfter warmup: ${FREE_READS} free Reads, then need Serena navigation.\n\n` +
|
|
115
|
+
`Blocked: ${filePath}\n`
|
|
116
|
+
);
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
const readFiles = Array.isArray(flag.read_files) ? flag.read_files : [];
|
|
120
|
+
const navCount = flag.nav_count || 0;
|
|
121
|
+
const alreadyRead = readFiles.includes(filePath);
|
|
122
|
+
const nextReadNum = alreadyRead ? readFiles.length : readFiles.length + 1;
|
|
123
|
+
|
|
124
|
+
if (navCount >= 2 || alreadyRead) {
|
|
125
|
+
if (!alreadyRead) persistRead(flagPath, filePath);
|
|
126
|
+
process.exit(0);
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
if (nextReadNum <= FREE_READS) {
|
|
130
|
+
persistRead(flagPath, filePath);
|
|
131
|
+
process.exit(0);
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
if (nextReadNum === WARN_AT && navCount === 0) {
|
|
135
|
+
emitWarning(
|
|
136
|
+
`⚠️ SERENA-FIRST WARNING (Read ${nextReadNum}) — consider Serena navigation.\n` +
|
|
137
|
+
`Use mcp__serena__find_symbol / find_referencing_symbols before more Reads.\n` +
|
|
138
|
+
`Next Read will be BLOCKED unless you use at least 1 Serena nav call.\n` +
|
|
139
|
+
`After 2 nav calls, all Reads are unlimited (surgical mode).`
|
|
140
|
+
);
|
|
141
|
+
persistRead(flagPath, filePath);
|
|
142
|
+
process.exit(0);
|
|
143
|
+
}
|
|
144
|
+
|
|
145
|
+
if (nextReadNum < REQUIRE_NAV_2_AT && navCount < 1) {
|
|
146
|
+
emitBlock(
|
|
147
|
+
`⛔ SERENA-FIRST BLOCK (Gate 4 — Serena Navigation Required)\n\n` +
|
|
148
|
+
`Read #${nextReadNum} requires at least 1 Serena navigation call.\n` +
|
|
149
|
+
`After 1 nav call, Reads 4-5 unlock. After 2, unlimited.\n` +
|
|
150
|
+
buildConcreteCall(filePath) +
|
|
151
|
+
`\nBlocked: ${filePath}\n`
|
|
152
|
+
);
|
|
153
|
+
}
|
|
154
|
+
|
|
155
|
+
if (nextReadNum >= REQUIRE_NAV_2_AT && navCount < 2) {
|
|
156
|
+
emitBlock(
|
|
157
|
+
`⛔ SERENA-FIRST BLOCK (Gate 5 — Surgical Mode Required)\n\n` +
|
|
158
|
+
`Read #${nextReadNum} requires at least 2 Serena navigation calls.\n` +
|
|
159
|
+
`Current: ${navCount} nav calls. Need 2.\n` +
|
|
160
|
+
buildConcreteCall(filePath) +
|
|
161
|
+
`\nBlocked: ${filePath}\n`
|
|
162
|
+
);
|
|
163
|
+
}
|
|
164
|
+
|
|
165
|
+
persistRead(flagPath, filePath);
|
|
166
|
+
process.exit(0);
|
|
167
|
+
});
|
|
@@ -0,0 +1,117 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
'use strict';
|
|
3
|
+
|
|
4
|
+
const fs = require('fs');
|
|
5
|
+
const path = require('path');
|
|
6
|
+
const { getStateFilePath, readStateFile, shouldEnforceSerena } = require('./lib/serena');
|
|
7
|
+
|
|
8
|
+
const FORCE_LSP_CONTEXT_AGENTS = [
|
|
9
|
+
'backend-explorer', 'frontend-explorer', 'db-explorer',
|
|
10
|
+
];
|
|
11
|
+
|
|
12
|
+
const EXEMPT_AGENTS = [
|
|
13
|
+
'explore', 'security-reviewer', 'performance-reviewer', 'conventions-reviewer',
|
|
14
|
+
'conflict-detector', 'code-auditor', 'lint-types-checker', 'test-runner',
|
|
15
|
+
'code-reviewer', 'go-reviewer', 'doc-updater', 'architect', 'planner',
|
|
16
|
+
'deep-security-reviewer', 'typescript-reviewer', 'python-reviewer',
|
|
17
|
+
'ai-integration-reviewer', 'supabase-auth-reviewer', 'scraper-reviewer',
|
|
18
|
+
'nextjs-static-reviewer', 'build-error-resolver', 'e2e-runner',
|
|
19
|
+
'performance-optimizer', 'tdd-guide',
|
|
20
|
+
];
|
|
21
|
+
|
|
22
|
+
let input = '';
|
|
23
|
+
process.stdin.setEncoding('utf8');
|
|
24
|
+
process.stdin.on('data', d => { input += d; });
|
|
25
|
+
process.stdin.on('end', () => {
|
|
26
|
+
let data;
|
|
27
|
+
try { data = JSON.parse(input); } catch { process.exit(0); }
|
|
28
|
+
if (data.tool_name !== 'Agent') process.exit(0);
|
|
29
|
+
|
|
30
|
+
// Fail-open: skip enforcement when Serena is unhealthy for this project.
|
|
31
|
+
if (!shouldEnforceSerena(readStateFile(getStateFilePath()))) process.exit(0);
|
|
32
|
+
|
|
33
|
+
const toolInput = data.tool_input || {};
|
|
34
|
+
// String coercion: non-string fields would throw on subsequent string methods.
|
|
35
|
+
const prompt = String(toolInput.prompt ?? '');
|
|
36
|
+
const subagentType = String(toolInput.subagent_type ?? '');
|
|
37
|
+
const isForcedExplorer = FORCE_LSP_CONTEXT_AGENTS.includes(subagentType);
|
|
38
|
+
|
|
39
|
+
if (!isForcedExplorer) {
|
|
40
|
+
// Exact match only — previously `.includes(e)` allowed substring matches
|
|
41
|
+
// like `exploit-deep-security-reviewer` to bypass by containing a
|
|
42
|
+
// legitimate exempt name. Both checks now case-insensitive exact.
|
|
43
|
+
const subType = subagentType.toLowerCase();
|
|
44
|
+
if (EXEMPT_AGENTS.some(e => e.toLowerCase() === subType)) process.exit(0);
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
if (prompt.length < 200) process.exit(0);
|
|
48
|
+
|
|
49
|
+
const isolation = String(toolInput.isolation ?? '');
|
|
50
|
+
const cwd = String(data.cwd ?? process.cwd());
|
|
51
|
+
const taskDir = path.join(cwd, '.task');
|
|
52
|
+
|
|
53
|
+
if (!isForcedExplorer && isolation !== 'worktree') {
|
|
54
|
+
if (!fs.existsSync(taskDir)) process.exit(0);
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
let inImplementPhase = isForcedExplorer || isolation === 'worktree';
|
|
58
|
+
|
|
59
|
+
if (!inImplementPhase) {
|
|
60
|
+
try {
|
|
61
|
+
const entries = fs.readdirSync(taskDir).filter(e => {
|
|
62
|
+
return e.startsWith('20') && fs.statSync(path.join(taskDir, e)).isDirectory();
|
|
63
|
+
});
|
|
64
|
+
const twoHoursAgo = Date.now() - 2 * 60 * 60 * 1000;
|
|
65
|
+
for (const entry of entries) {
|
|
66
|
+
const folderPath = path.join(taskDir, entry);
|
|
67
|
+
const stat = fs.statSync(folderPath);
|
|
68
|
+
if (stat.mtimeMs < twoHoursAgo) continue;
|
|
69
|
+
const statePath = path.join(folderPath, 'state.json');
|
|
70
|
+
if (fs.existsSync(statePath)) {
|
|
71
|
+
try {
|
|
72
|
+
const state = JSON.parse(fs.readFileSync(statePath, 'utf8'));
|
|
73
|
+
if (state.phase === 'implement') { inImplementPhase = true; break; }
|
|
74
|
+
} catch {}
|
|
75
|
+
}
|
|
76
|
+
const taskMd = path.join(folderPath, '00-task.md');
|
|
77
|
+
if (fs.existsSync(taskMd)) {
|
|
78
|
+
try {
|
|
79
|
+
const content = fs.readFileSync(taskMd, 'utf8');
|
|
80
|
+
if (/\*{0,2}Phase\*{0,2}:\*{0,2}\s*implement/i.test(content)) { inImplementPhase = true; break; }
|
|
81
|
+
} catch {}
|
|
82
|
+
}
|
|
83
|
+
}
|
|
84
|
+
} catch {}
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
if (!inImplementPhase) process.exit(0);
|
|
88
|
+
|
|
89
|
+
const hasLspContext =
|
|
90
|
+
/\bLSP CONTEXT\b/i.test(prompt) ||
|
|
91
|
+
/\bSymbol Map\b/i.test(prompt) ||
|
|
92
|
+
/\bdefined\s+at\s+[\w\-\/]+\.\w{2,4}:\d+/i.test(prompt) ||
|
|
93
|
+
/\bcalled\s+from\s+[\w\-\/]+\.\w{2,4}:\d+/i.test(prompt) ||
|
|
94
|
+
/\bused\s+in\s+[\w\-\/]+\.\w{2,4}:\d+/i.test(prompt) ||
|
|
95
|
+
/\bimported\s+(?:in|by)\s+[\w\-\/]+\.\w{2,4}:\d+/i.test(prompt);
|
|
96
|
+
|
|
97
|
+
if (hasLspContext) process.exit(0);
|
|
98
|
+
|
|
99
|
+
const agentLabel = isForcedExplorer ? `explorer "${subagentType}"` : 'implement agent';
|
|
100
|
+
|
|
101
|
+
const decision = (isForcedExplorer || isolation === 'worktree') ? 'block' : 'warn';
|
|
102
|
+
console.log(JSON.stringify({
|
|
103
|
+
decision,
|
|
104
|
+
reason: [
|
|
105
|
+
`SERENA PRE-DELEGATION: ${agentLabel} without "## LSP CONTEXT".`,
|
|
106
|
+
'',
|
|
107
|
+
'DO THIS NOW (3 steps, then retry the Agent call):',
|
|
108
|
+
'1. mcp__serena__get_symbols_overview("<any project file>") — primes Serena',
|
|
109
|
+
'2. mcp__serena__find_symbol("<keyword from task>") — finds symbols',
|
|
110
|
+
'3. Add to EVERY agent prompt:',
|
|
111
|
+
' ## LSP CONTEXT (pre-resolved — do NOT re-search)',
|
|
112
|
+
' - symbolName: defined at file.ts:42, called from a.ts:15',
|
|
113
|
+
'',
|
|
114
|
+
'Then re-launch the same Agent calls with ## LSP CONTEXT included.',
|
|
115
|
+
].join('\n'),
|
|
116
|
+
}));
|
|
117
|
+
});
|
|
@@ -0,0 +1,45 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
'use strict';
|
|
3
|
+
|
|
4
|
+
/**
|
|
5
|
+
* serena-session-reset.js — SessionStart hook
|
|
6
|
+
*
|
|
7
|
+
* Wipes stale Serena navigation state for the current cwd at session start.
|
|
8
|
+
*
|
|
9
|
+
* Without this, `nav_count` persists for 24h across sessions (see
|
|
10
|
+
* serena-first-read-guard.js FLAG_EXPIRY_MS). A new session can inherit
|
|
11
|
+
* "surgical mode" (nav_count >= 2) from previous work and freely Read
|
|
12
|
+
* code files without ever calling Serena — a full bypass of the
|
|
13
|
+
* Serena-first enforcement chain.
|
|
14
|
+
*
|
|
15
|
+
* After reset:
|
|
16
|
+
* - Gate 1 (warmup): first code Read BLOCKED until mcp__serena__get_symbols_overview
|
|
17
|
+
* - Gate 4: read #4 BLOCKED unless nav_count >= 1
|
|
18
|
+
* - Gate 5: read #6 BLOCKED unless nav_count >= 2
|
|
19
|
+
*
|
|
20
|
+
* Side-effect: first session call forces one warmup (~1 Serena call). Cheap.
|
|
21
|
+
*/
|
|
22
|
+
|
|
23
|
+
const fs = require('fs');
|
|
24
|
+
const { getStateFilePath } = require('./lib/serena');
|
|
25
|
+
|
|
26
|
+
let raw = '';
|
|
27
|
+
process.stdin.setEncoding('utf8');
|
|
28
|
+
process.stdin.on('data', d => { raw += d; });
|
|
29
|
+
process.stdin.on('end', () => {
|
|
30
|
+
let cwd = process.cwd();
|
|
31
|
+
try {
|
|
32
|
+
const data = JSON.parse(raw || '{}');
|
|
33
|
+
if (data.cwd && typeof data.cwd === 'string') cwd = data.cwd;
|
|
34
|
+
} catch { /* ignore */ }
|
|
35
|
+
|
|
36
|
+
const flagPath = getStateFilePath(cwd);
|
|
37
|
+
|
|
38
|
+
try {
|
|
39
|
+
if (fs.existsSync(flagPath)) {
|
|
40
|
+
fs.unlinkSync(flagPath);
|
|
41
|
+
}
|
|
42
|
+
} catch { /* silent: hook must never block session start */ }
|
|
43
|
+
|
|
44
|
+
process.exit(0);
|
|
45
|
+
});
|
|
@@ -0,0 +1,186 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
'use strict';
|
|
3
|
+
|
|
4
|
+
/**
|
|
5
|
+
* serena-usage-tracker.js — PostToolUse + PostToolUseFailure hook
|
|
6
|
+
*
|
|
7
|
+
* Two jobs, keyed on the outcome of a Serena tool call:
|
|
8
|
+
*
|
|
9
|
+
* SUCCESS — record readiness in ~/.claude/state/lsp-ready-<hash> (the warmup
|
|
10
|
+
* / nav counters that serena-first-read-guard.js gates on) and restore the
|
|
11
|
+
* provider's health to enforcing/healthy.
|
|
12
|
+
*
|
|
13
|
+
* FAILURE — classify and drive fail-open enforcement:
|
|
14
|
+
* - tool-level (server alive, bad query / no matches / benign config
|
|
15
|
+
* decline): record the error, keep enforcing.
|
|
16
|
+
* - transport-level (process down / unreachable): probe the process
|
|
17
|
+
* (diagnostic only — never terminated; a hook invocation only exists
|
|
18
|
+
* because the round-trip completed, so the server already proved it's
|
|
19
|
+
* alive). If a live process remains, keep enforcing; if none remains,
|
|
20
|
+
* disable Serena-first enforcement for this project (fail open) and
|
|
21
|
+
* emit a one-time notice. Enforcement re-enables automatically on the
|
|
22
|
+
* next successful Serena call.
|
|
23
|
+
*
|
|
24
|
+
* Handles BOTH payload shapes: PostToolUse (`tool_response` / `result`) and
|
|
25
|
+
* PostToolUseFailure (top-level `error`). This dual handling is also the
|
|
26
|
+
* version-compatibility fallback — on Claude Code builds without
|
|
27
|
+
* PostToolUseFailure, failed Serena calls still surface here via the
|
|
28
|
+
* PostToolUse error-shaped `tool_response`.
|
|
29
|
+
*
|
|
30
|
+
* Recognises the standalone `mcp__serena__*` form and the plugin-wrapped
|
|
31
|
+
* `mcp__plugin_<name>_serena__*` form via ./lib/serena.js#isLspProviderTool.
|
|
32
|
+
*/
|
|
33
|
+
|
|
34
|
+
const {
|
|
35
|
+
isLspProviderTool,
|
|
36
|
+
getStateFilePath, updateStateFile, defaultFlag, defaultHealth,
|
|
37
|
+
classifySerenaFailure, isSerenaProcessAlive,
|
|
38
|
+
} = require('./lib/serena');
|
|
39
|
+
|
|
40
|
+
// Serena tools that advance the read-guard gate. The PostToolUse matcher is
|
|
41
|
+
// broadened to all Serena tools (so every call feeds health tracking), so the
|
|
42
|
+
// nav counters are gated HERE to preserve the read-guard's original behaviour:
|
|
43
|
+
// only these navigation/exploration tools bump warmup_done / nav_count.
|
|
44
|
+
const NAV_TOOLS = new Set([
|
|
45
|
+
'find_symbol', 'find_referencing_symbols', 'get_symbols_overview',
|
|
46
|
+
'find_file', 'search_for_pattern', 'list_dir',
|
|
47
|
+
]);
|
|
48
|
+
|
|
49
|
+
const UNHEALTHY_NOTICE =
|
|
50
|
+
'⚠️ Serena MCP is unhealthy for this project and no live process was found. ' +
|
|
51
|
+
'Serena-first enforcement is now disabled for this session; standard tools ' +
|
|
52
|
+
'(Read/Grep/Edit) are permitted. It will re-enable automatically when a ' +
|
|
53
|
+
'Serena call succeeds.';
|
|
54
|
+
|
|
55
|
+
/** Strip the mcp__serena__ / mcp__plugin_<x>_serena__ prefix from a tool name. */
|
|
56
|
+
function bareToolName(toolName) {
|
|
57
|
+
const m = /^mcp__(?:plugin_[^_]+_)?serena__(.+)$/.exec(String(toolName));
|
|
58
|
+
return m ? m[1] : '';
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
/**
|
|
62
|
+
* Classify a PostToolUse response payload:
|
|
63
|
+
* 'error' — a positive error signal (is_error flag, error field, "Error:" text)
|
|
64
|
+
* 'empty' — no usable payload (ambiguous — treat as a no-op, never a failure)
|
|
65
|
+
* 'ok' — a genuine success
|
|
66
|
+
*/
|
|
67
|
+
function respErrorKind(resp) {
|
|
68
|
+
if (resp == null) return 'empty';
|
|
69
|
+
if (resp.is_error === true || resp.isError === true || resp.error) return 'error';
|
|
70
|
+
if (Array.isArray(resp.content)) {
|
|
71
|
+
for (const item of resp.content) {
|
|
72
|
+
if (item && (item.is_error === true || item.isError === true)) return 'error';
|
|
73
|
+
if (item && item.type === 'tool_result_error') return 'error';
|
|
74
|
+
}
|
|
75
|
+
}
|
|
76
|
+
const s = typeof resp === 'string' ? resp : JSON.stringify(resp);
|
|
77
|
+
if (/^Error[: ]|Error searching|Error finding|Error at /i.test(s)) return 'error';
|
|
78
|
+
if (typeof resp === 'object' && !Array.isArray(resp) && Object.keys(resp).length === 0) return 'empty';
|
|
79
|
+
return 'ok';
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
function summarizeError(payload) {
|
|
83
|
+
let s;
|
|
84
|
+
if (payload == null) s = '';
|
|
85
|
+
else if (typeof payload === 'string') s = payload;
|
|
86
|
+
else { try { s = JSON.stringify(payload); } catch { s = String(payload); } }
|
|
87
|
+
return s.slice(0, 300);
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
let raw = '';
|
|
91
|
+
process.stdin.setEncoding('utf8');
|
|
92
|
+
process.stdin.on('data', d => { raw += d; });
|
|
93
|
+
process.stdin.on('end', () => {
|
|
94
|
+
try {
|
|
95
|
+
const data = JSON.parse(raw);
|
|
96
|
+
const toolName = data.tool_name || '';
|
|
97
|
+
if (!isLspProviderTool(toolName)) process.exit(0);
|
|
98
|
+
|
|
99
|
+
const flagPath = getStateFilePath();
|
|
100
|
+
|
|
101
|
+
if (data.error != null) {
|
|
102
|
+
// PostToolUseFailure — definitively a failure.
|
|
103
|
+
handleFailure(flagPath, data.error);
|
|
104
|
+
} else {
|
|
105
|
+
const resp = data.tool_response ?? data.result ?? {};
|
|
106
|
+
const kind = respErrorKind(resp);
|
|
107
|
+
if (kind === 'error') handleFailure(flagPath, resp);
|
|
108
|
+
else if (kind === 'ok') handleSuccess(flagPath, toolName);
|
|
109
|
+
// 'empty' ⇒ ambiguous PostToolUse with no payload: no-op (as before),
|
|
110
|
+
// so a benign empty response never gets misclassified as a failure.
|
|
111
|
+
}
|
|
112
|
+
} catch {}
|
|
113
|
+
process.exit(0);
|
|
114
|
+
});
|
|
115
|
+
|
|
116
|
+
function handleSuccess(flagPath, toolName) {
|
|
117
|
+
updateStateFile(flagPath, defaultFlag, (flag) => {
|
|
118
|
+
// A successful Serena call proves the server is alive — restore health
|
|
119
|
+
// and re-arm the Gate 1 deadlock backstop (see serena-first-read-guard.js).
|
|
120
|
+
flag.health = defaultHealth();
|
|
121
|
+
flag.health.last_check = Date.now();
|
|
122
|
+
flag.warmup_block_count = 0;
|
|
123
|
+
|
|
124
|
+
// Only navigation/exploration tools advance the read-guard gate.
|
|
125
|
+
if (NAV_TOOLS.has(bareToolName(toolName))) {
|
|
126
|
+
if (!flag.warmup_done) {
|
|
127
|
+
flag.warmup_done = true;
|
|
128
|
+
flag.cold_start_retries = 0;
|
|
129
|
+
} else {
|
|
130
|
+
flag.nav_count = (flag.nav_count || 0) + 1;
|
|
131
|
+
}
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
flag.timestamp = Date.now();
|
|
135
|
+
flag.last_tool = toolName;
|
|
136
|
+
return flag;
|
|
137
|
+
});
|
|
138
|
+
}
|
|
139
|
+
|
|
140
|
+
function handleFailure(flagPath, payload) {
|
|
141
|
+
const kind = classifySerenaFailure(payload);
|
|
142
|
+
const cwd = process.cwd();
|
|
143
|
+
let notice = null;
|
|
144
|
+
|
|
145
|
+
updateStateFile(flagPath, defaultFlag, (flag) => {
|
|
146
|
+
const health = flag.health || defaultHealth();
|
|
147
|
+
health.error_count = (health.error_count || 0) + 1;
|
|
148
|
+
health.last_error = summarizeError(payload);
|
|
149
|
+
health.last_check = Date.now();
|
|
150
|
+
|
|
151
|
+
// Tool-level failure: the server answered, the query just didn't
|
|
152
|
+
// resolve (or declined for a benign reason). Keep enforcing.
|
|
153
|
+
if (kind === 'tool') {
|
|
154
|
+
flag.health = health;
|
|
155
|
+
flag.timestamp = Date.now();
|
|
156
|
+
return flag;
|
|
157
|
+
}
|
|
158
|
+
|
|
159
|
+
// Transport-level failure: diagnostic-only probe. This never terminates
|
|
160
|
+
// the process — a hook invocation only exists because the MCP
|
|
161
|
+
// round-trip completed, so the server necessarily responded and is not
|
|
162
|
+
// "hung." See isSerenaProcessAlive's docstring in lib/serena.js.
|
|
163
|
+
const alive = isSerenaProcessAlive(cwd);
|
|
164
|
+
health.healthy = false;
|
|
165
|
+
|
|
166
|
+
if (alive) {
|
|
167
|
+
// A live process remains — keep enforcing, just record the error.
|
|
168
|
+
flag.health = health;
|
|
169
|
+
flag.timestamp = Date.now();
|
|
170
|
+
return flag;
|
|
171
|
+
}
|
|
172
|
+
|
|
173
|
+
// No live process — fail open so the agent isn't trapped between a
|
|
174
|
+
// broken Serena and blocked fallbacks.
|
|
175
|
+
health.should_enforce = false;
|
|
176
|
+
if (!health.notified) {
|
|
177
|
+
health.notified = true;
|
|
178
|
+
notice = JSON.stringify({ systemMessage: UNHEALTHY_NOTICE });
|
|
179
|
+
}
|
|
180
|
+
flag.health = health;
|
|
181
|
+
flag.timestamp = Date.now();
|
|
182
|
+
return flag;
|
|
183
|
+
});
|
|
184
|
+
|
|
185
|
+
if (notice) console.log(notice);
|
|
186
|
+
}
|