bookworm-smart-assistant/scripts/patches/patch-sc-hooks-optimize.js

63 lines
2.5 KiB
JavaScript
Raw Permalink Normal View History

#!/usr/bin/env node
// 幂等补丁: 优化 session-continuity hooks — 保留高价值,砍掉 context 膨胀源
// 策略: 保留 Stop+PreCompact+Bash错误检测, 移除 SessionStart+UserPromptSubmit+Edit/Write追踪
const fs = require('fs');
const path = require('path');
const SENTINEL = 'sc-hooks-optimize-v1';
const SETTINGS = path.join(require('os').homedir(), '.claude', 'settings.json');
const SC_MARKER = 'session-continuity-mcp/dist/hooks';
const raw = fs.readFileSync(SETTINGS, 'utf8');
if (raw.includes(SENTINEL)) {
console.log('[patch] already optimized, skipping');
process.exit(0);
}
const settings = JSON.parse(raw);
const hooks = settings.hooks || {};
let removed = 0;
// 1. 移除 SessionStart (Claude Code 不支持此事件)
if (hooks.SessionStart) {
hooks.SessionStart = hooks.SessionStart.filter(e => !JSON.stringify(e).includes(SC_MARKER));
if (hooks.SessionStart.length === 0) delete hooks.SessionStart;
removed++;
console.log(' - SessionStart: 移除 (事件不受支持)');
}
// 2. 移除 UserPromptSubmit 的 SC hook (每次提示注入记忆,context 膨胀主因)
if (hooks.UserPromptSubmit) {
const before = hooks.UserPromptSubmit.length;
hooks.UserPromptSubmit = hooks.UserPromptSubmit.filter(e => !JSON.stringify(e).includes(SC_MARKER));
if (hooks.UserPromptSubmit.length < before) {
removed++;
console.log(' - UserPromptSubmit: 移除 SC 记忆注入 (context 膨胀主因)');
}
}
// 3. PostToolUse: 只保留 Bash 错误检测, 移除 Edit/Write 文件追踪
if (hooks.PostToolUse) {
const before = hooks.PostToolUse.length;
hooks.PostToolUse = hooks.PostToolUse.filter(e => {
if (!JSON.stringify(e).includes(SC_MARKER)) return true;
return e.matcher === 'Bash'; // 只保留 Bash
});
const diff = before - hooks.PostToolUse.length;
if (diff > 0) {
removed += diff;
console.log(` - PostToolUse: 移除 Edit/Write 追踪 (${diff}个), 保留 Bash 错误检测`);
}
}
// 4. 保留: PreCompact (压缩前交接) + Stop (会话结束自动保存)
console.log(' ✓ PreCompact: 保留 (压缩前自动交接)');
console.log(' ✓ Stop: 保留 (会话结束自动保存 commit/决策/错误修复对)');
console.log(' ✓ PostToolUse[Bash]: 保留 (错误→历史方案自动匹配)');
settings.hooks = hooks;
fs.writeFileSync(SETTINGS, JSON.stringify(settings, null, 2));
console.log(`\n[patch] 优化完成: 移除 ${removed} 个低价值/高开销 hook, 保留 3 个核心 hook`);
console.log('[patch] 重启 Claude Code 生效');