@stalfh233/omc-cli 0.8.32 → 0.8.33
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.
- package/dist/arg-vocabulary.js +223 -0
- package/dist/artifact-cmd.js +443 -0
- package/dist/batch-call.js +56 -3
- package/dist/call-command.js +70 -0
- package/dist/call-execute.js +228 -0
- package/dist/call-input.js +557 -0
- package/dist/call-output.js +240 -0
- package/dist/cli.js +13 -1359
- package/dist/command-transport.js +4 -1
- package/dist/form-support.js +14 -3
- package/dist/intent/plan-apply.js +14 -24
- package/dist/lanes/datarule.js +21 -0
- package/dist/lanes/field.js +31 -0
- package/dist/lanes/list-view-shapes.js +8 -1
- package/dist/lanes/list-view.js +64 -2
- package/dist/lanes/runtime-data/aggregate-support.js +209 -0
- package/dist/lanes/runtime-data/aggregate.js +679 -0
- package/dist/lanes/runtime-data/field-options.js +52 -0
- package/dist/lanes/runtime-data/lane.js +4 -0
- package/dist/lanes/runtime-data/record-delete.js +419 -0
- package/dist/lanes/runtime-data/record-read.js +984 -0
- package/dist/lanes/runtime-data/record-write.js +562 -0
- package/dist/lanes/runtime-data/registration.js +22 -0
- package/dist/lanes/runtime-data/shapes.js +594 -0
- package/dist/lanes/runtime-data/submission.js +1293 -0
- package/dist/lanes/runtime-data/write-support.js +875 -0
- package/dist/lanes/runtime-data.js +10 -5590
- package/dist/lanes/workflow/approval-ops.js +983 -0
- package/dist/lanes/workflow/instance-read.js +284 -0
- package/dist/lanes/workflow/lifecycle-write.js +1499 -0
- package/dist/lanes/workflow/permissions.js +571 -0
- package/dist/lanes/workflow/recovery.js +361 -0
- package/dist/lanes/workflow/registration.js +14 -0
- package/dist/lanes/workflow/shapes.js +811 -0
- package/dist/lanes/workflow/template-fetch.js +197 -0
- package/dist/lanes/workflow/template-merge.js +1351 -0
- package/dist/lanes/workflow/template-read.js +327 -0
- package/dist/lanes/workflow.js +11 -6312
- package/dist/read-projection.js +442 -0
- package/dist/read.js +40 -335
- package/dist/rollback.js +17 -23
- package/dist/runtime-support.js +1 -1
- package/dist/verification.js +39 -0
- package/dist/write-coordinator.js +152 -0
- package/dist/write-outcome.js +295 -0
- package/dist/write.js +34 -115
- package/package.json +3 -3
- package/skills/omc-refusals.md +1 -1
- package/skills/omc-start-here.md +2 -2
|
@@ -0,0 +1,1351 @@
|
|
|
1
|
+
import { ENDPOINTS } from "../../endpoints.js";
|
|
2
|
+
import { ToolRefusalError } from "../../tool-types.js";
|
|
3
|
+
import { wireCall, wireRows } from "../../wire.js";
|
|
4
|
+
import { WORKFLOW_ACTIVITY_TYPES, WORKFLOW_POINT, WORKFLOW_CONDITION_TYPES, WORKFLOW_MATCH_TYPES, WORKFLOW_RULE_CONDITION_ITEM_KEYS, resolveBizPropertyTypeIndex, normalizeRuleConditionGroup, editsExistingNodeShape, draftNodeCandidateList, uniqueDraftRowForTypelessEdit, callerActivityWireEntries, linearWorkflowOrder, canonicalizeWorkflowLayout, deriveRulePoints, workflowRouteConditionView, activityTypeOf, activityNameOf, activityCodeOf, flattenRoleTree } from "./shapes.js";
|
|
5
|
+
import { getWorkflowDraftOrNull } from "./template-fetch.js";
|
|
6
|
+
/**
|
|
7
|
+
* Fail closed on a malformed structured branch condition BEFORE any wire call —
|
|
8
|
+
* an unknown conditionType or childMatchType deserializes to null on the platform
|
|
9
|
+
* and the line silently never fires (the same class of silent no-op that bit
|
|
10
|
+
* checkType=2). Only caller-supplied `routes`/`rules` are checked.
|
|
11
|
+
*/
|
|
12
|
+
/**
|
|
13
|
+
* AI-Platform 1.1.25 rejects a template whose first activity after START is not
|
|
14
|
+
* the originator fill node: WorkflowTemplateValidateUtility.validateStartActivity
|
|
15
|
+
* emits 401035 「发起节点的参与者只能是{Originator}」 and publish answers
|
|
16
|
+
* errcode 0 with a ValidateMessage[] (nothing is stored). Live 2026-10-21: a
|
|
17
|
+
* role-approval node placed directly after START failed publish with exactly
|
|
18
|
+
* that code, and the generic message did not name the cause.
|
|
19
|
+
*/
|
|
20
|
+
export function assertFirstActivityIsOriginator(template, tool, merged) {
|
|
21
|
+
// Only gate AUTHORING intent: the caller must have sent both a START node and
|
|
22
|
+
// routes. A partial/stored-draft publish is left to the platform validator
|
|
23
|
+
// (401035), which the tool already surfaces faithfully.
|
|
24
|
+
const callerRows = callerActivities(template);
|
|
25
|
+
const callerRoutes = template.routes ?? template.rules ?? template.edges;
|
|
26
|
+
if (!Array.isArray(callerRows) || !Array.isArray(callerRoutes))
|
|
27
|
+
return;
|
|
28
|
+
if (!callerRows.some((activity) => String(activity.activityType ?? activity.type ?? "") === "START"))
|
|
29
|
+
return;
|
|
30
|
+
// Assert on the MERGED body: participant shorthands ({type:Originator,name:…})
|
|
31
|
+
// are normalized to "{Originator}" there.
|
|
32
|
+
const activities = callerActivities(merged ?? template);
|
|
33
|
+
const rawRoutes = merged ? (merged.routes ?? merged.rules ?? merged.edges) : callerRoutes;
|
|
34
|
+
if (!Array.isArray(activities) || !Array.isArray(rawRoutes))
|
|
35
|
+
return;
|
|
36
|
+
const start = activities.find((activity) => String(activity.activityType ?? activity.type ?? "") === "START");
|
|
37
|
+
if (!start)
|
|
38
|
+
return;
|
|
39
|
+
const startCode = activityCodeOf(start);
|
|
40
|
+
const first = rawRoutes
|
|
41
|
+
.map((entry) => (entry ?? {}))
|
|
42
|
+
.find((route) => String(route.preNode ?? route.preActivityCode ?? route.pre ?? route.from ?? "") === startCode);
|
|
43
|
+
if (!first)
|
|
44
|
+
return;
|
|
45
|
+
const nextCode = String(first.postNode ?? first.postActivityCode ?? first.post ?? first.to ?? "");
|
|
46
|
+
const next = activities.find((activity) => activityCodeOf(activity) === nextCode);
|
|
47
|
+
if (!next)
|
|
48
|
+
return;
|
|
49
|
+
const type = String(next.activityType ?? next.type ?? "");
|
|
50
|
+
const participant = String(next.participant ?? "").trim();
|
|
51
|
+
if (type === "PARTICIPANT" && /^\{Originator\}$/i.test(participant))
|
|
52
|
+
return;
|
|
53
|
+
throw new ToolRefusalError({
|
|
54
|
+
status: "refused",
|
|
55
|
+
blocker: "workflow-first-activity-not-originator",
|
|
56
|
+
workflowCode: String(template.workflowCode ?? template.code ?? ""),
|
|
57
|
+
activityCode: nextCode,
|
|
58
|
+
message: `${tool}: START 之后的第一个节点必须是参与者为 {Originator} 的填写节点(当前是 ${type || "?"}「${String(next.activityName ?? next.name ?? nextCode)}」${participant ? `,参与者 ${participant}` : ""})。` +
|
|
59
|
+
`平台校验 WorkflowTemplateValidateUtility.validateStartActivity 对此报 401035「发起节点的参与者只能是{Originator}」,publish 回 errcode 0 但一个 ValidateMessage[] 就把模板挡在门外、不落库(真机 2026-10-21)。` +
|
|
60
|
+
`正确形状:Start → 填写({Originator}) → 审批/条件分支 … → End;审批节点不能直接接在 START 后。`,
|
|
61
|
+
});
|
|
62
|
+
}
|
|
63
|
+
export function validateWorkflowRouteConditions(template, tool) {
|
|
64
|
+
const raw = template.routes ?? template.rules ?? template.edges;
|
|
65
|
+
if (!Array.isArray(raw))
|
|
66
|
+
return;
|
|
67
|
+
for (const [index, entry] of raw.entries()) {
|
|
68
|
+
const route = (entry ?? {});
|
|
69
|
+
// `null` is the platform's stored form for an absent optional — a caller
|
|
70
|
+
// legitimately round-tripping get_draft sends `text:null`/`formula:null`. Treat
|
|
71
|
+
// null like undefined, not as a wrong type.
|
|
72
|
+
for (const booleanKey of ["utilizeElse", "fixedPoint", "alternativeFlag"])
|
|
73
|
+
if (route[booleanKey] !== undefined && route[booleanKey] !== null && typeof route[booleanKey] !== "boolean")
|
|
74
|
+
throw new ToolRefusalError({ status: "refused", blocker: "workflow-route-condition-invalid", message: `${tool}: routes[${index}].${booleanKey} must be boolean` });
|
|
75
|
+
for (const stringKey of ["text", "formula"])
|
|
76
|
+
if (route[stringKey] !== undefined && route[stringKey] !== null && typeof route[stringKey] !== "string")
|
|
77
|
+
throw new ToolRefusalError({ status: "refused", blocker: "workflow-route-condition-invalid", message: `${tool}: routes[${index}].${stringKey} must be a string` });
|
|
78
|
+
if (route.childMatchType !== undefined && route.childMatchType !== null && !(typeof route.childMatchType === "string" && WORKFLOW_MATCH_TYPES.has(route.childMatchType)))
|
|
79
|
+
throw new ToolRefusalError({ status: "refused", blocker: "workflow-route-condition-invalid", message: `${tool}: routes[${index}].childMatchType must be ALL or ANY` });
|
|
80
|
+
if (route.ruleConditionGroup === undefined || route.ruleConditionGroup === null)
|
|
81
|
+
continue;
|
|
82
|
+
const groups = route.ruleConditionGroup;
|
|
83
|
+
// r85(retro issue 02):空外层数组是平台自己的存量写法(get_draft 原样读回
|
|
84
|
+
// `ruleConditionGroup: []`,语义=无条件),导出→改→回写是最常用路径。此前这里
|
|
85
|
+
// fail closed,逼调用方手工剥。现在按平台口径(CollectionUtils.isEmpty → 无条件,
|
|
86
|
+
// mapCallerRules/remapRuleEndpoints 本就在写前剥键)视为缺席放行;仅非数组形状
|
|
87
|
+
// 仍拒。剥离计数见 countStrippedEmptyConditionGroups(回执 strippedEmptyConditionGroups)。
|
|
88
|
+
if (Array.isArray(groups) && groups.length === 0)
|
|
89
|
+
continue;
|
|
90
|
+
if (!Array.isArray(groups))
|
|
91
|
+
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)` });
|
|
92
|
+
for (const [groupIndex, group] of groups.entries()) {
|
|
93
|
+
if (!Array.isArray(group) || group.length === 0)
|
|
94
|
+
throw new ToolRefusalError({ status: "refused", blocker: "workflow-route-condition-invalid", message: `${tool}: routes[${index}].ruleConditionGroup[${groupIndex}] must be a non-empty array of RuleConditionItem` });
|
|
95
|
+
for (const [itemIndex, item] of group.entries()) {
|
|
96
|
+
const condition = (item ?? {});
|
|
97
|
+
if (typeof condition.currentDataItem !== "string" || condition.currentDataItem.trim() === "")
|
|
98
|
+
throw new ToolRefusalError({ status: "refused", blocker: "workflow-route-condition-invalid", message: `${tool}: routes[${index}].ruleConditionGroup[${groupIndex}][${itemIndex}].currentDataItem must be a non-empty field code (child fields use "childSchemaCode.fieldCode")` });
|
|
99
|
+
if (!(typeof condition.conditionType === "string" && WORKFLOW_CONDITION_TYPES.has(condition.conditionType)))
|
|
100
|
+
throw new ToolRefusalError({ status: "refused", blocker: "workflow-route-condition-invalid", message: `${tool}: routes[${index}].ruleConditionGroup[${groupIndex}][${itemIndex}].conditionType must be a ConditionType (${[...WORKFLOW_CONDITION_TYPES].join("/")})` });
|
|
101
|
+
if (condition.bizPropertyType !== undefined && condition.bizPropertyType !== null && resolveBizPropertyTypeIndex(condition.bizPropertyType) === null)
|
|
102
|
+
throw new ToolRefusalError({ status: "refused", blocker: "workflow-route-condition-invalid", message: `${tool}: routes[${index}].ruleConditionGroup[${groupIndex}][${itemIndex}].bizPropertyType must be a BizPropertyType index (NUMERICAL=2, DATE=3, SHORT_TEXT=0, STAFF_SELECTOR=50, …) or a known enum name` });
|
|
103
|
+
const unknownKeys = Object.keys(condition).filter((key) => !WORKFLOW_RULE_CONDITION_ITEM_KEYS.has(key));
|
|
104
|
+
if (unknownKeys.length > 0)
|
|
105
|
+
throw new ToolRefusalError({
|
|
106
|
+
status: "refused",
|
|
107
|
+
blocker: "workflow-route-condition-invalid",
|
|
108
|
+
message: `${tool}: routes[${index}].ruleConditionGroup[${groupIndex}][${itemIndex}] 含未知键 ${unknownKeys.join("/")}——RuleConditionItem 只接受 ${[...WORKFLOW_RULE_CONDITION_ITEM_KEYS].join("/")};未知键会让平台 workflow/update 返回**误导性的 401001 流程不存在!**(真机 2026-09-25)。业务规则条件组的 targetDataItem/ruleValueType 等键不能照抄到流程连线条件里。`,
|
|
109
|
+
});
|
|
110
|
+
}
|
|
111
|
+
}
|
|
112
|
+
}
|
|
113
|
+
}
|
|
114
|
+
/**
|
|
115
|
+
* r85(retro issue 02):数一数调用方模板里有几条连线带着平台存量写法
|
|
116
|
+
* `ruleConditionGroup: []`。这些键在写前会被 merge 路径剥掉(mapCallerRules /
|
|
117
|
+
* remapRuleEndpoints 的既有行为,语义=无条件),validator 现在也按缺席放行;
|
|
118
|
+
* 计数进 update/publish 与 dry-run 的回执(strippedEmptyConditionGroups),
|
|
119
|
+
* 让「导出→改→回写」的调用方能看见工具替它剥了多少。
|
|
120
|
+
*/
|
|
121
|
+
export function countStrippedEmptyConditionGroups(template) {
|
|
122
|
+
const raw = template.routes ?? template.rules ?? template.edges;
|
|
123
|
+
if (!Array.isArray(raw))
|
|
124
|
+
return 0;
|
|
125
|
+
return raw.filter((entry) => {
|
|
126
|
+
const groups = (entry ?? {}).ruleConditionGroup;
|
|
127
|
+
return Array.isArray(groups) && groups.length === 0;
|
|
128
|
+
}).length;
|
|
129
|
+
}
|
|
130
|
+
/**
|
|
131
|
+
* Ticket 77 — a START/END-only template cannot overwrite the platform's
|
|
132
|
+
* auto-generated full draft (PARTICIPANT 填写申请单/审批 nodes); the platform
|
|
133
|
+
* answers a stable 401001 流程不存在. Refuse pre-wire and point at the
|
|
134
|
+
* get_draft-based editing path (or workflow.bindRule for rule binding).
|
|
135
|
+
*/
|
|
136
|
+
/**
|
|
137
|
+
* Caller activities may arrive as an array OR as an index-keyed object
|
|
138
|
+
* (`{"0":{…},"1":{…}}` — the shape the published workflow recipe teaches and
|
|
139
|
+
* the shape get_draft-adjacent callers reach for). Every downstream merge/lint
|
|
140
|
+
* step keys on an ARRAY; before this coercion an object-shaped `activities`
|
|
141
|
+
* was destructured away and silently DROPPED, so `workflow.update` answered
|
|
142
|
+
* `ok` while writing the unchanged draft — bench10/11: an agent's two-level
|
|
143
|
+
* approval template vanished and it could never land the second approval,
|
|
144
|
+
* burning 7 get_draft + 7 update round-trips. Coerce object → array in numeric
|
|
145
|
+
* key order; a non-array/non-object value is left to the element checks.
|
|
146
|
+
*/
|
|
147
|
+
function callerActivities(template) {
|
|
148
|
+
const activities = template?.activities;
|
|
149
|
+
if (Array.isArray(activities))
|
|
150
|
+
return activities;
|
|
151
|
+
if (activities !== null && typeof activities === "object") {
|
|
152
|
+
return Object.keys(activities)
|
|
153
|
+
.sort((a, b) => Number(a) - Number(b))
|
|
154
|
+
.map((key) => activities[key]);
|
|
155
|
+
}
|
|
156
|
+
return undefined;
|
|
157
|
+
}
|
|
158
|
+
export function assertTemplateNotMinimal(template, tool) {
|
|
159
|
+
// An absent template (publish the stored draft as-is) is the platform's own
|
|
160
|
+
// path and is out of the guard's scope — the bench golden evals drive it.
|
|
161
|
+
if (template === undefined || template === null)
|
|
162
|
+
return;
|
|
163
|
+
const activities = callerActivities(template);
|
|
164
|
+
// W1: a TYPE-LESS edit row (participant/propertyPermissions/btnConfigList/
|
|
165
|
+
// rename) still names an existing draft node — the merge path backfills its
|
|
166
|
+
// type from that node. Counting only the literal type strings made a full
|
|
167
|
+
// replace like [START, {activityCode,participant}, END] look boundary-only
|
|
168
|
+
// and refused it as `workflow-template-minimal`.
|
|
169
|
+
const hasTypelessEditRow = (activities ?? []).some((activity) => {
|
|
170
|
+
if (activity === null || typeof activity !== "object")
|
|
171
|
+
return false;
|
|
172
|
+
const record = activity;
|
|
173
|
+
const type = record.type ?? record.activityType;
|
|
174
|
+
return (type === undefined || type === null || String(type).trim() === "") && editsExistingNodeShape(record);
|
|
175
|
+
});
|
|
176
|
+
if (hasTypelessEditRow)
|
|
177
|
+
return;
|
|
178
|
+
const types = activities
|
|
179
|
+
? activities
|
|
180
|
+
.map((activity) => (activity && typeof activity === "object" ? String(activity.type ?? activity.activityType ?? "") : ""))
|
|
181
|
+
.filter((type) => type.length > 0)
|
|
182
|
+
: [];
|
|
183
|
+
if (types.length > 0 && types.every((type) => type === "START" || type === "END")) {
|
|
184
|
+
throw new ToolRefusalError({
|
|
185
|
+
status: "refused",
|
|
186
|
+
blocker: "workflow-template-minimal",
|
|
187
|
+
message: `${tool} 收到仅含 START/END 的极简模板——平台为流程头自动生成含 PARTICIPANT 节点(填写申请单/审批)的完整草稿,极简模板无法覆盖,平台会稳定返回 401001 流程不存在。以 workflow.get_draft 返回的完整模板为基础修改后再 update/publish;只绑规则用 workflow.bindRule`,
|
|
188
|
+
});
|
|
189
|
+
}
|
|
190
|
+
}
|
|
191
|
+
/**
|
|
192
|
+
* Ticket 112 — dry-lint the caller template against the platform's update
|
|
193
|
+
* contract (8.6.26 decompiled source), zero wire:
|
|
194
|
+
* - `templateType:"BusinessProcess"` is NOT a WorkflowTemplateStatus member
|
|
195
|
+
* (WorkflowTemplateUtil.java:136 valueOf; the converter swallows the
|
|
196
|
+
* exception into a partial model and the save chain then fails with errcode
|
|
197
|
+
* 50000) — omit it and the draft's value rides along.
|
|
198
|
+
* - every activities element on the WIRE needs a type (platform keys on
|
|
199
|
+
* activityType; ActivityType.valueOf("null") throws the same swallowed way).
|
|
200
|
+
* An edit row of an EXISTING draft node may omit it — the merge path backfills
|
|
201
|
+
* the draft node's own type (uniqueDraftRowForTypelessEdit).
|
|
202
|
+
*/
|
|
203
|
+
export function lintWorkflowTemplate(template, tool) {
|
|
204
|
+
if (template === undefined || template === null)
|
|
205
|
+
return;
|
|
206
|
+
if (template.templateType === "BusinessProcess")
|
|
207
|
+
throw new ToolRefusalError({
|
|
208
|
+
status: "refused",
|
|
209
|
+
blocker: "workflow-template-type-invalid",
|
|
210
|
+
message: `${tool}: templateType "BusinessProcess" 不是 WorkflowTemplateStatus 枚举成员(WorkflowTemplateUtil.java:136 valueOf——转换异常被吞成残缺模型后保存链 50000)。省略 templateType,由 get_draft 草稿值回显`,
|
|
211
|
+
});
|
|
212
|
+
const activities = callerActivities(template);
|
|
213
|
+
if (activities) {
|
|
214
|
+
for (const activity of activities) {
|
|
215
|
+
const record = activity;
|
|
216
|
+
const type = record != null && typeof record === "object" ? (record.type ?? record.activityType) : undefined;
|
|
217
|
+
// Edit rows (permissions/rename/participant/buttons) target an existing
|
|
218
|
+
// draft node and inherit its type at merge time — only a bare new node
|
|
219
|
+
// must carry its own type here. The code→draft uniqueness check belongs
|
|
220
|
+
// to the merge paths (they hold the draft); this lint is shape-only.
|
|
221
|
+
const targetsExistingNode = record != null && typeof record === "object" && editsExistingNodeShape(record);
|
|
222
|
+
if ((type === undefined || type === null || String(type).trim() === "") && !targetsExistingNode)
|
|
223
|
+
throw new ToolRefusalError({
|
|
224
|
+
status: "refused",
|
|
225
|
+
blocker: "workflow-activity-type-missing",
|
|
226
|
+
message: `${tool}: activities 元素缺少 type/activityType(平台 ActivityType.valueOf 对 "null" 抛异常被吞成残缺模型 → 50000);新节点必须带类型(既有节点编辑行如 participant/propertyPermissions/btnConfigList/改名可省,类型继承自草稿同 code 节点)`,
|
|
227
|
+
});
|
|
228
|
+
}
|
|
229
|
+
}
|
|
230
|
+
}
|
|
231
|
+
/**
|
|
232
|
+
* Ticket 112 — normalize the caller template onto the platform DTO:
|
|
233
|
+
* - `routes[]` is NOT a WorkflowTemplateModel field (WorkflowTemplateModel
|
|
234
|
+
* .java:51-66 declares List<Rule> rules; Rule.java:40-57
|
|
235
|
+
* preActivityCode/postActivityCode). Caller routes are mapped to rules
|
|
236
|
+
* elements — with derived string `points` (the workflow designer canvas
|
|
237
|
+
* keys on them exactly like the rule graph does) — and the routes key
|
|
238
|
+
* never rides the wire.
|
|
239
|
+
* - caller activities may use the repo shorthand {id,type,name,participant};
|
|
240
|
+
* the platform wire keys are activityCode/activityType/activityName
|
|
241
|
+
* (WorkflowTemplateController update @ApiImplicitParam example;
|
|
242
|
+
* ActivityType.valueOf("null") makes the converter fail → 401001). Each
|
|
243
|
+
* caller activity is merged onto the matching DRAFT activity so the
|
|
244
|
+
* platform-required subfaces (todoDataItems, permittedAction,
|
|
245
|
+
* preCondition, geometry) echo instead of holing the model.
|
|
246
|
+
*/
|
|
247
|
+
function mapCallerActivities(callerActivities, draftActivities) {
|
|
248
|
+
const draftByCode = new Map(draftActivities.map((activity) => [String(activity.activityCode ?? ""), activity]));
|
|
249
|
+
const draftByType = (type) => draftActivities.find((activity) => String(activity.activityType ?? "") === type);
|
|
250
|
+
return callerActivities.map((entry) => {
|
|
251
|
+
const record = (entry ?? {});
|
|
252
|
+
const code = activityCodeOf(record);
|
|
253
|
+
const type = activityTypeOf(record);
|
|
254
|
+
// W1: a type-less edit row inherits the draft node's own activityType. Only
|
|
255
|
+
// a unique same-code draft row qualifies — the platform requires a type on
|
|
256
|
+
// every activity element of the body it receives (WorkflowTemplateUtil
|
|
257
|
+
// .convertActivity → ActivityType.valueOf), and a miss means this is a new
|
|
258
|
+
// node whose type must be explicit.
|
|
259
|
+
const base = type
|
|
260
|
+
? (draftByCode.get(code) ??
|
|
261
|
+
(type === "START" ? draftByType("START") : type === "END" ? draftByType("END") : type === "PARTICIPANT" ? draftByType("PARTICIPANT") : undefined) ??
|
|
262
|
+
{})
|
|
263
|
+
: uniqueDraftRowForTypelessEdit("workflow", code, draftActivities);
|
|
264
|
+
// Drop the input aliases AND the readback-only keys (`code`/`index` come
|
|
265
|
+
// from workflowSummary). Stray keys on an Activity/Rule make the platform
|
|
266
|
+
// answer a misleading 401001; only canonical keys may ride the wire. The
|
|
267
|
+
// participant is normalized as part of the record so the trailing spread
|
|
268
|
+
// cannot re-introduce a shorthand the platform cannot resolve.
|
|
269
|
+
// r85: a STRING-array bizActions is SystemActivity's own wire field and
|
|
270
|
+
// rides (callerActivityWireEntries); the object-shaped summary projection
|
|
271
|
+
// is still stripped.
|
|
272
|
+
const wireRecord = {
|
|
273
|
+
...Object.fromEntries(callerActivityWireEntries(record)),
|
|
274
|
+
...(record.participant !== undefined ? { participant: normalizeParticipantForWire(record.participant) } : {}),
|
|
275
|
+
};
|
|
276
|
+
const mapped = {
|
|
277
|
+
...base,
|
|
278
|
+
activityCode: code,
|
|
279
|
+
...(type ? { activityType: type } : {}),
|
|
280
|
+
...(record.name !== undefined ? { activityName: record.name } : {}),
|
|
281
|
+
...wireRecord,
|
|
282
|
+
};
|
|
283
|
+
// Replace path: a caller-only code with no type has no draft row to
|
|
284
|
+
// inherit from — refuse before the wire (same rule the merge path
|
|
285
|
+
// enforces for its appended nodes). uniqueDraftRowForTypelessEdit already
|
|
286
|
+
// refused the common case; this catches a draft row whose own type is empty.
|
|
287
|
+
if (String(mapped.activityType ?? "") === "")
|
|
288
|
+
throw new ToolRefusalError({
|
|
289
|
+
status: "refused",
|
|
290
|
+
blocker: "workflow-activity-type-missing",
|
|
291
|
+
message: `workflow: 节点 ${code} 在草稿里没有可继承的 type/activityType——新节点必须显式给 type;只有 activityCode 唯一命中既有草稿节点时才能省`,
|
|
292
|
+
});
|
|
293
|
+
return mapped;
|
|
294
|
+
});
|
|
295
|
+
}
|
|
296
|
+
export function validateCallerActivities(template, tool) {
|
|
297
|
+
const activities = callerActivities(template);
|
|
298
|
+
if (!activities)
|
|
299
|
+
return;
|
|
300
|
+
const codes = new Set();
|
|
301
|
+
for (const [index, raw] of activities.entries()) {
|
|
302
|
+
const activity = raw;
|
|
303
|
+
const code = String(activity?.activityCode ?? activity?.id ?? activity?.code ?? "").trim();
|
|
304
|
+
const rawType = String(activity?.activityType ?? activity?.type ?? "").trim();
|
|
305
|
+
const type = rawType === "APPROVAL" ? "PARTICIPANT" : rawType;
|
|
306
|
+
if (!code)
|
|
307
|
+
throw new ToolRefusalError({ status: "refused", blocker: "workflow-render-activity-code-invalid", message: `${tool}: activities[${index}] requires a non-empty activityCode/id` });
|
|
308
|
+
if (codes.has(code))
|
|
309
|
+
throw new ToolRefusalError({ status: "refused", blocker: "workflow-render-activity-code-duplicate", message: `${tool}: duplicate activityCode ${code}` });
|
|
310
|
+
if (!rawType) {
|
|
311
|
+
// An edit row (permissions/rename/participant/buttons) targets an
|
|
312
|
+
// EXISTING draft node and inherits its type at merge time — demanding a
|
|
313
|
+
// type here forced agents to re-send identity fields, and any spelling
|
|
314
|
+
// drift then minted `_2` codes. Bare new nodes still need a type; the
|
|
315
|
+
// merge paths refuse a type-less row whose code is not a unique draft hit
|
|
316
|
+
// (uniqueDraftRowForTypelessEdit).
|
|
317
|
+
const targetsExistingNode = activity != null && typeof activity === "object" && editsExistingNodeShape(activity);
|
|
318
|
+
if (!targetsExistingNode)
|
|
319
|
+
throw new ToolRefusalError({ status: "refused", blocker: "workflow-activity-type-missing", message: `${tool}: activities[${index}] requires type/activityType(既有节点编辑行——participant/propertyPermissions/btnConfigList/改名——可省,类型继承自草稿同 code 节点)` });
|
|
320
|
+
}
|
|
321
|
+
if (rawType !== "" && !WORKFLOW_ACTIVITY_TYPES.has(type))
|
|
322
|
+
throw new ToolRefusalError({ status: "refused", blocker: "workflow-render-activity-type-invalid", message: `${tool}: activities[${index}] has an illegal ActivityType` });
|
|
323
|
+
codes.add(code);
|
|
324
|
+
}
|
|
325
|
+
}
|
|
326
|
+
function mapCallerRules(callerRoutes, draftRules, activities) {
|
|
327
|
+
const baseRule = draftRules[0] ?? {};
|
|
328
|
+
return callerRoutes.map((entry) => {
|
|
329
|
+
const record = (entry ?? {});
|
|
330
|
+
const pre = String(record.preActivityCode ?? record.preNode ?? record.pre ?? record.from ?? "");
|
|
331
|
+
const post = String(record.postActivityCode ?? record.postNode ?? record.post ?? record.to ?? "");
|
|
332
|
+
// Derive points only when the caller gave none (absent or empty). A
|
|
333
|
+
// MALFORMED value must ride through untouched so validateWorkflowRender
|
|
334
|
+
// refuses it — silently repairing it would hide a shape error.
|
|
335
|
+
const pointsRaw = record.points;
|
|
336
|
+
const points = pointsRaw === undefined || pointsRaw === null || (Array.isArray(pointsRaw) && pointsRaw.length === 0)
|
|
337
|
+
? deriveRulePoints(pre, post, activities)
|
|
338
|
+
: pointsRaw;
|
|
339
|
+
const mapped = {
|
|
340
|
+
...baseRule,
|
|
341
|
+
...Object.fromEntries(Object.entries(record).filter(([key]) => !["preNode", "postNode", "pre", "post", "from", "to"].includes(key))),
|
|
342
|
+
preActivityCode: pre,
|
|
343
|
+
postActivityCode: post,
|
|
344
|
+
points,
|
|
345
|
+
};
|
|
346
|
+
// A structured branch line (round7) only fires when popupType is EXPRESSION
|
|
347
|
+
// and it is NOT the else/fallback line (ActivityContext
|
|
348
|
+
// .getNextFormulaActivities:82-99). The platform defaults are popupType
|
|
349
|
+
// FUNCTION (Rule.java:49) and utilizeElse true (Rule.java:37) — either would
|
|
350
|
+
// silently turn a supplied ruleConditionGroup into a no-op, and both ride in
|
|
351
|
+
// via the draft baseRule. So force them unless the caller set them itself.
|
|
352
|
+
if (record.ruleConditionGroup !== undefined) {
|
|
353
|
+
// The stored spelling for "no condition" is an empty outer array; drop it
|
|
354
|
+
// instead of forcing EXPRESSION/else on a plain edge.
|
|
355
|
+
if (Array.isArray(record.ruleConditionGroup) && record.ruleConditionGroup.length === 0)
|
|
356
|
+
delete mapped.ruleConditionGroup;
|
|
357
|
+
else {
|
|
358
|
+
if (record.popupType === undefined)
|
|
359
|
+
mapped.popupType = "EXPRESSION";
|
|
360
|
+
if (record.utilizeElse === undefined)
|
|
361
|
+
mapped.utilizeElse = false;
|
|
362
|
+
// The platform deserializes BizPropertyType from an INT index; normalize a
|
|
363
|
+
// caller's enum name before the wire (see WORKFLOW_BIZ_PROPERTY_TYPE_INDEX).
|
|
364
|
+
mapped.ruleConditionGroup = normalizeRuleConditionGroup(record.ruleConditionGroup);
|
|
365
|
+
}
|
|
366
|
+
}
|
|
367
|
+
return mapped;
|
|
368
|
+
});
|
|
369
|
+
}
|
|
370
|
+
/**
|
|
371
|
+
* Role participants are filtered by `ouScope ∩ originator's department chain`.
|
|
372
|
+
* A role whose members all have an empty scope therefore resolves to NOBODY —
|
|
373
|
+
* but the workflow still publishes, the submit still answers 0, and the todo
|
|
374
|
+
* silently falls back to the originator (r9/r10 live; r15 lost 12 calls to it).
|
|
375
|
+
* Refuse BEFORE the update wire (read-only check, fail-open when the member
|
|
376
|
+
* list is unavailable) so the trap is named where the participant is authored.
|
|
377
|
+
*/
|
|
378
|
+
export async function assertRoleParticipantScopes(session, body) {
|
|
379
|
+
const rows = Array.isArray(body.activities)
|
|
380
|
+
? body.activities
|
|
381
|
+
: body.activities && typeof body.activities === "object"
|
|
382
|
+
? Object.values(body.activities)
|
|
383
|
+
: [];
|
|
384
|
+
const roles = [];
|
|
385
|
+
const functionRoles = [];
|
|
386
|
+
for (const activity of rows) {
|
|
387
|
+
if (String(activity.activityType ?? "") !== "PARTICIPANT")
|
|
388
|
+
continue;
|
|
389
|
+
const raw = activity.participant;
|
|
390
|
+
if (typeof raw !== "string" || !raw.trim().startsWith("["))
|
|
391
|
+
continue;
|
|
392
|
+
const activityCode = String(activity.activityCode ?? "");
|
|
393
|
+
const activityName = String(activity.activityName ?? activity.name ?? activityCode);
|
|
394
|
+
for (const segment of raw.split("+")) {
|
|
395
|
+
let parsed;
|
|
396
|
+
try {
|
|
397
|
+
parsed = JSON.parse(segment.trim());
|
|
398
|
+
}
|
|
399
|
+
catch {
|
|
400
|
+
continue;
|
|
401
|
+
}
|
|
402
|
+
if (!Array.isArray(parsed))
|
|
403
|
+
continue;
|
|
404
|
+
for (const entry of parsed) {
|
|
405
|
+
if (entry === null || typeof entry !== "object")
|
|
406
|
+
continue;
|
|
407
|
+
const record = entry;
|
|
408
|
+
if (String(record.type ?? record.participantType ?? "") !== "2")
|
|
409
|
+
continue;
|
|
410
|
+
const roleId = String(record.id ?? "");
|
|
411
|
+
if (roleId)
|
|
412
|
+
roles.push({ activityCode, activityName, roleId, roleName: String(record.name ?? roleId) });
|
|
413
|
+
}
|
|
414
|
+
}
|
|
415
|
+
}
|
|
416
|
+
for (const activity of rows) {
|
|
417
|
+
if (String(activity.activityType ?? "") !== "PARTICIPANT")
|
|
418
|
+
continue;
|
|
419
|
+
const participant = typeof activity.participant === "string" ? activity.participant.trim() : "";
|
|
420
|
+
if (/^FindUserByRole\s*\(/i.test(participant)) {
|
|
421
|
+
const strict = /^FindUserByRole\s*\(\s*\{Originator\.OU\}\s*,\s*("(?:\\.|[^"\\])*"|'(?:\\.|[^'\\])*')\s*,\s*("(?:\\.|[^"\\])*"|'(?:\\.|[^'\\])*')\s*\)\s*$/i.exec(participant);
|
|
422
|
+
if (!strict)
|
|
423
|
+
throw new ToolRefusalError({ status: "refused", blocker: "workflow-find-user-by-role-parameters-invalid", activityCode: String(activity.activityCode ?? ""), nextCommand: "使用 FindUserByRole({Originator.OU},\"<真实角色code>\",\"random\");组织范围不得手填 id", message: `节点 ${String(activity.activityCode ?? "")} 的 FindUserByRole 参数不合法:x 必须是单一 {Originator.OU},不得手填 id;y 必须是带引号的单一角色 code。` });
|
|
424
|
+
const order = strict[2].slice(1, -1);
|
|
425
|
+
if (!new Set(["dept", "sortKey", "random"]).has(order))
|
|
426
|
+
throw new ToolRefusalError({ status: "refused", blocker: "workflow-find-user-by-role-order-invalid", activityCode: String(activity.activityCode ?? ""), order, candidates: ["dept", "sortKey", "random"], nextCommand: "将第三参数改为 dept、sortKey 或 random", message: `FindUserByRole 第三参数 ${order} 不在允许枚举 dept/sortKey/random。` });
|
|
427
|
+
}
|
|
428
|
+
const match = /^FindUserByRole\s*\(\s*\{Originator\.OU\}\s*,\s*("(?:\\.|[^"\\])*"|'(?:\\.|[^'\\])*')\s*,\s*("(?:\\.|[^"\\])*"|'(?:\\.|[^'\\])*')\s*\)\s*$/.exec(participant);
|
|
429
|
+
if (!match)
|
|
430
|
+
continue;
|
|
431
|
+
const quoted = match[1];
|
|
432
|
+
let roleCode;
|
|
433
|
+
try {
|
|
434
|
+
roleCode = quoted.startsWith('"') ? JSON.parse(quoted) : quoted.slice(1, -1).replace(/\\(['\\])/g, "$1");
|
|
435
|
+
}
|
|
436
|
+
catch {
|
|
437
|
+
continue;
|
|
438
|
+
}
|
|
439
|
+
if (roleCode.trim())
|
|
440
|
+
functionRoles.push({ activityCode: String(activity.activityCode ?? ""), activityName: String(activity.activityName ?? activity.name ?? activity.activityCode ?? ""), roleCode: roleCode.trim() });
|
|
441
|
+
}
|
|
442
|
+
if (functionRoles.length > 0) {
|
|
443
|
+
let listedRoles = [];
|
|
444
|
+
let roleListAvailable = false;
|
|
445
|
+
try {
|
|
446
|
+
const data = (await wireCall(session, { path: ENDPOINTS.organizationRoleList, query: { expandAll: "true" } })).data;
|
|
447
|
+
const flattened = flattenRoleTree(wireRows(data));
|
|
448
|
+
listedRoles = Array.isArray(flattened.roles) ? flattened.roles : [];
|
|
449
|
+
roleListAvailable = true;
|
|
450
|
+
}
|
|
451
|
+
catch {
|
|
452
|
+
throw new ToolRefusalError({ status: "refused", blocker: "workflow-participant-role-read-failed", nextCommand: "omc call org.role.list --args '{}'", message: "无法读取真实角色树,不能确认 FindUserByRole 的 role code;为避免流程静默回退发起人,已 fail-closed 拒绝写入。请恢复组织读面后重试。" });
|
|
453
|
+
}
|
|
454
|
+
if (roleListAvailable) {
|
|
455
|
+
const byCode = new Map(listedRoles
|
|
456
|
+
.map((role) => [String(role.code ?? ""), role])
|
|
457
|
+
.filter(([code]) => code.length > 0));
|
|
458
|
+
const missing = functionRoles.filter((role) => !byCode.has(role.roleCode));
|
|
459
|
+
if (missing.length > 0) {
|
|
460
|
+
const candidates = (needle) => {
|
|
461
|
+
const lower = needle.toLowerCase();
|
|
462
|
+
const distance = (left, right) => {
|
|
463
|
+
const row = Array.from({ length: right.length + 1 }, (_, index) => index);
|
|
464
|
+
for (let i = 1; i <= left.length; i++) {
|
|
465
|
+
let diagonal = row[0];
|
|
466
|
+
row[0] = i;
|
|
467
|
+
for (let j = 1; j <= right.length; j++) {
|
|
468
|
+
const prior = row[j];
|
|
469
|
+
row[j] = left[i - 1] === right[j - 1] ? diagonal : Math.min(row[j] + 1, row[j - 1] + 1, diagonal + 1);
|
|
470
|
+
diagonal = prior;
|
|
471
|
+
}
|
|
472
|
+
}
|
|
473
|
+
return row[right.length];
|
|
474
|
+
};
|
|
475
|
+
return listedRoles
|
|
476
|
+
.map((role) => {
|
|
477
|
+
const code = String(role.code ?? "");
|
|
478
|
+
const name = String(role.name ?? "");
|
|
479
|
+
const haystack = `${code} ${name}`.toLowerCase();
|
|
480
|
+
const substringRank = haystack.includes(lower) ? 0 : 1;
|
|
481
|
+
const editRank = Math.min(distance(lower, code.toLowerCase()), distance(lower, name.toLowerCase()));
|
|
482
|
+
return { code, name, substringRank, editRank };
|
|
483
|
+
})
|
|
484
|
+
.filter((role) => role.code.length > 0)
|
|
485
|
+
.sort((left, right) => left.substringRank - right.substringRank || left.editRank - right.editRank || left.code.localeCompare(right.code))
|
|
486
|
+
.slice(0, 5)
|
|
487
|
+
.map(({ code, name }) => ({ code, name }));
|
|
488
|
+
};
|
|
489
|
+
const first = missing[0];
|
|
490
|
+
throw new ToolRefusalError({
|
|
491
|
+
status: "refused",
|
|
492
|
+
blocker: "workflow-participant-role-not-found",
|
|
493
|
+
roles: missing,
|
|
494
|
+
candidates: candidates(first.roleCode),
|
|
495
|
+
nextCommand: "omc call org.role.list --args '{}'",
|
|
496
|
+
message: `写前拒绝:节点 ${first.activityCode}(${first.activityName})引用了不存在的角色 ${first.roleCode}。放行会导致待办静默回退给发起人(r9/r10/r15 真机)。请先用 org.role.list 确认真实 role code。`,
|
|
497
|
+
});
|
|
498
|
+
}
|
|
499
|
+
}
|
|
500
|
+
}
|
|
501
|
+
const problems = [];
|
|
502
|
+
for (const role of roles) {
|
|
503
|
+
let members;
|
|
504
|
+
try {
|
|
505
|
+
const data = (await wireCall(session, {
|
|
506
|
+
path: ENDPOINTS.organizationRoleUsers,
|
|
507
|
+
query: { corpId: session.enterpriseId(), roleId: role.roleId, page: "0", size: "500" },
|
|
508
|
+
})).data;
|
|
509
|
+
members = Array.isArray(data?.content) ? data.content : wireRows(data);
|
|
510
|
+
}
|
|
511
|
+
catch {
|
|
512
|
+
// A read failure must not block the write (fail open) — the platform
|
|
513
|
+
// will answer, and the participant warnings still ride the readback.
|
|
514
|
+
continue;
|
|
515
|
+
}
|
|
516
|
+
if (members.length === 0)
|
|
517
|
+
continue; // nothing to prove
|
|
518
|
+
const withScope = members.filter((member) => Array.isArray(member.ouScope) && member.ouScope.length > 0);
|
|
519
|
+
if (withScope.length === 0)
|
|
520
|
+
problems.push({ ...role, members: members.length });
|
|
521
|
+
}
|
|
522
|
+
if (problems.length === 0)
|
|
523
|
+
return;
|
|
524
|
+
const detail = problems.map((problem) => `${problem.activityCode} → 角色 ${problem.roleName}(${problem.roleId}) 的 ${problem.members} 名成员 ouScope 全为空`).join(";");
|
|
525
|
+
const first = problems[0];
|
|
526
|
+
throw new ToolRefusalError({
|
|
527
|
+
status: "refused",
|
|
528
|
+
blocker: "workflow-participant-role-scope-empty",
|
|
529
|
+
roles: problems,
|
|
530
|
+
nextCommand: `omc call org.role.users --args '${JSON.stringify({ roleId: first.roleId })}'`,
|
|
531
|
+
message: `节点参与者用了角色,但该角色成员的 ouScope 为空:${detail}。` +
|
|
532
|
+
`平台按「ouScope ∩ 发起人部门链」解析角色成员,空范围 = 永远解析不到人;流程仍会发布、submit 仍回 errcode 0,` +
|
|
533
|
+
`待办会**静默回退给发起人**(r9/r10/r15 真机)。` +
|
|
534
|
+
`先给成员补管理范围(部门节点):omc call org.role.setUserScope --args '{"roleId":"${first.roleId}","userId":"<成员recId>","scopes":[{"id":"<部门id>","name":"<部门名>","type":"1"}],"mode":"replace"}',` +
|
|
535
|
+
`或在 addUsers 时直接带 scopes。补完再重试本次 workflow.update。`,
|
|
536
|
+
});
|
|
537
|
+
}
|
|
538
|
+
/**
|
|
539
|
+
* Normalize a participant reference to a platform-resolvable form BEFORE it rides
|
|
540
|
+
* the wire. Live 2026-09-28: an intent that declares `participant: {type: Originator}`
|
|
541
|
+
* (or a bare `participant: Originator`) is stored as the JSON string
|
|
542
|
+
* `"{\"type\":\"Originator\"}"`, and `workflow.publish` refuses with
|
|
543
|
+
* `401035 填写申请单` — the originate participant never resolves, so the whole
|
|
544
|
+
* workflow will not publish. The platform understands three forms (see
|
|
545
|
+
* participantReferenceWarnings); this maps the natural shorthands onto them:
|
|
546
|
+
* - a lone originator (bare `Originator`, or `{type/participantType: "Originator"}`
|
|
547
|
+
* with only display keys) → the keyword `"{Originator}"`
|
|
548
|
+
* - a role/user object `{code|id: …}` → a one-element JSON array `[obj]`
|
|
549
|
+
* - an array → JSON string; a string is left verbatim (already a valid form)
|
|
550
|
+
* Existing `"{Originator}"`/function/role-array strings pass through unchanged.
|
|
551
|
+
*/
|
|
552
|
+
export function normalizeParticipantForWire(participant) {
|
|
553
|
+
if (participant === undefined || participant === null)
|
|
554
|
+
return participant;
|
|
555
|
+
if (typeof participant === "string") {
|
|
556
|
+
return /^originator$/i.test(participant.trim()) ? "{Originator}" : participant;
|
|
557
|
+
}
|
|
558
|
+
if (Array.isArray(participant))
|
|
559
|
+
return participant.length === 0 ? "" : JSON.stringify(participant);
|
|
560
|
+
if (typeof participant === "object") {
|
|
561
|
+
const record = participant;
|
|
562
|
+
const keys = Object.keys(record);
|
|
563
|
+
const typeValue = record.type ?? record.participantType;
|
|
564
|
+
const displayOnly = keys.every((key) => ["type", "participantType", "name", "i18nMessage", "label", "displayName"].includes(key));
|
|
565
|
+
if (displayOnly && typeof typeValue === "string" && /^originator$/i.test(typeValue.trim()))
|
|
566
|
+
return "{Originator}";
|
|
567
|
+
// A role/user descriptor must be a JSON ARRAY string; a bare object fails
|
|
568
|
+
// resolution too.
|
|
569
|
+
if ("code" in record || "id" in record)
|
|
570
|
+
return JSON.stringify([record]);
|
|
571
|
+
return JSON.stringify(record);
|
|
572
|
+
}
|
|
573
|
+
return participant;
|
|
574
|
+
}
|
|
575
|
+
export function workflowRenderCompat(template) {
|
|
576
|
+
const activities = Array.isArray(template.activities) ? template.activities : [];
|
|
577
|
+
const rules = Array.isArray(template.rules) ? template.rules : [];
|
|
578
|
+
const activityCodes = new Set(activities.map((activity) => String(activity.activityCode ?? "")));
|
|
579
|
+
const danglingViolations = rules.flatMap((rule, index) => {
|
|
580
|
+
const missing = ["preActivityCode", "postActivityCode"].filter((key) => !activityCodes.has(String(rule[key] ?? "")));
|
|
581
|
+
return missing.length > 0 ? [{ ruleIndex: index, missing }] : [];
|
|
582
|
+
});
|
|
583
|
+
// 2026-09-25 cost pass: geometry + route points are deterministic for the
|
|
584
|
+
// canonical single column (x=327, 158×40, 80px apart). Echoing all of them on
|
|
585
|
+
// every activity/edge was ~880 B per workflow write. Only a DEVIATION from the
|
|
586
|
+
// canonical seat/edge is meaningful (a caller-placed layout, or a collision the
|
|
587
|
+
// canonicalizer fixed), so only deviations are echoed; their absence proves the
|
|
588
|
+
// graph is canonical. This keeps the render-compat capability (ticket 109:
|
|
589
|
+
// catch a broken/off-column layout) at a fraction of the bytes.
|
|
590
|
+
const numberOr = (value, fallback) => (Number.isFinite(Number(value)) ? Number(value) : fallback);
|
|
591
|
+
const order = linearWorkflowOrder(activities, rules);
|
|
592
|
+
const seat = (activity, index) => ({
|
|
593
|
+
x: 327,
|
|
594
|
+
y: 36 + 80 * (order.length > 0 ? order.indexOf(String(activity.activityCode ?? "")) : index),
|
|
595
|
+
width: 158,
|
|
596
|
+
height: 40,
|
|
597
|
+
});
|
|
598
|
+
const canonicalGeometry = (activity, index) => {
|
|
599
|
+
const expected = seat(activity, index);
|
|
600
|
+
return numberOr(activity.x, Number.NaN) === expected.x && numberOr(activity.y, Number.NaN) === expected.y && numberOr(activity.width, expected.width) === expected.width && numberOr(activity.height, expected.height) === expected.height;
|
|
601
|
+
};
|
|
602
|
+
return {
|
|
603
|
+
activities: activities.map((activity, index) => {
|
|
604
|
+
const geometry = { x: activity.x, y: activity.y, width: activity.width, height: activity.height };
|
|
605
|
+
return { activityCode: String(activity.activityCode), activityType: String(activity.activityType), ...(canonicalGeometry(activity, index) ? {} : { geometry }) };
|
|
606
|
+
}),
|
|
607
|
+
rules: rules.map((rule) => {
|
|
608
|
+
const pre = String(rule.preActivityCode);
|
|
609
|
+
const post = String(rule.postActivityCode);
|
|
610
|
+
const stored = Array.isArray(rule.points) ? rule.points : [];
|
|
611
|
+
const derived = deriveRulePoints(pre, post, activities);
|
|
612
|
+
const canonicalPoints = stored.length === derived.length && stored.every((point, index) => point === derived[index]);
|
|
613
|
+
return { preActivityCode: pre, postActivityCode: post, ...(canonicalPoints ? {} : { points: rule.points }), ...workflowRouteConditionView(rule) };
|
|
614
|
+
}),
|
|
615
|
+
startEnd: {
|
|
616
|
+
start: activities.filter((activity) => activity.activityType === "START").map((activity) => String(activity.activityCode)),
|
|
617
|
+
end: activities.filter((activity) => activity.activityType === "END").map((activity) => String(activity.activityCode)),
|
|
618
|
+
},
|
|
619
|
+
danglingViolations,
|
|
620
|
+
};
|
|
621
|
+
}
|
|
622
|
+
export function validateWorkflowRender(template, tool) {
|
|
623
|
+
const activities = template.activities;
|
|
624
|
+
if (!Array.isArray(activities))
|
|
625
|
+
throw new ToolRefusalError({ status: "refused", blocker: "workflow-render-activities-invalid", message: `${tool}: activities must be an array` });
|
|
626
|
+
const codes = new Set();
|
|
627
|
+
for (const [index, raw] of activities.entries()) {
|
|
628
|
+
const activity = raw;
|
|
629
|
+
const code = String(activity?.activityCode ?? "").trim();
|
|
630
|
+
const type = String(activity?.activityType ?? "").trim();
|
|
631
|
+
if (!code)
|
|
632
|
+
throw new ToolRefusalError({ status: "refused", blocker: "workflow-render-activity-code-invalid", message: `${tool}: activities[${index}].activityCode must be non-empty` });
|
|
633
|
+
if (codes.has(code))
|
|
634
|
+
throw new ToolRefusalError({ status: "refused", blocker: "workflow-render-activity-code-duplicate", message: `${tool}: duplicate activityCode ${code}` });
|
|
635
|
+
if (!WORKFLOW_ACTIVITY_TYPES.has(type))
|
|
636
|
+
throw new ToolRefusalError({ status: "refused", blocker: "workflow-render-activity-type-invalid", message: `${tool}: activities[${index}].activityType is not an 8.6.26 ActivityType` });
|
|
637
|
+
codes.add(code);
|
|
638
|
+
}
|
|
639
|
+
const rules = template.rules;
|
|
640
|
+
if (!Array.isArray(rules))
|
|
641
|
+
throw new ToolRefusalError({ status: "refused", blocker: "workflow-render-rules-invalid", message: `${tool}: rules must be an array` });
|
|
642
|
+
for (const [index, raw] of rules.entries()) {
|
|
643
|
+
const rule = raw;
|
|
644
|
+
const pre = String(rule?.preActivityCode ?? "").trim();
|
|
645
|
+
const post = String(rule?.postActivityCode ?? "").trim();
|
|
646
|
+
if (!pre || !post || !codes.has(pre) || !codes.has(post))
|
|
647
|
+
throw new ToolRefusalError({ status: "refused", blocker: "workflow-render-dangling-rule", message: `${tool}: rules[${index}] references an unknown activity` });
|
|
648
|
+
const points = rule?.points;
|
|
649
|
+
if (!Array.isArray(points) || points.length === 0 || points.some((point) => typeof point !== "string" || !WORKFLOW_POINT.test(point)))
|
|
650
|
+
throw new ToolRefusalError({ status: "refused", blocker: "workflow-render-rules-invalid", message: `${tool}: rules[${index}].points must be a non-empty string[] of "x, y" coordinates` });
|
|
651
|
+
}
|
|
652
|
+
}
|
|
653
|
+
/** The three accepted spellings of the same edge list; refuse two non-empty ones. */
|
|
654
|
+
function pickRouteSpelling(spellings, tool) {
|
|
655
|
+
const present = Object.entries(spellings).filter(([, value]) => Array.isArray(value) && value.length > 0);
|
|
656
|
+
if (present.length > 1)
|
|
657
|
+
throw new ToolRefusalError({
|
|
658
|
+
status: "refused",
|
|
659
|
+
blocker: "workflow-routes-ambiguous",
|
|
660
|
+
spellings: present.map(([name]) => name),
|
|
661
|
+
message: `${tool}: routes/edges 与 rules 是同一条连线的三种写法(平台 DTO 字段名是 rules;recipe 写法是 routes/edges),本次同时给了 ${present.map(([name]) => name).join(" 和 ")}——只能给一种`,
|
|
662
|
+
});
|
|
663
|
+
return present.length === 1 ? present[0][1] : undefined;
|
|
664
|
+
}
|
|
665
|
+
export function completeWorkflowChain(rules, activities) {
|
|
666
|
+
const codes = activities.map((activity) => String(activity.activityCode ?? "")).filter((code) => code.length > 0);
|
|
667
|
+
if (codes.length < 2)
|
|
668
|
+
return rules;
|
|
669
|
+
const typeOf = (code) => String(activities.find((activity) => String(activity.activityCode ?? "") === code)?.activityType ?? "");
|
|
670
|
+
const codeSet = new Set(codes);
|
|
671
|
+
const inbound = new Map();
|
|
672
|
+
const outbound = new Map();
|
|
673
|
+
let valid = true;
|
|
674
|
+
for (const rule of rules) {
|
|
675
|
+
const pre = String(rule.preActivityCode ?? "");
|
|
676
|
+
const post = String(rule.postActivityCode ?? "");
|
|
677
|
+
if (!codeSet.has(pre) || !codeSet.has(post)) {
|
|
678
|
+
valid = false;
|
|
679
|
+
continue;
|
|
680
|
+
}
|
|
681
|
+
outbound.set(pre, (outbound.get(pre) ?? 0) + 1);
|
|
682
|
+
inbound.set(post, (inbound.get(post) ?? 0) + 1);
|
|
683
|
+
}
|
|
684
|
+
for (const code of codes) {
|
|
685
|
+
const type = typeOf(code);
|
|
686
|
+
if (type !== "START" && (inbound.get(code) ?? 0) < 1)
|
|
687
|
+
valid = false;
|
|
688
|
+
if (type !== "END" && (outbound.get(code) ?? 0) < 1)
|
|
689
|
+
valid = false;
|
|
690
|
+
}
|
|
691
|
+
if (valid)
|
|
692
|
+
return rules;
|
|
693
|
+
// r5-asset 2026-10-20: a node with TWO outgoing edges is a conditional
|
|
694
|
+
// branch (condition edge + utilizeElse fallback), NOT an invalid chain. The
|
|
695
|
+
// old rule demanded outbound === 1, so every branched graph fell through to
|
|
696
|
+
// the linear rebuild below — which maps consecutive activity codes and
|
|
697
|
+
// silently DROPS the else edge. Live symptom: a workflow.update that sent
|
|
698
|
+
// activities without routes erased A3→A5, every low-amount instance stalled
|
|
699
|
+
// in PROCESSING with errcode 0, and the only trace was a missing edge in
|
|
700
|
+
// get_published. Never linearize a graph that already branches.
|
|
701
|
+
//
|
|
702
|
+
// issue 2026-10-22 §1.2: a graph can also fan IN (several approval paths
|
|
703
|
+
// converging on one node). Such a graph has no node with out-degree > 1, so
|
|
704
|
+
// the out-degree-only test missed it and the linear rebuild below compressed
|
|
705
|
+
// 46 edges into 31 (r10/customer 8.6). A merge/shape check must treat BOTH
|
|
706
|
+
// directions as "not a chain": anything with a fork or a join is a graph.
|
|
707
|
+
const branched = [...outbound.values()].some((count) => count > 1) || [...inbound.values()].some((count) => count > 1);
|
|
708
|
+
if (branched)
|
|
709
|
+
return rules;
|
|
710
|
+
const byEdge = new Map(rules.map((rule) => [`${rule.preActivityCode}->${rule.postActivityCode}`, rule]));
|
|
711
|
+
return codes.slice(0, -1).map((code, index) => byEdge.get(`${code}->${codes[index + 1]}`) ?? { preActivityCode: code, postActivityCode: codes[index + 1] });
|
|
712
|
+
}
|
|
713
|
+
/**
|
|
714
|
+
* Live 2026-09-23: the platform's workflow/update CANNOT RENAME an existing
|
|
715
|
+
* activityCode — the stored name and type win. A caller list that reuses the
|
|
716
|
+
* auto-draft's `ActivityN` codes therefore corrupts: the caller's
|
|
717
|
+
* `Activity3` PARTICIPANT keeps the draft's name ("审批"), and a caller's
|
|
718
|
+
* `Activity4` PARTICIPANT merges onto the draft's END node (name "结束",
|
|
719
|
+
* type END) — reproduced on bench12/13/15, where the second approval node
|
|
720
|
+
* showed as "结束". Only a FRESH code receives the caller's name/type.
|
|
721
|
+
*
|
|
722
|
+
* Reconcile the caller list against the draft: keep a code when the caller
|
|
723
|
+
* re-sends the same type + name (idempotent re-update). A NAME change is an
|
|
724
|
+
* IN-PLACE rename — the new name rides `name_i18n` (zh/zh_TW/en) on the same
|
|
725
|
+
* code (live 2026-10-17: that is exactly what the designer's rename posts;
|
|
726
|
+
* activityName stays the first-created value server-side). Only a TYPE
|
|
727
|
+
* change still mints a collision-free fresh code. Returns the rewritten
|
|
728
|
+
* activities plus the original→final code map for route remapping.
|
|
729
|
+
*/
|
|
730
|
+
function reconcileCallerActivityCodes(callerActivities, draftActivities, options = {}) {
|
|
731
|
+
// 8.6 pins activityType on an existing code (live 2026-09-23), so a retype
|
|
732
|
+
// there needs a fresh code. AI-Platform 1.1.x does NOT pin it: a raw
|
|
733
|
+
// workflow/update that keeps the code and changes activityType returns
|
|
734
|
+
// errcode 0 and the draft reads back with the new type (live 2026-10-21,
|
|
735
|
+
// 1.1.25, END→PARTICIPANT in place). Minting `_2` there is OMC's own
|
|
736
|
+
// invention and churns every downstream reference (routes, buttons, logs),
|
|
737
|
+
// so only the pinned family mints.
|
|
738
|
+
const mintOnTypeChange = options.mintOnTypeChange !== false;
|
|
739
|
+
const draftByCode = new Map(draftActivities.map((activity) => [String(activity.activityCode ?? ""), activity]));
|
|
740
|
+
const used = new Set(draftActivities.map((activity) => String(activity.activityCode ?? "")));
|
|
741
|
+
const codeMap = new Map();
|
|
742
|
+
const activities = callerActivities.map((record) => {
|
|
743
|
+
const original = activityCodeOf(record);
|
|
744
|
+
const type = activityTypeOf(record);
|
|
745
|
+
const name = activityNameOf(record);
|
|
746
|
+
const draft = draftByCode.get(original);
|
|
747
|
+
let code = original;
|
|
748
|
+
let renameInPlace = false;
|
|
749
|
+
if (draft !== undefined) {
|
|
750
|
+
const draftType = String(draft.activityType ?? "").trim().toUpperCase() === "APPROVAL" ? "PARTICIPANT" : String(draft.activityType ?? "").trim().toUpperCase();
|
|
751
|
+
const draftName = activityNameOf(draft);
|
|
752
|
+
// Only a field the caller ACTUALLY supplied can constitute a change: a
|
|
753
|
+
// delta edit that re-sends `{activityCode, propertyPermissions}` (no
|
|
754
|
+
// type/name) inherits the draft's identity — minting `_2` codes for it
|
|
755
|
+
// churned the code on every edit (Activity3 → Activity3_2 →
|
|
756
|
+
// Activity3_2_2). An omitted type is "keep the stored one", not "changed
|
|
757
|
+
// to empty".
|
|
758
|
+
const callerHasType = record.activityType !== undefined || record.type !== undefined;
|
|
759
|
+
const typeChanged = callerHasType && draftType !== type;
|
|
760
|
+
const nameChanged = name !== undefined && draftName !== undefined && name !== draftName;
|
|
761
|
+
// Live 2026-10-17 (designer capture + raw replay, 8.6.26): a NAME change
|
|
762
|
+
// DOES land in place — the writable carrier is `name_i18n` (locale map;
|
|
763
|
+
// the designer's own rename posts exactly that and activityName stays
|
|
764
|
+
// the first-created value). Only a TYPE change still needs a fresh code
|
|
765
|
+
// (activityType is pinned for existing codes).
|
|
766
|
+
if (typeChanged && mintOnTypeChange) {
|
|
767
|
+
let suffix = 2;
|
|
768
|
+
while (used.has(`${original}_${suffix}`))
|
|
769
|
+
suffix += 1;
|
|
770
|
+
code = `${original}_${suffix}`;
|
|
771
|
+
}
|
|
772
|
+
else if (nameChanged) {
|
|
773
|
+
renameInPlace = true;
|
|
774
|
+
}
|
|
775
|
+
}
|
|
776
|
+
used.add(code);
|
|
777
|
+
codeMap.set(original, code);
|
|
778
|
+
return {
|
|
779
|
+
...record,
|
|
780
|
+
activityCode: code,
|
|
781
|
+
...(name !== undefined ? { activityName: name, i18nMessage: name } : {}),
|
|
782
|
+
...(renameInPlace ? { name_i18n: { zh: name, zh_TW: name, en: name } } : {}),
|
|
783
|
+
};
|
|
784
|
+
});
|
|
785
|
+
return { activities, codeMap };
|
|
786
|
+
}
|
|
787
|
+
/**
|
|
788
|
+
* Context-cost (round 15): a caller template that declares activities but NOT
|
|
789
|
+
* both boundaries is necessarily a partial edit — a workflow without START+END
|
|
790
|
+
* cannot stand alone on the platform (create always mints them). Treating it as
|
|
791
|
+
* a full replace dropped the draft's boundary nodes and answered a misleading
|
|
792
|
+
* `50000 服务异常` (bench43: a targeted `propertyPermissions` update on two
|
|
793
|
+
* PARTICIPANT nodes lost start/end, and the agent's recovery was to read the
|
|
794
|
+
* whole 43.7 KB body back and post it verbatim — 93 KB, 38% of the task).
|
|
795
|
+
* Route such a template through the delta merge instead, so the caller can send
|
|
796
|
+
* only the node(s) it touches. A template that DOES carry both boundaries keeps
|
|
797
|
+
* replace semantics (an explicit full-graph rewrite).
|
|
798
|
+
*/
|
|
799
|
+
export function activitiesLackBoundaries(template) {
|
|
800
|
+
const activities = callerActivities(template);
|
|
801
|
+
if (!activities || activities.length === 0)
|
|
802
|
+
return false;
|
|
803
|
+
const types = activities.map((raw) => {
|
|
804
|
+
const record = raw;
|
|
805
|
+
return record != null && typeof record === "object" ? String(record.activityType ?? record.type ?? "").trim().toUpperCase() : "";
|
|
806
|
+
});
|
|
807
|
+
return !(types.includes("START") && types.includes("END"));
|
|
808
|
+
}
|
|
809
|
+
/**
|
|
810
|
+
* Deep-merge a caller activity row onto its draft row, with `propertyPermissions`
|
|
811
|
+
* (and each entry's `subPropertyPermissions`) merged BY `propertyCode` rather
|
|
812
|
+
* than replaced. A targeted field-permission edit sends one or two permission
|
|
813
|
+
* entries; a raw array replace would silently drop every field the caller did
|
|
814
|
+
* not re-send. Only arrays deep-merge; an explicit non-array (e.g. null) is
|
|
815
|
+
* taken as the caller's intent to replace.
|
|
816
|
+
*/
|
|
817
|
+
function mergePermissionsByCode(base, caller) {
|
|
818
|
+
// 早退分支同样要过 summary 自动补全(首笔权限写入:draft 无既有 permissions 时
|
|
819
|
+
// base 不是数组,直接返回 caller 会绕过下面的补全——测试抓过这个洞)。
|
|
820
|
+
if (!Array.isArray(base) || !Array.isArray(caller)) {
|
|
821
|
+
if (!Array.isArray(caller))
|
|
822
|
+
return caller;
|
|
823
|
+
return caller.map((entry) => (entry && typeof entry === "object" && entry.summary === undefined
|
|
824
|
+
? { ...entry, summary: true }
|
|
825
|
+
: entry));
|
|
826
|
+
}
|
|
827
|
+
const byCode = new Map();
|
|
828
|
+
for (const entry of base) {
|
|
829
|
+
if (entry && typeof entry === "object") {
|
|
830
|
+
const row = entry;
|
|
831
|
+
byCode.set(String(row.propertyCode ?? ""), row);
|
|
832
|
+
}
|
|
833
|
+
}
|
|
834
|
+
for (const entry of caller) {
|
|
835
|
+
if (!entry || typeof entry !== "object")
|
|
836
|
+
continue;
|
|
837
|
+
const row = entry;
|
|
838
|
+
const key = String(row.propertyCode ?? "");
|
|
839
|
+
const prev = byCode.get(key);
|
|
840
|
+
// 用户指令(r49 后):调用方**不需要配置 summary**——平台怪癖是 summary 缺省时
|
|
841
|
+
// 权限行不进运行时 activitySummaries(editable:false 形同虚设)。工具在合并层
|
|
842
|
+
// 自动补 summary:true(显式 false 原样尊重,供刻意要默认回退的少数场景)。
|
|
843
|
+
const withSummary = row.summary === undefined ? { ...row, summary: true } : row;
|
|
844
|
+
byCode.set(key, prev
|
|
845
|
+
? {
|
|
846
|
+
...prev,
|
|
847
|
+
...withSummary,
|
|
848
|
+
...(withSummary.subPropertyPermissions !== undefined ? { subPropertyPermissions: mergePermissionsByCode(prev.subPropertyPermissions, withSummary.subPropertyPermissions) } : {}),
|
|
849
|
+
}
|
|
850
|
+
: withSummary);
|
|
851
|
+
}
|
|
852
|
+
return [...byCode.values()];
|
|
853
|
+
}
|
|
854
|
+
function deepMergeActivityRow(base, caller) {
|
|
855
|
+
const merged = { ...base, ...caller };
|
|
856
|
+
if (Array.isArray(caller.propertyPermissions))
|
|
857
|
+
merged.propertyPermissions = mergePermissionsByCode(base.propertyPermissions, caller.propertyPermissions);
|
|
858
|
+
return merged;
|
|
859
|
+
}
|
|
860
|
+
/**
|
|
861
|
+
* Live 2026-10-14 (designer-template parity): flows created/updated through
|
|
862
|
+
* the API miss three defaults the designer writes on its first save, and the
|
|
863
|
+
* node config visibly drifts in the UI:
|
|
864
|
+
*
|
|
865
|
+
* 1. the FILL node ({Originator}) carries an EMPTY buttonPermission
|
|
866
|
+
* .childTableBtns — the designer pre-checks ADD/DELETE/IMPORT/EXPORT for
|
|
867
|
+
* EVERY child-table container (BATCH_UPDATE stays disabled);
|
|
868
|
+
* 2. the fill node keeps the auto-draft showReject:true — the designer
|
|
869
|
+
* default is false (the originator cannot reject their own submission);
|
|
870
|
+
* 3. approval nodes keep rejectToStart:false — the designer default is true
|
|
871
|
+
* (reject goes back to the originator node).
|
|
872
|
+
*
|
|
873
|
+
* Backfill applies ONLY to keys the caller did not explicitly send for that
|
|
874
|
+
* node in this update, so an explicit permittedAction/buttonPermission always
|
|
875
|
+
* wins.
|
|
876
|
+
*/
|
|
877
|
+
/**
|
|
878
|
+
* Child-table fields of a schema, draft face first (the field lane's own
|
|
879
|
+
* draft-else-published semantics: after field.publish the draft face may be
|
|
880
|
+
* empty while the published face carries the row).
|
|
881
|
+
*/
|
|
882
|
+
async function childTableFieldsOf(session, schemaCode) {
|
|
883
|
+
const read = async (isPublish) => {
|
|
884
|
+
try {
|
|
885
|
+
return wireRows((await wireCall(session, { path: ENDPOINTS.fieldList, query: { schemaCode, isPublish } })).data);
|
|
886
|
+
}
|
|
887
|
+
catch {
|
|
888
|
+
return [];
|
|
889
|
+
}
|
|
890
|
+
};
|
|
891
|
+
const rows = (await read("false")).length > 0 ? await read("false") : await read("true");
|
|
892
|
+
return rows
|
|
893
|
+
.map((row) => {
|
|
894
|
+
const type = row.propertyType ?? row.type ?? 0;
|
|
895
|
+
// Live 2026-10-19: the list face carries `subSchema: null` on EVERY row,
|
|
896
|
+
// so `subSchema !== undefined` classified every scalar/relation field as
|
|
897
|
+
// a child table and refused `required` with a false reason. Only a
|
|
898
|
+
// NON-EMPTY subSchema marks a child table (plus the real type code:
|
|
899
|
+
// propertyType 8 = CHILD_TABLE / SHEET).
|
|
900
|
+
const subSchema = row.subSchema;
|
|
901
|
+
const hasSubSchema = subSchema !== undefined && subSchema !== null && String(subSchema).trim() !== "";
|
|
902
|
+
const isChild = Number(type) === 8 ||
|
|
903
|
+
String(type).toUpperCase() === "CHILD_TABLE" ||
|
|
904
|
+
String(type).toUpperCase() === "SHEET" ||
|
|
905
|
+
hasSubSchema;
|
|
906
|
+
return { code: String(row.code ?? row.propertyCode ?? ""), name: String(row.name ?? row.code ?? ""), isChild };
|
|
907
|
+
})
|
|
908
|
+
.filter((row) => row.isChild && row.code !== "");
|
|
909
|
+
}
|
|
910
|
+
const CHILD_TABLE_LIST_BUTTONS = [
|
|
911
|
+
{ code: "ADD", name: "新增", enabled: true },
|
|
912
|
+
{ code: "DELETE", name: "删除", enabled: true },
|
|
913
|
+
{ code: "IMPORT", name: "导入", enabled: true },
|
|
914
|
+
{ code: "EXPORT", name: "导出", enabled: true },
|
|
915
|
+
{ code: "BATCH_UPDATE", name: "批量编辑", enabled: false },
|
|
916
|
+
];
|
|
917
|
+
function isOriginatorFillNode(activity) {
|
|
918
|
+
return /\{originator\}/i.test(String(activity.participant ?? ""));
|
|
919
|
+
}
|
|
920
|
+
export async function backfillDesignerDefaults(session, schemaCode, body, callerTemplate) {
|
|
921
|
+
const activities = Array.isArray(body.activities) ? body.activities : [];
|
|
922
|
+
const participants = activities.filter((activity) => String(activity.activityType ?? "") === "PARTICIPANT");
|
|
923
|
+
if (participants.length === 0)
|
|
924
|
+
return;
|
|
925
|
+
// Caller rows by FINAL activityCode: keys the caller explicitly sent for a
|
|
926
|
+
// node must not be overwritten by the backfill.
|
|
927
|
+
const callerRows = new Map();
|
|
928
|
+
for (const row of (callerActivities(callerTemplate) ?? [])) {
|
|
929
|
+
const code = activityCodeOf(row);
|
|
930
|
+
if (code)
|
|
931
|
+
callerRows.set(code, row);
|
|
932
|
+
}
|
|
933
|
+
const childTables = await childTableFieldsOf(session, schemaCode);
|
|
934
|
+
for (const activity of participants) {
|
|
935
|
+
const code = String(activity.activityCode ?? "");
|
|
936
|
+
const callerRow = callerRows.get(code);
|
|
937
|
+
const fill = isOriginatorFillNode(activity);
|
|
938
|
+
// 2/3: reject-action designer defaults (fill: cannot reject self;
|
|
939
|
+
// approval: reject returns to the originator node).
|
|
940
|
+
// The auto-draft PRESENCE of these keys is not designer intent — it ships
|
|
941
|
+
// showReject:true / rejectToStart:false everywhere. Overwrite toward the
|
|
942
|
+
// designer default unless THIS update explicitly sent permittedAction for
|
|
943
|
+
// the node.
|
|
944
|
+
const action = (activity.permittedAction ?? {});
|
|
945
|
+
if (callerRow?.permittedAction === undefined) {
|
|
946
|
+
if (fill)
|
|
947
|
+
activity.permittedAction = { ...action, showReject: false, rejectToStart: false };
|
|
948
|
+
// 2026-11-02 用户实测:只补 rejectToStart 不够——showReject:false 时驳回
|
|
949
|
+
// 按钮根本不显示,驳回配置形同虚设(探针交付的多个流程中招)。审批节点的
|
|
950
|
+
// 设计器默认=两键齐备:showReject:true(可见)+ rejectToStart:true(回到开始)。
|
|
951
|
+
else
|
|
952
|
+
activity.permittedAction = { ...action, showReject: true, rejectToStart: true };
|
|
953
|
+
}
|
|
954
|
+
// 1: child-table list buttons on the fill node only (designer parity:
|
|
955
|
+
// approval nodes keep childTableBtns empty).
|
|
956
|
+
if (fill && !(callerRow?.buttonPermission !== undefined) && childTables.length > 0) {
|
|
957
|
+
const buttonPermission = (activity.buttonPermission ?? {});
|
|
958
|
+
const existing = Array.isArray(buttonPermission.childTableBtns) ? buttonPermission.childTableBtns : [];
|
|
959
|
+
if (existing.length === 0) {
|
|
960
|
+
activity.buttonPermission = {
|
|
961
|
+
...buttonPermission,
|
|
962
|
+
containerCode: buttonPermission.containerCode ?? schemaCode,
|
|
963
|
+
customBtns: buttonPermission.customBtns ?? [],
|
|
964
|
+
childTableBtns: childTables.map((table) => ({
|
|
965
|
+
containerCode: table.code,
|
|
966
|
+
containerName: table.name,
|
|
967
|
+
customBtns: CHILD_TABLE_LIST_BUTTONS.map((button) => ({
|
|
968
|
+
code: button.code,
|
|
969
|
+
name: button.name,
|
|
970
|
+
name_i18n: { zh: button.name, zh_TW: button.name, en: button.name },
|
|
971
|
+
disabled: !button.enabled,
|
|
972
|
+
type: "list",
|
|
973
|
+
enabled: button.enabled,
|
|
974
|
+
})),
|
|
975
|
+
})),
|
|
976
|
+
};
|
|
977
|
+
}
|
|
978
|
+
}
|
|
979
|
+
}
|
|
980
|
+
}
|
|
981
|
+
/**
|
|
982
|
+
* Rename pairs surfaced in the readback: a TYPE change (the only remaining
|
|
983
|
+
* mint trigger) mints `<original>_<n>` and DROPS the original code —
|
|
984
|
+
* re-sending the OLD code then reads as a brand-new node and APPENDS it,
|
|
985
|
+
* silently growing the flow. The readback names the pairs so the caller
|
|
986
|
+
* switches to the new code. (A pure NAME rename no longer mints — it rides
|
|
987
|
+
* name_i18n in place; see inPlaceRenames.)
|
|
988
|
+
*/
|
|
989
|
+
export function renamedActivityPairs(template, data) {
|
|
990
|
+
const callerCodes = new Set((callerActivities(template) ?? []).map((row) => activityCodeOf(row)).filter((code) => code !== ""));
|
|
991
|
+
const bodyCodes = new Set((Array.isArray(data.activities) ? data.activities : []).map((row) => String(row.activityCode ?? "")));
|
|
992
|
+
const pairs = [];
|
|
993
|
+
for (const code of bodyCodes) {
|
|
994
|
+
const match = /^(.+)_\d+$/.exec(code);
|
|
995
|
+
if (match && callerCodes.has(match[1]) && !bodyCodes.has(match[1]))
|
|
996
|
+
pairs.push({ from: match[1], to: code });
|
|
997
|
+
}
|
|
998
|
+
return pairs;
|
|
999
|
+
}
|
|
1000
|
+
/**
|
|
1001
|
+
* In-place renames in a readback: rows whose name_i18n (the rename carrier)
|
|
1002
|
+
* diverges from the first-created activityName. Display name =
|
|
1003
|
+
* name_i18n.zh ?? name_i18n.en ?? activityName.
|
|
1004
|
+
*/
|
|
1005
|
+
export function inPlaceRenames(data) {
|
|
1006
|
+
// The platform's draft face carries activities as an INDEX-KEYED OBJECT (the
|
|
1007
|
+
// compact projection already handles both shapes); accept either.
|
|
1008
|
+
const raw = data.activities;
|
|
1009
|
+
const rows = Array.isArray(raw)
|
|
1010
|
+
? raw
|
|
1011
|
+
: raw && typeof raw === "object"
|
|
1012
|
+
? Object.values(raw)
|
|
1013
|
+
: [];
|
|
1014
|
+
const out = [];
|
|
1015
|
+
for (const row of rows) {
|
|
1016
|
+
const i18n = row.name_i18n;
|
|
1017
|
+
const zh = i18n && typeof i18n === "object" ? String(i18n.zh ?? i18n.en ?? "") : "";
|
|
1018
|
+
const base = String(row.activityName ?? "");
|
|
1019
|
+
if (zh !== "" && zh !== base)
|
|
1020
|
+
out.push({ activityCode: String(row.activityCode ?? ""), activityName: base, displayName: zh });
|
|
1021
|
+
}
|
|
1022
|
+
return out;
|
|
1023
|
+
}
|
|
1024
|
+
/**
|
|
1025
|
+
* Live 2026-10-14: a workflow node's propertyPermissions ACCEPTS
|
|
1026
|
+
* `required:true` on a CHILD_TABLE (子表) property at the wire level, but the
|
|
1027
|
+
* designer refuses that shape — the node's field config cannot render/必填 a
|
|
1028
|
+
* sub-table control. Fail closed BEFORE the write (we never store a shape the
|
|
1029
|
+
* designer cannot represent); only CALLER-supplied rows are inspected, so an
|
|
1030
|
+
* inherited draft row never blocks an unrelated edit. The field-list read is
|
|
1031
|
+
* lazy: it fires only when the caller actually sets required somewhere.
|
|
1032
|
+
*/
|
|
1033
|
+
export async function refuseRequiredOnChildTableFields(session, schemaCode, template, tool) {
|
|
1034
|
+
const rows = (callerActivities(template) ?? []).flatMap((activity) => (Array.isArray(activity.propertyPermissions) ? activity.propertyPermissions : []));
|
|
1035
|
+
const requiredCodes = [...new Set(rows.filter((row) => row?.required === true).map((row) => String(row.propertyCode ?? "")))].filter((code) => code !== "");
|
|
1036
|
+
if (requiredCodes.length === 0)
|
|
1037
|
+
return;
|
|
1038
|
+
const childTables = await childTableFieldsOf(session, schemaCode);
|
|
1039
|
+
const hits = requiredCodes.filter((code) => childTables.some((table) => table.code === code));
|
|
1040
|
+
if (hits.length > 0)
|
|
1041
|
+
throw new ToolRefusalError({
|
|
1042
|
+
status: "refused",
|
|
1043
|
+
blocker: "workflow-child-table-not-required",
|
|
1044
|
+
schemaCode,
|
|
1045
|
+
propertyCodes: hits,
|
|
1046
|
+
message: `${tool}: 子表字段不能配置为必填(propertyPermissions.required)——接口形状接受但设计器节点字段配置不支持(子表控件无必填语义),存入后节点配置无法正常渲染。命中的子表字段:${hits.join("、")}。子表行只配置 visible/editable(summary 工具自动补);字段级必填请配到子表内部字段所在节点或改数据规则校验`,
|
|
1047
|
+
});
|
|
1048
|
+
}
|
|
1049
|
+
/**
|
|
1050
|
+
* Incremental (`merge:true`) workflow edit: the caller sends ONLY the activities/
|
|
1051
|
+
* routes it adds or changes; the draft is the base. Draft activities survive
|
|
1052
|
+
* unless overridden by `activityCode`, caller-only codes append (usually before
|
|
1053
|
+
* END via `completeWorkflowChain`), and route edges union (caller wins on the
|
|
1054
|
+
* same edge). This is the "read back, then send the delta" path — without it a
|
|
1055
|
+
* subset silently REPLACED the whole activity list and dropped nodes.
|
|
1056
|
+
*/
|
|
1057
|
+
function refusePartialBtnConfigList(activities) {
|
|
1058
|
+
// r32 实证(backlog 清算批):btnConfigList 局部行=整行替换——只传 {code, remark}
|
|
1059
|
+
// 会把 enabled 静默置 false、commentPermission 置 null(驳回意见必填丢失)。
|
|
1060
|
+
// fail-closed:按钮行不带显式 enabled 一律拒绝,指路 hazards 的整行回写法。
|
|
1061
|
+
for (const activity of activities) {
|
|
1062
|
+
const rows = activity.btnConfigList;
|
|
1063
|
+
if (!Array.isArray(rows))
|
|
1064
|
+
continue;
|
|
1065
|
+
const partial = rows.filter((row) => row !== null && typeof row === "object" && !("enabled" in row));
|
|
1066
|
+
if (partial.length > 0)
|
|
1067
|
+
throw new ToolRefusalError({
|
|
1068
|
+
status: "refused",
|
|
1069
|
+
blocker: "workflow-btnconfig-partial-row",
|
|
1070
|
+
message: `workflow.update: 节点 ${String(activity.activityCode ?? activity.id ?? "")} 的 btnConfigList 存在不带 enabled 的按钮行(${partial.map((row) => String(row.code ?? "?")).join("、")})——该平台按**整行替换**处理,缺省键会被静默重置(enabled→false、commentPermission→null)。先 workflow.get_published/get_draft 取该按钮整行,改目标属性后整条回写(见 omc help omc-write-hazards --section 按钮)。`,
|
|
1071
|
+
});
|
|
1072
|
+
}
|
|
1073
|
+
}
|
|
1074
|
+
function mergeCallerDelta(template, draft, options = {}) {
|
|
1075
|
+
const { routes: routesRaw, rules: rulesRaw, activities: _raw, edges: edgesRaw, ...rest } = template;
|
|
1076
|
+
// `routes` and `edges` are the recipe spellings; `rules` is the platform DTO
|
|
1077
|
+
// field name that `get_draft` returns and that a round-tripping caller sends
|
|
1078
|
+
// verbatim. Before this alias, `rules` rode `rest` and was then OVERWRITTEN by
|
|
1079
|
+
// `{...rest, activities, rules}` at the end — a caller that sent `rules` had
|
|
1080
|
+
// its edges silently ignored (issue 2026-10-22 §1.3②). Giving two spellings
|
|
1081
|
+
// with both non-empty is ambiguous; refuse instead of guessing. An EMPTY array
|
|
1082
|
+
// is "not given" (spreading a full template then overriding `rules` is the
|
|
1083
|
+
// documented shape).
|
|
1084
|
+
const routes = pickRouteSpelling({ routes: routesRaw, edges: edgesRaw, rules: rulesRaw }, "workflow.update");
|
|
1085
|
+
const draftActivities = Array.isArray(draft.activities) ? draft.activities : [];
|
|
1086
|
+
const draftRules = Array.isArray(draft.rules) ? draft.rules : [];
|
|
1087
|
+
const caller = (callerActivities(template) ?? []).map((raw) => {
|
|
1088
|
+
const type = activityTypeOf(raw);
|
|
1089
|
+
const name = activityNameOf(raw);
|
|
1090
|
+
return {
|
|
1091
|
+
// Drop the input aliases AND the readback-only keys (`code`/`index` come
|
|
1092
|
+
// from workflowSummary): the merge override is spread onto the draft row,
|
|
1093
|
+
// so an unstripped alias would ride the wire and make the platform answer
|
|
1094
|
+
// a misleading 401001 (same policy as mapCallerActivities).
|
|
1095
|
+
// r85: string-array bizActions = SystemActivity wire field, rides
|
|
1096
|
+
// (callerActivityWireEntries); object-shaped projection still stripped.
|
|
1097
|
+
...Object.fromEntries(callerActivityWireEntries(raw)),
|
|
1098
|
+
activityCode: activityCodeOf(raw),
|
|
1099
|
+
...(type ? { activityType: type } : {}),
|
|
1100
|
+
...(name !== undefined ? { activityName: name, i18nMessage: name } : {}),
|
|
1101
|
+
// Normalize a participant shorthand to a platform-resolvable form (the
|
|
1102
|
+
// merge path bypasses mapCallerActivities; see normalizeParticipantForWire).
|
|
1103
|
+
...(raw.participant !== undefined ? { participant: normalizeParticipantForWire(raw.participant) } : {}),
|
|
1104
|
+
};
|
|
1105
|
+
});
|
|
1106
|
+
// Live 2026-10-17 (designer traffic capture + raw replay on 8.6.26): for an
|
|
1107
|
+
// EXISTING activityCode the platform pins activityName/i18nMessage/
|
|
1108
|
+
// activityType at their first-created values — but `name_i18n` (locale map)
|
|
1109
|
+
// is writable and IS the rename carrier (the designer's rename posts exactly
|
|
1110
|
+
// that under the same code). reconcileCallerActivityCodes keeps the code for
|
|
1111
|
+
// a name change and stamps name_i18n; only a type change still mints a fresh
|
|
1112
|
+
// code and DROPS the old node (a retype, not a rename).
|
|
1113
|
+
const { activities: reconciledCaller, codeMap } = reconcileCallerActivityCodes(caller, draftActivities, options);
|
|
1114
|
+
const draftByCode = new Map(draftActivities.map((activity) => [String(activity.activityCode ?? ""), activity]));
|
|
1115
|
+
const originalOf = new Map();
|
|
1116
|
+
for (const [original, final] of codeMap)
|
|
1117
|
+
if (String(original) !== String(final))
|
|
1118
|
+
originalOf.set(String(final), String(original));
|
|
1119
|
+
// Map each caller node back to the DRAFT code it targets, so an override
|
|
1120
|
+
// (including a rename) replaces that draft row IN PLACE instead of moving
|
|
1121
|
+
// the node to the end of the chain. A renamed node inherits the old row's
|
|
1122
|
+
// subfaces (geometry, sheetCode, todoDataItems, …) — only code/name/type change.
|
|
1123
|
+
const callerByOriginal = new Map();
|
|
1124
|
+
for (const activity of reconciledCaller) {
|
|
1125
|
+
const final = String(activity.activityCode);
|
|
1126
|
+
const original = originalOf.get(final) ?? final;
|
|
1127
|
+
const base = draftByCode.get(original);
|
|
1128
|
+
callerByOriginal.set(original, base ? deepMergeActivityRow(base, activity) : activity);
|
|
1129
|
+
}
|
|
1130
|
+
const mergedActivities = draftActivities.map((activity) => {
|
|
1131
|
+
const key = String(activity.activityCode ?? "");
|
|
1132
|
+
const override = callerByOriginal.get(key);
|
|
1133
|
+
if (!override)
|
|
1134
|
+
return activity;
|
|
1135
|
+
callerByOriginal.delete(key);
|
|
1136
|
+
return { ...activity, ...override };
|
|
1137
|
+
});
|
|
1138
|
+
const newActivities = [...callerByOriginal.values()];
|
|
1139
|
+
refusePartialBtnConfigList([...mergedActivities, ...newActivities]);
|
|
1140
|
+
// A caller-only code that arrived WITHOUT a type has no draft row to inherit
|
|
1141
|
+
// from — refuse it here (the lint allows type-less edit-shape rows precisely
|
|
1142
|
+
// because they are expected to match an existing node; this list is what is
|
|
1143
|
+
// left after matching). W1: participant/btnConfigList rows get the same
|
|
1144
|
+
// exemption as permission rows, so a mistyped activityCode lands on THIS
|
|
1145
|
+
// message (not the old "must carry type" one) and gets the draft's node list.
|
|
1146
|
+
for (const activity of newActivities) {
|
|
1147
|
+
const type = activityTypeOf(activity);
|
|
1148
|
+
if (type === "") {
|
|
1149
|
+
const code = String(activity.activityCode ?? "");
|
|
1150
|
+
const candidates = draftNodeCandidateList(draftActivities);
|
|
1151
|
+
throw new ToolRefusalError({
|
|
1152
|
+
status: "refused",
|
|
1153
|
+
blocker: "workflow-activity-type-missing",
|
|
1154
|
+
activityCode: code,
|
|
1155
|
+
candidates,
|
|
1156
|
+
message: `workflow.update: 节点 ${code} 缺 type/activityType,且草稿里没有同 code 的既有节点可继承(省略类型仅当 activityCode 唯一命中草稿既有节点——participant/propertyPermissions/btnConfigList/改名等编辑行;新节点必须显式给 type)。草稿现有节点:${candidates.map((row) => `${row.activityCode}(${row.activityType})`).join("、") || "(空)"}`,
|
|
1157
|
+
});
|
|
1158
|
+
}
|
|
1159
|
+
}
|
|
1160
|
+
// Insert added nodes BEFORE the terminal END, so the auto-chain reads
|
|
1161
|
+
// START → …existing… → new → END (appending after END produced a chain that
|
|
1162
|
+
// ended on the new node instead of END).
|
|
1163
|
+
if (newActivities.length > 0) {
|
|
1164
|
+
let endIndex = mergedActivities.length;
|
|
1165
|
+
for (let index = mergedActivities.length - 1; index >= 0; index -= 1) {
|
|
1166
|
+
if (String(mergedActivities[index]?.activityType ?? "") === "END") {
|
|
1167
|
+
endIndex = index;
|
|
1168
|
+
break;
|
|
1169
|
+
}
|
|
1170
|
+
}
|
|
1171
|
+
mergedActivities.splice(endIndex, 0, ...newActivities);
|
|
1172
|
+
}
|
|
1173
|
+
const remapCode = (value) => codeMap.get(String(value ?? "")) ?? value;
|
|
1174
|
+
// Both draft edges and caller edges follow a renamed node; the caller may use
|
|
1175
|
+
// any endpoint spelling, so remap every alias.
|
|
1176
|
+
const remapRuleEndpoints = (rule) => {
|
|
1177
|
+
const mapped = { ...rule };
|
|
1178
|
+
for (const key of ["preActivityCode", "preNode", "pre", "from"])
|
|
1179
|
+
if (rule[key] !== undefined)
|
|
1180
|
+
mapped[key] = remapCode(rule[key]);
|
|
1181
|
+
for (const key of ["postActivityCode", "postNode", "post", "to"])
|
|
1182
|
+
if (rule[key] !== undefined)
|
|
1183
|
+
mapped[key] = remapCode(rule[key]);
|
|
1184
|
+
// Stored drafts on 8.x carry `ruleConditionGroup: []` for a plain edge.
|
|
1185
|
+
// Never echo that empty shape back onto the wire (see the validator note).
|
|
1186
|
+
if (Array.isArray(mapped.ruleConditionGroup) && mapped.ruleConditionGroup.length === 0)
|
|
1187
|
+
delete mapped.ruleConditionGroup;
|
|
1188
|
+
return mapped;
|
|
1189
|
+
};
|
|
1190
|
+
const edgeKey = (rule) => `${rule.preActivityCode ?? rule.preNode ?? rule.pre ?? rule.from}->${rule.postActivityCode ?? rule.postNode ?? rule.post ?? rule.to}`;
|
|
1191
|
+
const remappedDraftRules = draftRules.map(remapRuleEndpoints);
|
|
1192
|
+
const callerGaveRoutes = Array.isArray(routes);
|
|
1193
|
+
const mappedCallerRoutes = callerGaveRoutes ? mapCallerRules(routes.map((entry) => remapRuleEndpoints((entry ?? {}))), remappedDraftRules, mergedActivities) : [];
|
|
1194
|
+
const byEdge = new Map();
|
|
1195
|
+
for (const rule of remappedDraftRules)
|
|
1196
|
+
byEdge.set(edgeKey(rule), rule);
|
|
1197
|
+
for (const rule of mappedCallerRoutes)
|
|
1198
|
+
byEdge.set(edgeKey(rule), { ...(byEdge.get(edgeKey(rule)) ?? {}), ...rule });
|
|
1199
|
+
const unionRules = [...byEdge.values()];
|
|
1200
|
+
// A delta that neither sends routes nor adds a node is an edit of EXISTING
|
|
1201
|
+
// rows — the draft's graph is already the platform's own, so it must ride the
|
|
1202
|
+
// wire verbatim. Running the chain rebuild here is what destroyed the 46-edge
|
|
1203
|
+
// graph (issue 2026-10-22 §1.2: a converging graph failed the chain test and
|
|
1204
|
+
// was replaced by a 31-edge linear chain). Chain completion only makes sense
|
|
1205
|
+
// when the caller actually declares new topology.
|
|
1206
|
+
const needsChainCompletion = callerGaveRoutes || newActivities.length > 0;
|
|
1207
|
+
// Verbatim path: no caller topology and no new node. Return the draft edges
|
|
1208
|
+
// themselves — NOT the by-edge map, which keys on `pre->post` and would
|
|
1209
|
+
// collapse two conditional lines drawn between the same pair of nodes.
|
|
1210
|
+
const mergedRules = needsChainCompletion ? completeWorkflowChain(unionRules, mergedActivities) : remappedDraftRules;
|
|
1211
|
+
// Fail closed on topology CONTRACTION. Merge is a union — it can add edges but
|
|
1212
|
+
// never delete one — so fewer edges than the draft means a rebuild went wrong
|
|
1213
|
+
// (the r10/customer 46→31 incident). Refuse BEFORE the wire and name exactly
|
|
1214
|
+
// which draft edges would disappear, so the caller can re-send routes
|
|
1215
|
+
// explicitly instead of losing them silently.
|
|
1216
|
+
if (mergedRules.length < remappedDraftRules.length) {
|
|
1217
|
+
const kept = new Set(mergedRules.map((rule) => edgeKey(rule)));
|
|
1218
|
+
const dropped = remappedDraftRules.map((rule) => edgeKey(rule)).filter((key) => !kept.has(key));
|
|
1219
|
+
throw new ToolRefusalError({
|
|
1220
|
+
status: "refused",
|
|
1221
|
+
blocker: "workflow-merge-would-drop-routes",
|
|
1222
|
+
workflowCode: String(draft.workflowCode ?? ""),
|
|
1223
|
+
routesBefore: remappedDraftRules.length,
|
|
1224
|
+
routesAfter: mergedRules.length,
|
|
1225
|
+
droppedRoutes: dropped.slice(0, 40),
|
|
1226
|
+
message: `workflow.update merge 会把草稿的连线从 ${remappedDraftRules.length} 条压到 ${mergedRules.length} 条(merge 只会并集、不会删边,减少即工具重算失控)。${dropped.length > 0 ? `缺失连线:${dropped.slice(0, 12).join("、")}${dropped.length > 12 ? `…等 ${dropped.length} 条` : ""}。` : "(多落在同一节点对的多条条件线上,被按节点对合并了。)"}已拒绝写入,草稿未变。改法:要么把要保留的连线随 routes 一起显式发(平台 DTO 名 rules),要么用 merge:false 整模板替换`,
|
|
1227
|
+
});
|
|
1228
|
+
}
|
|
1229
|
+
// Same layout + points derivation as the replace path: a chain-completion edge
|
|
1230
|
+
// synthesized above carries no points, and the designer canvas needs them.
|
|
1231
|
+
const laidOut = canonicalizeWorkflowLayout(mergedActivities, mergedRules);
|
|
1232
|
+
const rules = mergedRules.map((rule) => {
|
|
1233
|
+
const absent = rule.points === undefined || rule.points === null;
|
|
1234
|
+
return laidOut.changed || absent
|
|
1235
|
+
? { ...rule, points: deriveRulePoints(String(rule.preActivityCode ?? ""), String(rule.postActivityCode ?? ""), laidOut.activities) }
|
|
1236
|
+
: rule;
|
|
1237
|
+
});
|
|
1238
|
+
return { ...rest, activities: laidOut.activities, rules };
|
|
1239
|
+
}
|
|
1240
|
+
function normalizeWorkflowTemplate(template, draft, options = {}) {
|
|
1241
|
+
if (template === undefined || template === null)
|
|
1242
|
+
return {};
|
|
1243
|
+
const { routes: routesRaw, activities: rawActivities, edges: edgesRaw, ...rest } = template;
|
|
1244
|
+
const routes = pickRouteSpelling({ routes: routesRaw, edges: edgesRaw, rules: rest.rules }, "workflow.update/publish");
|
|
1245
|
+
if (routes !== undefined)
|
|
1246
|
+
delete rest.rules;
|
|
1247
|
+
void rawActivities;
|
|
1248
|
+
// Array OR index-keyed object; `rest` must not carry the raw form or an
|
|
1249
|
+
// object-shaped activities would ride the wire unmerged.
|
|
1250
|
+
const rawCaller = callerActivities(template);
|
|
1251
|
+
const draftActivities = Array.isArray(draft.activities) ? draft.activities : [];
|
|
1252
|
+
const draftRules = Array.isArray(draft.rules) ? draft.rules : [];
|
|
1253
|
+
// The platform cannot rename an existing activityCode (see the reconcile
|
|
1254
|
+
// comment); give every changed/new node a fresh code, and remap caller routes
|
|
1255
|
+
// so they follow.
|
|
1256
|
+
const reconciled = rawCaller ? reconcileCallerActivityCodes(rawCaller, draftActivities, options) : undefined;
|
|
1257
|
+
if (rawCaller !== undefined)
|
|
1258
|
+
refusePartialBtnConfigList(rawCaller);
|
|
1259
|
+
const activities = reconciled?.activities;
|
|
1260
|
+
const codeMap = reconciled?.codeMap ?? new Map();
|
|
1261
|
+
const remapCode = (value) => codeMap.get(String(value ?? "")) ?? value;
|
|
1262
|
+
const remappedRoutes = Array.isArray(routes)
|
|
1263
|
+
? routes.map((entry) => {
|
|
1264
|
+
const record = (entry ?? {});
|
|
1265
|
+
return {
|
|
1266
|
+
...record,
|
|
1267
|
+
...(record.preNode !== undefined ? { preNode: remapCode(record.preNode) } : {}),
|
|
1268
|
+
...(record.postNode !== undefined ? { postNode: remapCode(record.postNode) } : {}),
|
|
1269
|
+
...(record.pre !== undefined ? { pre: remapCode(record.pre) } : {}),
|
|
1270
|
+
...(record.post !== undefined ? { post: remapCode(record.post) } : {}),
|
|
1271
|
+
};
|
|
1272
|
+
})
|
|
1273
|
+
: routes;
|
|
1274
|
+
const normalized = { ...rest };
|
|
1275
|
+
if (activities)
|
|
1276
|
+
normalized.activities = mapCallerActivities(activities, draftActivities);
|
|
1277
|
+
if (Array.isArray(remappedRoutes)) {
|
|
1278
|
+
const mapped = mapCallerRules(remappedRoutes, draftRules, normalized.activities ?? draftActivities);
|
|
1279
|
+
normalized.rules = Array.isArray(rest.rules) ? [...rest.rules, ...mapped] : mapped;
|
|
1280
|
+
}
|
|
1281
|
+
if (Array.isArray(rest.rules) && !Array.isArray(remappedRoutes))
|
|
1282
|
+
normalized.rules = mapCallerRules(rest.rules, draftRules, normalized.activities ?? draftActivities);
|
|
1283
|
+
if (activities && !Array.isArray(remappedRoutes) && !Array.isArray(rest.rules)) {
|
|
1284
|
+
const mappedActivities = normalized.activities;
|
|
1285
|
+
const remapped = draftRules.map((rule) => {
|
|
1286
|
+
const preIndex = draftActivities.findIndex((activity) => String(activity.activityCode ?? "") === String(rule.preActivityCode ?? ""));
|
|
1287
|
+
const postIndex = draftActivities.findIndex((activity) => String(activity.activityCode ?? "") === String(rule.postActivityCode ?? ""));
|
|
1288
|
+
const pre = mappedActivities[preIndex]?.activityCode ?? rule.preActivityCode;
|
|
1289
|
+
const post = mappedActivities[postIndex]?.activityCode ?? rule.postActivityCode;
|
|
1290
|
+
return { ...rule, preActivityCode: pre, postActivityCode: post };
|
|
1291
|
+
});
|
|
1292
|
+
normalized.rules = completeWorkflowChain(remapped, mappedActivities);
|
|
1293
|
+
}
|
|
1294
|
+
// Live 2026-09-17: merged activities may collide (two PARTICIPANT nodes both
|
|
1295
|
+
// inheriting the draft PARTICIPANT's box) — lay the chain out canonically,
|
|
1296
|
+
// then re-derive every rule's points from the final geometry so the designer
|
|
1297
|
+
// lines follow the boxes instead of drawing a horizontal stub.
|
|
1298
|
+
if (Array.isArray(normalized.activities)) {
|
|
1299
|
+
const laidOut = canonicalizeWorkflowLayout(normalized.activities, Array.isArray(normalized.rules) ? normalized.rules : []);
|
|
1300
|
+
normalized.activities = laidOut.activities;
|
|
1301
|
+
// Caller-authored points on an already-renderable layout stay verbatim;
|
|
1302
|
+
// points are re-derived when the geometry was repaired — or when a rule
|
|
1303
|
+
// carries none at all (a chain-completion edge synthesized above). A
|
|
1304
|
+
// provided-but-malformed points value is left for validateWorkflowRender to
|
|
1305
|
+
// refuse (never silently repaired).
|
|
1306
|
+
if (Array.isArray(normalized.rules))
|
|
1307
|
+
normalized.rules = normalized.rules.map((rule) => {
|
|
1308
|
+
const absent = rule.points === undefined || rule.points === null;
|
|
1309
|
+
return laidOut.changed || absent
|
|
1310
|
+
? { ...rule, points: deriveRulePoints(String(rule.preActivityCode ?? ""), String(rule.postActivityCode ?? ""), laidOut.activities) }
|
|
1311
|
+
: rule;
|
|
1312
|
+
});
|
|
1313
|
+
}
|
|
1314
|
+
return normalized;
|
|
1315
|
+
}
|
|
1316
|
+
/**
|
|
1317
|
+
* Ticket 112 — merge the caller template onto the FULL get_draft row before
|
|
1318
|
+
* the update/publish wire. The platform save is a full-row write; posting a
|
|
1319
|
+
* minimal template leaves converter-swallowed holes and answers errcode
|
|
1320
|
+
* 50000 (live incident). Caller keys override; everything else echoes the
|
|
1321
|
+
* draft verbatim (the same merge pattern workflow.bindRule uses).
|
|
1322
|
+
*/
|
|
1323
|
+
export async function mergedTemplateBody(session, schemaCode, code, template, merge = false) {
|
|
1324
|
+
const draft = await getWorkflowDraftOrNull(session, code);
|
|
1325
|
+
if (draft == null)
|
|
1326
|
+
throw new ToolRefusalError({
|
|
1327
|
+
status: "refused",
|
|
1328
|
+
blocker: "workflow-not-found",
|
|
1329
|
+
workflowCode: code,
|
|
1330
|
+
message: `流程 ${code} 不存在(get_draft 401001 缺席)——先 workflow.create 再 update/publish`,
|
|
1331
|
+
});
|
|
1332
|
+
// Type changes are only pinned on the 8.x family (see reconcileCallerActivityCodes).
|
|
1333
|
+
// Unknown versions keep the conservative 8.x behaviour (mint) — writes fail
|
|
1334
|
+
// closed elsewhere, and a spurious `_2` is recoverable while a silent
|
|
1335
|
+
// in-place retype on a pinned platform is not.
|
|
1336
|
+
const version = session.detectedVersion();
|
|
1337
|
+
const mintOnTypeChange = !(version !== undefined && version.startsWith("1."));
|
|
1338
|
+
const normalized = merge ? mergeCallerDelta(template, draft, { mintOnTypeChange }) : normalizeWorkflowTemplate(template, draft, { mintOnTypeChange });
|
|
1339
|
+
// S29 contract: a PARTICIPANT activity requires sheetCode = the schema's
|
|
1340
|
+
// sheet, else validate/publish answers 401026 WORKFLOW_ACTIVITY_NO_SHEET. The
|
|
1341
|
+
// platform's own draft sets each participant's sheetCode to the model code;
|
|
1342
|
+
// an activity the caller ADDED has no draft row to inherit it from, so
|
|
1343
|
+
// backfill it (the default-form slot is the model code — same rule as
|
|
1344
|
+
// configure_form's omitted sheetCode).
|
|
1345
|
+
if (Array.isArray(normalized.activities))
|
|
1346
|
+
normalized.activities = normalized.activities.map((activity) => String(activity.activityType ?? "") === "PARTICIPANT" && (activity.sheetCode === undefined || activity.sheetCode === null || activity.sheetCode === "")
|
|
1347
|
+
? { ...activity, sheetCode: schemaCode }
|
|
1348
|
+
: activity);
|
|
1349
|
+
return { ...draft, ...normalized, schemaCode, workflowCode: code };
|
|
1350
|
+
}
|
|
1351
|
+
//# sourceMappingURL=template-merge.js.map
|