Files
dacli/scripts/check-doc-drift.ts
sushub f403a7e80e import: ssw/dacli@eea0ebc (2026-08-12) 起点版本
本仓 2026-08-12 从 ssw main (192.168.1.18:13300/ssw/ssw-mvp) 的
dacli/ subpath 抽取,作为独立仓托管到 gitea:3000/ssw/dacli.git。

- 工作树为 ssw main dacli subpath 最新版 (110 commit, 08-12)
- 历史未带 ssw main 整体历史(避免大仓污染)
- 此为新仓基线 commit,未来以本仓历史为主
2026-08-12 15:58:06 +08:00

339 lines
15 KiB
TypeScript

/**
* check-doc-drift.ts — 防止 dacli 文档漂移 (DESIGN §6, 2026-07-24)
*
* 跑: npx tsx scripts/check-doc-drift.ts
*
* 检查 3 类文档源:
* 1. DacliHelp.{required, optional} 的 option/arg 名 — 必须与命令树定义匹配
* 2. ANTI_PATTERNS.right/wrong — 必须引用真实存在的 dacli 命令
* 3. DacliHelp.source.{web, ref} 路径 — 必须指向真实文件 (相对 $ccWorkDir)
*
* 退出码: 0=全过 / 1=有 drift (输出问题列表)
*
* 设计 (呼应审计报告 §5 根因 — 无 CI 守门):
* - 命令引用层自洽 (P0 命令全部存在)
* - 但反模式/参数/路径层漂移 (P0-1 enCode / P0-3 F_ / P1-2 Java 路径)
* - 本脚本填补"改了 CLI 文档不报警"的空白
*/
import { existsSync, statSync } from 'node:fs'
import { join, resolve } from 'node:path'
import type { Command } from 'commander'
import { buildProgram, VERSION } from '../src/program.ts'
import { getCcWorkDir } from '../src/core/paths.ts'
import { currentWebSrc } from '../src/core/config.ts' // 2026-08-06 webSrc Task 6: source root 用 cfg.webSrc
import { currentJnpfSrc } from '../src/core/config.ts' // 2026-08-06 jnpfSrc: vendor 源码根
import { ANTI_PATTERNS } from '../src/commands/_anti_patterns.ts'
interface CmdSpec {
path: string
args: string[]
opts: string[]
}
function walkCmd(cmd: Command, prefix: string, out: CmdSpec[]): void {
// 根命令 (program) 的 name() 与 prefix 重复, 跳过; 直接遍历子命令
const path = `${prefix} ${cmd.name()}`.trim()
if (cmd.name() && cmd.name() !== 'dacli') {
const args = ((cmd as unknown as { registeredArguments?: Array<{ name: () => string }> })
.registeredArguments ?? []).map((a) => a.name())
const opts = (cmd.options ?? []).map((o) => o.flags as string)
out.push({ path, args, opts })
}
for (const sub of cmd.commands as Command[]) {
walkCmd(sub, path, out)
}
}
function flattenFlags(opts: string[]): string[] {
// opts 形如 "--fields <json>" / "--cascade" / "-h, --help" → 提取所有 flag
const out: string[] = []
for (const f of opts) {
const parts = f.split(/[ ,]+/)
for (const p of parts) {
if (p.startsWith('-')) out.push(p)
}
}
return out
}
interface Drift {
file: string
line: number
kind: 'arg' | 'opt' | 'command' | 'path' | 'deprecated_marker'
detail: string
}
const program = buildProgram()
// ccWorkDir: CCWORKDIR 环境变量优先, 否则默认 /home/ubuntu/ccWorkDir (web/ jnpf/ docs/ 同级)
// dacliRoot: dacli 源码根目录 (跟脚本同目录)
// 注意: 大小写敏感 — getCcWorkDir() 用 process.env.CCWORKDIR (大写), 跟旧脚本一致
const cc = process.env.CCWORKDIR || process.env.ccWorkDir || '/home/ubuntu/ccWorkDir'
const dacliRoot = resolve(import.meta.dirname, '..') // scripts/check-doc-drift.ts → ../
const cmds: CmdSpec[] = []
walkCmd(program, '', cmds) // 用空 prefix, walkCmd 内部拼 'dacli <name>' (根命令 name='dacli' 会被自动跳过)
const cmdMap = new Map(cmds.map((c) => [c.path, c]))
const drifts: Drift[] = []
// ─────────────────────────────────────────────────────────────
// 检查 1: DacliHelp.{required, optional} 引用的 arg/option 是否真实存在
// ─────────────────────────────────────────────────────────────
import { readdirSync, readFileSync } from 'node:fs'
function findCommandFiles(dir: string): string[] {
const out: string[] = []
for (const e of readdirSync(dir, { withFileTypes: true })) {
if (e.name.startsWith('.')) continue
const p = join(dir, e.name)
if (e.isDirectory()) out.push(...findCommandFiles(p))
else if (e.name.endsWith('.ts')) out.push(p)
}
return out
}
const cmdFiles = findCommandFiles(join(dacliRoot, 'src/commands'))
/** 在文件 content 中第 i 行之前最近的 installHelpHook(...) 调用, 提取第二个参数 (cmd path) */
function findHelpContext(content: string, lineIdx: number): string | null {
// 跨多行匹配: installHelpHook(\n cmd,\n 'cmd-name',\n {
// 反向匹配到 lineIdx 行之前最近一个未配对的 installHelpHook 调用
const before = content.slice(0, content.split('\n').slice(0, lineIdx).join('\n').length)
// 找最近的 'xxx' (cmd name) 出现在 installHelpHook(...) 内
const matches = [...before.matchAll(/installHelpHook(?:WithPatterns)?\s*\(\s*\w+\s*,\s*'([^']+)'\s*,/g)]
return matches.length > 0 ? matches[matches.length - 1][1] : null
}
for (const file of cmdFiles) {
const rel = file.replace(dacliRoot + '/', '')
const content = readFileSync(file, 'utf8')
const lines = content.split('\n')
for (let i = 0; i < lines.length; i++) {
const line = lines[i]
// required: { '<arg>': '...' } 或 { '--flag': '...' } (option-as-required)
// 注: argName 可能含 '|' 表示二选一 (e.g. '--fullName | --ai'), 这种跳过校验
const reqMatch = line.match(/required:\s*\{\s*'([^']+)'\s*:\s*['"]/)
if (reqMatch) {
const argName = reqMatch[1]
// '|' 表示二选一语法 (e.g. '--fullName | --ai'), 跳过
if (argName.includes('|')) continue
const helpName = findHelpContext(content, i)
const cmdPath = helpName ? `dacli ${helpName}` : '(unknown)'
const spec = cmdMap.get(cmdPath)
if (!spec) {
if (helpName) {
drifts.push({ file: rel, line: i + 1, kind: 'command', detail: `DacliHelp required 引用未注册命令: ${cmdPath}` })
}
continue
}
// required 段可引用 arg (<arg>) 或 option (--flag)
if (argName.startsWith('-')) {
// option: 跟 flags 比
const allFlags = flattenFlags(spec.opts)
if (!allFlags.includes(argName)) {
drifts.push({
file: rel, line: i + 1, kind: 'arg',
detail: `${cmdPath}: DacliHelp required 引用 option '${argName}' 但命令实际 flags=${JSON.stringify(spec.opts)}`,
})
}
} else {
// arg: 跟 args 比
const argBase = argName.replace(/^<|>$/g, '').split('|')[0]
const exists = spec.args.some((a) => a.replace(/^<|>$/g, '').split('|')[0] === argBase)
if (!exists) {
drifts.push({
file: rel, line: i + 1, kind: 'arg',
detail: `${cmdPath}: DacliHelp required 引用 arg '${argName}' 但命令实际 args=${JSON.stringify(spec.args)}`,
})
}
}
}
// optional: { '--fields': '...', '--cascade': '...' }
const optMatch = line.match(/optional:\s*\{\s*'(-{1,2}[^']+)'\s*:\s*['"]/)
if (optMatch) {
const flag = optMatch[1]
const helpName = findHelpContext(content, i)
const cmdPath = helpName ? `dacli ${helpName}` : '(unknown)'
const spec = cmdMap.get(cmdPath)
if (!spec) continue
const allFlags = flattenFlags(spec.opts)
if (!allFlags.includes(flag)) {
drifts.push({
file: rel, line: i + 1, kind: 'opt',
detail: `${cmdPath}: DacliHelp optional 引用 '${flag}' 但命令实际 flags=${JSON.stringify(spec.opts)}`,
})
}
}
}
}
// ─────────────────────────────────────────────────────────────
// 检查 2: ANTI_PATTERNS.{wrong, right} 引用的命令是否真实存在
// ─────────────────────────────────────────────────────────────
const cmdPaths = new Set(cmds.map((c) => c.path))
// 抓所有反模式的 right/wrong 段, 提取 `dacli <cmd>` 引用
for (const [group, patterns] of Object.entries(ANTI_PATTERNS)) {
for (const p of patterns) {
const re = /`dacli\s+([a-z][a-z\s]*?)(?:[\s`'|<])/g
for (const text of [p.wrong, p.right]) {
let m: RegExpExecArray | null
while ((m = re.exec(text)) !== null) {
const ref = `dacli ${m[1].trim()}`
if (!cmdPaths.has(ref)) {
drifts.push({
file: 'src/commands/_anti_patterns.ts',
line: 0,
kind: 'command',
detail: `ANTI_PATTERN ${p.id} (${group}) 引用未注册命令: "${ref}"`,
})
}
}
}
}
}
// ─────────────────────────────────────────────────────────────
// 检查 3: DacliHelp.source.{web, ref} 路径是否真实存在
// ─────────────────────────────────────────────────────────────
for (const file of cmdFiles) {
const rel = file.replace(dacliRoot + '/', '')
const content = readFileSync(file, 'utf8')
const lines = content.split('\n')
for (let i = 0; i < lines.length; i++) {
const line = lines[i]
// web: 'web/apps/jnpf-web-apps-main/src/...' — 匹配单引号字符串内容
const webMatch = line.match(/(?:web|ref):\s*'([^']+)'/)
if (!webMatch) continue
const raw = webMatch[1]
// 跳过 url/api/option 路径 (以 http/api/v1 等开头)
if (/^(https?:|\/api|\/oauth|v\d|\/visual|\/blade)/.test(raw)) continue
// 复合路径 (含 ' + '): 只检查第一个 segment (避免拼接字符串误报)
const firstSeg = raw.split(' + ')[0].trim()
// 大括号展开 (e.g. '{index,Form}.vue'): 表示多个文件, 跳过 (脚本无法展开 brace expansion)
if (firstSeg.includes('{') || firstSeg.includes('}')) continue
// 剥离后缀: ' (xxx)' / ':123-456' / ' getInfo()' 等描述性后缀
// 真实路径以扩展名结尾: .vue / .ts / .java / .md 等
// 注意: 路径含中文 (e.g. jnpf/后端/...) — 用 [^\s'(]+ 匹配任意非空白非括号字符
const m = firstSeg.match(/^([^\s'(]+\.[a-z]{1,5})/)
const pathStr = m ? m[1] : firstSeg
// 真实路径
if (pathStr.startsWith('web/apps/jnpf-web-apps-main/') || pathStr.startsWith('jnpf-web-apps-main/')) {
// 2026-08-06 webSrc Task 6: 老 web/apps/jnpf-web-apps-main/... 路径走 cfg.webSrc 作 root
const webSrcRoot = currentWebSrc()
const relPath = pathStr.replace(/^web\/apps\/jnpf-web-apps-main\//, '').replace(/^jnpf-web-apps-main\//, '')
const abs = join(webSrcRoot, relPath)
if (!existsSync(abs)) {
drifts.push({
file: rel, line: i + 1, kind: 'path',
detail: `source 路径不存在: ${pathStr} → ${abs}`,
})
}
} else if (pathStr.startsWith('web/')) {
// 老 web/ 临时前端栈路径 (e.g. 'web/index.html', 'web/src/...'): 仍走 cc/web/
const abs = resolve(cc, pathStr)
if (!existsSync(abs)) {
drifts.push({
file: rel, line: i + 1, kind: 'path',
detail: `source 路径不存在: ${pathStr} → ${abs}`,
})
}
} else if (pathStr.startsWith('jnpf/')) {
// 2026-08-06 jnpfSrc: vendor 源码根用 cfg.jnpfSrc
const jnpfSrcRoot = currentJnpfSrc()
const relPath = pathStr.replace(/^jnpf\//, '')
const abs = join(jnpfSrcRoot, relPath)
if (!existsSync(abs)) {
drifts.push({
file: rel, line: i + 1, kind: 'path',
detail: `source 路径不存在: ${pathStr} → ${abs}`,
})
}
} else if (pathStr.startsWith('docs/')) {
const abs = resolve(cc, pathStr)
if (!existsSync(abs)) {
drifts.push({
file: rel, line: i + 1, kind: 'path',
detail: `source 路径不存在: ${pathStr} → ${abs}`,
})
}
} else if (pathStr.startsWith('src/')) {
// dacli 内部 src 路径 (相对 dacliRoot, 不是 ccWorkDir)
const abs = resolve(dacliRoot, pathStr)
if (!existsSync(abs)) {
drifts.push({
file: rel, line: i + 1, kind: 'path',
detail: `source 路径不存在: ${pathStr} → ${abs}`,
})
}
}
}
}
// ─────────────────────────────────────────────────────────────
// 检查 4: dacli 文档结构 (2026-08-06 dacli 清理)
// - CLAUDE.md ≤ 80 行 (防止再次膨胀)
// - 不含 http://nginx (URL 走 ${webUrl} 占位符)
// - 不含 P*-* 优先级标记 (CLAUDE.md §"文档与注释规范" 自己禁止)
// - 不含 <TODO> 占位符
// - .claude/skills/dacli/SKILL.md 必须存在
// ─────────────────────────────────────────────────────────────
const dacliDocPath = join(dacliRoot, 'CLAUDE.md')
if (!existsSync(dacliDocPath)) {
drifts.push({ file: 'CLAUDE.md', line: 0, kind: 'path', detail: 'CLAUDE.md missing' })
} else {
const dacliDoc = readFileSync(dacliDocPath, 'utf-8')
const dacliDocLines = dacliDoc.split('\n')
if (dacliDocLines.length > 80) {
drifts.push({
file: 'CLAUDE.md', line: 0, kind: 'deprecated_marker',
detail: `CLAUDE.md must be ≤ 80 lines (got ${dacliDocLines.length}). See .claude/skills/dacli/SKILL.md for full content.`,
})
}
if (/http:\/\/nginx/.test(dacliDoc)) {
drifts.push({
file: 'CLAUDE.md', line: 0, kind: 'deprecated_marker',
detail: 'CLAUDE.md must not hardcode http://nginx (use ${webUrl} placeholder)',
})
}
if (/P\d-\d/.test(dacliDoc)) {
drifts.push({
file: 'CLAUDE.md', line: 0, kind: 'deprecated_marker',
detail: 'CLAUDE.md must not contain P*-* priority markers (see "文档与注释规范")',
})
}
if (/<TODO>/.test(dacliDoc)) {
drifts.push({
file: 'CLAUDE.md', line: 0, kind: 'deprecated_marker',
detail: 'CLAUDE.md must not contain <TODO> placeholders',
})
}
}
const skillPath = resolve(cc, '.claude/skills/dacli/SKILL.md')
if (!existsSync(skillPath)) {
drifts.push({ file: 'SKILL.md', line: 0, kind: 'path', detail: `.claude/skills/dacli/SKILL.md must exist (see "文档与注释规范")` })
}
// ─────────────────────────────────────────────────────────────
// 输出
// ─────────────────────────────────────────────────────────────
if (drifts.length === 0) {
console.log(`✅ dacli doc-drift check passed (dacli v${VERSION})`)
console.log(` 扫描 ${cmdFiles.length} 文件 / ${cmds.length} 命令 / ${Object.values(ANTI_PATTERNS).reduce((s, a) => s + a.length, 0)} 反模式`)
process.exit(0)
}
console.error(`❌ dacli doc-drift check FAILED (${drifts.length} issues)\n`)
const byFile = new Map<string, Drift[]>()
for (const d of drifts) {
if (!byFile.has(d.file)) byFile.set(d.file, [])
byFile.get(d.file)!.push(d)
}
for (const [f, list] of byFile) {
console.error(` ${f}`)
for (const d of list) {
const ln = d.line > 0 ? `:${d.line}` : ''
console.error(` [${d.kind}]${ln} ${d.detail}`)
}
}
process.exit(1)