bookworm-smart-assistant/scripts/patches/patch-r5-bash-separators-extension.js

41 lines
2.2 KiB
JavaScript
Raw Normal View History

#!/usr/bin/env node
/**
* patch-r5-bash-separators-extension.js · 2026-04-26
* 扩展 R5 B3 检测: 从仅 && 计数, 改为统计 && | ; | 换行 三类分隔符
* 同时排除单引号/双引号字符串内的分隔符 (轻量剥离), 避免 heredoc 误报
* Idempotent: sentinel 'R5-SEPARATORS-V2'
*/
'use strict';
const fs = require('fs');
const path = require('path');
const HOOK = path.join(process.env.HOME || process.env.USERPROFILE || 'C:/Users/leesu', '.claude', 'hooks', 'agent-isolation-gate.js');
const SENTINEL = 'R5-SEPARATORS-V2';
const OLD = " // B3) && 链 ≥6 且含 io 动词\n const ands = c.split('&&').length - 1;\n if (ands >= 5 && /\\b(mkdir|touch|cp|mv|echo|cat)\\b/.test(c)) {\n return { rule: 'B3', detail: '&&-chain ' + (ands + 1) + ' commands' };\n }";
const NEW = " // R5-SEPARATORS-V2: B3 扩展为 && / ; / 换行 三类分隔符联合统计\n // 先剥离引号字符串避免误统计 (heredoc/echo 内分号)\n const stripped = stripQuoted(c);\n const sepCount = ((stripped.match(/&&|;|\\n(?!\\s*$)/g)) || []).length;\n if (sepCount >= 5 && /\\b(mkdir|touch|cp|mv|echo|cat|rm|ln)\\b/.test(c)) {\n return { rule: 'B3', detail: 'separators ' + (sepCount + 1) + ' commands' };\n }";
const HELPER_ANCHOR = "function detectBashRule(cmd) {";
const HELPER_FN = "function stripQuoted(s) {\n // 移除 '...' 和 \"...\" 内的内容, 防字符串内分号干扰分隔符计数\n // 不处理 heredoc (<<EOF...EOF), heredoc 由调用侧的动词正则间接限制\n return s.replace(/'[^']*'/g, \"''\").replace(/\"[^\"]*\"/g, '\"\"');\n}\n\n";
try {
let raw = fs.readFileSync(HOOK, 'utf8');
if (raw.includes(SENTINEL)) {
console.log('[r5-sep] already applied, skip');
process.exit(0);
}
if (!raw.includes(OLD) || !raw.includes(HELPER_ANCHOR)) {
console.error('[r5-sep] anchor not found, abort');
process.exit(1);
}
fs.writeFileSync(HOOK + '.bak.r5sep.' + Date.now(), raw, 'utf8');
raw = raw.replace(OLD, NEW);
raw = raw.replace(HELPER_ANCHOR, HELPER_FN + HELPER_ANCHOR);
fs.writeFileSync(HOOK, raw, 'utf8');
console.log('[r5-sep] applied');
} catch (e) {
console.error('[r5-sep] error:', e.message);
process.exit(1);
}