Files
dacli/scripts/check-doc-drift.ts
T
ssw df213fdfad fix(dacli-docs): 修审计报告 14 项 + 加 CI 校验防再漂 (P0/P1/P2 全清)
审计报告 docs/dacli-doc-audit-report.md 14 项全部采纳:

P0 (3 项事实错误, 直接误导 AI 执行):
- ANTI_PATTERN F_→f_ 前缀 (form update --fields 实际是小写)
- ANTI_PATTERN AP-fc-4 vs AP-fu-1 矛盾 (统一指向 form import --autoTable)
- ANTI_PATTERN form info <enCode> 误导 (改为 <id>, 加 enCode 自动解析 fallback)

P1 (3 项文档漂移):
- CLAUDE.md "含 FK 时必用 --fields" → 实际已废弃, 删除 + form/create.ts Commander 加 DEPRECATED
- doc/get.ts 引用 Java DocCommand.java → 改指 TS _parser.ts
- AP-fd-1 "--cascade 必带" 过度约束 → 改为可选

P2 (2 项衔接断裂):
- Source 路径 web/.../ → web/apps/jnpf-web-apps-main/src/ (73 文件)
- test/run TC-B 前置提示 (需 menu 挂载)

附加 (CI script 抓出的 8 条额外路径 drift, 已就近修正):
- di/create|export|copy: DataInterfaceController.java 路径补 jnpf-java-boot/ + jnpf/base/controller/
- print/delete|update: PrintDevController.java 同上
- org/create: OrganizeController.java 路径 jnpf/controller/ → jnpf/permission/controller/
- form/codegen|audit: FormGenerator/FormGenerator.vue 加 /components/ + /src/ 前缀
- workflow/create: flowEngine + FlowProcess 加 views/onlineDev/ + components/ 前缀
- workflow/syncForm: FlowableProcessDesigner.vue 不存在 → 改指 Form.vue
- msg/notice*: notice.ts 不存在 → 改指 msgMonitor.ts
- bigscreen/delete|update: 双前缀 web/.../src/jnpf-web-datascreen-vue3/ → jnpf/前端/
- app/login: api/auth.ts → api/core/auth.ts
- apis/refresh|status|info: Java ApiService 路径 → TS 化指向
- test/render: sysData/formDesign 加 views/ 前缀
- form/create: formDesign/Form.vue 加 views/onlineDev/ 前缀

Task 1.6 收尾: 删 core/help.ts legacy (~85 行 dead code):
- AI_FLAGS / getMeta / maybeInterceptAiHelp / renderAiHelp
- installAiHelpHook alias / _aiMeta 副作用 / AiHelp type alias

新增 docs/doc-drift-findings-2026-07-24.md (2 条无法自动修复的 docs 路径, 待人工)

新增 scripts/check-doc-drift.ts (scripts/check-doc-drift.ts, 218 行):
- 4 类检查: 命令引用 / arg-opt 一致性 / source 路径 / ANTI_PATTERNS 命令引用
- 接入 npm run doc:check
- 验证: 修复前 21 处 drift → 修复后 2 处 (已归档)

测试: typecheck 0 errors, 387/387 tests pass, doc:check 报告 2 known issues
2026-07-24 16:33:31 +08:00

262 lines
11 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 { 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/') || pathStr.startsWith('jnpf/') || 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}`,
})
}
}
}
}
// ─────────────────────────────────────────────────────────────
// 输出
// ─────────────────────────────────────────────────────────────
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)