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,未来以本仓历史为主
This commit is contained in:
sushub committed 2026-08-12 15:58:06 +08:00
commit f403a7e80e
764 files changed
+132974

No files matched your search

+339
View File
@@ -0,0 +1,339 @@
/**
* 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)
+58
View File
@@ -0,0 +1,58 @@
#!/bin/bash
# 检查 dacli/src/** 内违规注释:
# - BS-* / BS-new* / R\d+ / Round\d+
# - jxcj / workSystem / developSystem / tds
# - v0\.\d+\+? 版本号
# - ssw-...-biz / ssw-common 跨语言反向引用
# 命中即报错 (含具体文件:行号).
set -uo pipefail
DACLI_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
SRC_DIR="$DACLI_DIR/src"
PATTERNS=(
'BS-[a-zA-Z]*[0-9]'
'R[0-9]+[a-z]*\b'
'Round[0-9]+'
'\b(jxcj|workSystem|developSystem|tds)\b'
'v0\.[0-9]+[a-z]*\+'
'ssw-[a-z]+-(biz|common)'
)
# 白名单文件 (必须保留 source 引用)
WHITELIST=(
"_anti_patterns.ts"
)
EXIT_CODE=0
for pattern in "${PATTERNS[@]}"; do
while IFS=: read -r file line content; do
if [ -z "$file" ]; then continue; fi
# Check whitelist
basename_file=$(basename "$file")
skip=0
for wl in "${WHITELIST[@]}"; do
if [ "$basename_file" = "$wl" ]; then skip=1; break; fi
done
[ $skip -eq 1 ] && continue
# Only flag comment lines (//, *, or /* ... */)
trimmed=$(echo "$content" | sed 's/^[[:space:]]*//')
if ! echo "$trimmed" | grep -qE '^(//|/\*|\*)'; then
continue # skip code/string lines, only check comments
fi
echo "VIOLATION: $file:$line"
echo " pattern: /$pattern/"
echo " content: $content"
EXIT_CODE=1
done < <(grep -rnE "$pattern" "$SRC_DIR" --include="*.ts" --include="*.tsx" 2>/dev/null || true)
done
if [ $EXIT_CODE -eq 0 ]; then
echo "OK: no violations found"
fi
exit $EXIT_CODE
+10
View File
@@ -0,0 +1,10 @@
#!/bin/bash
# CI 关卡: 全 dacli/ + .claude/ 代码库内 `dacli-ts` 引用应为 0.
set -uo pipefail
WORKDIR="$(cd "$(dirname "${BASH_SOURCE[0]}")/../.." && pwd)"
HITS=$(grep -rn "dacli-ts" "$WORKDIR/dacli/" "$WORKDIR/.claude/" --include="*.md" --include="*.ts" --include="*.tsx" --include="*.sh" 2>/dev/null | grep -v "check_no_dacli_ts_refs" | wc -l)
if [ "$HITS" -gt 0 ]; then
echo "ERROR: $HITS dacli-ts references remain (should be 0)"
exit 1
fi
echo "OK: no dacli-ts references remain"
+138
View File
@@ -0,0 +1,138 @@
#!/usr/bin/env python3
"""Clean violation patterns from dacli source comments.
Targets 6 patterns from check_clean_comments.sh:
1. BS-[a-zA-Z]*[0-9] 2. R[0-9]+[a-z]* 3. Round[0-9]+
4. jxcj|workSystem|developSystem|tds 5. v0.XX.YY+ 6. ssw-XXX-biz/common
Only modifies comment lines (//, *, /*).
"""
import re, sys, os
def clean_line(line: str) -> str:
"""Clean one line. Returns '' to delete the line entirely."""
s = line.strip()
if not (s.startswith('//') or s.startswith('*') or s.startswith('/*')):
return line # code line, don't touch
# --- Pattern 1: BS-* tags ---
# Delete lines that are ONLY a BS tag comment (no other useful content)
if re.match(r'^\s*//\s*BS-\S+\s*(?:fix|修复|修正|强化|兜底)?\s*$', line): return ''
if re.match(r'^\s*\*\s*BS-\S+\s*(?:fix|修复|修正|强化|兜底)?\s*$', line): return ''
# Strip BS tag from mixed-content lines: "// BS-XX fix: real text" -> "// real text"
line = re.sub(r'BS-\S+\s*(?:fix|修复|修正|强化|兜底)?\s*:\s*', '', line)
line = re.sub(r'BS-\S+\s+', '', line) # "// BS-XX explanation" -> "// explanation"
# --- Pattern 2: R tags (R17, R3.3, R13a, etc.) ---
if re.match(r'^\s*//\s*\(?R\d+(?:\.\d+)?[a-z]*\)?\s*$', line): return ''
if re.match(r'^\s*\*\s*\(?R\d+(?:\.\d+)?[a-z]*\)?\s*$', line): return ''
# R17 P1-3: text
line = re.sub(r'R\d+(?:\.\d+)?[a-z]*\s+P\d+-\d+\s*:\s*', '', line)
# (R3.3): text or R3.3: text or R3.3 fix: text
line = re.sub(r'\(?R\d+(?:\.\d+)?[a-z]*\)?\s*(?:fix|修复|修正)?\s*:\s*', '', line)
# (R3.3) text or R3.3 text
line = re.sub(r'\(?R\d+(?:\.\d+)?[a-z]*\)?\s+', '', line)
# --- Pattern 3: Round tags ---
if re.match(r'^\s*//\s*Round\d+\s*$', line): return ''
if re.match(r'^\s*\*\s*Round\d+\s*$', line): return ''
line = re.sub(r'Round\d+\s+BS-\S+\s*:\s*', '', line)
line = re.sub(r'Round\d+\s+', '', line)
# --- Pattern 4: jxcj/workSystem/developSystem/tds ---
# Only in comments. Replace with generic term.
line = re.sub(r'\bjxcj\b', 'app', line)
line = re.sub(r'\bworkSystem\b', 'reference app', line)
line = re.sub(r'\bdevelopSystem\b', 'reference app', line)
line = re.sub(r'\btds\b', 'app', line)
# --- Pattern 5: v0.x+ version markers (handle v0.10, v0.10.1, v0.11h+, v0.21+, etc.) ---
if re.match(r'^\s*//\s*v0\.\d+(?:\.\d+)?[a-z]*\+?\s*$', line): return ''
if re.match(r'^\s*\*\s*v0\.\d+(?:\.\d+)?[a-z]*\+?\s*$', line): return ''
# v0.XX+: text or v0.XX.YY: text or v0.XX fix: text
line = re.sub(r'v0\.\d+(?:\.\d+)?[a-z]*\+?\s*(?:fix|修复|修正)?\s*:', '', line)
# v0.XX+, text or v0.XX+ text or v0.XX+ — text
line = re.sub(r'v0\.\d+(?:\.\d+)?[a-z]*\+?[,]?\s+(?:fix|修复|修正)?\s*', '', line)
# v0.XX+ remaining (at end of line, no text after)
line = re.sub(r'\(?v0\.\d+(?:\.\d+)?[a-z]*\+?\)?', '', line)
# --- Pattern 6: ssw-*-biz/ssw-common ---
# Only in comments. Remove or simplify.
line = re.sub(r'ssw-[a-z]+-biz', 'ssw module', line)
line = re.sub(r'ssw-common', 'shared module', line)
# --- Additional cleanup: dates, B-*, P* tags in comments ---
line = re.sub(r'\(\d{4}-\d{2}-\d{2}\)\s*', '', line)
line = re.sub(r'\(\d{4}-\d{2}-\d{2}\s+[^)]+\)\s*:?\s*', '', line)
line = re.sub(r'\d{4}-\d{2}-\d{2}\s+', '', line)
line = re.sub(r'B-\d+\s*(?:fix|修复)?\s*:\s*', '', line)
line = re.sub(r'P[01]-\d+\s*(?:fix|修复|兜底)?\s*:\s*', '', line)
# --- Cleanup whitespace ---
line = re.sub(r'//\s{2,}', '// ', line)
line = re.sub(r'\*\s{2,}', '* ', line)
# Delete line if it became just empty comment noise
stripped = line.strip()
if stripped in ('//', '// fix:', '// 修复:', '// 修正:', '*', '* fix:', '* 修复:',
'// app', '* app', '// app M1', '* app M1',
'// ssw module', '* ssw module', '// shared module', '* shared module'):
return ''
# Remove leading "修复: " or "fix: " at comment start (when marker was prefix)
line = re.sub(r'^(\s*//\s*)(?:fix:|修复:|修正:|强化:|兜底:)\s*', r'\1', line)
line = re.sub(r'^(\s*\*\s*)(?:fix:|修复:|修正:|强化:|兜底:)\s*', r'\1', line)
# Remove leading ": " after stripping version/date markers at comment start
line = re.sub(r'^(\s*//\s*):\s+', r'\1', line)
line = re.sub(r'^(\s*\*\s*):\s+', r'\1', line)
# After all stripping, if main content is gone, delete
if re.match(r'^\s*//\s*$', line): return ''
if re.match(r'^\s*\*\s*$', line): return ''
# Trim trailing whitespace
line = line.rstrip() + '\n' if line.endswith('\n') else line.rstrip()
return line
def clean_file(filepath: str) -> int:
with open(filepath, 'r', encoding='utf-8') as f:
lines = f.readlines()
new_lines = []
modified = 0
for line in lines:
cleaned = clean_line(line)
if cleaned != line:
modified += 1
if cleaned:
new_lines.append(cleaned)
elif cleaned == '':
continue
else:
new_lines.append(line)
if modified > 0:
with open(filepath, 'w', encoding='utf-8') as f:
f.writelines(new_lines)
return modified
def main():
files = sys.argv[1:]
if not files:
print("Usage: clean_comments.py <file1> [file2 ...]")
sys.exit(1)
total = 0
for f in files:
if not os.path.exists(f):
print(f"SKIP: {f}")
continue
n = clean_file(f)
total += n
print(f" {n:4d} lines: {f}")
print(f"Total: {total} lines modified across {len(files)} files")
if __name__ == '__main__':
main()
+61
View File
@@ -0,0 +1,61 @@
#!/bin/bash
# ensure-tc-b-todo.sh — 确保 TC-B workflow 7 检查有真实待办数据
#
# 背景: dacli test browser --module=workflow 测 workFlow/flowTodo 页面
# 0 待办时 check 1-3 (页面/table/tabs) PASS, check 4-7 (审批 modal) 正确识别无任务
# ≥1 待办时 7/7 PASS, 覆盖完整运行时
#
# 用法: bash scripts/ensure-tc-b-todo.sh [appCode]
set -e
APP_CODE=${1:-testspace}
cd "$(dirname "$0")/.."
alias dacli='npx tsx src/cli.ts'
dacli app switch --appCode="$APP_CODE" >/dev/null 2>&1
dacli app login --account=admin --password=123456 --appCode="$APP_CODE" >/dev/null 2>&1
echo "[ensure-tc-b-todo] appCode=$APP_CODE"
# 调 /workflow/operator/List/1 (镜像 web flowTodo L121 getSearchInfo = {category: 1, ...})
cat > _check_todo.ts <<INNER
import { JnpfClient } from './src/core/client.ts'
async function main() {
const c = await JnpfClient.fromToken({ appCode: '$APP_CODE', baseUrl: 'http://127.0.0.1:30000/api' })
const r: any = await c.get('/workflow/operator/List/1', { currentPage: 1, pageSize: 50 })
const recs = r?.data?.list || []
const out = JSON.stringify({code: r?.code, count: recs.length, sample: recs[0] ? {id: recs[0].id, fullName: recs[0].fullName, flowId: recs[0].flowId} : null})
process.stdout.write(out)
}
main().catch(e => { process.stderr.write('ERR ' + (e as Error).message); process.exit(1) })
INNER
TODO_JSON=$(npx tsx _check_todo.ts 2>/dev/null)
rm -f _check_todo.ts
COUNT=$(echo "$TODO_JSON" | python3 -c "import json,sys; print(json.load(sys.stdin).get('count',0))" 2>/dev/null || echo 0)
SAMPLE=$(echo "$TODO_JSON" | python3 -c "import json,sys; d=json.load(sys.stdin); s=d.get('sample',{}); print(f\"id={s.get('id')} fullName={s.get('fullName')!r} flowId={s.get('flowId')}\")" 2>/dev/null || echo "")
echo " 待办数: $COUNT"
[ -n "$SAMPLE" ] && echo " 样本: $SAMPLE"
if [ "$COUNT" -ge 1 ]; then
echo ""
echo "✓ 待办数 ≥1, TC-B 7 检查 (含 4-7 审批 modal) 可全 PASS"
echo " 跑测试:"
echo " dacli test browser --module=workflow --appCode=$APP_CODE"
exit 0
fi
echo ""
echo "✗ 待办 = 0, TC-B check 4-7 (审批 modal) 将无法验证"
echo ""
echo "恢复待办的方法:"
echo " 方法 1 (testspace 推荐): 切到 testspace, 它有 3 个 admin 待办"
echo " dacli app switch --appCode=testspace"
echo " bash scripts/ensure-tc-b-todo.sh testspace"
echo ""
echo " 方法 2 (其他 app): admin 登录 web 端 → 找一个 workflow → 发起 1 次"
echo " admin 自己的待办出现 1 条后, 再跑 dacli test browser"
echo ""
echo " 方法 3 (API 模拟): launch API 在 FlowParser 状态机里, 完整模拟要拼 formData+flowId+BPMN, 当前未实现"
exit 1
+80
View File
@@ -0,0 +1,80 @@
/**
* gen-command-reference.ts — 从 commander 命令树生成 ssw-loop 参考 (P7, 2026-07-24)
*
* 跑: npx tsx scripts/gen-command-reference.ts
* 产出: .claude/skills/ssw-loop/references/command-reference.generated.md
*
* 目的 (DESIGN §6): ssw-loop 子代理模板手写 dacli 命令语法会漂移 (典型: 缺 --category)。
* 命令树是唯一真相源 — 参考文件自动生成, CLI 一改重跑即同步, 永不漂移。
*/
import { writeFileSync } from 'node:fs'
import { join } from 'node:path'
import type { Command } from 'commander'
import { buildProgram, VERSION } from '../src/program.ts'
import { getCcWorkDir } from '../src/core/paths.ts'
interface CmdDoc {
path: string
desc: string
args: Array<{ name: string; desc: string }>
opts: Array<{ flags: string; desc: string; def?: unknown }>
}
function walk(cmd: Command, prefix: string, out: CmdDoc[]): void {
const subs = cmd.commands as Command[]
for (const c of subs) {
const path = `${prefix} ${c.name()}`.trim()
const args = ((c as any).registeredArguments ?? []).map((a: any) => ({
name: a.name?.() ?? a._name ?? '',
desc: a.description ?? '',
}))
const opts = (c.options ?? []).map((o: any) => ({
flags: o.flags as string,
desc: (o.description as string) ?? '',
def: o.defaultValue,
}))
// 只收叶子命令 (有 action / 无子命令) 和有内容的父命令
if (c.commands.length === 0 || args.length || opts.length) {
out.push({ path, desc: c.description() ?? '', args, opts })
}
if (c.commands.length > 0) walk(c, path, out)
}
}
const program = buildProgram()
const docs: CmdDoc[] = []
walk(program, 'dacli', docs)
const lines: string[] = []
lines.push('<!-- 自动生成, 请勿手改。改命令后跑: npx tsx scripts/gen-command-reference.ts -->')
lines.push(`# dacli 命令参考 (generated, dacli v${VERSION})`)
lines.push('')
lines.push('> ssw-loop 子代理引用本文件而非内联命令语法 (永不漂移)。')
lines.push(`> 共 ${docs.length} 条命令。`)
lines.push('')
let group = ''
for (const d of docs) {
const top = d.path.split(' ')[1] ?? ''
if (top !== group) {
group = top
lines.push(`\n## ${top}\n`)
}
lines.push(`### \`${d.path}\``)
if (d.desc) lines.push(d.desc)
if (d.args.length) {
lines.push('- 参数: ' + d.args.map(a => `\`${a.name}\`${a.desc ? ' — ' + a.desc : ''}`).join('; '))
}
if (d.opts.length) {
lines.push('- 选项:')
for (const o of d.opts) {
const def = (o.def !== undefined && o.def !== false) ? ` (默认 ${JSON.stringify(o.def)})` : ''
lines.push(` - \`${o.flags}\`${o.desc ? ' — ' + o.desc : ''}${def}`)
}
}
lines.push('')
}
const outPath = join(getCcWorkDir(), '.claude/skills/ssw-loop/references/command-reference.generated.md')
writeFileSync(outPath, lines.join('\n'), 'utf-8')
console.log(`✓ 生成 ${docs.length} 条命令 → ${outPath}`)
+38
View File
@@ -0,0 +1,38 @@
#!/bin/sh
# dacli pre-commit hook (P3, 2026-07-24) — 版本受控, 团队共用
#
# 激活: git config core.hooksPath scripts/githooks (或跑 scripts/install-hooks.sh)
#
# 顺序:
# 1. 真质量门 scripts/quality-gate.sh (tsc+vitest+doc:check+validate-baseline+smoke) → FAIL 阻塞 commit
# 2. 仪式门 _gate_webapi (webapi 引用率报告) → 降级 advisory, 永不阻塞
#
# 病根修复 (audit 2026-07-23 §12.4): 之前唯一门是 _gate_webapi, 只查注释出处/引用率,
# 从不跑 tsc/vitest → 48 类型错误 + 20 失败单测能在"全绿"下合入 (假绿).
# 现在编译+单测是硬门, 出处报告只作参考.
ROOT="$(git rev-parse --show-toplevel)"
# 只在 dacli 仓库内跑 (在其他仓库提交时跳过)
if [ ! -f "$ROOT/scripts/quality-gate.sh" ]; then
exit 0
fi
# === 1. 真质量门 (阻塞) ===
sh "$ROOT/scripts/quality-gate.sh"
GATE_EXIT=$?
if [ $GATE_EXIT -ne 0 ]; then
echo ""
echo "❌ dacli 质量门 FAIL (exit=$GATE_EXIT), commit 阻塞"
echo " 修复 tsc/vitest 错误后重试, 或紧急绕过: DACLI_SKIP_GATE=1 git commit ..."
exit 1
fi
# === 2. 仪式门 _gate_webapi (advisory, 不阻塞) ===
if [ -f "$ROOT/src/commands/_gate_webapi.ts" ]; then
echo ""
echo "ℹ️ webapi 镜像引用率报告 (advisory, 不阻塞):"
npx tsx "$ROOT/src/commands/_gate_webapi.ts" 2>/dev/null || true
fi
exit 0
+10
View File
@@ -0,0 +1,10 @@
#!/bin/sh
# 激活 dacli 版本受控 git hooks (P3, 2026-07-24)
# 用法: sh scripts/install-hooks.sh
set -e
ROOT="$(git rev-parse --show-toplevel)"
cd "$ROOT"
chmod +x scripts/githooks/* scripts/quality-gate.sh 2>/dev/null || true
git config core.hooksPath scripts/githooks
echo "✅ core.hooksPath = scripts/githooks (真质量门已激活: tsc+vitest+smoke)"
echo " 验证: 故意加一个类型错误后 git commit 应被阻塞"
+10
View File
@@ -0,0 +1,10 @@
#!/usr/bin/env bash
# proxy-down.sh — 停止本机 nginx (不影响 ssw-admin/jweb/datareport)
set -euo pipefail
if command -v nginx >/dev/null; then
sudo nginx -s stop
else
echo "nginx not found in PATH" >&2
exit 1
fi
echo "nginx down"
+12
View File
@@ -0,0 +1,12 @@
#!/usr/bin/env bash
# proxy-status.sh — 健康检查 (dacli proxy status)
set -euo pipefail
ENDPOINT="${1:-http://nginx/api/system/DbLink/List}"
HTTP_CODE="$(curl -s -o /dev/null -w '%{http_code}' "$ENDPOINT" || echo "000")"
if [[ "$HTTP_CODE" =~ ^2 ]]; then
echo "OK $ENDPOINT ($HTTP_CODE)"
exit 0
else
echo "FAIL $ENDPOINT ($HTTP_CODE)" >&2
exit 1
fi
+41
View File
@@ -0,0 +1,41 @@
#!/usr/bin/env bash
#
# proxy-up.sh — 启动本机 nginx 反代 (dacli proxy up)
#
# 前置: brew install nginx (Intel Mac 路径 /usr/local/, ARM Mac 路径 /opt/homebrew/)
#
set -euo pipefail
# 检测 brew nginx 路径
if command -v nginx >/dev/null; then
: # nginx 已在 PATH
elif [[ -x /usr/local/bin/nginx ]]; then
export PATH="/usr/local/bin:$PATH"
elif [[ -x /opt/homebrew/bin/nginx ]]; then
export PATH="/opt/homebrew/bin:$PATH"
else
echo "nginx not found. Install: brew install nginx" >&2
exit 1
fi
# 解析 brew prefix (兼容 Intel/ARM)
BREW_PREFIX="$(brew --prefix 2>/dev/null || echo /usr/local)"
SERVERS_DIR="${BREW_PREFIX}/etc/nginx/servers"
SSW_CONF_SRC="$(cd "$(dirname "$0")/.." && pwd)/config/nginx/ssw.conf"
mkdir -p "$SERVERS_DIR"
ln -sf "$SSW_CONF_SRC" "$SERVERS_DIR/ssw.conf"
if ! sudo nginx -t; then
echo "nginx config test failed" >&2
exit 1
fi
if pgrep -x nginx >/dev/null; then
sudo nginx -s reload
else
sudo nginx
fi
echo "nginx up: http://nginx/"
echo "verify: curl -fsS http://nginx/api/system/DbLink/List"
+81
View File
@@ -0,0 +1,81 @@
#!/bin/sh
# dacli 真质量门 (P3, 2026-07-24) — 取代"仪式门"作为唯一阻塞门
#
# 六道检查, 呼应 docs/dacliv2/DESIGN.md §1 质量契约:
# [1] tsc --noEmit → 0 错误 (硬阻断)
# [2] vitest run tests/unit → 全绿 (硬阻断)
# [3] doc:check → 0 drift (硬阻断)
# [4] validate-baseline → JNPF 4 层验证闭环 L1-L4 全绿 (硬阻断, P1-16)
# [5] backend smoke → 有 live 后端才跑 (本地 advisory, CI 强制)
# [6] workflow runtime → 5 步梯子 (tdd7 复盘, 跨 app 文档契约, advisory)
#
# 无仪式: 不 grep 魔法串 / 不查注释出处 / 不看行数下限.
# 紧急绕过: DACLI_SKIP_GATE=1 git commit ... (不推荐)
# 复用: pre-commit 与 CI 都调本脚本 (单一真相源).
set -e
ROOT="$(git rev-parse --show-toplevel)"
cd "$ROOT"
if [ "$DACLI_SKIP_GATE" = "1" ]; then
echo "⚠️ dacli 质量门跳过 (DACLI_SKIP_GATE=1)"
exit 0
fi
echo "🔒 dacli 质量门 [1/6] tsc --noEmit ..."
npx tsc --noEmit --project tsconfig.json
echo " ✓ tsc: 0 错误"
echo "🔒 dacli 质量门 [2/6] vitest run tests/unit ..."
npx vitest run tests/unit
echo " ✓ vitest unit: 全绿"
echo "🔒 dacli 质量门 [3/6] doc:check (防文档漂移, 呼应 audit 2026-07-24 §6 治本建议) ..."
if npx tsx scripts/check-doc-drift.ts; then
echo " ✓ doc:check: 0 drift"
else
echo " ✗ doc:check: 有 drift — 阻断 commit"
echo " 详见上方输出, 或跑 npm run doc:check 看详情"
exit 1
fi
echo "🔒 dacli 质量门 [4/6] validate-baseline (JNPF 4 层验证闭环, P1-16) ..."
if sh scripts/validate-baseline.sh >/tmp/dacli-validate-baseline.log 2>&1; then
echo " ✓ validate-baseline: L1-L4 全绿 (23/29 handled + 6 pass-through)"
else
echo " ✗ validate-baseline: 有失败 — 阻断 commit"
echo " 详见 /tmp/dacli-validate-baseline.log 或跑 bash scripts/validate-baseline.sh"
tail -30 /tmp/dacli-validate-baseline.log
exit 1
fi
echo "🔒 dacli 质量门 [5/6] backend smoke ..."
if command -v dacli >/dev/null 2>&1 && dacli form list >/dev/null 2>&1; then
echo " ✓ smoke: dacli form list 返回真实数据"
else
echo " ⚠ smoke 跳过: 无 live 后端/dacli 不在 PATH (本地 advisory; CI 必须强制)"
fi
echo "🔒 dacli 质量门 [6/6] workflow runtime ladder (tdd7 复盘, advisory) ..."
ADVISORY_FAIL=0
WORKFLOW_SSW_LOOP="${WORKFLOW_SSW_LOOP:-/home/ubuntu/ccWorkDir/.claude/skills/ssw-loop/scripts/check_workflow_runtime_contract.sh}"
if [ -d "$ROOT/../docs" ]; then
for app_dir in "$ROOT/../docs"/*/; do
if [ -d "$app_dir" ] && [ -f "$app_dir/summary.md" ]; then
if ! bash "$WORKFLOW_SSW_LOOP" "$app_dir" >/tmp/dacli-gate-w.log 2>&1; then
ADVISORY_FAIL=1
echo " ✗ $app_dir 关卡 W FAIL"
tail -20 /tmp/dacli-gate-w.log
fi
fi
done
else
echo " ⚠ 跳过: 未发现 docs/ 父目录 (advisory, CI 启用时 export WORKFLOW_SSW_LOOP)"
fi
if [ "$ADVISORY_FAIL" = "0" ]; then
echo " ✓ workflow runtime ladder: 全部 docs/{app} PASS"
else
echo " ⚠ 关卡 W 失败: 不阻断 commit (advisory), 补 summary.md § 4.1 5 步证据"
fi
echo "✅ dacli 质量门通过"
+187
View File
@@ -0,0 +1,187 @@
/**
* scripts/seed-kb.ts — 4 域初始数据 (非交互)
*
* 运行: cd dacli && npx tsx scripts/seed-kb.ts
*
* 幂等: 重复运行会清掉旧数据重建 (DELETE 域级联 entries/source_files)
*
* 4 域: dacli, jnpf, ssw-loop, ssw-e2e-test
* 条目数: 每域 12-16, 累计 ~55
*/
import { query, execute, transaction, close, SCHEMA } from '../src/commands/kb/_client.ts';
interface SeedDomain {
domain: string;
title: string;
tags: string[];
keywords: string[];
sources: string[];
entries: Array<{ section: string; content: string; expiresOn?: string }>;
}
const SEED: SeedDomain[] = [
{
domain: 'dacli',
title: 'dacli CLI 工具 KB',
tags: ['dacli', 'cli', 'jnpf'],
keywords: ['dacli form create', 'dacli menu create', 'dacli webapi', 'dacli skill'],
sources: [
'dacli/src/cli.ts',
'dacli/docs/cmd-review/_summary.md',
'dacli/docs/cmd-review/form.md',
'dacli/docs/cmd-review/menu.md',
'dacli/docs/cmd-review/workflow.md',
'dacli/docs/cmd-review/dm.md',
'.claude/skills/dacli/SKILL.md',
'.claude/skills/dacli/references/commands.md',
'.claude/skills/dacli/references/blindspots.md',
],
entries: [
{ section: '业务背景', content: 'dacli 是 JNPF 平台 CLI 入口, 22 父命令/116 子命令, v0.14+ 镜像 web 端 (webapi/)' },
{ section: '关键决策', content: '**decision**: dacli form create --ai 用 NCPF backend (复用 JNPF AI 端点, 不需独立 LLM 配置)' },
{ section: '关键决策', content: '**decision**: dacli webapi 镜像架构 v0.11+ 落地, 0 复刻 web 端 (commit d4506fe)' },
{ section: '关键决策', content: '**decision**: ssw-common 提供 SSW 修复层, dacli 端优先 webapi, fallback 才走 ssw AI 修复端点' },
{ section: '踩坑教训', content: '**lesson**: form create AI 输出截断时失败 → ssw-common JsonRepairUtil 兜底 (BS-新30, commit 038bd98)' },
{ section: '踩坑教训', content: '**lesson**: webapi visualDev.ts import 替换 #/api/request → _defhttp_shim.ts' },
{ section: '踩坑教训', content: '**lesson**: form create 简版 --fields 缺 use*Permission 关键字段 → "Database exception" (BS-48)' },
{ section: '踩坑教训', content: '**lesson**: form create 失败残留 enCode → "Encoding cannot be repeated" (BS-49), 解: 加 _v2 后缀或 form delete 重建' },
{ section: '踩坑教训', content: '**lesson**: menu create --formId 缺主表时走低级模式 --type=3 --urlAddress=model/{enCode} (BS-50)' },
{ section: '踩坑教训', content: '**lesson**: dm list 报 400 "Database connection failed" → dacli app init -- --appCode=X --force-rebuild --restart (BS-C.5.8)' },
{ section: '复用清单', content: 'dacli form create --ai "<描述>" --autoRelease 端到端建表+发布 (v0.13+ 推荐, BS-新28 后唯一推荐路径)' },
{ section: '复用清单', content: 'dacli menu create --formId=<id> --type=3 --urlAddress=model/<enCode> (BS-50 fallback)' },
{ section: '复用清单', content: 'dacli dict dataList 看已有字典, 新建走 enCode/fullName 复检避免 BS-47' },
{ section: '对应技术架构', content: '模块: dacli/src/commands/{form,menu,dm,di,...}; webapi/_loader.ts; webapi/visualDev.ts' },
],
},
{
domain: 'jnpf',
title: 'JNPF 平台基线 KB',
tags: ['jnpf', 'platform', 'baseline'],
keywords: ['scanBasePackages', 'TemplateCodeVue3', 'ServiceImpMarco', 'MybatisPlusConfig'],
sources: [
'.claude/CLAUDE.md',
'jnpf/后端/jnpf-java-boot/jnpf-admin/src/main/java/jnpf/JnpfAdminApplication.java',
'jnpf/静态资源/jnpf-resources/TemplateCodeVue3/PublicMacro/ServiceImpMarco.vm',
'dacli/docs/web-patches/_jnpf-admin-scanBasePackages-ssw.md',
'dacli/docs/web-patches/_codegen-ServiceImpMarco-virtual-field.md',
],
entries: [
{ section: '业务背景', content: 'JNPF 是低代码平台, jnpf/ 目录是官方源代码 (只读), 业务行为调整走 boot/ssw-common/ 扩展层' },
{ section: '关键决策', content: '**decision**: 业务行为调整走 boot/ssw-common/ 扩展层, 不改 jnpf 源码 (CLAUDE.md §代码修改权限)' },
{ section: '关键决策', content: '**decision**: @SpringBootApplication scanBasePackages 加 \'ssw\' 才能扫到 ssw-common bean (BS-14 集中化后由 SswMapperConfig 接管)' },
{ section: '关键决策', content: '**decision**: MybatisPlusConfig @MapperScan 只扫 jnpf.*.mapper / jnpf.mapper / xxl.mapper, 不扫 ssw.*.mapper' },
{ section: '踩坑教训', content: '**lesson**: JNPF 升级几乎每次覆盖 JnpfAdminApplication.java, scanBasePackages 必须重新应用 (web-patches/_jnpf-admin-scanBasePackages-ssw.md)' },
{ section: '踩坑教训', content: '**lesson**: ServiceImpMarco.vm 虚拟字段 (searchList 不在主表) 会输出字面 ${} 到 Java → javac 失败' },
{ section: '踩坑教训', content: '**lesson**: jnpf-common-ai/SendAiMessage.java:148 硬编码 maxTokens=1500 且不修复 LLM 输出 → ssw-common JsonRepairUtil + SswLLMClient + AIRepairService 兜底' },
{ section: '踩坑教训', content: '**lesson**: 表名 f_version 是系统关键字, 禁止使用 (CLAUDE.md §3)' },
{ section: '踩坑教训', content: '**lesson**: 类名 PascalCase 不重复 appCode, 包名已带; web/uniapp 文件名小写' },
{ section: '复用清单', content: 'Java 8 only, 禁止 var/records/text blocks (CLAUDE.md §8)' },
{ section: '复用清单', content: 'Ant Design Vue only, 禁止 Element Plus (CLAUDE.md §7)' },
{ section: '复用清单', content: '业务行为调整走 ssw-common-biz/util/service + ssw-common-controller /api/ssw/... 暴露端点' },
{ section: '对应技术架构', content: 'jnpf 模块: jnpf-common-ai/SendAiMessage.java:148, jnpf-resources/TemplateCodeVue3/PublicMacro/ServiceImpMarco.vm' },
{ section: '对应技术架构', content: '扩展层: boot/ssw-common/ssw-common-biz/config/SswMapperConfig.java + ssw-common-ai/JsonRepairUtil' },
],
},
{
domain: 'ssw-loop',
title: 'ssw-loop 开发循环 KB',
tags: ['ssw-loop', 'workflow', 'process'],
keywords: ['7 阶段', '4 关卡 CI', '子代理派发', 'HTML 产物'],
sources: [
'.claude/skills/ssw-loop/SKILL.md',
'.claude/skills/ssw-loop/references/stages.md',
'.claude/skills/ssw-loop/references/lessons-from-apps.md',
'.claude/skills/ssw-loop/references/anti-patterns.md',
'.claude/skills/ssw-loop/references/html-assets-rules.md',
'.claude/skills/ssw-loop/references/stage-prompts.md',
'.claude/skills/ssw-loop/references/dacli-doc-pattern.md',
'.claude/skills/ssw-loop/references/subagent-must-do.md',
],
entries: [
{ section: '业务背景', content: 'ssw-loop 是 JNPF 应用的 H5 开发主流程, 7 阶段 + 4 关卡 CI (init→design→review→execute→test→summary→iterate)' },
{ section: '关键决策', content: '**decision**: 阶段 7.2 用真实业务数据 CRUD, 不接受 test fixture (BS-109~111)' },
{ section: '关键决策', content: '**decision**: HTML 产物放 docs/{app}/, 不入 git (CI 关卡 G 警告)' },
{ section: '关键决策', content: '**decision**: 零应用信息硬编码, 所有上下文通过 dacli app context --json / dacli form info <enCode> 动态获取' },
{ section: '关键决策', content: '**decision**: 主 SKILL.md 只保留规则/用法, 详细参考放 references/ (SKILL.md > 800 行 → 抽出低频内容)' },
{ section: '踩坑教训', content: '**lesson**: 子代理派发要给出完整上下文, 否则盲点扩散 (anti-patterns.md §2.6)' },
{ section: '踩坑教训', content: '**lesson**: 应用特定信息(form ID / 菜单结构 / DB 凭证 / 字段名)写 docs/{app_code}/ 不入 CLAUDE.md / skill' },
{ section: '踩坑教训', content: '**lesson**: 复现的盲点先在测试场 (testspace) 跑通验证, 再固化到 dacli / skill, 禁止用 developSystem/workSystem 验证' },
{ section: '踩坑教训', content: '**lesson**: AI prompt 是 JSON 生成器, JSON 是契约 (MEMORY ai-prompt-is-just-json-generator)' },
{ section: '踩坑教训', content: '**lesson**: 改 web 端 Vue 组件要保存到 dacli/docs/web-patches/<comp>.md (MEMORY feedback-web-patch-docs)' },
{ section: '复用清单', content: 'dacli form create + menu create + di create 一气呵成, 不手写 schema' },
{ section: '复用清单', content: '派子代理前给完整上下文: appCode + dbLinkId + existingEnCodes + 关键 skill 路径' },
{ section: '复用清单', content: 'HTML 产物: docs/{app}/{design|testcase|plan|debug|summary}.html + assets/' },
{ section: '对应技术架构', content: '7 阶段: init → design → review → execute → test → summary → iterate; 4 关卡 CI: A/B/C/D' },
],
},
{
domain: 'ssw-e2e-test',
title: 'ssw-e2e-test 测试模式 KB',
tags: ['e2e', 'playwright', 'testing'],
keywords: ['TC-A', 'TC-B', 'webapi', 'real-data'],
sources: [
'.claude/skills/ssw-e2e-test/SKILL.md',
'.claude/skills/ssw-e2e-test/references/tc-ab-real-test.md',
],
entries: [
{ section: '业务背景', content: 'ssw-e2e-test 是 Playwright + dacli 的端到端测试 skill, TC-A/B/C 分级' },
{ section: '关键决策', content: '**decision**: TC-B 构造/查找/触发/注入走 webapi (快), 验证走浏览器 (真实) (MEMORY feedback-tc-b-webapi-setup)' },
{ section: '关键决策', content: '**decision**: test fixture 不能当业务验证, 必须真实数据 (dacli-test-run-real-data-upgrade-2026-06-28)' },
{ section: '关键决策', content: '**decision**: 默认 ON real-data + keep-data + 关联表真实 ID lookup + 跨表 join + 业务规则' },
{ section: '踩坑教训', content: '**lesson**: test fixture 当业务验证 → 后续真实场景全失败 (BS-109)' },
{ section: '踩坑教训', content: '**lesson**: 不重复已有基础设施 (MEMORY feedback-no-duplicate-infra)' },
{ section: '踩坑教训', content: '**lesson**: API 替换必须服务 AI 痛点, 不为替换而替换 (MEMORY feedback-api-replace-must-serve-ai)' },
{ section: '复用清单', content: 'TC-B 复用 webapi 镜像能力, 跨表 join, 关联表真实 ID lookup' },
{ section: '复用清单', content: 'webapi 构造数据 + 浏览器验证两步走, 测试快且真实' },
{ section: '复用清单', content: 'playwright Node.js: cd $ccWorkDir/test && npx playwright test --project=chromium' },
{ section: '对应技术架构', content: 'TC-A: 浏览器纯操作; TC-B: webapi 构造 + 浏览器验证; TC-C: 跨进程多端协同' },
{ section: '对应技术架构', content: 'webapi 模块: webapi/_loader.ts (动态加载 web 端模块), webapi/visualDev.ts (form schema 生成)' },
],
},
];
async function seed() {
console.log(`Seeding ${SEED.length} domains into ${SCHEMA}...\n`);
await transaction(async (client) => {
// 1. 清旧 seed 数据 (幂等)
for (const s of SEED) {
await client.query(`DELETE FROM ${SCHEMA}.domains WHERE domain = $1`, [s.domain]);
}
console.log('✓ Cleared old seed data\n');
// 2. 插 4 域 + source_files + entries
for (const s of SEED) {
const { rows: [d] } = await client.query<{ id: number }>(
`INSERT INTO ${SCHEMA}.domains (domain, title, tags, keywords) VALUES ($1, $2, $3, $4) RETURNING id`,
[s.domain, s.title, s.tags, s.keywords]
);
console.log(`✓ Domain '${s.domain}' (id=${d.id}) — ${s.entries.length} entries, ${s.sources.length} sources`);
for (const path of s.sources) {
await client.query(
`INSERT INTO ${SCHEMA}.source_files (domain_id, path, kind) VALUES ($1, $2, 'source')`,
[d.id, path]
);
}
for (let i = 0; i < s.entries.length; i++) {
const e = s.entries[i];
await client.query(
`INSERT INTO ${SCHEMA}.entries (domain_id, section, content, sort_order, expires_on)
VALUES ($1, $2, $3, $4, $5)`,
[d.id, e.section, e.content, i, e.expiresOn || null]
);
}
}
});
console.log(`\n=== Seeded ${SEED.length} domains, ${SEED.reduce((s, d) => s + d.entries.length, 0)} entries ===`);
await close();
}
seed().catch(e => {
console.error('✗ Seed failed:', e);
process.exit(1);
});
+76
View File
@@ -0,0 +1,76 @@
#!/bin/bash
# dacli/scripts/validate-baseline.sh — CI gate for JNPF antipattern baseline
#
# Runs all 4 validation layers + vitest regression suite.
# Exit 0 = all pass; Exit 1 = one or more failures
#
# 注: 原 L5 (Static Prompt A/B Comparison) 已移除 (2026-07-29).
# jnpf7 是临时对照目录, 该层不再需要. tools/prompt-ab-static.ts 已删除.
#
# Usage:
# bash scripts/validate-baseline.sh
# bash scripts/validate-baseline.sh --skip-llm # skip tests that need base_ai
set -e
cd "$(dirname "$0")/.."
SKIP_LLM=false
[ "$1" = "--skip-llm" ] && SKIP_LLM=true
echo "=========================================="
echo " dacli 4-Layer Validation Baseline"
echo "=========================================="
echo ""
# Layer 1.1 — VisualAiModel schema
echo "── L1.1: VisualAiModel JSON Schema ──"
if [ -f "/tmp/dacli-baseline-form.json" ]; then
npx tsx tools/validate-form-schema.ts /tmp/dacli-baseline-form.json || echo " ⚠ skipped (no baseline file)"
else
echo " ⚠ skipped (no /tmp/dacli-baseline-form.json)"
fi
echo ""
# Layer 1.2 — BPMN XSD
echo "── L1.2: BPMN XSD ──"
if [ -f "/tmp/dacli-baseline-bpmn.xml" ]; then
npx tsx tools/validate-bpmn-xsd.ts /tmp/dacli-baseline-bpmn.xml || echo " ⚠ skipped (no baseline file)"
else
echo " ⚠ skipped (no /tmp/dacli-baseline-bpmn.xml)"
fi
echo ""
# Layer 1.3 — JNPF antipattern scanner
echo "── L1.3: JNPF Antipattern Static Scanner ──"
npx tsx tools/scan-antipatterns.ts
echo ""
# Layer 2.1 — Prompt rules coverage
echo "── L2.1: Prompt Rules Coverage ──"
npx tsx tools/check-prompt-rules.ts
echo ""
# Layer 2.2 — Parser coverage
echo "── L2.2: Parser Coverage ──"
# check-parsers.ts (P0-9): reads config/components-whitelist.yaml.
# Exits 0 when 6 documented pass-through components lack refs; exits 1 only on a
# real regression (a 'handled' component losing coverage). Let set -e propagate.
npx tsx tools/check-parsers.ts
echo ""
# Layer 3 — Vitest regression tests
echo "── L3: Vitest Regression Tests ──"
npx vitest run tests/unit/bs117-regression.test.ts tests/unit/bpmn-bs-regression.test.ts tests/unit/antipattern-output.test.ts
echo ""
# Layer 4 — Historical BS replay
echo "── L4: Historical BS Case Replay ──"
npx tsx tools/replay-history.ts
echo ""
echo "=========================================="
echo " ✓ All baseline validations completed"
echo "=========================================="
echo ""
echo "See: docs/dacli-validation-baseline-2026-07-27.md"