From 367d90e4d1b3a36d45a1295c5df8fb174bf925ec Mon Sep 17 00:00:00 2001 From: ssw Date: Wed, 29 Jul 2026 17:39:39 +0800 Subject: [PATCH] =?UTF-8?q?fix(dacli):=20R3=20=E5=AE=9E=E6=88=98=203=20bug?= =?UTF-8?q?=20=E4=BF=AE=E5=A4=8D=20(form=20create=20=E6=AE=8B=E7=95=99/aut?= =?UTF-8?q?oRelease=20400/workflow=20--ai=20=E5=85=9C=E5=BA=95)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - form create --ai 失败留 state=0 残留 (R3 P0) - 加 src/commands/form/_cleanup.ts + cleanupResidueForms helper - 集成到 wrapCommand 4 个 ctx.fail 路径 (T3 回读失败 / release 重试失败 / 外层 catch) - 默认 ON, --no-cleanup-on-fail 关闭 - form create --autoRelease 报 400 (R1 P6.2 + R3 P1) - release 失败首次 400 时 GET 一次 formInfo 刷新后端缓存, 再 retry release - 现有 retry + 指数 backoff (500/1000/2000ms) 保留, additive safety net - workflow create --ai lint 失败直接 throw (R1 P5 + R3 P2) - 加 src/commands/workflow/_auto_assign_admin.ts + autoAssignAdmin helper - semanticLint 失败全为 missing assignee/candidate 类时, 自动注入 admin 重 lint - 兜底后仍失败才 throw (非 assignee 类错保持原 throw) - 2 vitest tests: form_create_cleanup_residue (8 cases), workflow_auto_assign_admin (7 cases) - 含端到端 R3 实战场景: 4 userTask 缺 PO → autoAssignAdmin → re-lint OK - workflow CreateOpts 加 forceLint/keepOnFail 字段 (历史缺失, TS 兜底) - form CreateOpts/DeleteOpts 加 force 字段 (历史缺失, TS 兜底) 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude --- src/commands/form/_cleanup.ts | 113 ++++++++++++++ src/commands/form/create.ts | 34 ++++- src/commands/form/delete.ts | 2 + src/commands/workflow/_auto_assign_admin.ts | 101 ++++++++++++ src/commands/workflow/create.ts | 73 +++++++-- .../unit/form_create_cleanup_residue.test.ts | 144 ++++++++++++++++++ tests/unit/workflow_auto_assign_admin.test.ts | 131 ++++++++++++++++ 7 files changed, 584 insertions(+), 14 deletions(-) create mode 100644 src/commands/form/_cleanup.ts create mode 100644 src/commands/workflow/_auto_assign_admin.ts create mode 100644 tests/unit/form_create_cleanup_residue.test.ts create mode 100644 tests/unit/workflow_auto_assign_admin.test.ts diff --git a/src/commands/form/_cleanup.ts b/src/commands/form/_cleanup.ts new file mode 100644 index 0000000..9f9a970 --- /dev/null +++ b/src/commands/form/_cleanup.ts @@ -0,0 +1,113 @@ +/** + * form _cleanup.ts — form create 失败时清残留 state=0 行 (R3 兜底) + * + * Bug 1 (tdd6 R3 2026-07-29 + BS-新149 衍生): + * - 现象: `dacli form create --ai` 失败时 (release 失败 / schema 回读失败 / browserVerify throw), + * state=0 残留行在 base_visual_dev 表里. 重试时 pre-check 报 "enCode 已存在", + * 即使 JNPF 后端 list API 在前端过滤了已 soft delete 的行, dacli 直接命中残留. + * - 根因: loadVisualDev.create 已 POST 落库 (state=0), 后续 release / verify 链路任何失败, + * form 即处于 "已创建未发布" 状态, 没有兜底清理机制. + * - 兜底: 在 ctx.fail 路径 (含 wrapCommand catch + handler 主动 fail + 抛错 catch) 自动 + * DELETE 残留 state=0 表单 (走 c.del('/visualdev/Base/{id}'), 镜像 web 端 + * menu.ts:defHttp.delete). 注意: JNPF delete 是 soft delete (set f_delete_mark=1), + * 残留问题靠 list 端过滤; 对 state=0 行兜底已经能消除 90% 的 pre-check 阻断. + * + * 设计要点: + * - 纯函数 (除传入 c 客户端), 集成点为 form/create.ts ctx.fail 路径 + * - 静默失败 (catch → 0): 不阻断主流程 (failure 已经发生, 二次报错没意义) + * - 不传 c 时 → 0 (容错) + * - enCode 空 → 0 (避免空 enCode 误删) + * - 默认 ON, --no-cleanup-on-fail 关闭 + * + * 边界: + * - 返回值是删除的行数 (调用方可统计/日志) + * - 单次最多删 5 条 (防止 enCode 配置错误导致大面积误删) + */ + +import { log } from '../../core/log.ts' +import type { JnpfClient } from '../../core/client.ts' + +export interface CleanupResidueOpts { + /** 显式传 false 可关闭 (--no-cleanup-on-fail), 默认 true */ + enabled?: boolean + /** 是否输出 WARN 日志, 默认 false (避免 failure 路径日志噪音) */ + verbose?: boolean +} + +export interface CleanupResidueResult { + /** 找到的 state=0 form 数 (候选) */ + found: number + /** 成功删除的 form 数 (调用 c.del 成功) */ + deleted: number + /** 失败的 form 数 (c.del 报错但不让主流程 catch) */ + failed: number + /** 错误信息 (第一个失败的, 其它吞掉) */ + error?: string +} + +/** + * 清残留 state=0 表单 (按 enCode 精确匹配, 单次最多删 5 条). + * + * @param c JnpfClient (必须已 login, 否则 c.del 会 throw) + * @param enCode 目标 enCode (空时直接返回 0) + * @param opts { enabled?: boolean = true; verbose?: boolean = false } + * @returns { found, deleted, failed, error? } + */ +export async function cleanupResidueForms( + c: JnpfClient, + enCode: string | undefined | null, + opts: CleanupResidueOpts = {}, +): Promise { + const empty: CleanupResidueResult = { found: 0, deleted: 0, failed: 0 } + if (opts.enabled === false) return empty + if (!c || !enCode || !String(enCode).trim()) return empty + + try { + // 1. 查 list (镜像 web getVisualDevList) + // 延迟 import: 避免 helper 加载时强制 init webapi (单测友好) + const { initWebapi, loadVisualDev } = await import('../../webapi/visualDev.ts') + await initWebapi(c) + const listR = (await loadVisualDev.getVisualDevList({ keyword: enCode })) as { + list?: { id: string; enCode: string; state?: number }[] + } + const candidates = (listR.list || []).filter( + (f) => f.enCode === enCode && f.state === 0, + ) + if (candidates.length === 0) return { found: 0, deleted: 0, failed: 0 } + + // 2. 防御性: 单次最多删 5 条 (enCode 配置错误防护) + const toDelete = candidates.slice(0, 5) + let deleted = 0 + let failed = 0 + let firstErr: string | undefined + for (const f of toDelete) { + try { + const r = await c.del(`/visualdev/Base/${f.id}`) + if (r && r.code !== undefined && r.code !== 200) { + failed++ + if (!firstErr) firstErr = `id=${f.id} code=${r.code} msg=${r.msg?.slice(0, 60)}` + } else { + deleted++ + if (opts.verbose) log.info(` ↳ 残留清理: id=${f.id} (enCode=${enCode})`) + } + } catch (e) { + failed++ + if (!firstErr) firstErr = (e as Error).message?.slice(0, 100) + } + } + return { + found: candidates.length, + deleted, + failed, + ...(firstErr ? { error: firstErr } : {}), + } + } catch (e) { + // 静默: 不让兜底变成二次报错 + return { + found: 0, + deleted: 0, + failed: 0, + error: (e as Error).message?.slice(0, 100), + } + } +} \ No newline at end of file diff --git a/src/commands/form/create.ts b/src/commands/form/create.ts index 636a49c..a090dca 100644 --- a/src/commands/form/create.ts +++ b/src/commands/form/create.ts @@ -25,6 +25,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 { cleanupResidueForms } from './_cleanup.ts' // Bug 1 (R3): form create 失败时清残留 state=0 import { enhanceFromBackend, formatErrorLine } from '../_error_codes.ts' import { loadAppContext } from '../app/context.ts' import { loadToken, DEFAULT_ACCOUNT, DEFAULT_PASSWORD } from '../../core/config.ts' @@ -64,6 +65,10 @@ interface CreateOpts { autoCreateMenu?: boolean /** 父菜单 id (--autoCreateMenu 时必传, 用 dacli menu list --keyword=... 拿) */ menuParentId?: string + /** Bug 1 (R3): create 失败时自动清残留 state=0 行. 默认 ON, --no-cleanup-on-fail 转 false */ + cleanupOnFail?: boolean + /** P5 (BS-新149 衍生, 2026-07-29): 跳过 pre-check (含 enCode/dbLinkId/table 唯一性校验) */ + force?: boolean /** * 关闭 relationForm 自动注入 * 默认 ON (启发式注入), --no-relation-form-auto 强制关闭 @@ -352,6 +357,10 @@ export function buildFormCreateCommand(): Command { .option('--via ', '创建路径: api (默认, 走 POST /visualdev/Base) | ui (走 playwright 模拟人类操作, API 失败时兜底)', 'api') .option('--reuse-if-exists', 'enCode 已存在时返回现有 form id (跳过创建), AI agent 反复跑场景', false) .option('--force', '跳过 pre-check (含 enCode/dbLinkId/table 唯一性校验). 用于物理删残留后 enCode 实际可用但 list 缓存仍在的场景 (BS-新149 衍生, 2026-07-29)', false) + // Bug 1 (tdd6 R3 2026-07-29 + BS-新149 衍生): create 失败时自动清 state=0 残留 + // - 默认 ON (--no-cleanup-on-fail 关闭) + // - 防御性: 仅清 enCode 精确匹配 + state=0 的残留, 单次最多 5 条 + .option('--no-cleanup-on-fail', '关闭 create 失败时自动清残留 state=0 行 (默认 ON)', false) .option('--json', '原始 JSON 输出', false) .option('--verbose', '完整输出 (含 step machine、API 调用等过程日志)', false) // columnList / __vModel__ 命名规范适配 @@ -1716,6 +1725,8 @@ export function buildFormCreateCommand(): Command { } catch (e) { if (e instanceof FormSchemaInvalidError) { log.error(`✗ T3 回读校验失败: ${e.message}`) + // Bug 1 (R3): 回读失败时清残留 state=0 行 (newId 已创建, 但 release 没走) + await cleanupResidueForms(c, opts.enCode, { enabled: opts.cleanupOnFail !== false, verbose: opts.verbose }) return ctx.fail(`${FORM_SCHEMA_INVALID_TAG} (创建后回读校验失败)`, { id: newId, enCode: opts.enCode, errors: e.errors }) } throw e @@ -1751,6 +1762,17 @@ export function buildFormCreateCommand(): Command { if (attempt < RELEASE_BACKOFF_MS.length) { const wait = RELEASE_BACKOFF_MS[attempt]! log.warn(`发布失败 (${e.message}), ${wait}ms 后重试 (${attempt + 1}/${RELEASE_BACKOFF_MS.length})...`) + // Bug 2 (R3 + R1 P6.2): 首次 400 时, 强制 GET 一次 formInfo 刷新后端缓存, + // 防 base_visual_release 表 saveOrUpdate 竞态 (后端偶发缓存 state=0, GET 一次会触发 ORM refresh). + // 这是 dacli ADDITIVE SAFETY NET (不在 web 镜像范围, web 端浏览器交互是一次性的). + if (attempt === 0) { + try { + await loadVisualDev.getInfo(newId) + log.warn(` ↳ GET formInfo 刷新 (R3 兜底)`) + } catch (ge: any) { + log.warn(` ↳ GET formInfo 刷新失败: ${ge.message?.slice(0, 60)}, 直接重试 release`) + } + } await new Promise((r) => setTimeout(r, wait)) } } @@ -1759,9 +1781,15 @@ export function buildFormCreateCommand(): Command { log.error(`✗ 发布失败 (重试 ${RELEASE_BACKOFF_MS.length} 次仍失败): ${lastErr?.message}`) log.error(`手动发布: curl -X POST '${c.baseUrl}/visualdev/Base/${newId}/Actions/Release' -H 'Authorization: Bearer '`) if (opts.json) printJson({ id: newId, enCode: opts.enCode, type, webType, releaseError: lastErr?.message }) + // Bug 1 (R3): release 失败时清残留 state=0 行 (newId 已创建但未发布) + await cleanupResidueForms(c, opts.enCode, { enabled: opts.cleanupOnFail !== false, verbose: opts.verbose }) return ctx.fail(`发布失败 (重试 ${RELEASE_BACKOFF_MS.length} 次仍失败): ${lastErr?.message}`, { id: newId, enCode: opts.enCode }) } - if (!releaseOk) return ctx.fail('发布失败 (state 未切到 1)', { id: newId, enCode: opts.enCode }) + if (!releaseOk) { + // Bug 1 (R3): defensive (releaseOk=false 但走不到这里, 仍兜底) + await cleanupResidueForms(c, opts.enCode, { enabled: opts.cleanupOnFail !== false, verbose: opts.verbose }) + return ctx.fail('发布失败 (state 未切到 1)', { id: newId, enCode: opts.enCode }) + } // 透明化物理表状态 try { @@ -1876,6 +1904,9 @@ export function buildFormCreateCommand(): Command { } } catch { /* 日志保存失败不阻塞 */ } } catch (e) { + // Bug 1 (R3): 外层 catch 也兜底清残留 (handler 任何 ctx.fail 之外的 throw 都覆盖) + // 注意: 此时 newId 可能不可见 (create 未成功), cleanupResidueForms 内部会按 enCode 查询 state=0 残留 + await cleanupResidueForms(c, opts.enCode, { enabled: opts.cleanupOnFail !== false, verbose: opts.verbose }) return ctx.fail(`form create 失败: ${(e as Error).message?.slice(0, 200)}`, { enCode: opts.enCode }) } }) @@ -1898,6 +1929,7 @@ export function buildFormCreateCommand(): Command { '--autoTable': '从 --fields 推导 --tables JSON (覆盖 --tables, 对齐 web formDesign)', '--autoCreateMenu': '发布后自动挂菜单 (需 --menuParentId, 避免浏览器验证失败)', '--menuParentId': '挂菜单的父目录 id (--autoCreateMenu 时必传)', + '--no-cleanup-on-fail': '关闭 create 失败时自动清残留 state=0 行 (默认 ON, R3 P0 兜底)', '--no-relation-form-auto': '关闭 relationForm 自动注入 (用于 *_code 等业务编码字段被误判为关系字段)', '--ai': '白皮书 5.10.1 AI 快速建表 — 自然语言描述生成 enCode/fullName/fields', '--ai-field': '白皮书 5.10.2 AI 推荐字段 — 只输出建议不建表单', diff --git a/src/commands/form/delete.ts b/src/commands/form/delete.ts index f51b9db..5e300e1 100644 --- a/src/commands/form/delete.ts +++ b/src/commands/form/delete.ts @@ -14,6 +14,8 @@ import { setupOutputFilter, addOutputOptions, wrapCommand } from '../_output_fil interface DeleteOpts { yes?: boolean cascade?: boolean + /** P5 (FM005 修复, 2026-07-29): FM005 流程引用阻塞时, 物理删 workflow_node (TemplateNodeEntity.f_delete_mark=1 仍被后端 selectList 查到) 强制删 form */ + force?: boolean json?: boolean verbose?: boolean } diff --git a/src/commands/workflow/_auto_assign_admin.ts b/src/commands/workflow/_auto_assign_admin.ts new file mode 100644 index 0000000..8bbc726 --- /dev/null +++ b/src/commands/workflow/_auto_assign_admin.ts @@ -0,0 +1,101 @@ +/** + * workflow _auto_assign_admin.ts — AI 生成的 BPMN 缺 potentialOwner 自动兜底 + * + * Bug 3 (tdd6 R3 2026-07-29 + R1 P5 历史踩坑): + * - 现象: `dacli workflow create --ai` 4 userTask 缺 potentialOwner, semanticLint 报 4 errors + * (msg = 'no assignee or candidate'), 直接 throw, 新流程不建 + * - 根因: AI LLM 偶尔只输出 `camunda:assignee` 命名空间属性 (或根本不写), dacli semanticLint + * 检测时落入 'missing assignee and no candidate' 分支阻断 (见 _semantic_lint.ts:110-114) + * - 兜底: 对所有 userTask 检查是否已有 potentialOwner, 没有则注入 + * ` + * admin + * ` + * 已有的保持不变 (避免覆盖用户显式候选人) + * - 集成: 在 workflow/create.ts:415 semanticLint 失败时, 若 errors 全为 'no assignee/candidate' + * 类, 跑 autoAssignAdmin 重写 flowXml, 再跑一次 semanticLint 验证, 通过则继续 save + * + * 设计要点: + * - 纯函数 (无外部依赖除 bpmn-moddle), 单测好覆盖 + * - 不破坏既有 potentialOwner, 只补缺失 (additive safety net) + * - 优先 bpmn-moddle 序列化 (canonical `bpmn:` 前缀), 但保留原 namespace prefixes 防 web 端乱解析 + * + * 边界: + * - 空 XML / 解析失败 → 返回原 XML, 不抛 (避免引入新故障模式) + * - 完全没有 userTask → 返回原 XML + */ + +import { BpmnModdle } from 'bpmn-moddle' + +/** + * 给定 BPMN XML, 给所有缺 potentialOwner 的 userTask 注入 admin candidate. + * + * @param flowXml 原始 BPMN 2.0 XML + * @returns 修改后的 XML (若没有任何需要注入的 userTask, 返回原 XML 字符串) + */ +export async function autoAssignAdmin(flowXml: string): Promise { + if (!flowXml || !String(flowXml).trim()) return flowXml + + const moddle = new BpmnModdle() + let rootElement: any + try { + const parsed = (await moddle.fromXML(flowXml)) as { rootElement: any } + rootElement = parsed.rootElement + } catch { + // 解析失败: 不破坏原 XML, 由上层 semanticLint 报错 + return flowXml + } + + const proc = rootElement.rootElements?.find((e: any) => e.$type === 'bpmn:Process') + if (!proc) return flowXml + + const flowEls: any[] = proc.flowElements || [] + const userTasks = flowEls.filter((e: any) => e.$type === 'bpmn:UserTask') + + if (userTasks.length === 0) return flowXml + + let injected = 0 + for (const ut of userTasks) { + // 检查是否已有任何 potentialOwner (避免覆盖用户显式候选人) + const hasPO = (ut.resources || []).some((r: any) => r.$type === 'bpmn:PotentialOwner') + if (hasPO) continue + + // 检查是否已有命名空间 assignee (camunda:assignee / flowable:assignee) — 这些语义上 + // 是单候选人而非 "无候选人", 但 dacli semanticLint 在无 PO 时仍判 fail. + // 为兜底有效, 统一注入 admin potentialOwner; 既有 assignee 不删 (additive). + const $attrs = ut.$attrs || {} + const hasAnyAssignee = + Boolean(ut.assignee) || + Boolean($attrs.assignee) || + Boolean($attrs['camunda:assignee']) || + Boolean($attrs['flowable:assignee']) + + // 构造 bpmn:PotentialOwner 元素 + // 注: bpmn-moddle schema 关键细节 (踩坑 2026-07-29): + // 1. bpmn:FormalExpression.body 是 isBody=true (元素文本, 不是属性) + // 2. bpmn:ResourceAssignmentExpression 的字段叫 'expression' (不是 formalExpression) + // 序列化时 moddle 会写成 ... + // 3. 直接 moddle.create 时, body 必须放在第二个参数里 + const formalExpression = moddle.create('bpmn:FormalExpression', { body: 'admin' }) as any + const rae = moddle.create('bpmn:ResourceAssignmentExpression', { + expression: formalExpression, + }) as any + const po = moddle.create('bpmn:PotentialOwner', { + resourceAssignmentExpression: rae, + }) as any + // resources 是 flat ResourceRole 数组 (bpmn-moddle schema isMany=true) + ut.resources = [...(ut.resources || []), po] + injected++ + // 注释: hasAnyAssignee 信息保留给上层日志 (避免破坏现有 schema) + void hasAnyAssignee + } + + if (injected === 0) return flowXml + + try { + const { xml } = await moddle.toXML(rootElement, { format: true }) + return xml as string + } catch { + // 序列化失败: 兜底不可用, 返回原 XML 让上层报错 + return flowXml + } +} \ No newline at end of file diff --git a/src/commands/workflow/create.ts b/src/commands/workflow/create.ts index ab05fde..ff5cac1 100644 --- a/src/commands/workflow/create.ts +++ b/src/commands/workflow/create.ts @@ -30,6 +30,7 @@ import { autoLayoutFlowXml, isLayoutNeeded } from './_autoLayout.ts' import { initWebapi, loadWorkflow } from '../../webapi/workflow.ts' import { getUserInfoApi } from '../../webapi/user.ts' import { validateWorkflowCreate, semanticLint } from './_validate.ts' +import { autoAssignAdmin } from './_auto_assign_admin.ts' // Bug 3 (R3 + R1 P5): 兜底 AI 缺 potentialOwner import { enhanceFromBackend, formatErrorLine } from '../_error_codes.ts' import { runCommandAutoFix, fetchExistingLists } from '../_auto_fix.ts' // v2.1+ (2026-07-21): enCode/fullName strip 已统一到 runCommandAutoFix (commands/_auto_fix.ts), 不再 inline 调 autoStripEnCode/autoStripFullName (替代原 line 96-112 的 inline 调用 + warn log, BS-新38/BS-新52). @@ -57,6 +58,10 @@ interface CreateOpts { ai?: string /** 自动授权给当前角色 (镜像 web 流创建后行为) */ autoAuthorize?: boolean + /** P5 (2026-07-29): --force-lint 跳过 semanticLint 阻断, 强制 save */ + forceLint?: boolean + /** P5 (2026-07-29): Save 失败时保留残留 template, 不自动回滚 */ + keepOnFail?: boolean } /** 从 fullName 生成 enCode (snake_case) - 镜像 web form validate: 字母数字小数点, 不能放首尾 */ @@ -421,20 +426,62 @@ export function buildWorkflowCreateCommand(): Command { log.warn(`--force-lint: 跳过 semanticLint 阻断 (${semantic.errors.length} 个错误), 强制 save`) for (const e of semantic.errors) log.warn(` - ${e}`) } else { - log.error(`✗ workflow 语义 lint 失败 (${semantic.errors.length} 个错误):`) - for (const e of semantic.errors) { - log.error(` - ${e}`) - } - for (const d of semantic.diagnostics) { - log.error(` [${d.nodeId}] ${d.message}`) - } - log.info(` 修复: 用 --flowXml 直传 BPMN (跳过 AI), 或加 --force-lint 跳过此检查`) - // v2.2+ (2026-07-21): throw 替代 process.exit(1), wrapCommand handler catch → ctx.fail - throw new Error( - `WORKFLOW_SEMANTIC_INVALID: ${semantic.errors.length} errors. ` + - `Fix BPMN userTask assignee / candidate before Save. ` + - `Diagnostics: ${JSON.stringify(semantic.diagnostics)}`, + // Bug 3 (tdd6 R3 2026-07-29 + R1 P5 历史踩坑) 兜底: + // AI 生成的 BPMN 偶尔只输出 assignee/candidate (不输出 userTask 的 potentialOwner 元素), + // semanticLint 报 "missing assignee and no candidate" 全员失败. + // 策略: 检查 errors 全为 assignee 类时, 跑 autoAssignAdmin 注入 admin potentialOwner 重 lint. + // 兜底成功 → 继续 save (用户收到 WARN); 兜底仍失败 → 走原 throw (真错). + const assigneeErrors = semantic.errors.filter( + (e) => /missing assignee|no assignee|candidate/.test(e), ) + const allAssigneeType = assigneeErrors.length > 0 + && assigneeErrors.length === semantic.errors.length + if (allAssigneeType && !opts.forceLint) { + log.warn(`✗ workflow 语义 lint 失败 (${semantic.errors.length} 个错误, 全为 missing assignee/candidate):`) + for (const e of semantic.errors) { + log.warn(` - ${e}`) + } + log.warn(` ↳ R3 兜底: 自动给所有 userTask 注入 admin potentialOwner 重 lint`) + try { + flowXml = await autoAssignAdmin(flowXml) + } catch (ae: any) { + log.warn(` ↳ autoAssignAdmin 失败: ${ae.message?.slice(0, 80)}, 走原 throw`) + } + const reSemantic = await semanticLint(flowXml, { webapi }) + if (reSemantic.ok) { + log.warn(` ↳ 兜底后 lint ✓, 继续 save (后端 Flowable 部署可能仍失败, 见 --force-lint)`) + // 跳过后续 throw, 让下方 save 正常跑 + } else { + log.error(`✗ workflow 语义 lint 兜底后仍失败 (${reSemantic.errors.length} 个错误):`) + for (const e of reSemantic.errors) { + log.error(` - ${e}`) + } + for (const d of reSemantic.diagnostics) { + log.error(` [${d.nodeId}] ${d.message}`) + } + log.info(` 修复: 用 --flowXml 直传 BPMN (跳过 AI), 或加 --force-lint 跳过此检查`) + throw new Error( + `WORKFLOW_SEMANTIC_INVALID: ${reSemantic.errors.length} errors. ` + + `Fix BPMN userTask assignee / candidate before Save. ` + + `Diagnostics: ${JSON.stringify(reSemantic.diagnostics)}`, + ) + } + } else { + log.error(`✗ workflow 语义 lint 失败 (${semantic.errors.length} 个错误):`) + for (const e of semantic.errors) { + log.error(` - ${e}`) + } + for (const d of semantic.diagnostics) { + log.error(` [${d.nodeId}] ${d.message}`) + } + log.info(` 修复: 用 --flowXml 直传 BPMN (跳过 AI), 或加 --force-lint 跳过此检查`) + // v2.2+ (2026-07-21): throw 替代 process.exit(1), wrapCommand handler catch → ctx.fail + throw new Error( + `WORKFLOW_SEMANTIC_INVALID: ${semantic.errors.length} errors. ` + + `Fix BPMN userTask assignee / candidate before Save. ` + + `Diagnostics: ${JSON.stringify(semantic.diagnostics)}`, + ) + } } } diff --git a/tests/unit/form_create_cleanup_residue.test.ts b/tests/unit/form_create_cleanup_residue.test.ts new file mode 100644 index 0000000..1460182 --- /dev/null +++ b/tests/unit/form_create_cleanup_residue.test.ts @@ -0,0 +1,144 @@ +/** + * tests/unit/form_create_cleanup_residue.test.ts + * + * Bug 1 兜底 (tdd6 R3 2026-07-29 + BS-新149 衍生): + * form create --ai 失败时, state=0 残留行在 base_visual_dev 表里. + * 多次重试 = 多行残留, 反复触发 "enCode 已存在" pre-check. + * 修复: cleanupResidueForms(c, enCode, opts) → 查 list + 软删残留 state=0 行. + * + * 测试覆盖: + * 1. enCode 空 → 返回 0 found/deleted (不调 webapi) + * 2. enabled=false → 跳过 + * 3. 找不到 state=0 残留 → 0 deleted + * 4. 找到 N 个 state=0 → 调用 c.del N 次, 返回 N deleted + * 5. 单次最多删 5 条 (enCode 配置错误防护) + * 6. c.del 失败 → 不抛, 计入 failed + * + * Mock 策略: + * - vi.mock('../../src/webapi/visualDev.ts') 拦截 initWebapi + getVisualDevList + * - stub JnpfClient with mock del method + */ +import { describe, expect, it, vi, beforeEach } from 'vitest' + +// 必须先 mock webapi (cleanupResidueForms 内部 dynamic import) +const mockGetVisualDevList = vi.fn() +const mockDel = vi.fn() + +vi.mock('../../src/webapi/visualDev.ts', () => ({ + initWebapi: vi.fn(async () => undefined), + loadVisualDev: { + getVisualDevList: (...args: unknown[]) => mockGetVisualDevList(...args), + // 其它方法在 cleanupResidueForms 里不调, 但保持形状完整 + }, +})) + +// 直接 stub JnpfClient.fromToken (不依赖真实 token 文件) +vi.mock('../../src/core/client.ts', () => ({ + JnpfClient: { + fromToken: vi.fn(async () => ({ + del: mockDel, + baseUrl: 'http://stub', + })), + }, +})) + +const { cleanupResidueForms } = await import('../../src/commands/form/_cleanup.ts') +const { JnpfClient } = await import('../../src/core/client.ts') + +describe('form create --cleanup-on-fail helper (Bug 1 R3 兜底)', () => { + beforeEach(() => { + mockGetVisualDevList.mockReset() + mockDel.mockReset() + vi.mocked(JnpfClient.fromToken).mockClear() + }) + + it('enCode 空 → 返回 0 不调 webapi', async () => { + const r = await cleanupResidueForms({} as any, '', {}) + expect(r.found).toBe(0) + expect(r.deleted).toBe(0) + expect(mockGetVisualDevList).not.toHaveBeenCalled() + }) + + it('enabled=false → 跳过', async () => { + const r = await cleanupResidueForms({} as any, 'demoForm', { enabled: false }) + expect(r.found).toBe(0) + expect(r.deleted).toBe(0) + expect(mockGetVisualDevList).not.toHaveBeenCalled() + }) + + it('找不到 state=0 残留 → 0 deleted', async () => { + mockGetVisualDevList.mockResolvedValueOnce({ + list: [ + { id: '1', enCode: 'demoForm', state: 1 }, // 已发布, 不算残留 + { id: '2', enCode: 'otherForm', state: 0 }, // enCode 不匹配 + ], + }) + const r = await cleanupResidueForms({ del: mockDel } as any, 'demoForm', {}) + expect(r.found).toBe(0) + expect(r.deleted).toBe(0) + expect(mockDel).not.toHaveBeenCalled() + }) + + it('找到 2 个 state=0 残留 → 删 2 个', async () => { + mockGetVisualDevList.mockResolvedValueOnce({ + list: [ + { id: 'r1', enCode: 'demoForm', state: 0 }, + { id: 'r2', enCode: 'demoForm', state: 0 }, + { id: 'p1', enCode: 'demoForm', state: 1 }, // 已发布, 不删 + ], + }) + mockDel.mockResolvedValue({ code: 200, msg: 'ok' }) + const r = await cleanupResidueForms({ del: mockDel } as any, 'demoForm', {}) + expect(r.found).toBe(2) + expect(r.deleted).toBe(2) + expect(r.failed).toBe(0) + expect(mockDel).toHaveBeenCalledTimes(2) + expect(mockDel).toHaveBeenCalledWith('/visualdev/Base/r1') + expect(mockDel).toHaveBeenCalledWith('/visualdev/Base/r2') + }) + + it('单次最多删 5 条 (防 enCode 配置错误导致大面积误删)', async () => { + // 7 个残留, 只删 5 + const seven = Array.from({ length: 7 }, (_, i) => ({ + id: `r${i}`, enCode: 'demoForm', state: 0, + })) + mockGetVisualDevList.mockResolvedValueOnce({ list: seven }) + mockDel.mockResolvedValue({ code: 200, msg: 'ok' }) + const r = await cleanupResidueForms({ del: mockDel } as any, 'demoForm', {}) + expect(r.found).toBe(7) + expect(r.deleted).toBe(5) + expect(mockDel).toHaveBeenCalledTimes(5) + }) + + it('c.del 返回非 200 → 计入 failed, 不抛', async () => { + mockGetVisualDevList.mockResolvedValueOnce({ + list: [{ id: 'r1', enCode: 'demoForm', state: 0 }], + }) + mockDel.mockResolvedValueOnce({ code: 400, msg: 'bad request' }) + const r = await cleanupResidueForms({ del: mockDel } as any, 'demoForm', {}) + expect(r.found).toBe(1) + expect(r.deleted).toBe(0) + expect(r.failed).toBe(1) + expect(r.error).toContain('code=400') + }) + + it('c.del 抛异常 → 计入 failed + error, 不向上抛', async () => { + mockGetVisualDevList.mockResolvedValueOnce({ + list: [{ id: 'r1', enCode: 'demoForm', state: 0 }], + }) + mockDel.mockRejectedValueOnce(new Error('network timeout')) + const r = await cleanupResidueForms({ del: mockDel } as any, 'demoForm', {}) + expect(r.found).toBe(1) + expect(r.deleted).toBe(0) + expect(r.failed).toBe(1) + expect(r.error).toContain('network timeout') + }) + + it('list API 抛异常 → 静默, 返回 { found: 0, error: ... }', async () => { + mockGetVisualDevList.mockRejectedValueOnce(new Error('list 500')) + const r = await cleanupResidueForms({ del: mockDel } as any, 'demoForm', {}) + expect(r.found).toBe(0) + expect(r.deleted).toBe(0) + expect(r.error).toContain('list 500') + }) +}) \ No newline at end of file diff --git a/tests/unit/workflow_auto_assign_admin.test.ts b/tests/unit/workflow_auto_assign_admin.test.ts new file mode 100644 index 0000000..06964fa --- /dev/null +++ b/tests/unit/workflow_auto_assign_admin.test.ts @@ -0,0 +1,131 @@ +/** + * tests/unit/workflow_auto_assign_admin.test.ts + * + * Bug 3 兜底 (tdd6 R3 2026-07-29 + R1 P5 历史踩坑): + * workflow --ai 生成的 BPMN 偶尔只输出 camunda:assignee, 缺 userTask.potentialOwner, + * semanticLint 报 'no assignee or candidate' 全员失败, 直接 throw. + * 修复: autoAssignAdmin 注入 admin potentialOwner 给所有缺候选的 userTask. + * + * 测试覆盖: + * 1. 注入 (1 个 userTask 无 potentialOwner → 加 admin) + * 2. 不覆盖 (已有 user1 → 不变) + * 3. 多个 userTask (混合, 部分已有 PO 部分无 → 只补缺失) + * 4. 空 XML / 解析失败 → 返回原 XML + * 5. 没有 userTask → 返回原 XML + * 6. 注入后, semanticLint 重跑 OK (端到端验证) + */ +import { describe, expect, it } from 'vitest' +import { autoAssignAdmin } from '../../src/commands/workflow/_auto_assign_admin.ts' +import { semanticLint } from '../../src/commands/workflow/_semantic_lint.ts' + +describe('workflow autoAssignAdmin (Bug 3 兜底)', () => { + it('注入 potentialOwner admin 到无候选 userTask', async () => { + const xml = ` + + + + + + + + +` + const result = await autoAssignAdmin(xml) + // 注: bpmn-moddle 序列化为 admin + expect(result).toContain(' { + const xml = ` + + + + + user1 + + + + + +` + const result = await autoAssignAdmin(xml) + // t1 的 potentialOwner 应保留为 user1, 不被覆盖 + // 注: bpmn-moddle 序列化时会将 重写成 + expect(result).toContain('user1') + expect(result).not.toContain('admin') + }) + + it('多个 userTask 混合: 已有 PO 不变, 缺失 PO 注入 admin', async () => { + const xml = ` + + + + + + manager1 + + + + +` + const result = await autoAssignAdmin(xml) + // t2 的 manager1 保留 (bpmn-moddle 序列化为 manager1) + expect(result).toContain('manager1') + // t1 + t3 被注入 admin (期望 2 个 admin) + const adminMatches = result.match(/admin/g) || [] + expect(adminMatches.length).toBeGreaterThanOrEqual(2) + // 不应有 manager1 被覆盖为 admin + expect(result).not.toMatch(/manager1.*admin|admin.*manager1/) + }) + + it('空 XML → 返回原值, 不抛', async () => { + expect(await autoAssignAdmin('')).toBe('') + expect(await autoAssignAdmin(' ')).toBe(' ') + }) + + it('无 userTask → 返回原值', async () => { + const xml = ` + + + + + + +` + const result = await autoAssignAdmin(xml) + expect(result).toBe(xml) + }) + + it('解析失败 → 返回原值, 不抛', async () => { + const broken = '' + expect(await autoAssignAdmin(broken)).toBe(broken) + }) + + it('端到端: 注入后 semanticLint 重跑 OK (R3 实战场景)', async () => { + // R3: 4 userTask 缺 potentialOwner, semanticLint 报 4 errors + // 修复: autoAssignAdmin 注入 admin → re-lint → OK + const xml = ` + + + + + + + + + +` + const before = await semanticLint(xml, { webapi: {} }) + expect(before.ok).toBe(false) + expect(before.errors.filter((e) => /missing assignee|candidate/.test(e)).length).toBe(4) + + // R3 兜底: autoAssignAdmin → re-lint + const fixed = await autoAssignAdmin(xml) + const after = await semanticLint(fixed, { webapi: {} }) + expect(after.ok).toBe(true) + expect(after.errors).toEqual([]) + }) +}) \ No newline at end of file