diff --git a/src/commands/workflow/_semantic_lint.ts b/src/commands/workflow/_semantic_lint.ts new file mode 100644 index 0000000..17b0800 --- /dev/null +++ b/src/commands/workflow/_semantic_lint.ts @@ -0,0 +1,122 @@ +/** + * workflow 语义 lint (webapi hardening) + * + * 与 BPMN layout lint 分离: layout 自动修复不掩盖语义错误. + * 使用 bpmn-moddle 解析 (项目已有依赖 ^10.0.0). + * + * 与 _webapi_helpers.validateFlowNodeStructure 的区别: + * - validateFlowNodeStructure 基于 dacli 解析后的 flowNodes Map 校验 start/end 数量 (web bpmnLintUtil 镜像) + * - semanticLint 基于原始 BPMN XML 解析 (bpmn-moddle), 检查: + * 1. 节点完整性 (no start / no end) + * 2. 多结束节点无合流网关 + * 3. userTask assignee 解析 (空字符串 / ${var} 无法解析) + * + * 设计原则: 在 Save(type=1) 之前阻断, 不让坏 BPMN 进入后端 Flowable 部署阶段. + */ + +import { BpmnModdle } from 'bpmn-moddle' + +export interface SemanticDiagnostic { + nodeId: string + message: string +} + +export interface SemanticResult { + ok: boolean + errors: string[] + diagnostics: SemanticDiagnostic[] +} + +export interface ResolverCtx { + /** 解析 ${var} 表达式到候选人列表. T5 会替换为真实的 resolveApproverExpr. */ + candidateResolver: (assigneeExpr: string) => Array<{ id: string; name: string }> +} + +/** + * 跑 workflow 语义 lint. + * + * @param xml - 原始 BPMN 2.0 XML + * @param ctx - 解析上下文 (T4 阶段 candidateResolver 占位, T5 接 resolveApproverExpr) + */ +export async function semanticLint(xml: string, ctx: ResolverCtx): Promise { + const errors: string[] = [] + const diagnostics: SemanticDiagnostic[] = [] + + if (!xml || !String(xml).trim()) { + return { ok: false, errors: ['flowXml is empty'], diagnostics: [] } + } + + const moddle = new BpmnModdle() + let rootElement: any + try { + const parsed = (await moddle.fromXML(xml)) as { rootElement: any } + rootElement = parsed.rootElement + } catch (e) { + return { + ok: false, + errors: [`flowXml XML parse error: ${(e as Error).message?.slice(0, 200)}`], + diagnostics: [], + } + } + + // 1. 找 process + const proc = rootElement.rootElements?.find((e: any) => e.$type === 'bpmn:Process') + if (!proc) { + return { ok: false, errors: ['no Process element'], diagnostics: [] } + } + + const flowEls: any[] = proc.flowElements || [] + const starts = flowEls.filter((e: any) => e.$type === 'bpmn:StartEvent') + const ends = flowEls.filter((e: any) => e.$type === 'bpmn:EndEvent') + const userTasks = flowEls.filter((e: any) => e.$type === 'bpmn:UserTask') + + // 2. 节点完整性 + if (starts.length === 0) { + errors.push('no start event') + } + if (ends.length === 0) { + errors.push('no end event') + } + if (ends.length > 1 && !hasConvergingGateway(flowEls, ends)) { + errors.push('multiple-end without converging gateway') + } + + // 3. userTask assignee / potentialOwner 解析 + // 注: bpmn-moddle 不识别 camunda/flowable extension 属性 (assignee / candidateUsers), + // 这些属性会落到 ut.$attrs 而不是 ut.assignee. 需要两个地方都查. + for (const ut of userTasks) { + const assignee = String(ut.assignee || ut.$attrs?.assignee || '').trim() + // bpmn-moddle 解析 userTask 时, potentialOwner 在 ut.resources?.potentialOwner + // (如果 XML 用 camunda/ns 命名空间, 也可能在 ut.$attrs, 这里按 bpmn-moddle 标准处理) + const resources = (ut as any).resources + const po: any[] = resources?.potentialOwner || [] + + // 3a. 缺 assignee 且缺 candidate → 阻断 + if (!assignee && po.length === 0) { + errors.push(`userTask ${ut.id}: missing assignee and no candidate`) + diagnostics.push({ nodeId: ut.id, message: 'no assignee or candidate' }) + continue + } + + // 3b. assignee 是 ${var} 表达式, 尝试解析 + if (assignee && /\$\{.+\}/.test(assignee)) { + const resolved = ctx.candidateResolver(assignee) || [] + if (resolved.length === 0) { + errors.push(`userTask ${ut.id}: assignee ${assignee} unresolved (no candidate)`) + diagnostics.push({ nodeId: ut.id, message: `unresolved: ${assignee}` }) + } + } + } + + return { ok: errors.length === 0, errors, diagnostics } +} + +/** + * 简化版: 存在任何类型的 Gateway 视为有合流. + * BPMN 严格语义需走 sequenceFlow 边, 但 dacli 不解析边 (镜像 _webapi_helpers.ts:215 注释), + * 简化为"流程里同时存在 Gateway + 多个 End" 即认为有合并意图. + */ +function hasConvergingGateway(flowEls: any[], ends: any[]): boolean { + if (ends.length <= 1) return true + return flowEls.some((e: any) => String(e.$type || '').includes('Gateway')) +} diff --git a/src/commands/workflow/_validate.ts b/src/commands/workflow/_validate.ts index 82e7181..419fbf7 100644 --- a/src/commands/workflow/_validate.ts +++ b/src/commands/workflow/_validate.ts @@ -29,6 +29,11 @@ export interface StepValidation { errors: ValidationError[] } +/** 语义 lint — workflow/create.ts 在 Save(type=1) 之前调用, 阻断坏 BPMN 进后端. + * T4: 多结束无合并 / 无 start / assignee 空 / ${var} 无法解析 4 场景. */ +export { semanticLint } from './_semantic_lint.ts' +export type { SemanticResult, SemanticDiagnostic, ResolverCtx } from './_semantic_lint.ts' + /** enCode 正则 — (Round 12 fix 复用共享 _encode_validator * 旧: 本地 ENCODE_REGEXP 常量 (与 form/dict/menu/role 重复 4 份) * 新: import 共享 ENCODE_REGEXP + validateEnCode (增强信息含 suggestedAlias) diff --git a/src/commands/workflow/create.ts b/src/commands/workflow/create.ts index e5c2e9f..28c60d9 100644 --- a/src/commands/workflow/create.ts +++ b/src/commands/workflow/create.ts @@ -28,7 +28,7 @@ import { callAiWorkflow, detectTrivialFlowXml } from '../form/_ai.ts' import { buildFlowNodes, validateFlowNodeStructure } from './_webapi_helpers.ts' import { autoLayoutFlowXml, isLayoutNeeded } from './_autoLayout.ts' import { initWebapi, loadWorkflow } from '../../webapi/workflow.ts' -import { validateWorkflowCreate } from './_validate.ts' +import { validateWorkflowCreate, semanticLint } from './_validate.ts' 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). @@ -380,6 +380,28 @@ export function buildWorkflowCreateCommand(): Command { log.ok(` ↳ ${structCheck.okMessage}`) } + // 语义 lint (T4) — 阻断坏 BPMN 进后端 Flowable 部署. + // 与 _webapi_helpers.validateFlowNodeStructure 互补: + // - validateFlowNodeStructure 检查 flowNodes Map 形态 (数量/类型) + // - semanticLint 检查原始 flowXml BPMN 语义 (assignee 解析, 多结束无合并) + // T4 阶段 candidateResolver 是占位, T5 会替换为真实 resolveApproverExpr. + const semantic = await semanticLint(flowXml, { candidateResolver: () => [] }) + if (!semantic.ok) { + 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}`) + } + // 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)}`, + ) + } + // ========== 6. save(type=1) 真正发布 + 部署 ========== log.info(`[step 5/6] POST /workflow/template/Save type=1 (关键: 真正发布+部署)`) const saveBody = { diff --git a/tests/unit/workflow_semantic_lint.test.ts b/tests/unit/workflow_semantic_lint.test.ts new file mode 100644 index 0000000..2c8b7ce --- /dev/null +++ b/tests/unit/workflow_semantic_lint.test.ts @@ -0,0 +1,70 @@ +/** + * workflow semantic lint tests (Task 4 — webapi hardening) + * + * 4 场景: + * 1. 多结束节点且无合并 → 阻断 + * 2. 无 start → 阻断 + * 3. userTask assignee 空字符串 → 阻断 + * 4. 显式 ${deptManager} 无法解析 → 阻断并 diagnostics + * + * 与 BPMN layout lint 分离: layout 自动修复不掩盖语义错误. + */ +import { describe, expect, it } from 'vitest' +import { semanticLint } from '../../src/commands/workflow/_semantic_lint.ts' + +describe('workflow semantic lint (Task 4)', () => { + it('多结束无合并 → ok=false, errors 含 multiple-end', async () => { + const xml = ` + + + + + + + + ` + const r = await semanticLint(xml, { candidateResolver: () => [] }) + expect(r.ok).toBe(false) + expect(r.errors.some(e => /multiple-end/.test(e))).toBe(true) + }) + + it('无 start → ok=false', async () => { + const xml = ` + + + + + + ` + const r = await semanticLint(xml, { candidateResolver: () => [] }) + expect(r.ok).toBe(false) + }) + + it('userTask assignee 空字符串 → ok=false', async () => { + const xml = ` + + + + + + + ` + const r = await semanticLint(xml, { candidateResolver: () => [] }) + expect(r.ok).toBe(false) + expect(r.errors.some(e => /assignee|candidate/.test(e))).toBe(true) + }) + + it('assignee=${deptManager} 候选人为空 → 阻断并给 reason', async () => { + const xml = ` + + + + + + + ` + const r = await semanticLint(xml, { candidateResolver: () => [] }) + expect(r.ok).toBe(false) + expect(r.diagnostics.some(d => /unresolved/.test(d.message))).toBe(true) + }) +})