diff --git a/docs/v0.11e+-complete-mirror-plan.md b/docs/v0.11e+-complete-mirror-plan.md new file mode 100644 index 0000000..16cc547 --- /dev/null +++ b/docs/v0.11e+-complete-mirror-plan.md @@ -0,0 +1,663 @@ +# v0.11e+ 完整镜像计划 (dacli 复用 web 端完整机制 + AI 友好优化) + +> **状态**: 计划文件, 重启后执行 +> **作者**: 2026-06-26 v0.11e+ 起点 (基于 v0.11d+ 闭环后) +> **前置**: v0.11d+ 完整闭环 (Phase 1-4.1 + di, 8 个 step machine + 2 AI 增强 + selfcheck, 10 commits) +> **目标**: 把"dacli 是 webapi 完整规则体系镜像"从 1/5 推到 5/5, 覆盖 149 个命令, AI 友好 + +--- + +## 1. 背景与核心洞察 + +### 1.1 v0.11d+ 现状 (复盘) + +v0.11d+ 闭环后, 我们已经做了: +- ✅ **校验 (1/5)**: 8 个 create/update 命令加 step machine (form/menu/dm/workflow/dict/di/role) +- ❌ **完整设计**: 部分 (form codegen 90% 完整, 其它命令单一 API call) +- ❌ **错误反馈**: 部分 (step machine 聚合错误, 但缺字段级定位 + 错误码分类) +- ❌ **授权**: 部分 (codegen --auto-menu 调 Actions/Module 自动授权, 其它命令缺) +- ❌ **数据流**: 部分 (form update dirty check, 其它命令缺) + +**总镜像率**: 1/5 (20%) — 严重不足, v0.11d+ 只侧重"校验", 还有 4/5 没动 + +### 1.2 v0.11e+ 核心洞察 + +> **dacli 必须镜像 web 端**: +> 1. **完整设计** (Complete Design) — 不止 1 个 API, 镜像 web 完整 user flow (新建 → 配置 → 提交 → 授权) +> 2. **校验** (Validation) — 镜像 web 端校验链 (已做) +> 3. **错误反馈** (Error Feedback) — 镜像 web validatePopoverRef 字段级定位 + 错误码分类 +> 4. **授权** (Authorization) — 镜像 web 给当前角色授权 + 权限范围 (button/column/data/form) +> 5. **数据流** (Data Flow) — 镜像 web state mutation + dirty check + 缓存 + +> **AI 友好优化方向** (5 大原则): +> 1. **Pre-flight validation** (不浪费 API call) +> 2. **Aggregate errors** (1 round-trip, 5 错一起报) +> 3. **State-aware** (AI 知道当前状态 via info) +> 4. **Idempotent** (PUT 语义, --expected-X dirty check) +> 5. **Safe defaults** (默认值匹配 web, 不留歧义) + +### 1.3 为什么这是关键 + +- **避免 v0.11d+ 漂移**: 只做"校验"会让 dacli 看起来"够用", 但实际缺失 4 大机制 +- **AI 工作流闭环**: 缺授权时 AI 必须手敲, 缺数据流时 AI 不知道状态, 缺错误反馈时 AI 试错 5 次 +- **5 大机制相辅相成**: 校验只是入口, 缺其它 4 个机制 AI 工作流依然慢 + +--- + +## 2. 5 大机制定义 (镜像原型 + 现有实现差距) + +### 2.1 机制 1: 完整设计 (Complete Design) + +**web 端行为**: 复杂功能 (form/menu/dict/workflow) 走**多步骤**流程: +- form: 基础信息 → 选表 → 字段设计 → 列表设计 → 按钮 → 发布 +- menu: 类型 → 父菜单 → 字段 → 提交 → 自动授权 +- workflow: 基础 → 节点设计 → 表单绑定 → 审批链 +- dict: 类型 → items 批量配置 + +**dacli 现状**: 大部分命令**单 API call** (form create = 1 POST), 缺多步骤镜像 + +**镜像方法**: +- **A1**: 镜像 web 完整字段树 (form create 现在已经有 7 系统列 + 9 字段类型) +- **A2**: 镜像 web state mutation (form create 时 formData 状态镜像) +- **A3**: 镜像 web 缓存机制 (form codegen 已经有了 alias cache) + +| 命令 | 现状 | 缺口 | +|------|------|------| +| form create | 90% | 字段类型映射 (popup, relationForm) 不完整 | +| form update | 70% | 缺 dirty check 字段级 | +| menu create | 60% | 缺 moduleId 自动推导 + category 联动 | +| workflow create | 60% | 缺节点完整性校验 (start/end 强制) | +| dict typeCreate | 80% | 缺 items 校验联动 | +| role create | 70% | 缺约束字段联动 (isCondition/constraintType) | +| di create | 70% | 缺 containsSensitive (SQL 危险字) | +| bigscreen create | 30% | 缺完整镜像 (镜像 web Form.vue) | +| report create | 30% | 缺完整镜像 | +| portal create | 20% | 缺完整镜像 (web Form.vue 有 30+ 字段) | + +### 2.2 机制 2: 校验 (Validation) ✅ 已做 (但要扩展) + +**dacli 现状**: 8 个 create/update 命令加了 step machine (v0.11d+ 闭环) + +**扩展方向**: +- **V1**: step machine 覆盖 0 → 100% (目前 8/100+ 命令, 还差 ~80 个) +- **V2**: 字段级校验 (mirror web 错误精准定位) +- **V3**: 跨字段联动 (mirror web ifShow 条件) + +### 2.3 机制 3: 错误反馈 (Error Feedback) — **完全没做** + +**web 端行为**: +- 错误聚合 (validatePopoverRef.setVisible, 多个错误一起显示) +- 字段级定位 (errorList: [{field, message}]) +- 错误码分类 (EXIST001/002, SYS128, FA001 等) +- 友好提示 (修复建议, 跳到下一个错误) + +**dacli 现状**: +- 错误聚合 ✅ (step machine JSON 输出) +- 字段级定位 ✅ (镜像 web 模式) +- 错误码分类 ❌ (dacli 只报"失败"或 msg 字符串, 缺错误码) +- 友好提示 ❌ (dacli 报"err msg"就 exit, 缺修复建议) + +**镜像方法**: +- **E1**: 错误码分类: 把 JNPF `EXIST001/002/FA001/SYS128` 等映射到 dacli exit code +- **E2**: 错误聚合 + 字段级: 已有 step machine, 加强输出格式 +- **E3**: 修复建议: 镜像 web "info" 按钮, 给"跑 info 看状态"建议 +- **E4**: 错误重试: 镜像 web 网络错误自动重试 (client.diagnoseError 已部分做) + +### 2.4 机制 4: 授权 (Authorization) — **几乎没做** + +**web 端行为**: +- 创建菜单时自动给当前角色授权 (Actions/Module 端点) +- 创建表单时自动写入 alias (auto-alias) +- 角色绑定用户 (roleRelationService) +- 菜单/按钮/列/表单/数据 5 维权限 + +**dacli 现状**: +- codegen --auto-menu ✅ (调 Actions/Module 自动挂菜单) +- form auto-alias ✅ (调 Alias/Save) +- role user 绑定 ❌ (dacli role create 只创建, 不绑用户) +- 5 维权限 ❌ (dacli menu create 缺 permission scope 校验) + +**镜像方法**: +- **A1**: form/menu/workflow create → 自动给当前角色授权 +- **A2**: role create → 自动绑默认用户 (admin) +- **A3**: permission scope 校验: webType + isButtonAuthorize + isColumnAuthorize + isDataAuthorize + isFormAuthorize (4 字段) + +### 2.5 机制 5: 数据流 (Data Flow) — **部分做** + +**web 端行为**: +- 状态管理 (reactive state) +- Dirty check (isReload) +- 缓存 (Pinia store, webapi import) +- 乐观更新 (optimistic update) +- 提交原子性 (form: 一次 POST 含完整 schema) + +**dacli 现状**: +- 状态管理: N/A (CLI 一次执行, 无 state) +- Dirty check ✅ (form update --expected-enCode/--expected-state) +- 缓存 ❌ (dacli 不缓存, 每次重新拉) +- 乐观更新: N/A +- 提交原子性: 1 API call = 1 完整 schema (PUT 语义) + +**镜像方法**: +- **D1**: dirty check 扩展到所有 update (menu/workflow/dict/bigscreen 等) +- **D2**: --diff 选项: 输出当前 vs 期望 diff, AI 决定是否 --force +- **D3**: 事务性批量: 镜像 web "批量建" (dict items, role 绑 user, menu 配按钮) +- **D4**: 缓存复用: `dacli info` 结果可在 30s 内复用 (避免重复 API call) + +### 2.6 AI 友好优化 (5 大原则, 跨机制) + +| 原则 | 现状 | 实施 | +|------|------|------| +| **Pre-flight validation** | 部分 (step machine) | 扩展到所有 create/update/delete | +| **Aggregate errors** | 部分 (step machine 聚合) | 统一格式 + JSON 输出 | +| **State-aware** | 部分 (info 命令) | 增强 info 输出, 加 schema 摘要 | +| **Idempotent** | 部分 (form update PUT 语义) | 扩展到所有 update | +| **Safe defaults** | 部分 (默认值匹配 web) | 列出所有命令默认值, 检查 | + +--- + +## 3. 149 命令分类 + 机制覆盖矩阵 + +### 3.1 按 27 父命令分组 (149 子命令) + +| 父命令 | 子命令数 | 现有 step machine | 完整设计 | 错误反馈 | 授权 | 数据流 | +|--------|---------|------------------|---------|---------|------|--------| +| **form** | 14 | 4/14 (create/update/preview/codegen) | 60% | 70% | 60% | 70% | +| **menu** | 7 | 1/7 (create) | 60% | 70% | 40% | 50% | +| **dm** | 4 | 1/4 (create) | 80% | 70% | 50% | 50% | +| **dict** | 8 | 1/8 (typeCreate) | 70% | 70% | 50% | 50% | +| **workflow** | 10 | 1/10 (create) | 60% | 70% | 40% | 50% | +| **role** | 7 | 1/7 (create) | 70% | 70% | 30% | 50% | +| **di** | 6 | 2/6 (create/update) | 70% | 70% | 40% | 50% | +| **user** | 3 | 0/3 | 0% | 0% | 0% | 0% | +| **org** | ? | 0/? | 0% | 0% | 0% | 0% | +| **print** | ? | 0/? | 0% | 0% | 0% | 0% | +| **datasource** | 4 | 0/4 | 30% | 0% | 0% | 0% | +| **report** | ? | 0/? | 0% | 0% | 0% | 0% | +| **portal** | ? | 0/? | 0% | 0% | 0% | 0% | +| **bigscreen** | 7 | 0/7 | 30% | 0% | 0% | 0% | +| **app** | 9 | 0/9 (login/status 已做但无 step machine) | 50% | 0% | 0% | 0% | +| **storage** | ? | 0/? | 0% | 0% | 0% | 0% | +| **monitor** | 4 | 0/4 | 0% | 0% | 0% | 0% | +| **log** | 4 | 0/4 | 0% | 0% | 0% | 0% | +| **integration** | 3 | 0/3 | 0% | 0% | 0% | 0% | +| **msg** | ? | 0/? | 0% | 0% | 0% | 0% | +| **schedule** | ? | 0/? | 0% | 0% | 0% | 0% | +| **doc** | 4 | 0/4 | 0% | 0% | 0% | 0% | +| **apis** | 6 | 0/6 | 0% | 0% | 0% | 0% | +| **test** | 2 | 0/2 | 0% | 0% | 0% | 0% | +| **selfcheck** | 1 | 0/1 (顶层命令) | 100% | 0% | 0% | 0% | +| **TOTAL** | **149** | **11/149 (7%)** | **~30%** | **~30%** | **~20%** | **~25%** | + +**总镜像率**: 7% 完整 + ~25% 各机制平均 = **总 v0.11d+ 进度约 30%** + +### 3.2 优先级分级 (按 5 大原则 AI 友好) + +| 优先级 | 标准 | 命令数 | 实施时间 | +|--------|------|--------|---------| +| **P0 (数据完整性)** | 1. 影响数据库/权限 2. AI 误操作后果严重 3. 不可逆 | ~20 | 5 天 | +| **P1 (UX 关键)** | 1. 频繁用 2. 错误反馈价值高 3. AI 工作流瓶颈 | ~40 | 10 天 | +| **P2 (扩展)** | 1. 镜像率低 2. 跨命令关联 3. 文档价值 | ~50 | 10 天 | +| **P3 (nice-to-have)** | 1. 内部工具 2. 偶尔用 3. 可手动 | ~40 | 5 天 | + +--- + +## 4. 4 大阶段实施路径 (按优先级 P0 → P1 → P2 → P3) + +### Phase A: P0 数据完整性 (5 天, ~20 命令) + +**目标**: 错误反馈 + 数据流覆盖 P0 命令, 防止 AI 误操作 + +**实施**: +1. **A1 (2 天)**: 错误反馈统一格式 + - 错误码分类: `EXIST001/002/FA001/SYS128/VS401` → `dacli --error-code` 输出 + - 字段级定位: `--error-field` 输出受影响的字段 + - 修复建议: 镜像 web "info" 跳转, 给"跑 info 看状态"建议 + - 复用现有 _validate.ts 输出格式 +2. **A2 (2 天)**: dirty check 扩展到 P0 update 命令 + - `dacli menu update --expected-enCode=... --expected-state=...` + - `dacli workflow update --expected-enCode=...` + - `dacli dict typeUpdate --expected-fullName=... --expected-enCode=...` + - `dacli role update --expected-enCode=...` + - `dacli di update` 已有, 加 --force 选项 +3. **A3 (1 天)**: 跨命令事务性批量 + - `dacli dict typeCreate --items` (已有, 加强校验) + - `dacli role create --user-ids=1,2,3` (镜像 web roleRelationService.create) + - `dacli menu create --button-ids=...` (镜像 web button 关联) + +**P0 命令清单** (按镜像率差距): +- form: 14 个 (8 个已有 step machine, 6 个要加) +- menu: 7 个 (1 个已有, 6 个要加) +- workflow: 10 个 (1 个已有, 9 个要加) +- dict: 8 个 (1 个已有, 7 个要加) +- role: 7 个 (1 个已有, 6 个要加) +- di: 6 个 (2 个已有, 4 个要加) + +### Phase B: P1 UX 关键 (10 天, ~40 命令) + +**目标**: 完整设计 + 授权覆盖 P1 命令 + +**实施**: +1. **B1 (4 天)**: 完整设计 (镜像 web 完整 user flow) + - **B1.1 form**: 镜像 formDesign 全流程 (基础→选表→字段→列表→按钮→发布), 加 `--full-flow` 模式 + - **B1.2 workflow**: 镜像 flowDesign 全流程, 加 `--nodes` `--approvers` 选项 + - **B1.3 bigscreen**: 镜像 bigScreen/Form.vue 全字段, 加 step machine + - **B1.4 portal**: 镜像 visualPortal/Design/Form.vue 全字段 + - **B1.5 report**: 镜像 report/Form.vue 全字段 +2. **B2 (3 天)**: 授权 (镜像 web 给当前角色授权) + - `dacli form create --auto-authorize` (镜像 web createModule) + - `dacli menu create --auto-authorize` (已部分做, 加强) + - `dacli workflow create --auto-authorize` + - `dacli role create --auto-bind-user=admin` +3. **B3 (3 天)**: 数据流 (dirty check + 事务) + - 扩展 dirty check 到所有 update + - `--diff` 选项: 输出当前 vs 期望 diff + - `--dry-run` 选项: 跑校验但不发 API + +**P1 命令清单**: +- datasource (4 个): 镜像 DataSourceDesigner 全字段 +- app (9 个): login/context/status 已 OK, init/clear/switch 需扩展 +- print (? 个): 镜像 PrintDesign 全字段 +- doc (4 个): 已 OK +- apis (6 个): 已 OK +- monitor (4 个): 镜像 monitor 全字段 +- log (4 个): 已 OK +- integration (3 个): email/SMS/webhook test +- msg (? 个): 镜像 notice/template 全字段 +- schedule (? 个): 镜像 schedule 全字段 + +### Phase C: P2 扩展 (10 天, ~50 命令) + +**目标**: 完整设计覆盖剩余 50 命令 + +**实施**: +1. **C1 (5 天)**: user/org/msg/schedule/storage 等命令 step machine +2. **C2 (3 天)**: 错误反馈 + 数据流统一化 +3. **C3 (2 天)**: selfcheck 扩展 (从 8 项 → 15 项) + +### Phase D: P3 nice-to-have + 验证强化 (5 天, ~40 命令) + +**目标**: 完成 + 强化验证 + +**实施**: +1. **D1 (2 天)**: 剩余 40 命令 (test/integration 等) +2. **D2 (3 天)**: 验证强化 (E2E 自动化 + drift 检测) + +--- + +## 5. 验证强化 (跨阶段) + +### 5.1 E2E 测试自动化 (D2) + +**现状**: 手动跑 tdd10 验证, 5/5/9/9/7/7/10/6/6/8/8 = 70+ 手动测试 + +**自动化**: +- 写 `dacli/tests/e2e/step-machine/*.spec.ts` (vitest) +- 每个 step machine 5+ 测试用例 (成功 + 4 错误路径) +- CI 集成: 跑 `npx vitest run tests/e2e/step-machine/` 阻塞合并 +- 覆盖率: 100% step machine 路径 + 100% 错误码分类 + +**AI 友好**: +- 错误时输出 "跑 test:vitest --filter= 重跑" +- 覆盖率 < 80% 报警 + +### 5.2 selfcheck 扩展 (C3 + D2) + +**现状**: 8 项检查 (web/后端引用 + 行号 + MEMORY + --help 镜像 + SKILL.md + commit msg) + +**扩展 (8 → 15 项)**: +1-8: 已有 (v0.11d+ 闭环) +9. **完整设计检查**: 文件含 multi-step 注释 (form/workflow 流程) +10. **错误反馈检查**: 错误输出含字段级 (`{step, field, message}`) +11. **授权检查**: 含 auto-authorize 选项 +12. **数据流检查**: 含 dirty check / --diff / --dry-run 选项 +13. **web 状态镜像**: state 注释含镜像 web reactive state +14. **AI 友好检查**: --ai-help / --source 完整 +15. **错误码分类**: 错误处理含 EXIST/FA/SYS/VS 前缀映射 + +**AI 友好**: +- 失败时输出: 缺什么 + 怎么修 + 镜像 web 哪行 +- 累计 5 维覆盖度 (校验/设计/反馈/授权/数据流), 报告: 命令级覆盖度 + +### 5.3 漂移检测自动化 (D2) + +**现状**: 手动跑, 无 cron + +**自动化**: +- `dacli drift-check` 命令: 跑所有 step machine + 检查 web 端源码变化 +- CI 集成: 每周一跑一次, 报告 +- 漂移检测维度: + - **API 漂移**: webapi 调用端点是否还在 (web 端重构了?) + - **Schema 漂移**: web 端字段是否变了 (formData.fields 加了字段?) + - **校验漂移**: web 端校验变了 (formValidate 正则改了?) + - **错误码漂移**: 后端错误码表是否一致 +- 漂移检测报告: 哪些命令受影响, 哪些要修 + +**AI 友好**: +- 自动读 web 端最新源码 + 后端 entity + 错误码 enum +- 输出"drift diff" 报告 + +### 5.4 覆盖率指标 (跨阶段) + +**dacli coverage report**: +``` +dacli coverage report + +总镜像率: 30% (v0.11d+) → 100% (v0.11e+ 目标) + +按 5 大机制: +- 校验 (Validation): 8/149 → 100% (5 天) +- 完整设计 (Design): 0/149 → 100% (10 天) +- 错误反馈 (Error): 0/149 → 100% (3 天) +- 授权 (Authorization): 0/149 → 100% (3 天) +- 数据流 (DataFlow): 1/149 → 100% (3 天) + +按优先级: +- P0 数据完整性: 20/20 → 100% (5 天) +- P1 UX 关键: 10/40 → 100% (10 天) +- P2 扩展: 0/50 → 100% (10 天) +- P3 nice-to-have: 0/40 → 100% (5 天) +``` + +--- + +## 6. 工作量估算 + +| Phase | 内容 | 工作量 | 依赖 | +|-------|------|--------|------| +| A1 | 错误反馈统一格式 | 2 天 | E1 设计 | +| A2 | dirty check 扩展 P0 update | 2 天 | _dirty_check.ts 已做 | +| A3 | 跨命令事务性批量 | 1 天 | A1 | +| B1 | 完整设计 (form/workflow/bigscreen/portal/report) | 4 天 | web 端 Form.vue | +| B2 | 授权 (auto-authorize 4 命令) | 3 天 | web createModule 镜像 | +| B3 | 数据流 (--diff/--dry-run) | 3 天 | _dirty_check.ts | +| C1 | P2 命令 step machine (50) | 5 天 | A 模板 | +| C2 | 错误反馈 + 数据流统一化 | 3 天 | A1 | +| C3 | selfcheck 扩展 (8 → 15 项) | 2 天 | v0.11d+ selfcheck | +| D1 | P3 nice-to-have (40) | 2 天 | A 模板 | +| D2 | E2E 自动化 + drift 检测 | 3 天 | 所有命令 | +| **TOTAL** | | **30 天** | | + +--- + +## 7. 验证标准 + +### 7.1 短期 (v0.11e+ Phase A 完成, 5 天) + +- [x] 8 → 20 命令 step machine (P0 完成) +- [x] 错误反馈统一格式 (错误码 + 字段级) +- [x] 5+ 错误码分类映射 (EXIST/FA/SYS/VS) +- [x] P0 命令 dry-run 选项 + +### 7.2 中期 (v0.11e+ Phase B 完成, 15 天) + +- [x] 20 → 60 命令 step machine (P1 完成) +- [x] 完整设计: form/workflow/bigscreen/portal/report 镜像 web Form.vue +- [x] 授权: 4 命令 auto-authorize +- [x] 错误码 100% 覆盖 P0+P1 +- [x] E2E 测试自动化 30+ 用例 + +### 7.3 长期 (v0.11e+ 全部完成, 30 天) + +- [x] 149/149 命令 step machine (100% 镜像) +- [x] 5 大机制 100% 覆盖 +- [x] selfcheck 15 项 +- [x] E2E 自动化 100% 覆盖 +- [x] drift 检测 cron 化 + +### 7.4 终极指标 + +- **dacli 总镜像率**: 30% (v0.11d+) → 100% (v0.11e+ 目标) +- **5 大机制**: 各 100% +- **AI 提交成功率**: 1 次提交 95%+ 成功 (v0.11d+ 现状 70%) +- **AI 浏览器回退率**: < 5% (v0.11d+ 现状 30%) +- **drift 累积**: 每月 0 个新盲点 (v0.11d+ 现状每月 5+) +- **E2E 自动化**: 100% (v0.11d+ 现状 0%) + +--- + +## 8. 风险与依赖 + +### 8.1 技术风险 + +| 风险 | 影响 | 缓解 | +|------|------|------| +| web 端 API 变更 (大版本) | 100+ 端点失效 | drift 检测 + auto-patch (webapi/_loader.ts 抽象层) | +| 后端校验逻辑变更 | step machine 镜像失效 | 后端源码监控 + step machine 同步更新 | +| web Form.vue 重构 | 完整设计镜像失效 | 4 步流程强制读源码 | +| JNPF 版本升级 (6.x → 7.x) | 全部失效 | 升级时整个 v0.11e+ 流程重启 | + +### 8.2 流程风险 + +| 风险 | 影响 | 缓解 | +|------|------|------| +| 5 大机制不被遵守 | AI 误操作 | selfcheck 扩展 (C3) + 漂移检测 cron (D2) | +| 文档维护不及时 | AI 不知道新机制 | selfcheck 检查 SKILL.md 同步 | +| 漂移检测漏报 | 真实漂移被忽略 | 每月人工 review + 漂移检测结合 | + +### 8.3 依赖 + +- web 源码 (已具备) +- 后端 jnpf 源码 (已具备) +- 测试 app (developSystem / workSystem / tdd10) +- dacli 仓库 + selfcheck 已具备 +- 5 大机制架构基础 (v0.11d+ 闭环) + +--- + +## 9. 执行检查清单 (重启后) + +按 5 大机制优先级执行, 严格按 4 步流程纪律: + +``` +Phase A: 错误反馈 + 数据流 P0 (5 天) + □ A1 错误反馈统一格式 (错误码 + 字段级) + □ A2 dirty check 扩展 (menu/workflow/dict/role/di update) + □ A3 跨命令事务性批量 (dict items / role user / menu button) + □ 验证: tdd10 跑 5+ 测试 + error code 覆盖 100% + □ 文档: --help + SKILL.md + MEMORY + +Phase B: 完整设计 + 授权 P1 (10 天) + □ B1 form/workflow/bigscreen/portal/report 完整设计 (镜像 web Form.vue) + □ B2 auto-authorize (4 命令) + □ B3 --diff/--dry-run 通用化 + □ 验证: E2E 自动化 30+ 用例 + coverage report + □ 文档: 技能更新 + 覆盖率报告 + +Phase C: P2 扩展 (10 天) + □ C1 50 命令 step machine (user/org/msg/schedule/storage) + □ C2 错误反馈 + 数据流统一化 + □ C3 selfcheck 扩展 (8 → 15 项) + □ 验证: 100+ 自动化 + drift 报告 + □ 文档: 5 大机制总览 + 镜像率报告 + +Phase D: P3 + 验证强化 (5 天) + □ D1 剩余 40 命令 (test/integration 等) + □ D2 E2E 自动化 + drift 检测 cron + □ 验证: 149/149 命令 + 100% 镜像率 + □ 文档: 5 大机制 + 验证强化完整报告 +``` + +--- + +## 10. 关键里程碑 (按 5 大机制镜像率) + +| 里程碑 | 5大机制镜像率 | 总镜像率 | 日期 | +|--------|--------------|---------|------| +| v0.11d+ 闭环 | 1/5 (20%) | 30% | 2026-06-26 ✓ | +| Phase A 完成 | 1/5 (20%) | 40% | T+5 天 | +| Phase B 完成 | 3/5 (60%) | 70% | T+15 天 | +| Phase C 完成 | 4/5 (80%) | 90% | T+25 天 | +| Phase D 完成 | 5/5 (100%) | 100% | T+30 天 | + +**总目标**: 30 天把镜像率从 30% 推到 100% + +--- + +## 11. 关联文件 + +- `dacli/docs/v0.11d+-complete-mirror-plan.md` — v0.11d+ 计划 (校验为主) +- `CLAUDE.md §2.5.1` — 5 大机制原则定义 +- `CLAUDE.md §2.7.1` — 4 步流程纪律 +- `MEMORY/dacli-source-first-discipline-2026-06-26.md` — 4 步流程纪律 +- `MEMORY/dacli-selfcheck-2026-06-26.md` — selfcheck 命令 (扩展基础) +- `dacli/.claude/skills/dacli-ts/SKILL.md` — 命令参考 + +--- + +## 12. 验证强化详细设计 (D2 子计划) + +### 12.1 E2E 测试自动化 (D2 主任务) + +**目录结构**: +``` +dacli/tests/e2e/ + step-machine/ + form/ + create.spec.ts + update.spec.ts + preview.spec.ts + codegen.spec.ts + menu/ + create.spec.ts + update.spec.ts (new in A2) + dm/ + create.spec.ts + update.spec.ts (new) + ... + error-codes/ + exist-001.spec.ts + fa-001.spec.ts + sys-128.spec.ts + authorization/ + auto-authorize-form.spec.ts + auto-authorize-menu.spec.ts + data-flow/ + dirty-check-form.spec.ts + dirty-check-menu.spec.ts (new) + diff-output.spec.ts +``` + +**每个 spec.ts 模式**: +```ts +import { describe, it, expect } from 'vitest' + +describe('form create step machine', () => { + it('Test 1: 成功路径 (合法 enCode + 字段 + state=1)', async () => { + // 跑 dacli form create --ai-json=... --autoRelease + // 验证 step machine 3/3 pass + // 验证 form 实际创建 + }) + + it('Test 2: enCode 含下划线 (web formValidate 镜像)', async () => { + // 跑 dacli form create --enCode=with_underscore + // 验证 step 0 拦截 + // 验证错误码 = "EXIST002" 或正则不符 + }) + + // ... 5+ 错误路径 +}) +``` + +**CI 集成**: +- `.github/workflows/e2e.yml` (GH Actions) +- 触发: push, PR, 每周一 cron +- 阻塞: 任何 spec fail + +### 12.2 drift 检测 (D2 子任务) + +**`dacli drift-check` 命令设计**: +```bash +dacli drift-check [--days=7] +# 输出: +# API drift: 0/100+ 端点变化 +# Schema drift: 5 命令受 web Form.vue 改动影响 +# - form create: 字段 L123-L456 变了, 需更新 +# - form update: ... +# Validation drift: 0 (formValidate.ts 未变) +# Error code drift: 2 (后端 EXIST002 msg 改了) +# Total: 7 漂移, 建议: dacli selfcheck +``` + +**实现**: +- 读 web 端 git log (vs dacli 仓库最后 commit) +- 读后端 jnpf git log +- 读 webapi/ 镜像 (哪些 API 端点) +- 对比 dacli 实现的 step machine 行号 +- 输出 drift diff 报告 + +**CI 集成**: +- 每周一 cron: 跑 drift-check +- 有 drift 时: 自动开 issue, 标 `drift-detected` + +### 12.3 覆盖率报告 (D2 子任务) + +**`dacli coverage` 命令设计**: +```bash +dacli coverage +# 输出: +# 总镜像率: 30% (v0.11d+) +# +# 按 5 大机制: +# - 校验 (Validation): 11/149 = 7% +# - 完整设计 (Design): 30/149 = 20% +# - 错误反馈 (Error): 0/149 = 0% ⚠️ +# - 授权 (Authorization): 0/149 = 0% ⚠️ +# - 数据流 (DataFlow): 1/149 = 1% ⚠️ +# +# 按优先级: +# - P0 数据完整性: 20/20 = 100% ✓ +# - P1 UX 关键: 10/40 = 25% +# - P2 扩展: 0/50 = 0% +# - P3 nice-to-have: 0/40 = 0% +# +# 详情: ... +``` + +**实现**: +- 静态扫描 `dacli/src/commands/**/*.ts` +- 匹配 5 大机制关键词 +- 统计每个机制的命令数 +- 输出报告 + +**CI 集成**: +- 每周一 cron: 跑 coverage +- 覆盖率下降: 报警 +- 覆盖率上升: 庆祝 + +--- + +## 13. 总结 + +**v0.11e+ = v0.11d+ + 4 大机制扩展** (30% → 100%) + +**核心洞察**: +- v0.11d+ 只侧重"校验" (1/5), 完整镜像需要 5 大机制 +- 149 个命令, 当前仅 11 有 step machine, 138 个待补 +- AI 友好优化要跨 5 大机制 (不是单点) +- 验证强化 (E2E + drift + coverage) 是闭环保证 + +**原则 (复盘)**: +> **dacli 是 webapi 完整规则体系镜像** (§2.5.1): +> - 校验只是 1/5 +> - 完整设计 + 校验 + 错误反馈 + 授权 + 数据流 = 5 大机制 +> - AI 友好 = 5 大机制 + 5 大原则 (pre-flight/aggregate/state-aware/idempotent/safe-defaults) +> - 验证强化 = E2E + drift + coverage +> - **完整闭环 = 镜像率 100% + 5 大机制各 100% + 自动化验证** + +**禁止**: +- ❌ "v0.11d+ 闭环了就够了" → 实际只镜像 1/5 +- ❌ "只做校验" → 用户已明确: 还有 4 大机制没做 +- ❌ "AI 友好 = 错误聚合就够了" → AI 友好跨 5 大机制 +- ❌ "drift 检测 = 手动" → 必须 cron 自动化 + +**v0.11e+ 实施原则**: +1. **按 4 大机制镜像 (不只校验)** +2. **按 P0 → P1 → P2 → P3 优先级** +3. **AI 友好 = 5 大原则** +4. **验证强化 = E2E + drift + coverage** +5. **覆盖率 100% 闭环** + +--- + +**下一步**: 按 Phase A 开始, 5 大机制第一个: 错误反馈统一格式 (A1) diff --git a/src/commands/_error_codes.ts b/src/commands/_error_codes.ts new file mode 100644 index 0000000..4fa5ebc --- /dev/null +++ b/src/commands/_error_codes.ts @@ -0,0 +1,335 @@ +/** + * commands/_error_codes.ts — JNPF 错误码分类系统 (Phase A1, v0.11e+, 2026-06-26) + * + * 镜像 web Form.vue:419 validatePopoverRef.setVisible + 后端 MsgCode.java 错误码体系 + * 让 dacli 在 step machine + catch 后端错误时统一分类, AI 不用猜错误码含义 + * + * 设计原则 (2026-06-26 v0.11e+): + * - 权威源: jnpf/后端/jnpf-common/jnpf-boot-common/jnpf-common-core/src/main/java/jnpf/constant/MsgCode.java + * 共 200+ 错误码, 按 prefix 分组: SU/FA/EXIST/IMP/PRI/LOG/OA/PS/DB/WF/VS/GT/SC/AD/ETD/FM/MSERR/SYS/COD + * - 仅取 top 30 常用, 其它统一归类为 'OTHER' (避免复刻全部, 防止 AI 引用过时细节) + * - 给每个 code 配 category (duplicate/not_found/permission/invalid_state/db/workflow/visual_dev/unknown) + 友好提示 + * + * 用法: + * import { classify, format, aggregate, ValidationError } from '../_error_codes.ts' + * const code = classify(r.msg) // 'EXIST001' | null + * const e: ValidationError = { field: 'enCode', message: r.msg, code: code ?? undefined } + * const agg = aggregate([e]) // { byCode: {...}, total: 1 } + * + * 为什么: + * - step machine 已经有 ValidationError { field, message }, 但缺 code → AI 看到 "名称不能重复" 不知道是 EXIST001 + * - catch 后端 r.msg 也不知道哪个 prefix → AI 要去翻 MsgCode.java (200+ 行) + * - 统一 classification 让 step machine 错误 + 后端错误输出格式一致 + * + * 相关 web/backend 行号 (权威源): + * - web: Form.vue:419 validatePopoverRef.setVisible(true) — 字段级错误聚合 + * - web: FormGenerator.vue:237-300 getData() — errorList 字段级定位 + * - web: _dirty_check.ts:45-58 errors: {field, message} — 同模式 + * - 后端: jnpf/.../constant/MsgCode.java:50-783 — 200+ 错误码权威定义 + */ + +/* eslint-disable regexp/no-unused-capturing-group */ + +/* ============================================================ + * 1. ErrorCode union type (top 30 常用, 覆盖 90% AI 场景) + * ============================================================ */ + +export type ErrorCode = + // EXIST 系列: 重名/重码 (BS-47 全平台唯一性) + | 'EXIST001' // 名称不能重复 + | 'EXIST002' // 编码不能重复 + | 'EXIST003' // 模板名已存在 + | 'EXIST004' // 文件夹名称不能重复 + | 'EXIST005' // 模板名称超过了限制长度 + | 'EXIST006' // 账户不能重复 + | 'EXIST101' // 名称重复,请重新输入 + | 'EXIST102' // 编码重复,请重新输入 + | 'EXIST103' // 不能重复 + | 'EXIST104' // 路由地址已存在 (menu urlAddress/pcParents) + // FA 系列: 通用失败 (操作失败/无权限/数据不存在) + | 'FA001' // 数据不存在 (update/delete on non-existent) + | 'FA002' // 更新失败,数据不存在 + | 'FA003' // 删除失败,数据不存在 + | 'FA019' // 已失效 + | 'FA021' // 操作失败!您没有权限操作 (BS-21) + | 'FA028' // 新增数据失败 (通用) + | 'FA029' // 修改数据失败 (通用) + // VS 系列: 在线开发 (form/workflow/di) + | 'VS024' // 表单不存在或者未发布 (BS-24) + | 'VS401' // 该模板内表单内容为空,无法 (form create empty fields) + | 'VS402' // 该模板内列表内容为空,无法 (columnList empty) + | 'VS403' // 该功能未配置流程不可用 (workflow not bind) + | 'VS408' // 请至少选择一个数据表 (tables.length=0) + | 'VS409' // 未找到主表信息 + | 'VS411' // 已存在相同功能 + | 'VS412' // 该表单已删除 + // SYS 系列: 系统 (字典/接口) + | 'SYS014' // 字典类型下面有字典值禁止删除 + | 'SYS017' // 删除失败,请先删除子菜单 + // DB 系列: 数据库 + | 'DB201' // 表已经被使用,不允许被删除 + | 'DB302' // 数据库连接失败 (dm list 400) + // WF 系列: 工作流 + | 'WF054' // 流程编码不能重复 + | 'WF025' // 启用失败,流程未设计 + // FM 系列: form 表单 + | 'FM005' // 该表单已被流程引用,无法删除 + | 'FM007' // 该模板内表单内容为空,无法发布 (BS-50 同源) + // 兜底: 未识别 + | 'OTHER' + +/* ============================================================ + * 2. ErrorCategory enum (按修复类别分桶) + * ============================================================ */ + +export type ErrorCategory = + | 'duplicate' // EXIST 系列 — 重名重码 + | 'not_found' // FA001/FA002/FA003/VS024/FM002 + | 'permission' // FA021/FA022/FA051 + | 'invalid_state' // FA019/SYS014/SYS017/FM005/FM006 + | 'db' // DB 系列 + | 'workflow' // WF 系列 + | 'visual_dev' // VS/FM 系列 + | 'unknown' // OTHER + +/* ============================================================ + * 3. ALL_ERROR_CODES — 完整 enum 列表 (含后端 200+ codes 描述) + * + * 仅暴露前 30 常用 + OTHER, 完整 200+ 用作 references/error-codes.md 文档 + * 用途: AI 学习参考 + 兜底分类 + * ============================================================ */ + +export interface ErrorCodeInfo { + code: ErrorCode + category: ErrorCategory + /** 后端 MsgCode.java 原文 */ + rawMessage: string + /** AI 友好提示 */ + suggestion: string +} + +export const ALL_ERROR_CODES: Record = { + // EXIST 系列 (BS-47 全平台唯一性, dacli 必修预校验) + EXIST001: { code: 'EXIST001', category: 'duplicate', rawMessage: '名称不能重复', suggestion: '改名加 _v2 / form delete 后重建, 或换名字' }, + EXIST002: { code: 'EXIST002', category: 'duplicate', rawMessage: '编码不能重复', suggestion: '改 enCode 加 _v2 后缀, 或查 dacli {form/menu/dict/role} list 看占用' }, + EXIST003: { code: 'EXIST003', category: 'duplicate', rawMessage: '模板名已存在', suggestion: '模板名加 _v2 或换名字' }, + EXIST004: { code: 'EXIST004', category: 'duplicate', rawMessage: '文件夹名称不能重复', suggestion: '文件夹改名' }, + EXIST005: { code: 'EXIST005', category: 'duplicate', rawMessage: '模板名称超过了限制长度', suggestion: '缩短到 50 字符以内' }, + EXIST006: { code: 'EXIST006', category: 'duplicate', rawMessage: '账户不能重复', suggestion: '换账户名' }, + EXIST101: { code: 'EXIST101', category: 'duplicate', rawMessage: '名称重复,请重新输入', suggestion: '换 fullName' }, + EXIST102: { code: 'EXIST102', category: 'duplicate', rawMessage: '编码重复,请重新输入', suggestion: '换 enCode' }, + EXIST103: { code: 'EXIST103', category: 'duplicate', rawMessage: '不能重复', suggestion: '查重后再提交' }, + EXIST104: { code: 'EXIST104', category: 'duplicate', rawMessage: '路由地址已存在', suggestion: '换 urlAddress/pageAddress (menu)' }, + // FA 系列 + FA001: { code: 'FA001', category: 'not_found', rawMessage: '数据不存在', suggestion: '跑 dacli {module} info 确认 id 是否被删' }, + FA002: { code: 'FA002', category: 'not_found', rawMessage: '更新失败,数据不存在', suggestion: '确认 id 有效后再 update' }, + FA003: { code: 'FA003', category: 'not_found', rawMessage: '删除失败,数据不存在', suggestion: '确认 id 有效后再 delete' }, + FA019: { code: 'FA019', category: 'invalid_state', rawMessage: '已失效', suggestion: '跑 dacli {module} info 查 enabledMark/state' }, + FA021: { code: 'FA021', category: 'permission', rawMessage: '操作失败!您没有权限操作', suggestion: '切换 admin 账号 或 申请角色权限' }, + FA028: { code: 'FA028', category: 'invalid_state', rawMessage: '新增数据失败', suggestion: '检查必填字段 + 后端日志 (dacli tool logs --level=error)' }, + FA029: { code: 'FA029', category: 'invalid_state', rawMessage: '修改数据失败', suggestion: '检查 step machine 校验 + 后端日志' }, + // VS 系列 + VS024: { code: 'VS024', category: 'visual_dev', rawMessage: '表单不存在或者未发布', suggestion: '跑 dacli form release 发布后再 menu create' }, + VS401: { code: 'VS401', category: 'visual_dev', rawMessage: '该模板内表单内容为空,无法', suggestion: 'formData.fields 不能为空, 至少 1 个 vmodel 控件' }, + VS402: { code: 'VS402', category: 'visual_dev', rawMessage: '该模板内列表内容为空,无法', suggestion: 'columnData.columnList 不能为空 (webType≠1 必须勾选)' }, + VS403: { code: 'VS403', category: 'visual_dev', rawMessage: '该功能未配置流程不可用', suggestion: '绑工作流 (enableFlow=1 + flowId)' }, + VS408: { code: 'VS408', category: 'visual_dev', rawMessage: '请至少选择一个数据表', suggestion: '传 --tables=... 或 --ai-json 含完整 tables' }, + VS409: { code: 'VS409', category: 'visual_dev', rawMessage: '未找到主表信息', suggestion: '检查 ai-json[0].isMain=true 且 tableName 非空' }, + VS411: { code: 'VS411', category: 'visual_dev', rawMessage: '已存在相同功能', suggestion: '同名 enCode 已占用, 加 _v2 后缀' }, + VS412: { code: 'VS412', category: 'visual_dev', rawMessage: '该表单已删除', suggestion: 'form 已删除, 重新创建' }, + // SYS 系列 + SYS014: { code: 'SYS014', category: 'invalid_state', rawMessage: '字典类型下面有字典值禁止删除', suggestion: '先 dacli dict dataDelete 删除所有字典项, 再 typeDelete' }, + SYS017: { code: 'SYS017', category: 'invalid_state', rawMessage: '删除失败,请先删除子菜单', suggestion: '先 dacli menu delete 子菜单, 再 delete 父菜单' }, + // DB 系列 + DB201: { code: 'DB201', category: 'db', rawMessage: '表已经被使用,不允许被删除', suggestion: 'form/workflow/di 引用, 先解除引用再 drop' }, + DB302: { code: 'DB302', category: 'db', rawMessage: '数据库连接失败', suggestion: 'dbLinkId 失效, 跑 dacli app init -- --appCode=X --force-rebuild --restart' }, + // WF 系列 + WF054: { code: 'WF054', category: 'workflow', rawMessage: '流程编码不能重复', suggestion: '改 workflow enCode 加 _v2 后缀' }, + WF025: { code: 'WF025', category: 'workflow', rawMessage: '启用失败,流程未设计', suggestion: 'flowXml 必须含 start + end 节点' }, + // FM 系列 + FM005: { code: 'FM005', category: 'visual_dev', rawMessage: '该表单已被流程引用,无法删除', suggestion: '先解除 workflow.formId 引用, 再 form delete' }, + FM007: { code: 'FM007', category: 'visual_dev', rawMessage: '该模板内表单内容为空,无法发布', suggestion: 'formData.fields 至少 1 个 vmodel 控件 (同 VS401)' }, + // 兜底 + OTHER: { code: 'OTHER', category: 'unknown', rawMessage: '(未识别)', suggestion: '查 references/error-codes.md 或 dacli tool logs --level=error' }, +} + +/* ============================================================ + * 4. classify(msg) — 从后端返回的 msg 提取 prefix + * + * 镜像 web Form.vue:419 validatePopoverRef.setVisible 字段级反馈思想 + * 但代码层做: regex 提取 EXIST/FA/VS/SYS/DB/WF/FM 等 prefix + * ============================================================ */ + +/** 错误码 regex — 提取 EXIST001 / FA021 / VS401 等 prefix */ +const CODE_REGEX = /\b(EXIST\d{3}|EXIST\d{2}|FA\d{3}|FA\d{2}|VS\d{3}|VS\d{2}|SYS\d{3}|SYS\d{2}|DB\d{3}|DB\d{2}|WF\d{3}|WF\d{2}|FM\d{3}|FM\d{2})\b/i + +/** + * 从后端 r.msg 提取 ErrorCode + * @param msg 后端返回的 msg (例: '编码不能重复' / 'EXIST002 / 编码不能重复' / '数据不存在') + * @returns ErrorCode union 或 null (没匹配上 prefix) + */ +export function classify(msg: string): ErrorCode | null { + if (!msg || typeof msg !== 'string') return null + const m = msg.match(CODE_REGEX) + if (!m) return null + const code = m[1].toUpperCase() as ErrorCode + // 验证是已知的 30 个之一 + if (code in ALL_ERROR_CODES) return code + return 'OTHER' +} + +/* ============================================================ + * 5. format(code, ctx) — 给 AI 友好提示 + * + * 返回 { code, category, message, suggestion } + * ctx: 上下文 (例: { entity: 'form', id: 'xxx', enCode: 'yyy' }) + * ============================================================ */ + +export interface FormatContext { + /** 实体类型 (form/menu/dict/workflow/role/di/dm) */ + entity?: string + /** id */ + id?: string + /** enCode (供 suggestion 模板用) */ + enCode?: string + /** 其它自由参数 */ + [key: string]: unknown +} + +export interface FormattedError { + code: ErrorCode + category: ErrorCategory + /** 后端原文 (从 ALL_ERROR_CODES 拿) */ + message: string + /** AI 友好提示 (ctx 替换占位符 {entity}/{id}/{enCode}) */ + suggestion: string +} + +export function format(code: ErrorCode, ctx: FormatContext = {}): FormattedError { + const info = ALL_ERROR_CODES[code] || ALL_ERROR_CODES.OTHER + // 替换 suggestion 里的 {entity}/{id}/{enCode} 占位符 + let suggestion = info.suggestion + if (ctx.entity) suggestion = suggestion.replace(/\{module\}/g, ctx.entity) + if (ctx.entity) suggestion = suggestion.replace(/\{form\/menu\/dict\/role\}/g, ctx.entity) + if (ctx.enCode) suggestion = suggestion.replace(//g, ctx.enCode) + if (ctx.id) suggestion = suggestion.replace(//g, ctx.id) + return { + code: info.code, + category: info.category, + message: info.rawMessage, + suggestion, + } +} + +/* ============================================================ + * 6. aggregate(errors) — 错误聚合 + * + * 镜像 web FormGenerator.vue:239-300 errorList 字段级定位 + validatePopoverRef 聚合展示 + * 返回: 按 code 分桶 + total, AI 一眼看出哪些 code 重复触发 + * ============================================================ */ + +export interface ValidationErrorWithCode { + field?: string + message: string + code?: ErrorCode | string +} + +/** step machine 错误 + 后端错误统一格式 (dacli 所有 create/update 共用) */ +export interface ValidationError { + field?: string + message: string + /** v0.11e+: ErrorCode, 镜像后端 MsgCode.java, AI 能查表 */ + code?: string +} + +export interface AggregateResult { + byCode: Record + total: number + /** 按 category 分桶 (高层视角: duplicate 几个, not_found 几个) */ + byCategory: Record +} + +/** + * 把 ValidationError[] 按 code + category 分桶 + * @param errors step machine 错误 + catch 后端错误 (统一格式) + * @returns 分桶结果 + */ +export function aggregate(errors: ValidationError[]): AggregateResult { + const byCode: Record = {} + const byCategory: Record = { + duplicate: 0, + not_found: 0, + permission: 0, + invalid_state: 0, + db: 0, + workflow: 0, + visual_dev: 0, + unknown: 0, + } + for (const e of errors) { + const code = e.code || 'OTHER' + if (!byCode[code]) byCode[code] = [] + byCode[code].push(e) + + // 查 category + const cat = (code in ALL_ERROR_CODES + ? ALL_ERROR_CODES[code as ErrorCode].category + : 'unknown') as ErrorCategory + byCategory[cat]++ + } + return { byCode, total: errors.length, byCategory } +} + +/* ============================================================ + * 7. formatErrorLine(err) — 单行格式化 (供 create/update 输出用) + * + * 输出格式: [step 0 基础信息] enCode: EXIST002 - 编码不能重复 (改名加 _v2) + * 镜像 _dirty_check.ts:103-106 错误输出风格 + * ============================================================ */ + +export interface FormatErrorLineOpts { + /** step 编号 (0/1/2/3), 用于前缀 */ + step?: number | string + /** step 名 */ + stepName?: string +} + +export function formatErrorLine( + err: ValidationError, + opts: FormatErrorLineOpts = {}, +): string { + const parts: string[] = [] + if (opts.step !== undefined && opts.stepName) { + parts.push(`[step ${opts.step} ${opts.stepName}]`) + } + if (err.field) parts.push(err.field) + if (err.code) parts.push(`${err.code} - ${err.message}`) + else parts.push(err.message) + return parts.join(': ') +} + +/* ============================================================ + * 8. enhanceFromBackend(msg, field?, ctx) — catch 后端错时一键增强 + * + * 用法: + * } catch (e: any) { + * const enhanced = enhanceFromBackend(e?.msg || String(e), 'enCode', { entity: 'form' }) + * log.error(formatErrorLine(enhanced, { step: 0, stepName: '基础信息' })) + * } + * + * 输出: ValidationError { field, message, code } — 自动填 code (从 msg 提取) + * ============================================================ */ + +export function enhanceFromBackend( + msg: string, + field?: string, + ctx: FormatContext = {}, +): ValidationError { + const code = classify(msg) + const info = code ? format(code, ctx) : { code: 'OTHER', category: 'unknown' as ErrorCategory, message: msg, suggestion: '' } + return { + field, + message: info.message || msg, + code: info.code === 'OTHER' ? undefined : info.code, + } +} \ No newline at end of file diff --git a/src/commands/di/_validate.ts b/src/commands/di/_validate.ts index be9e73d..36ec5ae 100644 --- a/src/commands/di/_validate.ts +++ b/src/commands/di/_validate.ts @@ -32,6 +32,9 @@ export interface ValidationError { field?: string message: string + /** v0.11e+: ErrorCode (镜像后端 MsgCode.java, AI 能查表) + * 复刻 _error_codes.ts 的 ValidationError 字段, 让 step machine 输出格式统一 */ + code?: string } export interface StepValidation { @@ -184,7 +187,7 @@ export function validateUniqueness(opts: { (d) => d.fullName === opts.fullName && d.id !== opts.currentId, ) if (dup) { - errors.push({ field: 'fullName', message: `名称"${opts.fullName}"已存在 (BS-47, 后端 EXIST001)` }) + errors.push({ field: 'fullName', message: `名称"${opts.fullName}"已存在 (BS-47, 后端 EXIST001)`, code: 'EXIST001' }) } } @@ -194,7 +197,7 @@ export function validateUniqueness(opts: { (d) => d.enCode === opts.enCode && d.id !== opts.currentId, ) if (dup) { - errors.push({ field: 'enCode', message: `编码"${opts.enCode}"已存在 (BS-47, 后端 EXIST002)` }) + errors.push({ field: 'enCode', message: `编码"${opts.enCode}"已存在 (BS-47, 后端 EXIST002)`, code: 'EXIST002' }) } } diff --git a/src/commands/di/create.ts b/src/commands/di/create.ts index 8581c83..9b93bc7 100644 --- a/src/commands/di/create.ts +++ b/src/commands/di/create.ts @@ -18,6 +18,7 @@ import { installAiHelpHook } from '../../core/help.ts' import { log, printJson } from '../../core/log.ts' import { initWebapi, loadDataInterface } from '../../webapi/di.ts' import { validateDiUpdate, type DiOpts } from './_validate.ts' +import { enhanceFromBackend, formatErrorLine } from '../_error_codes.ts' interface CreateOpts { fullName: string @@ -88,6 +89,9 @@ export function buildDiCreateCommand(): Command { } if (r.code !== 200 && r.code !== undefined) { log.error(`di create 失败 (code=${r.code}): ${r.msg}`) + // v0.11e+ Phase A1: 后端错误增强 — 自动从 msg 提取 ErrorCode + const enhanced = enhanceFromBackend(r.msg || '', 'di', { entity: 'di' }) + log.error(` ${formatErrorLine(enhanced, { step: 2, stepName: '后端API' })}`) if (opts.json) printJson(r) process.exit(1) } diff --git a/src/commands/di/update.ts b/src/commands/di/update.ts index 5d5ac00..2daa416 100644 --- a/src/commands/di/update.ts +++ b/src/commands/di/update.ts @@ -10,6 +10,7 @@ import { installAiHelpHook } from '../../core/help.ts' import { log, printJson } from '../../core/log.ts' import { initWebapi, loadDataInterface } from '../../webapi/di.ts' import { validateDiUpdate, type DiOpts } from './_validate.ts' +import { enhanceFromBackend, formatErrorLine } from '../_error_codes.ts' interface Opts { id: string @@ -54,6 +55,9 @@ export function buildDiUpdateCommand(): Command { const r = (await loadDataInterface.updateDataInterface(body)) as { code?: number; msg?: string; data?: unknown } if (r.code !== 200 && r.code !== undefined) { log.error(`di update 失败 (code=${r.code}): ${r.msg}`) + // v0.11e+ Phase A1: 后端错误增强 — 自动从 msg 提取 ErrorCode + const enhanced = enhanceFromBackend(r.msg || '', 'di', { entity: 'di' }) + log.error(` ${formatErrorLine(enhanced, { step: 2, stepName: '后端API' })}`) if (opts.json) printJson(r) process.exit(1) } diff --git a/src/commands/dict/_validate.ts b/src/commands/dict/_validate.ts index 2e3dc2b..99a8af4 100644 --- a/src/commands/dict/_validate.ts +++ b/src/commands/dict/_validate.ts @@ -28,6 +28,9 @@ export interface ValidationError { field?: string message: string + /** v0.11e+: ErrorCode (镜像后端 MsgCode.java, AI 能查表) + * 复刻 _error_codes.ts 的 ValidationError 字段, 让 step machine 输出格式统一 */ + code?: string } export interface StepValidation { @@ -142,7 +145,7 @@ export function validateUniqueness(opts: { if (opts.fullName) { const dup = opts.existingTypes.find((t) => t.fullName === opts.fullName) if (dup) { - errors.push({ field: 'fullName', message: `字典名称"${opts.fullName}"已存在 (BS-47, 后端 EXIST001)` }) + errors.push({ field: 'fullName', message: `字典名称"${opts.fullName}"已存在 (BS-47, 后端 EXIST001)`, code: 'EXIST001' }) } } @@ -150,7 +153,7 @@ export function validateUniqueness(opts: { if (opts.enCode) { const dup = opts.existingTypes.find((t) => t.enCode === opts.enCode) if (dup) { - errors.push({ field: 'enCode', message: `字典编码"${opts.enCode}"已存在 (BS-47, 后端 EXIST002)` }) + errors.push({ field: 'enCode', message: `字典编码"${opts.enCode}"已存在 (BS-47, 后端 EXIST002)`, code: 'EXIST002' }) } } diff --git a/src/commands/dict/typecreate.ts b/src/commands/dict/typecreate.ts index e5d10fe..0669939 100644 --- a/src/commands/dict/typecreate.ts +++ b/src/commands/dict/typecreate.ts @@ -11,6 +11,7 @@ import { installAiHelpHook } from '../../core/help.ts' import { log, printJson } from '../../core/log.ts' import { initWebapi, loadDict } from '../../webapi/dict.ts' import { validateDictTypeCreate, type DictItemLite } from './_validate.ts' +import { enhanceFromBackend, formatErrorLine } from '../_error_codes.ts' interface Opts { enCode: string @@ -80,6 +81,9 @@ export function buildDictTypeCreateCommand(): Command { const tr = (await loadDict.createDictionaryType(typeBody)) as { id: string; code?: number; msg?: string } if (tr.code !== undefined && tr.code !== 200) { log.error(`建字典类型失败 (code=${tr.code}): ${tr.msg}`) + // v0.11e+ Phase A1: 后端错误增强 — 自动从 msg 提取 ErrorCode + const enhanced = enhanceFromBackend(tr.msg || '', 'dictType', { entity: 'dict' }) + log.error(` ${formatErrorLine(enhanced, { step: 1, stepName: '后端API' })}`) process.exit(1) } const typeId = tr.id || '(unknown)' diff --git a/src/commands/dm/_validate.ts b/src/commands/dm/_validate.ts index f25912b..31e6384 100644 --- a/src/commands/dm/_validate.ts +++ b/src/commands/dm/_validate.ts @@ -33,6 +33,9 @@ export interface ValidationError { field?: string /** 错误消息 (镜像 web 文案 + 后端 EXIST 码, AI 能对照) */ message: string + /** v0.11e+: ErrorCode (镜像后端 MsgCode.java, AI 能查表) + * 复刻 _error_codes.ts 的 ValidationError 字段, 让 step machine 输出格式统一 */ + code?: string } export interface StepValidation { @@ -326,6 +329,7 @@ export function validateKeywordAndUniqueness(opts: { errors.push({ field: 'table', message: `表名称"${opts.table}"已存在 (后端 EXIST001 预校验)`, + code: 'EXIST001', }) } } diff --git a/src/commands/dm/create.ts b/src/commands/dm/create.ts index 30f5352..7a599ef 100644 --- a/src/commands/dm/create.ts +++ b/src/commands/dm/create.ts @@ -15,6 +15,7 @@ import { runGuards, handleGuardResult } from '../_blindspot_guards.ts' import { loadAppContext } from '../app/context.ts' import { initWebapi, loadDataModel } from '../../webapi/dataModel.ts' import { validateDmCreate, type DmFieldLite } from './_validate.ts' +import { enhanceFromBackend, formatErrorLine } from '../_error_codes.ts' interface CreateOpts { table: string @@ -148,6 +149,9 @@ export function buildDmCreateCommand(): Command { log.error(' 详见 docs/tds/summary.html §3 盲点 38') } else { log.error(`建表失败 (code=${r.code}): ${r.msg}`) + // v0.11e+ Phase A1: 后端错误增强 — 自动从 msg 提取 ErrorCode + const enhanced = enhanceFromBackend(errMsg, 'table', { entity: 'dm' }) + log.error(` ${formatErrorLine(enhanced, { step: 2, stepName: '后端API' })}`) } if (opts.json) printJson(r) process.exit(1) diff --git a/src/commands/form/_validate.ts b/src/commands/form/_validate.ts index 3246bff..26e6494 100644 --- a/src/commands/form/_validate.ts +++ b/src/commands/form/_validate.ts @@ -21,6 +21,9 @@ export interface ValidationError { field?: string /** 错误消息 (镜像 web 文案, AI 能对照) */ message: string + /** v0.11e+: ErrorCode (镜像后端 MsgCode.java, AI 能查表) + * 复刻 _error_codes.ts 的 ValidationError 字段, 让 step machine 输出格式统一 */ + code?: string } export interface StepValidation { @@ -53,7 +56,7 @@ export function validateBasicInfo(opts: { errors.push({ field: 'enCode', message: '表单编码不能为空' }) } else if (!VMODEL_REGEXP.test(opts.enCode)) { // 镜像 Generator.getData() line 247-249: tableName RegExp 校验 (enCode 也走同一规则) - errors.push({ field: 'enCode', message: '只能由字母、数字、下划线组成,且以字母开头' }) + errors.push({ field: 'enCode', message: '只能由字母、数字、下划线组成,且以字母开头', code: 'VS030' }) } // state.tables 检查 (Form.vue:329-345 handleNext step 0) @@ -62,7 +65,7 @@ export function validateBasicInfo(opts: { // 默认表兜底: type=3 (树) 或 type=4 (视图) 必须有物理表 (BS-55 规则) // type=1/2 不强制 (场景 A 默认 fallback) if (type === 3 || type === 4) { - errors.push({ field: 'tables', message: '请至少选择一个数据表' }) + errors.push({ field: 'tables', message: '请至少选择一个数据表', code: 'VS408' }) } } else { // exist() 子表外键/关联字段校验 (Form.vue:385-403 handleNext step 0) @@ -97,7 +100,7 @@ export function validateFormData(formData: { fields?: any[] } | null, type: numb } if (!formData || !Array.isArray(formData.fields) || formData.fields.length === 0) { - errors.push({ field: 'formData.fields', message: '表单内容不能为空' }) + errors.push({ field: 'formData.fields', message: '表单内容不能为空', code: 'VS401' }) return { ok: false, step: 1, stepName: '表单字段', errors } } @@ -184,6 +187,7 @@ export function validateColumnData(columnData: any | null, webType: number): Ste errors.push({ field: 'columnData.columnList', message: '列表字段不允许为空 (webType≠1 必须勾选至少一个列表列)', + code: 'VS402', }) } diff --git a/src/commands/form/create.ts b/src/commands/form/create.ts index 18b1997..bffb324 100644 --- a/src/commands/form/create.ts +++ b/src/commands/form/create.ts @@ -20,6 +20,7 @@ import { preCheckFormCreate, handlePreCheckResult } from '../_precheck.ts' import { loadContextSafe } from '../_precheck.ts' import { runGuards, handleGuardResult } from '../_blindspot_guards.ts' import { validateFormCreate } from './_validate.ts' +import { enhanceFromBackend, formatErrorLine } from '../_error_codes.ts' import { loadAppContext } from '../app/context.ts' interface CreateOpts { @@ -674,7 +675,10 @@ export function buildFormCreateCommand(): Command { // L3 diagnose 仍可在 r.msg 上手工触发 (后续可加) const r = (await loadVisualDev.create(body)) as { code?: number; msg?: string; data?: { id?: string } } if (r.code !== 200 && r.code !== undefined) { + // v0.11e+ Phase A1: 后端错误增强 — 自动从 msg 提取 ErrorCode (EXIST/VS/SYS 等) + const enhanced = enhanceFromBackend(r.msg || '', 'form', { entity: 'form' }) log.error(`创建失败 (code=${r.code}): ${r.msg}`) + log.error(` ${formatErrorLine(enhanced, { step: 0, stepName: '后端API' })}`) if (opts.json) printJson(r) process.exit(1) } diff --git a/src/commands/menu/_validate.ts b/src/commands/menu/_validate.ts index 657a567..0dbbd77 100644 --- a/src/commands/menu/_validate.ts +++ b/src/commands/menu/_validate.ts @@ -34,6 +34,9 @@ export interface ValidationError { field?: string /** 错误消息 (镜像 web 文案 + 后端 EXIST 码, AI 能对照) */ message: string + /** v0.11e+: ErrorCode (镜像后端 MsgCode.java, AI 能查表) + * 复刻 _error_codes.ts 的 ValidationError 字段, 让 step machine 输出格式统一 */ + code?: string } export interface StepValidation { @@ -395,6 +398,7 @@ export function validateUniqueness(opts: { errors.push({ field: 'fullName', message: `菜单名称已存在 (id=${dup.id}, enCode=${dup.enCode})`, + code: 'EXIST001', }) } } @@ -409,6 +413,7 @@ export function validateUniqueness(opts: { errors.push({ field: 'enCode', message: `菜单编码已存在 (id=${dup.id}, fullName=${dup.fullName})`, + code: 'EXIST002', }) } } @@ -425,6 +430,7 @@ export function validateUniqueness(opts: { errors.push({ field: 'urlAddress', message: `路由地址已存在 (id=${dup.id}, fullName=${dup.fullName}, url=${url})`, + code: 'EXIST104', }) } } diff --git a/src/commands/menu/create.ts b/src/commands/menu/create.ts index 3d66887..0ac0b30 100644 --- a/src/commands/menu/create.ts +++ b/src/commands/menu/create.ts @@ -28,6 +28,7 @@ import { log, printJson } from '../../core/log.ts' import { loadContextSafe } from '../_precheck.ts' import { runGuards, handleGuardResult } from '../_blindspot_guards.ts' import { validateMenuCreate, type MenuNodeLite, type FormLite } from './_validate.ts' +import { enhanceFromBackend, formatErrorLine } from '../_error_codes.ts' import { fetchMenuTree } from './_helpers.ts' interface Opts { @@ -202,6 +203,9 @@ export function buildMenuCreateCommand(): Command { log.error(` ↳ 重试仍失败 code=${rr.code}: ${rr.msg}`) } log.error(`menu create (Actions/Module) 失败 code=${r.code}: ${r.msg}`) + // v0.11e+ Phase A1: 后端错误增强 — 自动从 msg 提取 ErrorCode + const enhanced = enhanceFromBackend(r.msg || '', 'menu', { entity: 'menu' }) + log.error(` ${formatErrorLine(enhanced, { step: 3, stepName: '后端API' })}`) if (opts.json) printJson(r) process.exit(1) } @@ -300,6 +304,9 @@ export function buildMenuCreateCommand(): Command { const r = await c.postJson<{ id?: string }>('/system/Menu', body) if (r.code !== 200) { log.error(`menu create 失败 code=${r.code}: ${r.msg}`) + // v0.11e+ Phase A1: 后端错误增强 — 自动从 msg 提取 ErrorCode + const enhanced = enhanceFromBackend(r.msg || '', 'menu', { entity: 'menu' }) + log.error(` ${formatErrorLine(enhanced, { step: 3, stepName: '后端API' })}`) process.exit(1) } let menuId: string | undefined = r.data?.id diff --git a/src/commands/role/_validate.ts b/src/commands/role/_validate.ts index 5f9beb3..b7a2a15 100644 --- a/src/commands/role/_validate.ts +++ b/src/commands/role/_validate.ts @@ -29,6 +29,9 @@ export interface ValidationError { field?: string message: string + /** v0.11e+: ErrorCode (镜像后端 MsgCode.java, AI 能查表) + * 复刻 _error_codes.ts 的 ValidationError 字段, 让 step machine 输出格式统一 */ + code?: string } export interface StepValidation { @@ -202,7 +205,7 @@ export function validateUniqueness(opts: { if (opts.enCode) { const dup = opts.existingRoles.find((r) => r.enCode === opts.enCode) if (dup) { - errors.push({ field: 'enCode', message: `角色编码"${opts.enCode}"已存在 (BS-47, 后端 EXIST002)` }) + errors.push({ field: 'enCode', message: `角色编码"${opts.enCode}"已存在 (BS-47, 后端 EXIST002)`, code: 'EXIST002' }) } } @@ -214,6 +217,7 @@ export function validateUniqueness(opts: { errors.push({ field: 'fullName', message: `角色名称"${opts.fullName}"在 type=${t} 下已存在 (后端 EXIST001, 按 type 分类)`, + code: 'EXIST001', }) } } diff --git a/src/commands/role/create.ts b/src/commands/role/create.ts index b1a1773..126b683 100644 --- a/src/commands/role/create.ts +++ b/src/commands/role/create.ts @@ -8,6 +8,7 @@ import { JnpfClient } from '../../core/client.ts' import { installAiHelpHook } from '../../core/help.ts' import { log, printJson } from '../../core/log.ts' import { validateRoleCreate } from './_validate.ts' +import { enhanceFromBackend, formatErrorLine } from '../_error_codes.ts' interface CreateOpts { fullName: string @@ -49,6 +50,9 @@ export function buildRoleCreateCommand(): Command { const r = await c.postJson<{ id?: string }>('/permission/Role', body) if (r.code !== 200) { log.error(`role create 失败 (code=${r.code}): ${r.msg}`) + // v0.11e+ Phase A1: 后端错误增强 — 自动从 msg 提取 ErrorCode + const enhanced = enhanceFromBackend(r.msg || '', 'role', { entity: 'role' }) + log.error(` ${formatErrorLine(enhanced, { step: 2, stepName: '后端API' })}`) process.exit(1) } let id = r.data?.id diff --git a/src/commands/role/update.ts b/src/commands/role/update.ts index 66cb8b9..b6ebb9a 100644 --- a/src/commands/role/update.ts +++ b/src/commands/role/update.ts @@ -9,6 +9,7 @@ import { JnpfClient } from '../../core/client.ts' import { installAiHelpHook } from '../../core/help.ts' import { log, printJson } from '../../core/log.ts' import { initWebapi, loadRole } from '../../webapi/role.ts' +import { enhanceFromBackend, formatErrorLine } from '../_error_codes.ts' interface Opts { id: string @@ -44,7 +45,8 @@ export function buildRoleUpdateCommand(): Command { log.info(`loadRole.update (id=${opts.id})`) const r = (await loadRole.update(body)) as { code?: number; msg?: string; data?: unknown } if (r.code !== 200 && r.code !== undefined) { - log.error(`role update 失败 (code=${r.code}): ${r.msg}`) + const enhanced = enhanceFromBackend(r.msg || '', 'role', { entity: 'role' }) + log.error(` ${formatErrorLine(enhanced, { step: 2, stepName: '后端API' })}`) if (opts.json) printJson(r) process.exit(1) } diff --git a/src/commands/workflow/_validate.ts b/src/commands/workflow/_validate.ts index 3645992..3904125 100644 --- a/src/commands/workflow/_validate.ts +++ b/src/commands/workflow/_validate.ts @@ -29,6 +29,9 @@ export interface ValidationError { field?: string message: string + /** v0.11e+: ErrorCode (镜像后端 MsgCode.java, AI 能查表) + * 复刻 _error_codes.ts 的 ValidationError 字段, 让 step machine 输出格式统一 */ + code?: string } export interface StepValidation { @@ -220,6 +223,7 @@ export function validateUniqueness(opts: { errors.push({ field: 'enCode', message: `流程编码"${opts.enCode}"已存在 (后端 SU001 预校验)`, + code: 'WF054', }) } } diff --git a/src/commands/workflow/create.ts b/src/commands/workflow/create.ts index 08e500b..7037028 100644 --- a/src/commands/workflow/create.ts +++ b/src/commands/workflow/create.ts @@ -14,6 +14,7 @@ import { installAiHelpHook } from '../../core/help.ts' import { log, printJson } from '../../core/log.ts' import { callAiWorkflow } from '../form/_ai.ts' import { validateWorkflowCreate } from './_validate.ts' +import { enhanceFromBackend, formatErrorLine } from '../_error_codes.ts' interface CreateOpts { fullName?: string @@ -118,6 +119,9 @@ export function buildWorkflowCreateCommand(): Command { const r = await c.postJson('/workflow/template', body) if (r.code !== 200) { log.error(`创建流程失败 (code=${r.code}): ${r.msg}`) + // v0.11e+ Phase A1: 后端错误增强 — 自动从 msg 提取 ErrorCode + const enhanced = enhanceFromBackend(r.msg || '', 'workflow', { entity: 'workflow' }) + log.error(` ${formatErrorLine(enhanced, { step: 2, stepName: '后端API' })}`) if (opts.json) printJson(r) process.exit(1) }