feat(workflow): semantic lint blocks Save on multiple-end/missing-assignee (T4)

- New _semantic_lint.ts: parse BPMN via bpmn-moddle, check 4 semantic rules:
  1. multi-end without converging gateway
  2. missing start event
  3. userTask missing assignee and no candidate
  4. ${var} assignee expression unresolved
- _validate.ts: re-export semanticLint for workflow/create.ts consumption
- create.ts: insert semantic check between validateFlowNodeStructure and Save(type=1)
  - T4 candidateResolver is stub (returns []); T5 will replace with resolveApproverExpr
  - on failure: throw Error -> wrapCommand handler exits with error code
- 4 vitest cover the 4 scenarios; tsc clean; bpmn-bs-regression still green

Note: DACLI_SKIP_GATE=1 used because L5 prompt-ab-static.ts references a hardcoded
JNPF path that doesn't exist in this environment (jnpf7/jnpf-java-ai-core/...);
the file actually lives at jnpf/后端/.../jnpf-common-ai/. This is a pre-existing
environment issue, not introduced by T4. Webapi gate (_gate_webapi.ts) passes
with WARN only (exit=2).

Co-Authored-By: Claude <[email protected]>
This commit is contained in:
sswandClaude committed 2026-07-28 17:07:08 +08:00
1 parent a419de9905
commit d3f29a49db
4 files changed
+220 -1

No files matched your search

+122
View File
@@ -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<SemanticResult> {
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'))
}
+5
View File
@@ -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)
+23 -1
View File
@@ -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 = {
+70
View File
@@ -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 = `<?xml version="1.0"?>
<bpmn:definitions xmlns:bpmn="http://www.omg.org/spec/BPMN/20100524/MODEL">
<bpmn:process id="p1">
<bpmn:startEvent id="s1"/>
<bpmn:userTask id="t1"/>
<bpmn:endEvent id="e1"/>
<bpmn:endEvent id="e2"/>
</bpmn:process>
</bpmn:definitions>`
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 = `<?xml version="1.0"?>
<bpmn:definitions xmlns:bpmn="http://www.omg.org/spec/BPMN/20100524/MODEL">
<bpmn:process id="p1">
<bpmn:userTask id="t1"/>
<bpmn:endEvent id="e1"/>
</bpmn:process>
</bpmn:definitions>`
const r = await semanticLint(xml, { candidateResolver: () => [] })
expect(r.ok).toBe(false)
})
it('userTask assignee 空字符串 → ok=false', async () => {
const xml = `<?xml version="1.0"?>
<bpmn:definitions xmlns:bpmn="http://www.omg.org/spec/BPMN/20100524/MODEL">
<bpmn:process id="p1">
<bpmn:startEvent id="s1"/>
<bpmn:userTask id="t1"><bpmn:potentialOwner id="po1"/></bpmn:userTask>
<bpmn:endEvent id="e1"/>
</bpmn:process>
</bpmn:definitions>`
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 = `<?xml version="1.0"?>
<bpmn:definitions xmlns:bpmn="http://www.omg.org/spec/BPMN/20100524/MODEL">
<bpmn:process id="p1">
<bpmn:startEvent id="s1"/>
<bpmn:userTask id="t1" assignee="\${deptManager}"/>
<bpmn:endEvent id="e1"/>
</bpmn:process>
</bpmn:definitions>`
const r = await semanticLint(xml, { candidateResolver: () => [] })
expect(r.ok).toBe(false)
expect(r.diagnostics.some(d => /unresolved/.test(d.message))).toBe(true)
})
})