/** * commands/_selfcheck.ts — v0.11d+ 强制纪律自检脚本 * * 镜像 plan §4.1 + CLAUDE.md §2.7.1 自检清单 (8 项): * 1. web 端源文件引用 (注释含 web/...) * 2. 后端源文件引用 (注释含 jnpf/...) * 3. web 行号标注 (L\\d+ 或 :L\\d+) * 4. 后端行号标注 * 5. MEMORY 记录 (drift 防御) * 6. --help 描述含 "镜像" * 7. SKILL.md 同步 (含 v0.11d+ 段) * 8. commit msg 含 web 行号 (git log) * * 用法: dacli selfcheck [more files...] * 输出: 8 项 pass/fail 报告, 失败 exit 2 * * 设计原则 (2026-06-26 v0.11d+): * - 跟 _precheck / _blindspot_guards / _dirty_check 模式一致 * - 失败: 列出缺什么, 不阻断 (warn 模式), 严重错误才 exit 2 * - AI 场景补充 (不是 web 镜像) */ import { Command } from 'commander' import * as fs from 'node:fs' import * as path from 'node:path' import { installAiHelpHook } from '../core/help.ts' import { log, printJson } from '../core/log.ts' import { execSync } from 'node:child_process' interface CheckResult { name: string ok: boolean message: string } const CCWORKDIR = process.env.CCWORKDIR || '/home/ubuntu/ccWorkDir' // ⚠️ MEMORY 可能在 ~root/.claude 或 ~/.claude, 都试 const MEMORY_DIR_CANDIDATES = [ `${CCWORKDIR}/.claude/projects/-home-ubuntu-ccWorkDir/memory`, '/root/.claude/projects/-home-ubuntu-ccWorkDir/memory', `${process.env.HOME || ''}/.claude/projects/-home-ubuntu-ccWorkDir/memory`, ].filter(Boolean) const SKILLS_DIR = `${CCWORKDIR}/.claude/skills` /** 找到第一个存在的 MEMORY_DIR */ function resolveMemoryDir(): string { for (const dir of MEMORY_DIR_CANDIDATES) { try { if (fs.existsSync(dir) && fs.statSync(dir).isDirectory()) { return dir } } catch { // ignore } } return MEMORY_DIR_CANDIDATES[0] // fallback } /** 8 项检查函数 */ const checks: Array<{ name: string; fn: (file: string) => CheckResult }> = [ { name: '1. web 源文件引用 (注释含 web/...)', fn: (file) => { const basename = path.basename(file) // _*.ts 通用文件不要求 if (basename.startsWith('_')) { return { name: 'web 源文件引用', ok: true, message: '⊘ 通用文件 (_*.ts), 不要求' } } const content = fs.readFileSync(file, 'utf-8') const has = /web\/\S+\.vue|web\/\S+\.ts|web\/\S+\//.test(content) return { name: 'web 源文件引用', ok: has, message: has ? '✓ 找到 web 端源文件引用' : '✗ 注释缺 web 端源文件引用 (例: web/.../Form.vue)', } }, }, { name: '2. 后端源文件引用 (注释含 jnpf/...)', fn: (file) => { const basename = path.basename(file) if (basename.startsWith('_')) { return { name: '后端源文件引用', ok: true, message: '⊘ 通用文件 (_*.ts), 不要求' } } const content = fs.readFileSync(file, 'utf-8') // 检测后端源文件引用 (允许扩展名 .java 或目录) const has = /jnpf\/\S+\.java|jnpf\/\S+\/[\w]+\.java/.test(content) return { name: '后端源文件引用', ok: has, message: has ? '✓ 找到 jnpf 后端源文件引用' : '✗ 注释缺 jnpf 后端源文件引用 (例: jnpf/.../Controller.java)', } }, }, { name: '3. web 行号标注 (L\\d+)', fn: (file) => { const basename = path.basename(file) if (basename.startsWith('_')) { return { name: 'web 行号标注', ok: true, message: '⊘ 通用文件 (_*.ts), 不要求' } } const content = fs.readFileSync(file, 'utf-8') // 匹配行号: L123 / L123-456 / (L123) / :L123 const matches = content.match(/L\d+(?:[-:]\d+)?/g) || [] return { name: 'web 行号标注', ok: matches.length >= 2, message: matches.length >= 2 ? `✓ 找到 ${matches.length} 个 web 行号标注 (${matches.slice(0, 3).join(', ')}${matches.length > 3 ? '...' : ''})` : `✗ 缺 web 行号标注 (镜像 web 端: L123 / L123-456 / (L123) / :L123)`, } }, }, { name: '4. 后端行号标注 (L\\d+)', fn: (file) => { const basename = path.basename(file) if (basename.startsWith('_')) { return { name: '后端行号标注', ok: true, message: '⊘ 通用文件 (_*.ts), 不要求' } } const content = fs.readFileSync(file, 'utf-8') // 复用 web 匹配, 后端行号也用 L\d+ 格式 const matches = content.match(/L\d+(?:[-:]\d+)?/g) || [] // 检查是否有 jnpf/ 后跟 L\d+ 模式 const hasBackendLineRef = /jnpf\/[\w/.]+(?:L\d+|:L\d+|\.java:\d+)/.test(content) return { name: '后端行号标注', ok: matches.length >= 2 && hasBackendLineRef, message: hasBackendLineRef ? `✓ 找到 jnpf 后端行号标注` : `✗ 缺 jnpf 后端行号标注 (镜像后端: jnpf/.../Controller.java:L123)`, } }, }, { name: '5. MEMORY 记录 (drift 防御)', fn: (file) => { // 检查是否有对应 memory 文件 const basename = path.basename(file, '.ts') // 排除通用文件 (_precheck, _blindspot_guards 等) if (basename.startsWith('_')) { return { name: 'MEMORY 记录', ok: true, message: '⊘ 通用文件 (_*.ts), 不要求 MEMORY 单独记录', } } // 检查 MEMORY 目录是否有提及此文件 (支持两种命名约定) // 1. dacli-{cmdName}-*.md (v0.11d+ form 风格) // 2. dacli-{domain}-{cmdName}-*.md (v0.11d+ menu/dm/dict/workflow/role/di 风格) const cmdName = basename.split('.')[0] // 拿 "create" / "update" 等 // 推断 domain (file path 上一级) const parts = file.split('/commands/')[1]?.split('/') || [] const domain = parts[0] // form / menu / dm / etc. const tryPrefixes = [ `dacli-${cmdName}-`, `dacli-${domain}-${cmdName}-`, `dacli-${domain}-${cmdName}`, // 简化 ] try { const memDir = resolveMemoryDir() const files = fs.readdirSync(memDir) const found = files.find((f) => tryPrefixes.some((p) => f.startsWith(p))) return { name: 'MEMORY 记录', ok: !!found, message: found ? `✓ 找到 MEMORY 记录: ${found} (in ${memDir})` : `✗ 缺 MEMORY 记录 (期望命名之一: ${tryPrefixes.join(' 或 ')})`, } } catch (e) { return { name: 'MEMORY 记录', ok: false, message: `✗ MEMORY 目录读取失败: ${(e as Error).message}`, } } }, }, { name: '6. --help 描述含 "镜像"', fn: (file) => { const basename = path.basename(file) if (basename.startsWith('_')) { return { name: '--help 描述含 "镜像"', ok: true, message: '⊘ 通用文件 (_*.ts), 不要求' } as CheckResult } const content = fs.readFileSync(file, 'utf-8') // 找 installAiHelpHook 调用的 purpose 字段 const match = content.match(/purpose:\s*['"`]([^'"`]+)['"`]/) const has: boolean = !!(match && match[1].includes('镜像')) return { name: '--help 描述含 "镜像"', ok: has, message: has ? `✓ --help purpose 含 "镜像": "${match![1]}"` : '✗ --help purpose 缺 "镜像" 关键词 (AI 用户需要知道这是镜像)', } }, }, { name: '7. SKILL.md 同步 (含 v0.11d+ 段)', fn: (file) => { const basename = path.basename(file) if (basename.startsWith('_')) { return { name: 'SKILL.md 同步', ok: true, message: '⊘ 通用文件 (_*.ts), 不要求' } } // 根据文件路径推断对应技能 const parts = file.split('/commands/')[1]?.split('/') || [] if (parts.length < 1) { return { name: 'SKILL.md 同步', ok: true, message: '⊘ 非 commands 子目录, 跳过', } } const cmdDir = parts[0] // 推断 skill 目录 const skillMap: Record = { form: 'form-development', menu: 'menu-configuration', dm: 'data-management', workflow: 'workflow-development', dict: 'dict-management', di: 'data-interface', role: 'code-generator', // role 没有独立 skill, 归 code-generator } const skillDir = skillMap[cmdDir] if (!skillDir) { return { name: 'SKILL.md 同步', ok: true, message: `⊘ 未映射技能 (cmdDir=${cmdDir}), 跳过`, } } const skillPath = path.join(SKILLS_DIR, skillDir, 'SKILL.md') try { const content = fs.readFileSync(skillPath, 'utf-8') const hasV0d = /v0\.11d\+/.test(content) return { name: 'SKILL.md 同步', ok: hasV0d, message: hasV0d ? `✓ ${skillDir}/SKILL.md 含 v0.11d+ 段` : `✗ ${skillDir}/SKILL.md 缺 v0.11d+ 段 (AI 用户查不到 step machine 段)`, } } catch { return { name: 'SKILL.md 同步', ok: false, message: `✗ ${skillDir}/SKILL.md 不存在 (cmdDir=${cmdDir})`, } } }, }, { name: '8. commit msg 含 web 行号 (git log)', fn: (file) => { const basename = path.basename(file) if (basename.startsWith('_')) { return { name: 'commit msg 含 web 行号', ok: true, message: '⊘ 通用文件 (_*.ts), 不要求' } } // 检查最近 5 个 commit msg 是否含 web/.../L\d+ 模式 try { // 找包含此文件的最近 commit const relPath = file.replace(`${CCWORKDIR}/`, '') const logOut = execSync(`git log --oneline -5 -- ${relPath}`, { encoding: 'utf-8' }) if (!logOut.trim()) { return { name: 'commit msg 含 web 行号', ok: true, message: '⊘ 文件未 commit 过, 跳过 (新文件)', } } // 取第一个 (最近) commit 的完整 msg const firstHash = logOut.split('\n')[0].split(' ')[0] const fullMsg = execSync(`git log -1 --format=%B ${firstHash}`, { encoding: 'utf-8' }) const has = /web\/[\w/.]+\.?(?:vue|ts).*?L\d+/.test(fullMsg) || /L\d+.*?web\/[\w/.]+/.test(fullMsg) return { name: 'commit msg 含 web 行号', ok: has, message: has ? `✓ 最近 commit msg 含 web 行号标注` : `✗ 最近 commit msg 缺 web 行号 (建议: feat(...): ... (镜像 web/.../Form.vue L123))`, } } catch (e) { return { name: 'commit msg 含 web 行号', ok: false, message: `✗ git 命令失败: ${(e as Error).message?.slice(0, 80)}`, } } }, }, // ====== v0.11e+ Phase C3 新增 7 项检查 (8 → 15) ====== { name: '9. 完整设计检查 (multi-step 注释)', fn: (file) => { const basename = path.basename(file) if (basename.startsWith('_')) { return { name: '完整设计检查', ok: true, message: '⊘ 通用文件 (_*.ts), 不要求' } as CheckResult } // 仅检查 create.ts (其它文件无需 multi-step) if (basename !== 'create.ts' && basename !== 'update.ts' && basename !== 'typecreate.ts' && basename !== 'typeupdate.ts') { return { name: '完整设计检查', ok: true, message: '⊘ 非 create/update 命令, 跳过' } as CheckResult } const content = fs.readFileSync(file, 'utf-8') // 检查 step 0 / step 1 / step 2 等多步骤注释 const stepMatches = content.match(/step\s+\d+/gi) || [] const hasMultiStep = stepMatches.length >= 2 return { name: '完整设计检查', ok: hasMultiStep, message: hasMultiStep ? `✓ 找到 ${stepMatches.length} 个 step 注释 (multi-step 完整设计)` : `✗ 缺 multi-step 注释 (建议 step 0/1/2 标识, 镜像 web Form.vue handleNext 多步骤)`, } }, }, { name: '10. 错误反馈检查 (含 field 级输出)', fn: (file) => { const basename = path.basename(file) if (basename.startsWith('_')) { return { name: '错误反馈检查', ok: true, message: '⊘ 通用文件 (_*.ts), 不要求' } as CheckResult } const content = fs.readFileSync(file, 'utf-8') // 检查 formatErrorLine 调用 (A1 错误反馈统一格式) const hasFormat = /formatErrorLine\s*\(/.test(content) return { name: '错误反馈检查', ok: hasFormat, message: hasFormat ? '✓ 找到 formatErrorLine 调用 (v0.11e+ A1 错误反馈统一格式)' : '✗ 缺 formatErrorLine 调用 (catch 后端错误时应输出 [step N name] field: CODE - message)', } }, }, { name: '11. 授权检查 (含 auto-authorize 选项)', fn: (file) => { const basename = path.basename(file) if (basename.startsWith('_')) { return { name: '授权检查', ok: true, message: '⊘ 通用文件 (_*.ts), 不要求' } as CheckResult } if (basename !== 'create.ts' && basename !== 'codegen.ts') { return { name: '授权检查', ok: true, message: '⊘ 非 create/codegen 命令, 跳过' } as CheckResult } const content = fs.readFileSync(file, 'utf-8') // 检查 auto-authorize/autoMenu/Actions/Module 任一 (B2 授权) const hasAuth = /auto-authorize|autoMenu|Actions\/Module|auto-bind-user/.test(content) return { name: '授权检查', ok: hasAuth, message: hasAuth ? '✓ 找到 auto-authorize/autoMenu/Actions/Module (v0.11e+ B2 授权)' : '✗ 缺 auto-authorize 选项 (v0.11e+ B2 应镜像 web 自动授权当前角色)', } }, }, { name: '12. 数据流检查 (含 --diff/--dry-run 选项)', fn: (file) => { const basename = path.basename(file) if (basename.startsWith('_')) { return { name: '数据流检查', ok: true, message: '⊘ 通用文件 (_*.ts), 不要求' } as CheckResult } if (basename !== 'update.ts' && basename !== 'typeupdate.ts' && basename !== 'dataupdate.ts') { return { name: '数据流检查', ok: true, message: '⊘ 非 update 命令, 跳过' } as CheckResult } const content = fs.readFileSync(file, 'utf-8') // 检查 --diff / --dry-run / applyDataFlowOpts 任一 (B3 数据流) const hasDataFlow = /--diff|--dry-run|applyDataFlowOpts|dirtyCheck/.test(content) return { name: '数据流检查', ok: hasDataFlow, message: hasDataFlow ? '✓ 找到 --diff/--dry-run/dirtyCheck (v0.11e+ A2/B3 数据流)' : '✗ 缺 --diff/--dry-run/dirtyCheck (v0.11e+ B3 应支持数据流选项)', } }, }, { name: '13. web 状态镜像 (state 注释)', fn: (file) => { const basename = path.basename(file) if (basename.startsWith('_')) { return { name: 'web 状态镜像', ok: true, message: '⊘ 通用文件 (_*.ts), 不要求' } as CheckResult } const content = fs.readFileSync(file, 'utf-8') // 检查是否有 web reactive state 注释 const hasStateComment = /reactive\s+state|镜像 web.*state|state\.formConf|state\.tables|state\.isReload/.test(content) return { name: 'web 状态镜像', ok: hasStateComment, message: hasStateComment ? '✓ 找到 web reactive state 镜像注释' : '✗ 缺 web reactive state 镜像注释 (建议: 镜像 web state mutation 模式)', } }, }, { name: '14. AI 友好检查 (--ai-help/--source)', fn: (file) => { const basename = path.basename(file) if (basename.startsWith('_')) { return { name: 'AI 友好检查', ok: true, message: '⊘ 通用文件 (_*.ts), 不要求' } as CheckResult } const content = fs.readFileSync(file, 'utf-8') // 检查 installAiHelpHook + source 字段 const hasAiHelp = /installAiHelpHook/.test(content) const hasSource = /source:\s*\{/.test(content) return { name: 'AI 友好检查', ok: hasAiHelp && hasSource, message: hasAiHelp && hasSource ? '✓ 找到 installAiHelpHook + source 字段 (AI 学习材料完整)' : `✗ 缺 installAiHelpHook 或 source 字段 (AI 调试时查不到 web/backend 权威源)`, } }, }, { name: '15. 错误码分类 (EXIST/FA/SYS/VS prefix 映射)', fn: (file) => { const basename = path.basename(file) if (basename.startsWith('_')) { return { name: '错误码分类', ok: true, message: '⊘ 通用文件 (_*.ts), 不要求' } as CheckResult } const content = fs.readFileSync(file, 'utf-8') // 检查 enhanceFromBackend 调用 (A1 错误码分类) 或 code: 'EXISTxxx' 字面量 const hasErrorCode = /enhanceFromBackend|classify\s*\(|code:\s*['"]EXIST\d{3}['"]|code:\s*['"]VS\d{3}['"]|code:\s*['"]WF\d{3}['"]|code:\s*['"]FA\d{3}['"]/.test(content) return { name: '错误码分类', ok: hasErrorCode, message: hasErrorCode ? '✓ 找到错误码分类 (EXIST/FA/VS/SYS/WF prefix)' : '✗ 缺错误码分类 (应使用 enhanceFromBackend() 或 code: "EXISTxxx")', } }, }, ] export function buildSelfCheckCommand(): Command { const cmd = new Command('selfcheck') .description('v0.11e+ 强制纪律自检 (15 项: 8 镜像 + 5 机制 + 2 漂移防御). AI 场景补充, 非 web 镜像') .argument('', '要检查的 TS 文件路径 (可多个)') .option('--json', '原始 JSON 输出', false) .action(async (files: string[], opts: { json?: boolean }) => { log.info(`=== dacli selfcheck (v0.11d+) ===`) log.info(`检查 ${files.length} 个文件, ${checks.length} 项检查`) log.info('') let totalPass = 0 let totalFail = 0 const allResults: Array<{ file: string; results: CheckResult[] }> = [] for (const file of files) { if (!fs.existsSync(file)) { log.warn(`✗ 文件不存在: ${file}`) totalFail++ allResults.push({ file, results: [{ name: 'file exists', ok: false, message: '文件不存在' }], }) continue } log.info(`📄 ${file}`) const results: CheckResult[] = [] for (const check of checks) { try { const r = check.fn(file) results.push(r) if (r.ok) { log.info(` ✓ ${r.message}`) totalPass++ } else { log.warn(` ✗ ${r.message}`) totalFail++ } } catch (e) { const errMsg = (e as Error).message?.slice(0, 100) log.error(` 💥 ${check.name} 异常: ${errMsg}`) totalFail++ results.push({ name: check.name, ok: false, message: `异常: ${errMsg}`, }) } } log.info('') allResults.push({ file, results }) } log.info(`=== 总结: ${totalPass} pass, ${totalFail} fail ===`) if (totalFail > 0) { log.error('💡 修复建议: 镜像 CLAUDE.md §2.7.1 8 项自检清单') log.error(' 1. 读 web 端源文件 + 后端源文件, 标注行号') log.error(' 2. 写 _validate_X.ts 镜像 step machine') log.error(' 3. 写 MEMORY 记录设计意图 + 反模式') log.error(' 4. --help 加 "镜像" 关键词') log.error(' 5. SKILL.md 加 v0.11d+ 段') } if (opts.json) { printJson({ summary: { totalPass, totalFail }, files: allResults, }) return } // 严重失败 exit 2 (≥3 项失败 = 纪律不到位) if (totalFail >= 3) { process.exit(2) } }) installAiHelpHook(cmd, { purpose: 'v0.11d+ 强制纪律自检 (镜像 CLAUDE.md §2.7.1 自检清单 8 项). AI 场景补充, 非 web 镜像. 防止改前漏读 web/backend 源码 / 漏写 MEMORY / --help 漏 "镜像" / SKILL.md 漏 v0.11d+ 段.', required: { '': 'TS 文件路径 (可多个)' }, optional: { '--json': '原始 JSON 输出' }, example: [ 'dacli selfcheck src/commands/menu/create.ts', 'dacli selfcheck src/commands/form/_validate.ts src/commands/dm/_validate.ts', '# 在 commit 前跑: dacli selfcheck $(git diff --name-only HEAD | grep .ts)', ], source: { ref: 'CLAUDE.md §2.7.1 8 项自检清单 (镜像 web 端行号 / 后端校验 / 文档同步 / 强制纪律)', api: 'dacli/docs/v0.11d+-complete-mirror-plan.md §4.1', }, notes: [ '8 项检查: web 源文件引用 / 后端源文件引用 / web 行号 / 后端行号 / MEMORY 记录 / --help 镜像 / SKILL.md 同步 / commit msg 行号', '镜像 CLAUDE.md §2.7.1 自检清单 (强制纪律自动化)', 'AI 场景补充 (类似 Phase 3.1 dirty checking), 非 web 镜像', '失败 ≥3 项 exit 2, 少失败 warn 不阻断 (区分严重程度)', '在 commit 前跑: dacli selfcheck $(git diff --name-only HEAD | grep .ts)', ], }) return cmd }