/** * _gate_webapi.ts — CI 关卡 G: webapi 镜像架构回归防御 (v3.0+ 新增, regression audit) * * 目的: 防止新代码继续走"经验复刻"老路, 自动检查 dacli 代码的 webapi 镜像质量 * * 检查项 (3 大维度): * 1. **webapi 引用率**: 每个命令目录的 webapi 引用次数 / 文件数 * - app/dict/menu/form/workflow 等应有 webapi 引用 * - apis/doc 等元工具 0 webapi 是正确的 (但要标记) * * 2. **_validate.ts 镜像精度**: * - "镜像 web" 注释数 / 文件数 (应 ≥ 4) * - 精确行号引用率 (L + 数字 应出现在注释里) * - BS-56 ENCODE_REGEXP 常量复用 (防止硬编码正则) * * 3. **回归盲点扫描**: * - 找出 webapi 引用 = 0 的命令目录 (标记 KEEP/REFACTOR/DEPRECATE) * - 找出没有"镜像 web"注释的 _validate.ts * - 找出缺 ENCODE_REGEXP 但用了 enCode 校验的文件 * * 退出码: * 0: PASS (无违规) * 1: FAIL (有违规, 阻塞 commit) — 排除已知故意 FAIL * 2: WARN (有提示但不阻塞) * * 已知故意 FAIL 白名单 (v3.0+, regression audit §4.4 防御误报): * - **di**: web 端 di/Form.vue:172-178 明确"无 formValidate 正则, 只必填+maxlength" * (架构差异, 不是 dacli 漏校验) * * 用法: * - CI: `npx tsx src/commands/_gate_webapi.ts` * - Hook: dacli/.git/hooks/pre-commit 自动跑 * - 跳过: DACLI_SKIP_GATE=1 环境变量 / git config dacli.gate.enabled false * * 注意: 这是 v3.0+ regression audit §4.4 建议的"CI 关卡 G 自动防御机制". */ import { getCcWorkDir } from '../core/paths.ts' import { readdirSync, readFileSync, statSync } from 'fs' import { join, basename } from 'path' const DACLI_COMMANDS_DIR = `${getCcWorkDir()}/dacli/src/commands` const WEBAPI_DIR = `${getCcWorkDir()}/dacli/src/webapi` /** 元工具 (正确地无 webapi 引用) */ const META_TOOLS = ['apis', 'doc', 'kb'] as const /** 已知"经验复刻"高风险目录 (web 端无对应 Form.vue, 应该标注) */ const EXPERIENCE_REPLICA_CANDIDATES = ['storage', 'integration'] as const /** * v0.15+ 已知故意 FAIL 白名单 (历史已知, 2026-07-02 强化): * - workflow has 1 cmd without webapi (selector): P0 cmd, web 端无 selector API 端点 * - role has 1 cmd without webapi (selector): P0 cmd, web 端 selector 走 menu 不是 role * - report has 1 cmd without webapi (templates): v0.14 templates 老命令, 推 v0.16 重构 * - workflow has 1 cmd without webapi (approve): BS-新26 v0.14 战时 cmd, web 走 task 不是 approve * - role has 1 cmd without webapi (assign): v0.15+ 走 webapi/roleRelation (P0-9) * * 这些 FAIL 算 WARN, 不阻塞 commit. v0.15+ 强化目标: 持续减少这个列表. */ const V015_KNOWN_NO_WEBAPI: Record = { // workflow/role/report 的 selector/templates/approve/assign 后续 webapi 化时移除 } /** * v3.0+ 已知故意 FAIL 白名单 (BS-47 类架构差异, 不是 dacli 漏校验) * * 格式: { cmd → 原因描述 } * - 列入白名单的 FAIL 会被转为 WARN, 不阻塞 commit * - 添加新白名单前必须明确 web 端架构差异, 避免掩盖真实问题 * - 白名单中的 FAIL 在输出中明确标注 "(已知)", 避免误读 */ const KNOWN_FALSE_POSITIVES: Record = { di: 'web 端 di/Form.vue:172-178 明确"无 formValidate 正则, 只必填+maxlength" (架构差异, 不是 dacli 漏校验)', } interface CommandCheck { cmd: string fileCount: number webapiRefs: number /** 0 = 元工具 / 1 = 高风险 / 2 = 正常 */ category: 'meta' | 'high-risk' | 'normal' status: 'PASS' | 'WARN' | 'FAIL' /** 已知故意 FAIL 原因 (白名单命中时填充) */ knownReason?: string } interface ValidateCheck { cmd: string hasValidate: boolean mirrorComments: number hasLineRef: boolean hasEncodeRegexp: boolean hasEnCodeField: boolean status: 'PASS' | 'WARN' | 'FAIL' | 'N/A' /** 已知故意 FAIL 原因 (白名单命中时填充) */ knownReason?: string } interface GateReport { commands: CommandCheck[] validates: ValidateCheck[] overall: 'PASS' | 'WARN' | 'FAIL' summary: { totalCommands: number passCommands: number warnCommands: number failCommands: number /** 已知故意 FAIL 数 (白名单命中, 算 WARN, 不阻塞) */ knownFalsePositives: number /** 真实 FAIL 数 (排除白名单, 阻塞 commit) */ realFailures: number totalValidates: number mirrorCommentRate: string encodeRegexpRate: string } recommendations: string[] } /** 读目录下所有 .ts 文件 (递归) */ function listTsFiles(dir: string): string[] { const files: string[] = [] try { for (const f of readdirSync(dir)) { const p = join(dir, f) const st = statSync(p) if (st.isDirectory()) { files.push(...listTsFiles(p)) } else if (f.endsWith('.ts') && !f.startsWith('_')) { files.push(p) } } } catch { // 目录不存在 } return files } /** 读文件全文 */ function readText(p: string): string { try { return readFileSync(p, 'utf-8') } catch { return '' } } /** 是否在已知故意 FAIL 白名单中 */ function getKnownReason(cmd: string): string | undefined { return KNOWN_FALSE_POSITIVES[cmd] } /** 检查单个命令目录 */ function checkCommandDir(cmd: string): CommandCheck { const dir = join(DACLI_COMMANDS_DIR, cmd) const files = listTsFiles(dir).filter((p) => !basename(p).startsWith('_')) const allText = files.map(readText).join('\n') const webapiRefs = (allText.match(/from\s+['"][^'"]*webapi\//g) || []).length const fileCount = files.length let category: CommandCheck['category'] = 'normal' if ((META_TOOLS as readonly string[]).includes(cmd)) category = 'meta' else if ((EXPERIENCE_REPLICA_CANDIDATES as readonly string[]).includes(cmd)) category = 'high-risk' let status: CommandCheck['status'] = 'PASS' const knownReason = getKnownReason(cmd) if (category === 'meta' && webapiRefs > 0) { // 元工具但有 webapi 引用 (可疑, 可能过度镜像) status = 'WARN' } else if (category === 'high-risk' && webapiRefs === 0) { // 高风险但无 webapi 引用 (经验复刻, 应有警告注释) status = 'WARN' } else if (category === 'normal' && webapiRefs === 0 && fileCount > 2) { // 正常命令无 webapi 引用 (主命令无 webapi 是 P0) status = 'FAIL' // v3.0+ 白名单: 已知故意 FAIL 转 WARN, 不阻塞 commit if (knownReason) status = 'WARN' } return { cmd, fileCount, webapiRefs, category, status, knownReason } } /** 检查单个 _validate.ts */ function checkValidate(cmd: string): ValidateCheck { const validateFile = join(DACLI_COMMANDS_DIR, cmd, '_validate.ts') const text = readText(validateFile) const hasValidate = text.length > 0 if (!hasValidate) { return { cmd, hasValidate: false, mirrorComments: 0, hasLineRef: false, hasEncodeRegexp: false, hasEnCodeField: false, status: 'N/A', } } // 1. "镜像 web" 注释数 const mirrorComments = (text.match(/镜像\s*web/g) || []).length // 2. 精确行号引用 (L + 数字 模式) const hasLineRef = /\bL\s*\d+/i.test(text) // 3. BS-56 ENCODE_REGEXP 复用 (本地声明 OR import 共享 _encode_validator) const hasEncodeRegexp = /const\s+ENCODE_REGEXP\b/.test(text) || /from\s+['"][^'"]*_encode_validator[^'"]*['"]/.test(text) // 4. 该文件处理 enCode 字段? const hasEnCodeField = /\benCode\b/.test(text) const knownReason = getKnownReason(cmd) let status: ValidateCheck['status'] = 'PASS' if (mirrorComments === 0 && cmd !== 'storage' && cmd !== 'integration') { // 没有"镜像 web" 注释 (除已知无 Form.vue 的命令) status = 'WARN' } if (hasEnCodeField && !hasEncodeRegexp) { // 处理 enCode 但没复用 ENCODE_REGEXP (硬编码正则) status = 'FAIL' // v3.0+ 白名单: 已知故意 FAIL 转 WARN, 不阻塞 commit if (knownReason) status = 'WARN' } if (mirrorComments >= 4 && hasLineRef && hasEncodeRegexp) { status = 'PASS' } return { cmd, hasValidate, mirrorComments, hasLineRef, hasEncodeRegexp, hasEnCodeField, status, knownReason, } } /** 主检查函数 */ export function runWebapiGate(): GateReport { // 1. 检查命令目录 const commandDirs = readdirSync(DACLI_COMMANDS_DIR) .filter((f) => { const p = join(DACLI_COMMANDS_DIR, f) return statSync(p).isDirectory() && !f.startsWith('_') }) .sort() const commands = commandDirs.map(checkCommandDir) // 2. 检查 _validate.ts const validates = commandDirs .map(checkValidate) .filter((v) => v.hasValidate) // 3. 汇总 const passCommands = commands.filter((c) => c.status === 'PASS').length const warnCommands = commands.filter((c) => c.status === 'WARN').length const failCommands = commands.filter((c) => c.status === 'FAIL').length const knownFalsePositives = commands.filter((c) => c.knownReason).length const totalValidates = validates.length const mirrorWithComments = validates.filter((v) => v.mirrorComments > 0).length const encodeWithRegexp = validates.filter((v) => v.hasEncodeRegexp).length // 真实 FAIL: 排除白名单命中 (白名单命中的 FAIL 已转 WARN) const realFailures = commands.filter((c) => c.status === 'FAIL').length + validates.filter((v) => v.status === 'FAIL').length // overall: 真实 FAIL 才阻塞, 否则根据 WARN 决定 const overall: GateReport['overall'] = realFailures > 0 ? 'FAIL' : warnCommands > 0 || validates.some((v) => v.status === 'WARN') ? 'WARN' : 'PASS' // 4. 改进建议 const recommendations: string[] = [] const realFailCmds = commands.filter((c) => c.status === 'FAIL') if (realFailCmds.length > 0) { recommendations.push( `**P0**: ${realFailCmds.map((c) => c.cmd).join(', ')} 无 webapi 引用 — 应走 webapi 镜像 (参考 app/list.ts 的重构模式)`, ) } const knownFalsePositiveCmds = commands.filter((c) => c.knownReason && c.status === 'WARN') if (knownFalsePositiveCmds.length > 0) { recommendations.push( `**已知故意 FAIL (白名单)**: ${knownFalsePositiveCmds.map((c) => c.cmd).join(', ')} — 不阻塞 commit, 详见 KNOWN_FALSE_POSITIVES (v3.0+ regression audit §4.4)`, ) } const noMirrorValidate = validates.filter((v) => v.mirrorComments === 0 && v.status === 'WARN') if (noMirrorValidate.length > 0) { recommendations.push( `**P1**: ${noMirrorValidate.map((v) => v.cmd).join(', ')} _validate.ts 缺"镜像 web" 注释 — 至少标注 web 端 Form.vue 镜像源`, ) } const realFailRegexp = validates.filter( (v) => v.hasEnCodeField && !v.hasEncodeRegexp && v.status === 'FAIL', ) if (realFailRegexp.length > 0) { recommendations.push( `**BS-56**: ${realFailRegexp.map((v) => v.cmd).join(', ')} 用了 enCode 但未复用 ENCODE_REGEXP — 改用统一常量 (防止正则硬编码)`, ) } if (recommendations.length === 0) { recommendations.push('✅ 所有维度 PASS, webapi 镜像架构健康') } return { commands, validates, overall, summary: { totalCommands: commandDirs.length, passCommands, warnCommands, failCommands, knownFalsePositives, realFailures, totalValidates, mirrorCommentRate: totalValidates > 0 ? `${mirrorWithComments}/${totalValidates}` : 'N/A', encodeRegexpRate: totalValidates > 0 ? `${encodeWithRegexp}/${totalValidates}` : 'N/A', }, recommendations, } } /** CLI 入口 (被 cli.ts 顶层 _gate_webapi 注册) */ export function printGateReport(verbose = false): number { const report = runWebapiGate() // 表头 console.log(`\n=== CI 关卡 G: webapi 镜像架构回归防御 (v3.0+) ===\n`) // 命令目录 console.log('【维度 1】命令 webapi 引用率:') console.log(' cmd files webapi_refs category status') console.log(' ' + '-'.repeat(80)) for (const c of report.commands) { const catStr = c.category.padEnd(12) const knownTag = c.knownReason ? ' (已知)' : '' const statusStr = statusEmoji(c.status).padEnd(2) + c.status + knownTag console.log( ` ${c.cmd.padEnd(20)}${String(c.fileCount).padEnd(7)}${String(c.webapiRefs).padEnd(13)}${catStr}${statusStr}`, ) } // _validate.ts console.log('\n【维度 2】_validate.ts 镜像精度:') console.log(' cmd mirror_comments line_ref encode_regexp status') console.log(' ' + '-'.repeat(80)) for (const v of report.validates) { if (v.status === 'N/A') continue const knownTag = v.knownReason ? ' (已知)' : '' const statusStr = statusEmoji(v.status).padEnd(2) + v.status + knownTag console.log( ` ${v.cmd.padEnd(20)}${String(v.mirrorComments).padEnd(17)}${(v.hasLineRef ? 'yes' : 'no').padEnd(10)}${(v.hasEncodeRegexp ? 'yes' : 'no').padEnd(15)}${statusStr}`, ) } // 汇总 console.log('\n【汇总】') console.log(` 命令: PASS ${report.summary.passCommands} / WARN ${report.summary.warnCommands} / FAIL ${report.summary.failCommands} / 总 ${report.summary.totalCommands}`) console.log(` _validate.ts: 总 ${report.summary.totalValidates}, "镜像 web" 注释率 ${report.summary.mirrorCommentRate}, ENCODE_REGEXP 复用率 ${report.summary.encodeRegexpRate}`) console.log(` 白名单命中: ${report.summary.knownFalsePositives} 个 (已知故意 FAIL, 不阻塞 commit)`) console.log(` 真实 FAIL: ${report.summary.realFailures} 个 (排除白名单, 阻塞 commit)`) console.log(` 总体: ${statusEmoji(report.overall)} ${report.overall}`) // 建议 console.log('\n【改进建议】') for (const r of report.recommendations) { console.log(` ${r}`) } // 白名单详情 (有命中时显示) const knownItems = [ ...report.commands.filter((c) => c.knownReason), ...report.validates.filter((v) => v.knownReason), ] if (knownItems.length > 0) { console.log('\n【白名单详情 (已知故意 FAIL)】') for (const item of knownItems) { console.log(` ${item.cmd}:`) console.log(` ${item.knownReason}`) } } console.log('') // 退出码: 真实 FAIL 才阻塞 if (report.overall === 'FAIL') return 1 if (report.overall === 'WARN') return 2 return 0 } function statusEmoji(status: string): string { if (status === 'PASS') return '✅' if (status === 'WARN') return '⚠️' if (status === 'FAIL') return '❌' return ' ' }// Run if executed directly if (import.meta.url === `file://${process.argv[1]}`) { process.exit(printGateReport()); }