feat(dacli): Tier 1 固化 3 项 — hook + idempotent + health check
回应用户"还有哪些要 dacli 固化的" — 落地 Tier 1 全部 3 件:
[1/3] Pre-commit hook 加 doc:check (scripts/quality-gate.sh)
- 质量门从 [1/3] tsc + [2/3] vitest + [3/3] smoke → [1/4]+[2/4]+[3/4]+[4/4]
- 新 [3/4] doc:check (npx tsx scripts/check-doc-drift.ts) — 防回归
- 任何 doc drift 立即阻断 commit (呼应 audit 2026-07-24 §6 治本建议)
- DACLI_SKIP_GATE=1 紧急绕过 (与现有 tsc/vitest 一致)
- 注释同步更新 pre-commit (scripts/githooks/pre-commit)
[2/3] form create --reuse-if-exists (src/commands/form/create.ts)
- 防 BS-新131 AI agent 反复跑场景返工
- 命中已存在 enCode → 跳过创建, 返回现有 id + state (state=0/1 都支持)
- 抽 findExistingForm() 纯函数 + 6 个单元测试 (exact match, 不 fuzzy)
- 新选项: --reuse-if-exists (默认 false, 向后兼容)
[3/3] app status 加 3 项深度健康检查 (src/commands/app/status.ts)
- dbPing: GET /system/DataSource/{dbLinkId}/Actions/TestConnection (防 BS-E14)
· 404/405 视为 skip (端点可能未暴露, 不阻断)
· dbLinkId=0 视为 skip (主库, 不需测试)
- llmPing: GET /visualdev/ai/health (防 --ai 路径 LLM 挂掉)
· 404 视为 skip (端点可能未部署 health)
- menuIntegrity: /oauth/CurrentUser menuList.urlAddress 不空 (防 BS-56 SPA 404)
· 任意 fail → 退出码 1 (AI agent 应停下修复)
- 人类可读模式 + --json 模式都展示 deepChecks 数组
- 实战验证: tdd8 跑出 menuIntegrity 真问题 (4 项 menu urlAddress 空)
验证:
- typecheck 0 errors
- vitest 39 文件 / 393 tests pass (含 6 新 reuse-if-exists 测试)
- doc:check 0 drift
- 实战: dacli app status 跑出 3 项深度检查 + 1 个真 backend finding
测试未跑 (需要 live JNPF):
- form create --reuse-if-exists 端到端 (受 auto-classifier 误判限制)
This commit is contained in:
1 parent
afc2a88105
commit
87a246ed9e
5 files changed
+230
-4
No files matched your search
@@ -4,7 +4,7 @@
|
||||
# 激活: git config core.hooksPath scripts/githooks (或跑 scripts/install-hooks.sh)
|
||||
#
|
||||
# 顺序:
|
||||
# 1. 真质量门 scripts/quality-gate.sh (tsc+vitest+smoke) → FAIL 阻塞 commit
|
||||
# 1. 真质量门 scripts/quality-gate.sh (tsc+vitest+doc:check+smoke) → FAIL 阻塞 commit
|
||||
# 2. 仪式门 _gate_webapi (webapi 引用率报告) → 降级 advisory, 永不阻塞
|
||||
#
|
||||
# 病根修复 (audit 2026-07-23 §12.4): 之前唯一门是 _gate_webapi, 只查注释出处/引用率,
|
||||
|
||||
+10
-1
@@ -27,7 +27,16 @@ echo "🔒 dacli 质量门 [2/3] vitest run tests/unit ..."
|
||||
npx vitest run tests/unit
|
||||
echo " ✓ vitest unit: 全绿"
|
||||
|
||||
echo "🔒 dacli 质量门 [3/3] backend smoke ..."
|
||||
echo "🔒 dacli 质量门 [3/4] 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/4] backend smoke ..."
|
||||
if command -v dacli >/dev/null 2>&1 && dacli form list >/dev/null 2>&1; then
|
||||
echo " ✓ smoke: dacli form list 返回真实数据"
|
||||
else
|
||||
|
||||
+125
-2
@@ -3,6 +3,11 @@
|
||||
*
|
||||
* v0.11e+ Phase E: 加 --check-system (默认 ON) — 检测 base_system 是否含 appCode
|
||||
* 解决盲点: dacli app clear 后旧版返 '未登录' / token 错误, 用户不知道 app 已删
|
||||
*
|
||||
* v2.3+ Tier 1.4 (2026-07-24): 加 3 项健康检查
|
||||
* - dbPing (dbLinkId 真实可达, 防 "Database connection failed" BS-E14)
|
||||
* - llmPing (NCPF backend LLM 端点可达, 防 --ai 路径 10s 后才发现 LLM 挂掉)
|
||||
* - menuIntegrity (menuList.urlAddress 不空, 防 SPA 路由 404)
|
||||
*/
|
||||
import { Command } from 'commander'
|
||||
import { loadToken, getTokenPath, currentBaseUrl } from '../../core/config.ts'
|
||||
@@ -15,6 +20,80 @@ import {
|
||||
formatSystemMissingForHuman,
|
||||
} from './_check_system.ts'
|
||||
|
||||
/**
|
||||
* 健康检查 3 项: DB / LLM / menu 完整性
|
||||
* 返回数组 — 每项 { name, ok, durationMs, error? }
|
||||
*/
|
||||
async function runHealthChecks(c: JnpfClient | null): Promise<Array<{ name: string; ok: boolean; durationMs: number; error?: string }>> {
|
||||
const out: Array<{ name: string; ok: boolean; durationMs: number; error?: string }> = []
|
||||
|
||||
// [1] DB ping — 通过 dbLinkId 走 GET /api/system/DataSource/{id}/Actions/TestConnection (web 端镜像)
|
||||
// 防 BS-E14 "Database connection failed" — 阶段 1 早期发现
|
||||
{
|
||||
const t0 = Date.now()
|
||||
try {
|
||||
if (!c) throw new Error('no client')
|
||||
const dbLinkId = c.dbLinkId
|
||||
if (!dbLinkId || dbLinkId === '0') {
|
||||
out.push({ name: 'dbPing', ok: true, durationMs: 0, error: 'skip (dbLinkId=0 主库, 不需测试)' })
|
||||
} else {
|
||||
await c.get(`/system/DataSource/${dbLinkId}/Actions/TestConnection`)
|
||||
out.push({ name: 'dbPing', ok: true, durationMs: Date.now() - t0 })
|
||||
}
|
||||
} catch (e) {
|
||||
// 404/405 也算 skip (端点可能不存在/不容许 GET; 不阻断 status). 仅 5xx 算 fail
|
||||
const msg = (e as Error).message
|
||||
if (msg.includes('404') || msg.includes('405')) {
|
||||
out.push({ name: 'dbPing', ok: true, durationMs: Date.now() - t0, error: 'skip (端点未暴露或不容许 GET, 不阻断)' })
|
||||
} else {
|
||||
out.push({ name: 'dbPing', ok: false, durationMs: Date.now() - t0, error: msg.slice(0, 120) })
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// [2] NCPF LLM ping — 走 /api/visualdev/ai/health (轻量端点; 后端挂掉时 503)
|
||||
// 防 --ai 路径: NCPF backend LLM 挂了 → 15s 后才发现, 浪费 AI agent 时间
|
||||
{
|
||||
const t0 = Date.now()
|
||||
try {
|
||||
if (!c) throw new Error('no client')
|
||||
await c.get('/visualdev/ai/health')
|
||||
out.push({ name: 'llmPing', ok: true, durationMs: Date.now() - t0 })
|
||||
} catch (e) {
|
||||
// 404 也算 ok (端点可能没部署 health, 不阻断). 仅 5xx/timeout 算 fail
|
||||
const msg = (e as Error).message
|
||||
if (msg.includes('404')) {
|
||||
out.push({ name: 'llmPing', ok: true, durationMs: Date.now() - t0, error: 'skip (端点未部署 health, 不阻断)' })
|
||||
} else {
|
||||
out.push({ name: 'llmPing', ok: false, durationMs: Date.now() - t0, error: msg.slice(0, 120) })
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// [3] menu integrity — 当前 user 的 menuList.urlAddress 不空 (SPA 路由防 404)
|
||||
// 已知 BS-56: 跨 app 引用未传 --urlAddress 时 menuList 缺 urlAddress → SPA 404
|
||||
{
|
||||
const t0 = Date.now()
|
||||
try {
|
||||
if (!c) throw new Error('no client')
|
||||
const r = await c.get<{ menuList?: Array<{ urlAddress?: string; enCode?: string }> } | any>('/oauth/CurrentUser', { isBackend: 0 })
|
||||
// c.get 返回 { code, data, msg } 结构, data 含 menuList (跟 test/browser.ts 同模式)
|
||||
const data = (r as any).data || r
|
||||
const list = data?.menuList || []
|
||||
const empty = list.filter((m: { urlAddress?: string }) => !m.urlAddress || m.urlAddress.trim() === '')
|
||||
if (empty.length > 0) {
|
||||
out.push({ name: 'menuIntegrity', ok: false, durationMs: Date.now() - t0, error: `${empty.length} 项 menu urlAddress 为空 (例: ${empty[0].enCode})` })
|
||||
} else {
|
||||
out.push({ name: 'menuIntegrity', ok: true, durationMs: Date.now() - t0 })
|
||||
}
|
||||
} catch (e) {
|
||||
out.push({ name: 'menuIntegrity', ok: false, durationMs: Date.now() - t0, error: (e as Error).message?.slice(0, 120) })
|
||||
}
|
||||
}
|
||||
|
||||
return out
|
||||
}
|
||||
|
||||
export function buildAppStatusCommand(): Command {
|
||||
const cmd = new Command('status')
|
||||
.description('显示当前登录状态 + baseUrl + appCode + dbLinkId + token 路径 + base_system 存在性')
|
||||
@@ -29,6 +108,18 @@ export function buildAppStatusCommand(): Command {
|
||||
// status 跑前先 HEAD 检查, 不通时给 nohup 重启指引
|
||||
const baseUrl = t?.baseUrl || currentBaseUrl()
|
||||
const healthR = await healthCheck(baseUrl)
|
||||
|
||||
// v2.3+ Tier 1.4 (2026-07-24): 3 项深度健康检查 (DB / LLM / menu 完整性)
|
||||
// 仅在已登录 + baseUrl OK 时跑 (否则前置已 fail, 不浪费调用)
|
||||
let deepChecks: Array<{ name: string; ok: boolean; durationMs: number; error?: string }> = []
|
||||
if (t && healthR.ok) {
|
||||
try {
|
||||
const c = await JnpfClient.fromToken({})
|
||||
deepChecks = await runHealthChecks(c)
|
||||
} catch (e) {
|
||||
log.debug(`深度健康检查初始化失败: ${(e as Error).message}`)
|
||||
}
|
||||
}
|
||||
if (opts.json) {
|
||||
// JSON 模式: 把 health 结果合并到输出
|
||||
}
|
||||
@@ -69,8 +160,10 @@ export function buildAppStatusCommand(): Command {
|
||||
error: healthR.error,
|
||||
durationMs: healthR.durationMs,
|
||||
},
|
||||
deepChecks: deepChecks.map((c) => ({ name: c.name, ok: c.ok, durationMs: c.durationMs, error: c.error })),
|
||||
}, null, 2))
|
||||
if (systemExists === false || !healthR.ok) process.exit(1)
|
||||
const allDeepOk = deepChecks.every((c) => c.ok)
|
||||
if (systemExists === false || !healthR.ok || !allDeepOk) process.exit(1)
|
||||
return
|
||||
}
|
||||
|
||||
@@ -108,10 +201,35 @@ export function buildAppStatusCommand(): Command {
|
||||
log.error('⚠ JNPF 不可达, 后续 form/menu/dict 操作会失败. 见上面修复指引')
|
||||
process.exit(1)
|
||||
}
|
||||
|
||||
// v2.3+ Tier 1.4 (2026-07-24): 3 项深度检查结果展示
|
||||
if (deepChecks.length > 0) {
|
||||
log.info('')
|
||||
log.info('🔬 深度健康检查 (v2.3+):')
|
||||
for (const c of deepChecks) {
|
||||
const status = c.ok ? '✓' : '✗'
|
||||
const dur = `${c.durationMs}ms`
|
||||
const err = c.error ? ` — ${c.error}` : ''
|
||||
if (c.ok) {
|
||||
log.info(` ${status} ${c.name.padEnd(16)} ${dur}${err}`)
|
||||
} else {
|
||||
log.error(` ${status} ${c.name.padEnd(16)} ${dur}${err}`)
|
||||
}
|
||||
}
|
||||
const allOk = deepChecks.every((c) => c.ok)
|
||||
if (!allOk) {
|
||||
log.error('')
|
||||
log.error('⚠ 深度检查失败, 部分功能可能不可用:')
|
||||
log.error(' - dbPing fail → 数据库连不上, dm/form 写入会失败 (BS-E14)')
|
||||
log.error(' - llmPing fail → --ai 路径会 15s 后才发现, 浪费时间')
|
||||
log.error(' - menuIntegrity fail → SPA 路由可能 404 (BS-56)')
|
||||
process.exit(1)
|
||||
}
|
||||
}
|
||||
})
|
||||
|
||||
installHelpHook(cmd, {
|
||||
purpose: '显示当前登录状态. 写脚本前先跑一下确认登录态',
|
||||
purpose: '显示当前登录状态 + baseUrl 健康 + 3 项深度健康检查 (DB/LLM/menu 完整性). 写脚本前先跑一下',
|
||||
optional: {
|
||||
'--json': '以 JSON 输出',
|
||||
'--no-check-system': '跳过 base_system 存在性检测 (默认 ON)',
|
||||
@@ -121,6 +239,11 @@ export function buildAppStatusCommand(): Command {
|
||||
'**v0.11e+ Phase E**: 默认检测 base_system 是否含当前 appCode',
|
||||
' 缺失时返明确错误 + 重建命令, 退出码 1 (旧版返间接错误, 用户困惑)',
|
||||
' AI 看到 systemExists=false 应立即停下, 不要继续 form/menu CRUD',
|
||||
'**v2.3+ Tier 1.4**: 3 项深度检查',
|
||||
' - dbPing: GET /system/DataSource/{dbLinkId}/Actions/TestConnection (防 BS-E14)',
|
||||
' - llmPing: GET /visualdev/ai/health (防 --ai 路径 LLM 挂掉)',
|
||||
' - menuIntegrity: /oauth/CurrentUser menuList.urlAddress 不空 (防 BS-56)',
|
||||
' 任何 fail 退出码 1, AI agent 应停下修复',
|
||||
],
|
||||
})
|
||||
|
||||
|
||||
@@ -71,6 +71,8 @@ interface CreateOpts {
|
||||
ai?: string
|
||||
/** columnList 命名规范: auto | snake | f_prefix (默认 snake). 见 --column-naming 选项 (create.ts:315) */
|
||||
columnNaming?: string
|
||||
/** Tier 1.2 (2026-07-24): enCode 已存在时返回现有 form id (跳过创建). 防 AI agent 反复跑场景 (BS-新131) */
|
||||
reuseIfExists?: boolean
|
||||
/** internal: AI/table 分支构建好的 formData 缓存, 供后续 smartProps/持久化复用 (非 CLI 选项) */
|
||||
__aiBuildFormData?: { formData: string }
|
||||
/** 5.10.2 AI 推荐字段 — 自然语言描述, 平台 LLM 推荐单字段, 不建表单 */
|
||||
@@ -106,6 +108,21 @@ export function shouldRunFinalSmartProps(opts: CreateOpts): boolean {
|
||||
return Boolean((opts as any).__aiBuildFormData)
|
||||
}
|
||||
|
||||
/**
|
||||
* Tier 1.2 (2026-07-24): --reuse-if-exists 命中的判定函数 (纯函数, 单元测试覆盖)
|
||||
* 输入 enCode + web 端 form list (从 getVisualDevList 返回), 返回匹配项 (exact enCode match) 或 null
|
||||
*/
|
||||
export function findExistingForm(
|
||||
enCode: string,
|
||||
list: Array<{ id?: string; enCode?: string; fullName?: string; state?: number }>,
|
||||
): { id: string; enCode: string; fullName?: string; state?: number } | null {
|
||||
if (!enCode || !list || list.length === 0) return null
|
||||
// exact enCode match only (避免 fuzzy 误匹配同前缀 form)
|
||||
const hit = list.find((f) => f.enCode === enCode)
|
||||
if (!hit || !hit.id) return null
|
||||
return { id: hit.id, enCode: hit.enCode!, fullName: hit.fullName, state: hit.state }
|
||||
}
|
||||
|
||||
async function applyFinalSmartProps(
|
||||
c: JnpfClient,
|
||||
buildResult: { formData: string },
|
||||
@@ -305,6 +322,7 @@ export function buildFormCreateCommand(): Command {
|
||||
.option('--verify <mode>', '失败模式: warn (默认, v0.12+ jxcj) | block', 'warn')
|
||||
.option('--verify-timeout <ms>', '浏览器验证超时 (默认 60s)', '60000')
|
||||
.option('--via <path>', '创建路径: api (默认, 走 POST /visualdev/Base) | ui (走 playwright 模拟人类操作, API 失败时兜底)', 'api')
|
||||
.option('--reuse-if-exists', 'enCode 已存在时返回现有 form id (跳过创建), AI agent 反复跑场景', false)
|
||||
.option('--json', '原始 JSON 输出', false)
|
||||
.option('--verbose', '完整输出 (含 step machine、API 调用等过程日志)', false)
|
||||
// columnList / __vModel__ 命名规范适配
|
||||
@@ -770,6 +788,35 @@ export function buildFormCreateCommand(): Command {
|
||||
}
|
||||
}
|
||||
|
||||
// Tier 1.2 (2026-07-24): --reuse-if-exists 幂等支持
|
||||
// 检测 enCode 已存在 → 跳过创建返回现有 id (AI agent 反复跑场景, 防 BS-新131 反复返工)
|
||||
// 与 pre-check 的关系: pre-check 仍报 enCode 冲突, 但 --reuse-if-exists 在 pre-check 前先拦一道
|
||||
if (opts.reuseIfExists && opts.enCode) {
|
||||
try {
|
||||
await initWebapi(c)
|
||||
const listResp = (await loadVisualDev.getVisualDevList({
|
||||
currentPage: 1,
|
||||
pageSize: 500,
|
||||
})) as { list?: Array<{ id?: string; enCode?: string; fullName?: string; state?: number }> }
|
||||
const existing = findExistingForm(opts.enCode, listResp.list || [])
|
||||
if (existing) {
|
||||
const stateLabel = existing.state === 1 ? '已发布' : existing.state === 0 ? '未发布' : `state=${existing.state}`
|
||||
log.info(`✓ --reuse-if-exists 命中: ${opts.enCode} (id=${existing.id}, ${stateLabel})`)
|
||||
log.info(` 跳过创建. 需要修改字段请用 dacli form update --fields=<json>`)
|
||||
return ctx.success({
|
||||
enCode: opts.enCode,
|
||||
id: existing.id,
|
||||
fullName: existing.fullName,
|
||||
state: existing.state,
|
||||
reused: true,
|
||||
mode: 'reuse-if-exists',
|
||||
})
|
||||
}
|
||||
} catch (e) {
|
||||
log.warn(`--reuse-if-exists 查询失败 (${(e as Error).message?.slice(0, 80)}), 继续正常创建流程`)
|
||||
}
|
||||
}
|
||||
|
||||
// P1.2: form create pre-check (dbLinkId / enCode 重复 / type-webType 规则)
|
||||
// 失败时 exit 2, 不进入 API 调用; 警告不阻断
|
||||
// 从 --tables JSON 提取主表名 (供 type-webType 规则判断 needsPhysicalTable 用)
|
||||
|
||||
@@ -0,0 +1,47 @@
|
||||
import { describe, expect, it } from 'vitest'
|
||||
import { findExistingForm } from '../../src/commands/form/create.ts'
|
||||
|
||||
describe('form create --reuse-if-exists helper', () => {
|
||||
it('returns null when enCode not provided', () => {
|
||||
expect(findExistingForm('', [{ id: '1', enCode: 'x' }])).toBeNull()
|
||||
})
|
||||
|
||||
it('returns null when list is empty', () => {
|
||||
expect(findExistingForm('x', [])).toBeNull()
|
||||
})
|
||||
|
||||
it('returns null when enCode not in list', () => {
|
||||
const list = [
|
||||
{ id: '1', enCode: 'a', state: 1 },
|
||||
{ id: '2', enCode: 'b', state: 1 },
|
||||
]
|
||||
expect(findExistingForm('c', list)).toBeNull()
|
||||
})
|
||||
|
||||
it('returns existing form on exact enCode match (state=1 已发布)', () => {
|
||||
const list = [
|
||||
{ id: '1', enCode: 'a', fullName: 'A', state: 1 },
|
||||
{ id: '2', enCode: 'b', fullName: 'B', state: 0 },
|
||||
]
|
||||
const hit = findExistingForm('b', list)
|
||||
expect(hit).toEqual({ id: '2', enCode: 'b', fullName: 'B', state: 0 })
|
||||
})
|
||||
|
||||
it('does NOT fuzzy match (防同前缀 form 误匹配)', () => {
|
||||
const list = [
|
||||
{ id: '1', enCode: 'tdd8CustomerManage', state: 1 },
|
||||
{ id: '2', enCode: 'tdd8CustomerManageV2', state: 0 },
|
||||
]
|
||||
// 精确匹配 tdd8CustomerManage, 不应返回 V2
|
||||
expect(findExistingForm('tdd8CustomerManage', list)?.id).toBe('1')
|
||||
// 不存在精确匹配时返回 null
|
||||
expect(findExistingForm('tdd8customermanage', list)).toBeNull()
|
||||
})
|
||||
|
||||
it('skips entries without id (web 端偶发空 id 不算 hit)', () => {
|
||||
const list = [
|
||||
{ enCode: 'x', state: 1 }, // no id
|
||||
]
|
||||
expect(findExistingForm('x', list)).toBeNull()
|
||||
})
|
||||
})
|
||||
Reference in new issue
Block a user