@stalfh233/omc-cli 0.6.81 → 0.6.82

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -180,8 +180,15 @@ function validateWorkflowRouteConditions(template, tool) {
180
180
  if (route.ruleConditionGroup === undefined || route.ruleConditionGroup === null)
181
181
  continue;
182
182
  const groups = route.ruleConditionGroup;
183
- if (!Array.isArray(groups) || groups.length === 0)
184
- throw new ToolRefusalError({ status: "refused", blocker: "workflow-route-condition-invalid", message: `${tool}: routes[${index}].ruleConditionGroup must be a non-empty array of AND-groups (each an array of conditions)(平台存量里的空数组写法在 rollback 重放时会自动剥离,调用方不要手写 [])` });
183
+ // r85(retro issue 02):空外层数组是平台自己的存量写法(get_draft 原样读回
184
+ // `ruleConditionGroup: []`,语义=无条件),导出→改→回写是最常用路径。此前这里
185
+ // fail closed,逼调用方手工剥。现在按平台口径(CollectionUtils.isEmpty → 无条件,
186
+ // mapCallerRules/remapRuleEndpoints 本就在写前剥键)视为缺席放行;仅非数组形状
187
+ // 仍拒。剥离计数见 countStrippedEmptyConditionGroups(回执 strippedEmptyConditionGroups)。
188
+ if (Array.isArray(groups) && groups.length === 0)
189
+ continue;
190
+ if (!Array.isArray(groups))
191
+ throw new ToolRefusalError({ status: "refused", blocker: "workflow-route-condition-invalid", message: `${tool}: routes[${index}].ruleConditionGroup must be an array of AND-groups (each an array of conditions);空数组=无条件,工具写前自动剥离(回执 strippedEmptyConditionGroups)` });
185
192
  for (const [groupIndex, group] of groups.entries()) {
186
193
  if (!Array.isArray(group) || group.length === 0)
187
194
  throw new ToolRefusalError({ status: "refused", blocker: "workflow-route-condition-invalid", message: `${tool}: routes[${index}].ruleConditionGroup[${groupIndex}] must be a non-empty array of RuleConditionItem` });
@@ -204,6 +211,22 @@ function validateWorkflowRouteConditions(template, tool) {
204
211
  }
205
212
  }
206
213
  }
214
+ /**
215
+ * r85(retro issue 02):数一数调用方模板里有几条连线带着平台存量写法
216
+ * `ruleConditionGroup: []`。这些键在写前会被 merge 路径剥掉(mapCallerRules /
217
+ * remapRuleEndpoints 的既有行为,语义=无条件),validator 现在也按缺席放行;
218
+ * 计数进 update/publish 与 dry-run 的回执(strippedEmptyConditionGroups),
219
+ * 让「导出→改→回写」的调用方能看见工具替它剥了多少。
220
+ */
221
+ function countStrippedEmptyConditionGroups(template) {
222
+ const raw = template.routes ?? template.rules ?? template.edges;
223
+ if (!Array.isArray(raw))
224
+ return 0;
225
+ return raw.filter((entry) => {
226
+ const groups = (entry ?? {}).ruleConditionGroup;
227
+ return Array.isArray(groups) && groups.length === 0;
228
+ }).length;
229
+ }
207
230
  /**
208
231
  * Fail closed on an unknown bindRule handler BEFORE any wire call. The MCP
209
232
  * transport validates the zod schema, but `omc call` (the first-class live
@@ -441,6 +464,17 @@ function lintWorkflowTemplate(template, tool) {
441
464
  * `workflow.update` verbatim, so every readback-only key must be stripped here.
442
465
  */
443
466
  const ACTIVITY_INPUT_ALIAS_KEYS = ["id", "type", "name", "code", "index", "permissions", "formButtons", "bizActions"];
467
+ /**
468
+ * r85(retro issue 05 深层病灶):`bizActions` 一键两义——
469
+ * ① summary 投影(`{<nodeEvent>:[ruleCode]}` 对象,r79-09,回喂必须剥);
470
+ * ② SYSTEM_ACTIVITY 的真实 wire 字段(`List<String>`,SystemActivity.java:19-21,
471
+ * 节点激活时执行)。此前无差别剥键,顶层绑定经 workflow.update 会被静默丢弃。
472
+ * 按形状区分:字符串数组=平台字段放行;对象=投影剥掉。
473
+ */
474
+ function callerActivityWireEntries(record) {
475
+ return Object.entries(record).filter(([key, value]) => !ACTIVITY_INPUT_ALIAS_KEYS.includes(key) ||
476
+ (key === "bizActions" && Array.isArray(value) && value.every((item) => typeof item === "string")));
477
+ }
444
478
  /**
445
479
  * Ticket 112 — normalize the caller template onto the platform DTO:
446
480
  * - `routes[]` is NOT a WorkflowTemplateModel field (WorkflowTemplateModel
@@ -472,8 +506,11 @@ function mapCallerActivities(callerActivities, draftActivities) {
472
506
  // answer a misleading 401001; only canonical keys may ride the wire. The
473
507
  // participant is normalized as part of the record so the trailing spread
474
508
  // cannot re-introduce a shorthand the platform cannot resolve.
509
+ // r85: a STRING-array bizActions is SystemActivity's own wire field and
510
+ // rides (callerActivityWireEntries); the object-shaped summary projection
511
+ // is still stripped.
475
512
  const wireRecord = {
476
- ...Object.fromEntries(Object.entries(record).filter(([key]) => !ACTIVITY_INPUT_ALIAS_KEYS.includes(key))),
513
+ ...Object.fromEntries(callerActivityWireEntries(record)),
477
514
  ...(record.participant !== undefined ? { participant: normalizeParticipantForWire(record.participant) } : {}),
478
515
  };
479
516
  const mapped = {
@@ -1768,7 +1805,9 @@ function mergeCallerDelta(template, draft, options = {}) {
1768
1805
  // from workflowSummary): the merge override is spread onto the draft row,
1769
1806
  // so an unstripped alias would ride the wire and make the platform answer
1770
1807
  // a misleading 401001 (same policy as mapCallerActivities).
1771
- ...Object.fromEntries(Object.entries(raw).filter(([key]) => !ACTIVITY_INPUT_ALIAS_KEYS.includes(key))),
1808
+ // r85: string-array bizActions = SystemActivity wire field, rides
1809
+ // (callerActivityWireEntries); object-shaped projection still stripped.
1810
+ ...Object.fromEntries(callerActivityWireEntries(raw)),
1772
1811
  activityCode: activityCodeOf(raw),
1773
1812
  ...(type ? { activityType: type } : {}),
1774
1813
  ...(name !== undefined ? { activityName: name, i18nMessage: name } : {}),
@@ -2075,7 +2114,7 @@ function workflowRollbackSpec(toolName) {
2075
2114
  kind: "irreversible",
2076
2115
  reason: "平台无 unpublish:发布是生命周期推进(workflowVersion 递增),不可参数重放撤销。内容回退路径:对该流程前一 workflow.update/bindRule 的 before 执行 rollback plan/apply 恢复草稿内容后,重新 workflow.publish",
2077
2116
  };
2078
- // update / bindRule:整模板替换回 before 草稿
2117
+ // update / bindRule / unbindRule:整模板替换回 before 草稿
2079
2118
  if (before == null)
2080
2119
  return { kind: "irreversible", reason: "before 快照为空(流程不存在),无内容可恢复" };
2081
2120
  return { kind: "calls", calls: [{ tool: "workflow.update", args: { schemaCode, code, template: sanitizeWorkflowSnapshotForReplay(before), merge: false } }] };
@@ -2173,9 +2212,11 @@ export async function scanModelWorkflowBindings(session, schemaCode) {
2173
2212
  const summary = workflowCompactProjection({ data: pub.data }).workflowSummary;
2174
2213
  const ruleBindings = summary?.ruleBindings ?? [];
2175
2214
  const nodeRuleBindings = summary?.nodeRuleBindings ?? [];
2215
+ const systemRuleBindings = summary?.systemRuleBindings ?? [];
2176
2216
  const ruleBindingCount = ruleBindings.reduce((sum, binding) => sum + binding.ruleCodes.length, 0) +
2177
- nodeRuleBindings.reduce((sum, binding) => sum + binding.ruleCodes.length, 0);
2178
- return { workflowCode, published, ruleBindings, nodeRuleBindings, ruleBindingCount };
2217
+ nodeRuleBindings.reduce((sum, binding) => sum + binding.ruleCodes.length, 0) +
2218
+ systemRuleBindings.reduce((sum, binding) => sum + binding.ruleCodes.length, 0);
2219
+ return { workflowCode, published, ruleBindings, nodeRuleBindings, systemRuleBindings, ruleBindingCount };
2179
2220
  }
2180
2221
  async function getWorkflowHeaderOrNull(session, workflowCode) {
2181
2222
  try {
@@ -2246,6 +2287,25 @@ function activityBizActions(activity) {
2246
2287
  }
2247
2288
  return Object.keys(map).length > 0 ? map : undefined;
2248
2289
  }
2290
+ /**
2291
+ * r85(retro 2026-11-19 issue 05):SYSTEM_ACTIVITY 节点在活动行上还有**顶层**
2292
+ * `bizActions` + `bizActionType`(SystemActivity.java:19-21「绑定的业务方法」,
2293
+ * BIZ_METHOD/BIZ_RULE 二态)——与八个节点事件 handler 完全不同的第三个绑定面。
2294
+ * 节点激活时执行它们(SystemActivityRuntime.java:54 processingBusiness),
2295
+ * 发布校验按 BIZ_RULE 比对规则清单(WorkflowTemplateValidateUtility
2296
+ * .validateSystemActivity:866-877)。客订规则绑在 Activity8 顶层 bizActions 而
2297
+ * summary 看不到 → 用户得出「没绑」的错误结论。投影为独立键 systemBizActions
2298
+ * (不占 activities[].bizActions——那个键是节点事件映射的既有投影)。
2299
+ */
2300
+ function activitySystemBizActions(activity) {
2301
+ const raw = activity.bizActions;
2302
+ if (!Array.isArray(raw))
2303
+ return undefined;
2304
+ const codes = raw.filter((value) => typeof value === "string" && value.length > 0);
2305
+ if (codes.length === 0)
2306
+ return undefined;
2307
+ return { bizActionType: typeof activity.bizActionType === "string" ? activity.bizActionType : null, ruleCodes: codes };
2308
+ }
2249
2309
  export function workflowCompactProjection(result) {
2250
2310
  const data = (result.data ?? null);
2251
2311
  if (data === null)
@@ -2281,6 +2341,13 @@ export function workflowCompactProjection(result) {
2281
2341
  const bizActions = activityBizActions(activity);
2282
2342
  return bizActions !== undefined ? { bizActions } : {};
2283
2343
  })(),
2344
+ // r85: TOP-LEVEL bizActions (SYSTEM_ACTIVITY's own binding surface — a rule
2345
+ // here fires on node activation, not on a node event). Separate key so the
2346
+ // node-event map above keeps its meaning.
2347
+ ...(() => {
2348
+ const system = activitySystemBizActions(activity);
2349
+ return system !== undefined ? { systemBizActions: system } : {};
2350
+ })(),
2284
2351
  }));
2285
2352
  const rules = data.rules;
2286
2353
  const edges = Array.isArray(rules)
@@ -2315,6 +2382,19 @@ export function workflowCompactProjection(result) {
2315
2382
  for (const [nodeEvent, ruleCodes] of Object.entries(activityBizActions(row) ?? {}))
2316
2383
  nodeRuleBindings.push({ activityCode, nodeEvent, ruleCodes });
2317
2384
  }
2385
+ // r85: the THIRD binding surface — SYSTEM_ACTIVITY's top-level bizActions.
2386
+ // Same predicate as the per-node projection (activitySystemBizActions), so
2387
+ // "what counts as a binding" stays single-sourced across the summary, the
2388
+ // flat scans, and workflow.list's ruleBindingCount.
2389
+ const systemRuleBindings = [];
2390
+ for (const row of Object.values(activities)) {
2391
+ const activityCode = String(row?.activityCode ?? "");
2392
+ if (activityCode === "")
2393
+ continue;
2394
+ const system = activitySystemBizActions(row);
2395
+ if (system !== undefined)
2396
+ systemRuleBindings.push({ activityCode, bizActionType: system.bizActionType, ruleCodes: system.ruleCodes });
2397
+ }
2318
2398
  const originate = data.originateActivity;
2319
2399
  // Count ALL propertyPermissions rows on the native template (including
2320
2400
  // all-false), so --full/--jq can answer "did my visibility edit land?" even
@@ -2335,6 +2415,8 @@ export function workflowCompactProjection(result) {
2335
2415
  // r79-09: mirror the same node-level bindings on the top-level projection —
2336
2416
  // `activities[].bizActions` is the literal path callers reach for (issue 09).
2337
2417
  ...(node.bizActions !== undefined ? { bizActions: node.bizActions } : {}),
2418
+ // r85: mirror the SYSTEM_ACTIVITY top-level face on the projectable row.
2419
+ ...(node.systemBizActions !== undefined ? { systemBizActions: node.systemBizActions } : {}),
2338
2420
  }));
2339
2421
  return {
2340
2422
  workflowSummary: {
@@ -2344,7 +2426,8 @@ export function workflowCompactProjection(result) {
2344
2426
  edges,
2345
2427
  ruleBindings,
2346
2428
  ...(nodeRuleBindings.length > 0 ? { nodeRuleBindings } : {}),
2347
- ruleBindingCount: ruleBindings.reduce((sum, binding) => sum + binding.ruleCodes.length, 0),
2429
+ ...(systemRuleBindings.length > 0 ? { systemRuleBindings } : {}),
2430
+ ruleBindingCount: ruleBindings.reduce((sum, binding) => sum + binding.ruleCodes.length, 0) + systemRuleBindings.reduce((sum, binding) => sum + binding.ruleCodes.length, 0),
2348
2431
  ...(originate ? { originateActivity: { code: originate.activityCode ?? null, type: originate.activityType ?? null, name: effectiveActivityName(originate), participant: originate.participant ?? null } } : {}),
2349
2432
  },
2350
2433
  // Projectable top-level face for --full / --jq (r30d F9/F14).
@@ -2355,7 +2438,7 @@ export function workflowCompactProjection(result) {
2355
2438
  // merges onto the stored draft, connects added nodes through to END, fills
2356
2439
  // sheetCode and geometry. Reading the 30–75 KB full body is NOT required —
2357
2440
  // bench17 pulled 61 KB `full:true` just to edit two node names.
2358
- summaryHint: "改流程只需把要改/新增的 activities(数组)+ routes 传给 workflow.update:缺 START/END 的部分模板会自动按增量 merge 到草稿(草稿为基,自动补 sheetCode/连线/坐标),无需读回整模板或 --full 正文;字段权限也只需在对应 PARTICIPANT 上给 propertyPermissions:[{propertyCode,...}],工具按 propertyCode 合并、未列的字段权限保留。只有要整图替换时才给全 START..END 的完整模板;要看通知等完整节点正文才用 detailArtifactId 或 --full。--full 外置时顶层仍有 activities[{code,name,participants}] + propertyPermissionsCount 可直接投影。",
2441
+ summaryHint: "改流程只需把要改/新增的 activities(数组)+ routes 传给 workflow.update:缺 START/END 的部分模板会自动按增量 merge 到草稿(草稿为基,自动补 sheetCode/连线/坐标),无需读回整模板或 --full 正文;字段权限也只需在对应 PARTICIPANT 上给 propertyPermissions:[{propertyCode,...}],工具按 propertyCode 合并、未列的字段权限保留。只有要整图替换时才给全 START..END 的完整模板;要看通知等完整节点正文才用 detailArtifactId 或 --full。--full 外置时顶层仍有 activities[{code,name,participants}] + propertyPermissionsCount 可直接投影。规则绑定共三个面:flow 级 handler(ruleBindings)、节点事件(activities[].bizActions/nodeRuleBindings)、**SYSTEM_ACTIVITY 顶层**(activities[].systemBizActions——规则绑在系统活动节点本身、激活时执行,别只看前两个面就下「没绑」结论)。",
2359
2442
  };
2360
2443
  }
2361
2444
  /**
@@ -2789,6 +2872,9 @@ export function registerWorkflowLane(tools) {
2789
2872
  const template = args.template ?? {};
2790
2873
  validateCallerActivities(template, "workflow.update");
2791
2874
  validateWorkflowRouteConditions(template, "workflow.update");
2875
+ // r85(issue 02):平台存量的空条件组写法在 validator 放行、merge 写前剥键;
2876
+ // 回执带计数让调用方看见剥离发生了。
2877
+ const strippedEmptyConditionGroups = countStrippedEmptyConditionGroups(template);
2792
2878
  assertTemplateNotMinimal(template, "workflow.update");
2793
2879
  lintWorkflowTemplate(template, "workflow.update");
2794
2880
  await refuseRequiredOnChildTableFields(session, args.schemaCode, template, "workflow.update");
@@ -2834,7 +2920,7 @@ export function registerWorkflowLane(tools) {
2834
2920
  const activityNames = Object.fromEntries(rawActivityRows
2835
2921
  .map((row) => [String(row.activityCode ?? ""), effectiveActivityName(row)])
2836
2922
  .filter(([code]) => code !== ""));
2837
- return { performed: { errcode: performed.errcode }, readback: { workflowCode: args.code, activities: Array.isArray(data.activities) ? data.activities.length : rawActivityRows.length, templateType: data.templateType ?? null, activityNames, rollbackHint: `本次改动的 before 快照已记录:omc rollback plan --target workflow:${args.schemaCode}/${args.code} 查看可回退项,omc rollback apply --target … --step <n> 执行(草稿回退后仍需 workflow.publish 才生效)`, ...(participantWarnings.length ? { participantWarnings } : {}), ...(rejectWarnings.length || originatorWarnings.length ? { workflowWarnings: [...rejectWarnings, ...originatorWarnings] } : {}), ...(branchEdges.length ? { routesInherited: { edges: branchEdges, hint: "本次未传 routes/edges:以上分支边沿用草稿(含 else 兜底)。要改连线请显式回传完整 routes" } } : {}), ...(renamedInPlace.length ? { renamedInPlace, renamedInPlaceHint: "改名已同 code 原地生效(载体 name_i18n,displayName 才是当前名;activityName 是首建值,平台不再变更)" } : {}), ...(renamedActivities.length ? { renamedActivities, renamedHint: "类型变更铸了新码(上表 from→to)且旧码已失效——后续读写一律用 to;再用旧码 from 会被当作新节点追加" } : {}), workflowRenderCompat: workflowRenderCompat(data) } };
2923
+ return { performed: { errcode: performed.errcode }, readback: { workflowCode: args.code, activities: Array.isArray(data.activities) ? data.activities.length : rawActivityRows.length, templateType: data.templateType ?? null, ...(strippedEmptyConditionGroups > 0 ? { strippedEmptyConditionGroups, strippedEmptyConditionGroupsNote: "调用方连线里有 N 条带平台存量写法 ruleConditionGroup:[](=无条件);工具写前已剥离该键,未上送" } : {}), activityNames, rollbackHint: `本次改动的 before 快照已记录:omc rollback plan --target workflow:${args.schemaCode}/${args.code} 查看可回退项,omc rollback apply --target … --step <n> 执行(草稿回退后仍需 workflow.publish 才生效)`, ...(participantWarnings.length ? { participantWarnings } : {}), ...(rejectWarnings.length || originatorWarnings.length ? { workflowWarnings: [...rejectWarnings, ...originatorWarnings] } : {}), ...(branchEdges.length ? { routesInherited: { edges: branchEdges, hint: "本次未传 routes/edges:以上分支边沿用草稿(含 else 兜底)。要改连线请显式回传完整 routes" } } : {}), ...(renamedInPlace.length ? { renamedInPlace, renamedInPlaceHint: "改名已同 code 原地生效(载体 name_i18n,displayName 才是当前名;activityName 是首建值,平台不再变更)" } : {}), ...(renamedActivities.length ? { renamedActivities, renamedHint: "类型变更铸了新码(上表 from→to)且旧码已失效——后续读写一律用 to;再用旧码 from 会被当作新节点追加" } : {}), workflowRenderCompat: workflowRenderCompat(data) } };
2838
2924
  },
2839
2925
  preflight: (args) => {
2840
2926
  // Zero-wire refusal (ticket 77): fires in semanticGate BEFORE the
@@ -2855,6 +2941,7 @@ export function registerWorkflowLane(tools) {
2855
2941
  validateWorkflowRouteConditions(template, "workflow.update");
2856
2942
  lintWorkflowTemplate(template, "workflow.update");
2857
2943
  await refuseRequiredOnChildTableFields(session, args.schemaCode, template, "workflow.update");
2944
+ const strippedEmptyConditionGroups = countStrippedEmptyConditionGroups(template);
2858
2945
  const merge = args.merge === true || (args.merge !== false && activitiesLackBoundaries(template));
2859
2946
  const draft = await getWorkflowDraftOrNull(session, args.code);
2860
2947
  if (draft === null)
@@ -2904,6 +2991,7 @@ export function registerWorkflowLane(tools) {
2904
2991
  return {
2905
2992
  merge,
2906
2993
  callerSentRoutes,
2994
+ ...(strippedEmptyConditionGroups > 0 ? { strippedEmptyConditionGroups, strippedEmptyConditionGroupsNote: "调用方连线里有 N 条带平台存量写法 ruleConditionGroup:[](=无条件);真写会在上送前剥离该键" } : {}),
2907
2995
  activitiesBefore: activityCodes(draft.activities).length,
2908
2996
  activitiesAfter: activityCodes(body.activities).length,
2909
2997
  routesBefore: beforeEdges.length,
@@ -2933,6 +3021,7 @@ export function registerWorkflowLane(tools) {
2933
3021
  const template = args.template ?? {};
2934
3022
  validateCallerActivities(template, "workflow.publish");
2935
3023
  validateWorkflowRouteConditions(template, "workflow.publish");
3024
+ const strippedEmptyConditionGroups = countStrippedEmptyConditionGroups(template);
2936
3025
  assertTemplateNotMinimal(template, "workflow.publish");
2937
3026
  await refuseRequiredOnChildTableFields(session, args.schemaCode, template, "workflow.publish");
2938
3027
  lintWorkflowTemplate(template, "workflow.publish");
@@ -2980,7 +3069,7 @@ export function registerWorkflowLane(tools) {
2980
3069
  const participantWarnings = participantReferenceWarnings(data);
2981
3070
  const rejectWarnings = rejectToStartCancelWarnings(data);
2982
3071
  const originatorWarnings = approvalByOriginatorWarnings(data);
2983
- return { performed: { errcode: performed.errcode }, readback: { workflowCode: args.code, published: isPublished, workflowVersion: data.workflowVersion ?? null, ...(warnings.length ? { warnings } : {}), ...(participantWarnings.length ? { participantWarnings } : {}), ...(rejectWarnings.length || originatorWarnings.length ? { workflowWarnings: [...rejectWarnings, ...originatorWarnings] } : {}), workflowRenderCompat: workflowRenderCompat(data) } };
3072
+ return { performed: { errcode: performed.errcode }, readback: { workflowCode: args.code, published: isPublished, workflowVersion: data.workflowVersion ?? null, ...(strippedEmptyConditionGroups > 0 ? { strippedEmptyConditionGroups, strippedEmptyConditionGroupsNote: "调用方连线里有 N 条带平台存量写法 ruleConditionGroup:[](=无条件);工具写前已剥离该键,未上送" } : {}), ...(warnings.length ? { warnings } : {}), ...(participantWarnings.length ? { participantWarnings } : {}), ...(rejectWarnings.length || originatorWarnings.length ? { workflowWarnings: [...rejectWarnings, ...originatorWarnings] } : {}), workflowRenderCompat: workflowRenderCompat(data) } };
2984
3073
  },
2985
3074
  preflight: (args) => {
2986
3075
  assertTemplateNotMinimal(args.template ?? {}, "workflow.publish");
@@ -3158,6 +3247,170 @@ export function registerWorkflowLane(tools) {
3158
3247
  },
3159
3248
  rollback: workflowRollbackSpec("workflow.bindRule"),
3160
3249
  });
3250
+ // r85(retro 2026-11-19 issue 01):bindRule 只有 merge 语义,误绑无法用 CLI
3251
+ // 撤销,只能 get_draft 导出整模板→手改→update(还要绕空条件组拒绝)→publish,
3252
+ // 一次撤销 4 次工具调用。unbindRule 镜像 bindRule 的两种目标形态做减法。
3253
+ writeTool({
3254
+ tools,
3255
+ name: "workflow.unbindRule",
3256
+ search: { intents: ["解绑规则", "解绑流程规则", "取消流程绑定", "移除规则绑定", "unbind rule"] },
3257
+ lane: WORKFLOW_LANE,
3258
+ scope: WORKFLOW_TOOLS["workflow.unbindRule"].scope,
3259
+ description: WORKFLOW_TOOLS["workflow.unbindRule"].description,
3260
+ inputSchema: {
3261
+ schemaCode: z.string().min(1),
3262
+ workflowCode: z.string().min(1),
3263
+ ruleCode: z.string().min(1).optional().describe("single-rule form: the rule to unbind (mutually exclusive with ruleCodes)"),
3264
+ ruleCodes: z.array(z.string().min(1)).min(1).optional().describe("batch form: several rules removed in ONE update + publish; only the listed codes are removed, the handler's other bindings are preserved"),
3265
+ handler: z
3266
+ .string()
3267
+ .optional()
3268
+ .describe("FLOW-level event handler to unbind from: start | cancel | activate | end (default end). 与 activityCode+nodeEvent 互斥"),
3269
+ activityCode: z
3270
+ .string()
3271
+ .min(1)
3272
+ .optional()
3273
+ .describe("NODE-level target activity (草稿里的 activityCode). 必须与 nodeEvent 同时给;节点不存在时报 workflow-activity-not-found 并列出可用 code"),
3274
+ nodeEvent: z
3275
+ .enum(["beforeActivate", "afterActivate", "endActivity", "cancelActivity", "activityApproved", "activityRejected", "jobSubmitted", "jobRejected"])
3276
+ .optional()
3277
+ .describe("NODE-level event on activityCode(与 bindRule 同一枚举). 与 handler 互斥"),
3278
+ publish: z.boolean().optional(),
3279
+ },
3280
+ execute: async (session, args) => {
3281
+ const target = resolveBindTarget(args.handler, args.nodeEvent, args.activityCode);
3282
+ const codes = (args.ruleCodes ?? [args.ruleCode]).map(String);
3283
+ const shouldPublish = args.publish !== false;
3284
+ const draft = (await getWorkflowDraftOrNull(session, args.workflowCode)) ?? {};
3285
+ if (Object.keys(draft).length === 0) {
3286
+ throw new ToolRefusalError({
3287
+ status: "refused",
3288
+ blocker: "workflow-not-found",
3289
+ workflowCode: args.workflowCode,
3290
+ message: `流程 ${args.workflowCode} 不存在(get_draft 401001 缺席)——先 workflow.create,再 unbindRule`,
3291
+ });
3292
+ }
3293
+ if (target.scope === "activity" && !findTemplateActivity(draft, target.activityCode)) {
3294
+ throw new ToolRefusalError({
3295
+ status: "refused",
3296
+ blocker: "workflow-activity-not-found",
3297
+ workflowCode: args.workflowCode,
3298
+ activityCode: target.activityCode,
3299
+ activities: templateActivityCodes(draft),
3300
+ message: `流程 ${args.workflowCode} 的草稿里没有活动 ${target.activityCode}——节点级事件必须指向已存在的活动。可用活动:${templateActivityCodes(draft).join("、") || "(无)"}(先用 workflow.get_draft 看 code,别用节点名)`,
3301
+ });
3302
+ }
3303
+ const handlerOf = (template) => {
3304
+ if (target.scope === "workflow")
3305
+ return (template?.[target.field] ?? {}) ?? {};
3306
+ return (findTemplateActivity(template, target.activityCode)?.[target.field] ?? {}) ?? {};
3307
+ };
3308
+ const existing = handlerOf(draft);
3309
+ const priorActions = Array.isArray(existing.bizActions)
3310
+ ? existing.bizActions.filter((value) => typeof value === "string")
3311
+ : [];
3312
+ // Fail closed BEFORE any wire call when the caller names codes the handler
3313
+ // does not carry — a typo'd ruleCode must not report a phantom success,
3314
+ // and the existing codes are the fix's raw material.
3315
+ const absent = codes.filter((code) => !priorActions.includes(code));
3316
+ if (absent.length > 0) {
3317
+ throw new ToolRefusalError({
3318
+ status: "refused",
3319
+ blocker: "workflow-unbind-rule-absent",
3320
+ workflowCode: args.workflowCode,
3321
+ absentRuleCodes: absent,
3322
+ bizActions: priorActions,
3323
+ ...(target.scope === "activity" ? { activityCode: target.activityCode, nodeEvent: target.key } : { handler: target.key }),
3324
+ message: `该处理器当前没有绑定 ${absent.join("、")}——现有绑定:${priorActions.join("、") || "(无)"}。解绑只对已绑定的 code 生效;要换目标先看 workflow.get_draft 的 ruleBindings/nodeRuleBindings`,
3325
+ });
3326
+ }
3327
+ const nextActions = priorActions.filter((code) => !codes.includes(code));
3328
+ // 移空后的写回形状按平台 canonical 未绑态:handler 对象保留、bizActions 与
3329
+ // bizActionType 置 null(WorkflowTemplateController 的模板示例即此形状;平台
3330
+ // 判空走 CollectionUtils.isEmpty,null 与 [] 等价,null 是平台自己的存量拼写)。
3331
+ const mergedHandler = nextActions.length > 0
3332
+ ? { ...(typeof existing === "object" && existing ? existing : {}), bizActions: nextActions, bizActionType: "BIZ_RULE" }
3333
+ : { ...(typeof existing === "object" && existing ? existing : {}), bizActions: null, bizActionType: null };
3334
+ let nextTemplate;
3335
+ if (target.scope === "workflow") {
3336
+ nextTemplate = { ...draft, [target.field]: mergedHandler, workflowCode: args.workflowCode, schemaCode: args.schemaCode };
3337
+ }
3338
+ else {
3339
+ // Keep the draft's activities container shape (array or index-keyed
3340
+ // object) — only the selected row's handler field changes.
3341
+ nextTemplate = mapTemplateActivity(draft, target.activityCode, (row) => ({ ...row, [target.field]: mergedHandler })).template;
3342
+ nextTemplate = { ...nextTemplate, workflowCode: args.workflowCode, schemaCode: args.schemaCode };
3343
+ }
3344
+ validateWorkflowRender(nextTemplate, "workflow.unbindRule");
3345
+ const performed = await wireCall(session, {
3346
+ path: ENDPOINTS.workflowUpdate,
3347
+ method: "POST",
3348
+ body: nextTemplate,
3349
+ });
3350
+ let publishedReadback = null;
3351
+ let publishMarked = false;
3352
+ if (shouldPublish) {
3353
+ const publishPerformed = await wireCall(session, {
3354
+ path: ENDPOINTS.workflowPublish,
3355
+ method: "POST",
3356
+ body: nextTemplate,
3357
+ });
3358
+ assertWorkflowWriteAccepted(publishPerformed, "workflow.unbindRule", args.workflowCode);
3359
+ const pub = await wireCall(session, { path: ENDPOINTS.workflowGetPublished, query: { workflowCode: args.workflowCode } });
3360
+ publishedReadback = (pub.data ?? null);
3361
+ publishMarked = publishedReadback !== null && (publishedReadback.templateType === "PUBLISH" || publishedReadback.published === true);
3362
+ }
3363
+ const draftReadback = await wireCall(session, { path: ENDPOINTS.workflowGetDraft, query: { workflowCode: args.workflowCode } });
3364
+ const data = (draftReadback.data ?? null);
3365
+ if (!data)
3366
+ throw new ToolRefusalError({ status: "refused", blocker: "workflow-render-readback-invalid", message: "workflow.unbindRule returned no draft" });
3367
+ validateWorkflowRender(data, "workflow.unbindRule readback");
3368
+ const handler = handlerOf(data);
3369
+ const bizActions = Array.isArray(handler?.bizActions) ? handler.bizActions.filter((value) => typeof value === "string") : [];
3370
+ const publishedHandler = publishedReadback ? handlerOf(publishedReadback) : undefined;
3371
+ const publishedBizActions = Array.isArray(publishedHandler?.bizActions)
3372
+ ? publishedHandler.bizActions.filter((value) => typeof value === "string")
3373
+ : [];
3374
+ const targetShape = target.scope === "workflow"
3375
+ ? { handler: target.key, handlerField: target.field }
3376
+ : { activityCode: target.activityCode, nodeEvent: target.key, nodeEventField: target.field };
3377
+ return {
3378
+ performed: { errcode: performed.errcode, scope: target.scope, ...targetShape, removedRuleCodes: codes, bizActions, publishRequested: shouldPublish },
3379
+ readback: {
3380
+ workflowCode: args.workflowCode,
3381
+ scope: target.scope,
3382
+ ...targetShape,
3383
+ semantics: "remove",
3384
+ unbound: codes.every((code) => !bizActions.includes(code)),
3385
+ bizActions,
3386
+ handlerCleared: bizActions.length === 0,
3387
+ // 解绑不回滚 bindRule 的 enable 副作用:规则可能被其它流程/事件绑定,
3388
+ // 这里绝不自动 disable。确认无引用(rule.references kind=rule)后要停用
3389
+ // 再单独 rule.disable。
3390
+ ruleEnableUntouched: true,
3391
+ published: publishMarked,
3392
+ publishedUnbound: codes.every((code) => !publishedBizActions.includes(code)),
3393
+ publishedBizActions,
3394
+ workflowRenderCompat: workflowRenderCompat(data),
3395
+ },
3396
+ };
3397
+ },
3398
+ preflight: (args) => {
3399
+ resolveBindTarget(args.handler, args.nodeEvent, args.activityCode);
3400
+ const hasSingle = typeof args.ruleCode === "string" && args.ruleCode.length > 0;
3401
+ const hasMany = Array.isArray(args.ruleCodes);
3402
+ if (hasSingle && hasMany)
3403
+ throw new ToolRefusalError({ status: "refused", blocker: "workflow-bindrule-codes-exclusive", message: "ruleCode 与 ruleCodes 互斥:单规则用 ruleCode,多规则用 ruleCodes[]" });
3404
+ if (!hasSingle && !hasMany)
3405
+ throw new ToolRefusalError({ status: "refused", blocker: "workflow-bindrule-codes-invalid", message: "需要 ruleCode(单个)或 ruleCodes(数组)之一" });
3406
+ if (hasMany) {
3407
+ const codes = args.ruleCodes;
3408
+ if (codes.length === 0 || new Set(codes.map(String)).size !== codes.length || codes.some((code) => typeof code !== "string" || code.length === 0))
3409
+ throw new ToolRefusalError({ status: "refused", blocker: "workflow-bindrule-codes-invalid", message: "ruleCodes 必须是非空、去重的规则 code 数组" });
3410
+ }
3411
+ },
3412
+ rollback: workflowRollbackSpec("workflow.unbindRule"),
3413
+ });
3161
3414
  /**
3162
3415
  * Friendly writer for the designer's 「表单操作」 checkboxes: each PARTICIPANT
3163
3416
  * activity carries `buttonPermission.customBtns[]` = the form-toolbar buttons
@@ -3470,7 +3723,7 @@ export function registerWorkflowLane(tools) {
3470
3723
  state: z
3471
3724
  .enum(["PENDING", "NOTSTARTED", "INPROGRESS", "DRAFT", "PAUSE", "FINISHED"])
3472
3725
  .optional()
3473
- .describe("待办状态,配合 participant 使用;默认 PENDING(在办)"),
3726
+ .describe("待办状态过滤(DRAFT=发起人草稿态待办)。走 list_workitems 端点原生过滤:给了 participant 按该用户;没给则自动解析当前登录人(解析失败回退 search_workitems 并在回执 stateFilter 标注未生效——该端点会静默丢弃 state)。默认不过滤(当前人在办)"),
3474
3727
  // r35: an agent sent page:1 expecting the first page and read
3475
3728
  // `total:1 / count:0` as a contradiction — the page index is ZERO-based
3476
3729
  // (like data.list). Say so at the parameter itself.
@@ -3488,19 +3741,17 @@ export function registerWorkflowLane(tools) {
3488
3741
  // `participant` takes the JPA-spec endpoint: it can answer "what is
3489
3742
  // pending for user X" and it does not resolve templates, so a dangling
3490
3743
  // reference elsewhere cannot take it down.
3491
- let page;
3492
- if (args.participant !== undefined) {
3493
- page = await listWorkItemsByParticipant(session, {
3494
- participant: args.participant,
3495
- ...(args.state !== undefined ? { status: args.state } : {}),
3496
- ...(args.workflowCode !== undefined ? { workflowCode: args.workflowCode } : {}),
3497
- page: args.page ?? 0,
3498
- size: args.size ?? 20,
3499
- });
3500
- }
3501
- else {
3744
+ //
3745
+ // r85(retro issue 10):`state` 也必须走 list_workitems——search_workitems
3746
+ // 的服务端组装 WorkItemQuerySpec 时**静默丢弃 state 参数**(RuntimeController
3747
+ // .searchWorkitems 反编译 1046-1082:无 setState,对照 listFinishedWorkItems
3748
+ // :1123 有),传了也无效;list_workitems 原生按 status 精确过滤(含 DRAFT,
3749
+ // WorkflowInstanceController:2242-2254)。没给 participant 时先解析当前登录
3750
+ // 人,保持「我的待办」口径;解析失败回退 search_workitems 并如实标注
3751
+ // stateFilter.applied:false。
3752
+ const searchWorkItemsSelf = async () => {
3502
3753
  try {
3503
- page = await searchWorkItems(session, {
3754
+ return await searchWorkItems(session, {
3504
3755
  ...(args.workflowInstanceId ? { instanceId: args.workflowInstanceId } : {}),
3505
3756
  ...(args.workflowCode ? { workflowCode: args.workflowCode } : {}),
3506
3757
  ...(args.schemaCode ? { schemaCode: args.schemaCode } : {}),
@@ -3531,6 +3782,46 @@ export function registerWorkflowLane(tools) {
3531
3782
  "若要彻底恢复全局搜索,需要维护者清掉那条脏待办(平台侧数据修复)。",
3532
3783
  });
3533
3784
  }
3785
+ };
3786
+ let page;
3787
+ let stateFilter;
3788
+ let selfParticipantId = null;
3789
+ if (args.participant !== undefined) {
3790
+ page = await listWorkItemsByParticipant(session, {
3791
+ participant: args.participant,
3792
+ ...(args.state !== undefined ? { status: args.state } : {}),
3793
+ ...(args.workflowCode !== undefined ? { workflowCode: args.workflowCode } : {}),
3794
+ page: args.page ?? 0,
3795
+ size: args.size ?? 20,
3796
+ });
3797
+ if (args.state !== undefined)
3798
+ stateFilter = { requested: args.state, applied: true, via: "list_workitems" };
3799
+ }
3800
+ else if (args.state !== undefined) {
3801
+ const actor = await resolvePermissionActor(session);
3802
+ selfParticipantId = actor.userId;
3803
+ if (actor.userId !== null) {
3804
+ page = await listWorkItemsByParticipant(session, {
3805
+ participant: actor.userId,
3806
+ status: args.state,
3807
+ ...(args.workflowCode !== undefined ? { workflowCode: args.workflowCode } : {}),
3808
+ page: args.page ?? 0,
3809
+ size: args.size ?? (args.workflowInstanceId ? 200 : 20),
3810
+ });
3811
+ stateFilter = { requested: args.state, applied: true, via: "list_workitems(self)" };
3812
+ }
3813
+ else {
3814
+ page = await searchWorkItemsSelf();
3815
+ stateFilter = {
3816
+ requested: args.state,
3817
+ applied: false,
3818
+ via: "search_workitems",
3819
+ note: "当前登录人 id 解析失败,回退到 search_workitems(服务端注入登录人,但该端点静默丢弃 state 参数——本结果的 state 过滤未生效,DRAFT 等非在办态可能查不全;重试或显式传 participant:<用户id>)",
3820
+ };
3821
+ }
3822
+ }
3823
+ else {
3824
+ page = await searchWorkItemsSelf();
3534
3825
  }
3535
3826
  // r32(2026-10-31):`participant` 分支此前忽略 workflowInstanceId——按人查
3536
3827
  // 时同回全部实例的待办,与参数语义(exact-match 过滤)不符。两个分支统一
@@ -3595,7 +3886,17 @@ export function registerWorkflowLane(tools) {
3595
3886
  ...(purposeHint ? { purposeHint } : {}),
3596
3887
  ...(othersScopeNote ? { scopeNote: othersScopeNote } : {}),
3597
3888
  ...(othersScopeNote === undefined && unscopedScopeNote !== undefined ? { scopeNote: unscopedScopeNote } : {}),
3598
- ...(args.participant !== undefined ? { participant: args.participant, state: args.state ?? "PENDING", source: "list_workitems" } : {}),
3889
+ ...(args.participant !== undefined || (args.state !== undefined && stateFilter?.applied === true)
3890
+ ? { participant: args.participant ?? selfParticipantId, state: args.state ?? "PENDING", source: "list_workitems" }
3891
+ : {}),
3892
+ ...(stateFilter !== undefined
3893
+ ? {
3894
+ stateFilter,
3895
+ stateFilterNote: stateFilter.applied
3896
+ ? `state=${stateFilter.requested} 经 list_workitems 端点原生过滤(search_workitems 会静默丢弃 state 参数,DRAFT 态此前因此查不到)`
3897
+ : stateFilter.note,
3898
+ }
3899
+ : {}),
3599
3900
  ...("unfilteredTotal" in page && page.unfilteredTotal !== undefined ? { unfilteredTotal: page.unfilteredTotal } : {}),
3600
3901
  items,
3601
3902
  };
@@ -4323,7 +4624,7 @@ export function registerWorkflowLane(tools) {
4323
4624
  search: { intents: ["换审批人", "转办", "改审批人", "调整审批人", "审批人换成"] },
4324
4625
  lane: WORKFLOW_LANE,
4325
4626
  scope: "runtime workflow admin adjust participant",
4326
- description: "流程运维·换当前审批人(`POST /api/api/runtime/workflow/workflow_operation`,operationType=ADJUST_PARTICIPANT;approval 是**对象** {activityCode,commonSet,deleted,resources,content},传字符串 10009;adjust_workItem_participators 是加签面不是换人)。**测试提速工具**:换过审批人的实例权限语义已变,不能用于真实流程/权限验证——正常审批链走 data.submit。实例必须在途且有激活节点;默认取第一个激活节点,也可显式 activityCode。",
4627
+ description: "流程运维·换当前审批人(`POST /api/api/runtime/workflow/workflow_operation`,operationType=ADJUST_PARTICIPANT;approval 是**对象** {activityCode,commonSet,deleted,resources,content},传字符串 10009;adjust_workItem_participators 是加签面不是换人)。回执带 `newWorkItems`:transfer 的 wire 回执只有布尔值,工具按 实例+目标审批人 补查 list_workitems 解析新 workItemId(原 id 换人后失效,重提报 405022)。**测试提速工具**:换过审批人的实例权限语义已变,不能用于真实流程/权限验证——正常审批链走 data.submit。实例必须在途且有激活节点;默认取第一个激活节点,也可显式 activityCode。",
4327
4628
  inputSchema: {
4328
4629
  workflowInstanceId: z.string().min(1).describe("流程实例 id(data.submit 读回 / workflow.instanceActivity)"),
4329
4630
  participants: z.array(z.string().min(1)).min(1).describe("目标审批人:userId 或姓名(混收;姓名按 organization/user/search 精确匹配解析)"),
@@ -4362,12 +4663,41 @@ export function registerWorkflowLane(tools) {
4362
4663
  },
4363
4664
  });
4364
4665
  const after = await activeActivitiesOf(session, args.workflowInstanceId);
4666
+ // r85(retro issue 10):transfer 的 wire 回执只是一个布尔值
4667
+ // (WorkflowInstanceController.workflow_operation:871 ResponseResult<Boolean>),
4668
+ // **不含新 workItemId**——换人后原 id 失效(重提报 405022 该任务已在其他页面
4669
+ // 处理),此前新 id 只能查库。这里按 instance + 目标审批人补一次
4670
+ // list_workitems(每批 +1 wire)解析新待办 id,回执直接可用。
4671
+ const newWorkItems = [];
4672
+ let workItemLookup = { resolved: 0, wire: "list_workitems", note: "" };
4673
+ try {
4674
+ for (const id of ids) {
4675
+ const rows = await listWorkItemsByParticipant(session, { participant: id, status: "PENDING", size: 200 });
4676
+ for (const row of rows.items) {
4677
+ if (wireString(row.instanceId) !== args.workflowInstanceId)
4678
+ continue;
4679
+ if (target.activityCode !== undefined && target.activityCode !== null && wireString(row.activityCode) !== target.activityCode)
4680
+ continue;
4681
+ newWorkItems.push({ workItemId: wireString(row.id), activityCode: wireString(row.activityCode), participant: id });
4682
+ }
4683
+ }
4684
+ workItemLookup = {
4685
+ resolved: newWorkItems.length,
4686
+ wire: "list_workitems",
4687
+ note: "transfer 回执本体只有布尔值(无新 id);以上 newWorkItems 来自按 实例+目标审批人 的补查(每批 +1 wire)",
4688
+ };
4689
+ }
4690
+ catch {
4691
+ workItemLookup = { resolved: 0, wire: "list_workitems", note: "补查失败(不影响换人结果):用 workitem.list --participant <新审批人id> 手查新待办" };
4692
+ }
4365
4693
  return {
4366
4694
  performed: { errcode: performed.errcode, operationType: "ADJUST_PARTICIPANT", activityCode: target.activityCode, participantors: ids },
4367
4695
  readback: {
4368
4696
  activeActivities: after,
4369
4697
  transferred: after.some((row) => row.activityCode === target.activityCode && row.participants.some((person) => ids.includes(person.id ?? ""))),
4370
- boundaryNote: "测试提速工具:换过审批人的实例权限语义已变,勿用于真实流程/权限验证;正常审批链走 data.submit(workItemId)。",
4698
+ newWorkItems,
4699
+ workItemLookup,
4700
+ boundaryNote: "测试提速工具:换过审批人的实例权限语义已变,勿用于真实流程/权限验证;正常审批链走 data.submit(workItemId)。后续 data.submit 请用 newWorkItems 里的新 workItemId——原 id 已失效(405022)。",
4371
4701
  },
4372
4702
  };
4373
4703
  },
@@ -189,7 +189,11 @@ export async function deleteInstancesForPurge(session, workflowCode, instanceIds
189
189
  if (workflowCode === undefined)
190
190
  return { failed, steps, unremovableInstances };
191
191
  const openWorkItemsFor = async (instanceId) => {
192
- let total = 0;
192
+ // 0.6.82(r85 保真连锁):平台把查询态 PENDING 映射为 state IN (NOTSTARTED,
193
+ // INPROGRESS)(BizWorkitemServiceImpl.searchWorkitems),同一行会同时出现在
194
+ // status=PENDING 与 status=INPROGRESS 两次查询里——按 workitem 身份去重,
195
+ // 否则 openWorkItems 双计(fake 保真后暴露;真平台同样双计)。
196
+ const seen = new Set();
193
197
  for (const status of ["DRAFT", "PENDING", "INPROGRESS", "NOTSTARTED"]) {
194
198
  try {
195
199
  const page = (await wireCall(session, {
@@ -197,13 +201,18 @@ export async function deleteInstancesForPurge(session, workflowCode, instanceIds
197
201
  query: { workflowCode, status, page: "0", size: "200" },
198
202
  })).data;
199
203
  const rows = Array.isArray(page?.content) ? page.content : wireRows(page);
200
- total += rows.filter((row) => String(row.instanceId ?? row.workflowInstanceId ?? "") === instanceId).length;
204
+ for (const row of rows) {
205
+ if (String(row.instanceId ?? row.workflowInstanceId ?? "") !== instanceId)
206
+ continue;
207
+ const identity = String(row.id ?? row.workItemId ?? `${row.instanceId ?? ""}|${row.activityCode ?? ""}|${row.code ?? ""}`);
208
+ seen.add(identity);
209
+ }
201
210
  }
202
211
  catch {
203
212
  return null;
204
213
  }
205
214
  }
206
- return total;
215
+ return seen.size;
207
216
  };
208
217
  for (const id of instanceIds) {
209
218
  if (failed)