@stalfh233/omc-cli 0.8.32 → 0.8.34

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.
Files changed (52) hide show
  1. package/dist/arg-vocabulary.js +223 -0
  2. package/dist/artifact-cmd.js +443 -0
  3. package/dist/batch-call.js +56 -3
  4. package/dist/call-command.js +70 -0
  5. package/dist/call-execute.js +228 -0
  6. package/dist/call-input.js +557 -0
  7. package/dist/call-output.js +240 -0
  8. package/dist/cli.js +13 -1359
  9. package/dist/command-transport.js +4 -1
  10. package/dist/form-support.js +14 -3
  11. package/dist/intent/plan-apply.js +14 -24
  12. package/dist/lanes/datarule.js +21 -0
  13. package/dist/lanes/field-contract.js +1 -1
  14. package/dist/lanes/field.js +128 -1
  15. package/dist/lanes/list-view-shapes.js +8 -1
  16. package/dist/lanes/list-view.js +64 -2
  17. package/dist/lanes/runtime-data/aggregate-support.js +209 -0
  18. package/dist/lanes/runtime-data/aggregate.js +679 -0
  19. package/dist/lanes/runtime-data/field-options.js +52 -0
  20. package/dist/lanes/runtime-data/lane.js +4 -0
  21. package/dist/lanes/runtime-data/record-delete.js +419 -0
  22. package/dist/lanes/runtime-data/record-read.js +984 -0
  23. package/dist/lanes/runtime-data/record-write.js +562 -0
  24. package/dist/lanes/runtime-data/registration.js +22 -0
  25. package/dist/lanes/runtime-data/shapes.js +594 -0
  26. package/dist/lanes/runtime-data/submission.js +1304 -0
  27. package/dist/lanes/runtime-data/write-support.js +875 -0
  28. package/dist/lanes/runtime-data.js +10 -5590
  29. package/dist/lanes/workflow/approval-ops.js +983 -0
  30. package/dist/lanes/workflow/instance-read.js +284 -0
  31. package/dist/lanes/workflow/lifecycle-write.js +1499 -0
  32. package/dist/lanes/workflow/permissions.js +571 -0
  33. package/dist/lanes/workflow/recovery.js +361 -0
  34. package/dist/lanes/workflow/registration.js +14 -0
  35. package/dist/lanes/workflow/shapes.js +811 -0
  36. package/dist/lanes/workflow/template-fetch.js +197 -0
  37. package/dist/lanes/workflow/template-merge.js +1351 -0
  38. package/dist/lanes/workflow/template-read.js +327 -0
  39. package/dist/lanes/workflow.js +11 -6312
  40. package/dist/model-scaffold.js +6 -2
  41. package/dist/plan.js +23 -1
  42. package/dist/read-projection.js +442 -0
  43. package/dist/read.js +40 -335
  44. package/dist/rollback.js +17 -23
  45. package/dist/runtime-support.js +1 -1
  46. package/dist/verification.js +39 -0
  47. package/dist/write-coordinator.js +152 -0
  48. package/dist/write-outcome.js +295 -0
  49. package/dist/write.js +34 -115
  50. package/package.json +3 -3
  51. package/skills/omc-refusals.md +1 -1
  52. package/skills/omc-start-here.md +2 -2
@@ -0,0 +1,811 @@
1
+ import { ToolRefusalError } from "../../tool-types.js";
2
+ import { WORKFLOW_EVENT_HANDLER_FIELDS, WORKFLOW_NODE_EVENT_HANDLER_FIELDS, WORKFLOW_LANE_CONTRACT } from "../workflow-contract.js";
3
+ export const WORKFLOW_LANE = WORKFLOW_LANE_CONTRACT.lane;
4
+ export const WORKFLOW_TOOLS = WORKFLOW_LANE_CONTRACT.tools;
5
+ export const WORKFLOW_ACTIVITY_TYPES = new Set(["START", "END", "CONNECTION", "PARTICIPANT", "SUB_INSTANCE", "CIRCULATE", "SYSTEM_ACTIVITY", "AGENT_ACTIVITY"]);
6
+ export const WORKFLOW_POINT = /^-?\d+(?:\.\d+)?,\s-?\d+(?:\.\d+)?$/;
7
+ /** workflow.list 的模型枚举上限:超出截断(partial + omittedModels + 点查指引)。 */
8
+ export const WORKFLOW_LIST_MODEL_CAP = 50;
9
+ /** Keep workitem.list's external envelope aligned with data.list. */
10
+ export function workItemListCompactProjection(result) {
11
+ const compact = {};
12
+ for (const [key, value] of Object.entries(result)) {
13
+ if (key !== "items" || !Array.isArray(value)) {
14
+ if (key !== "ids" && key !== "itemsPreview" && key !== "listArtifactHint")
15
+ compact[key] = value;
16
+ continue;
17
+ }
18
+ const rows = value;
19
+ const ids = rows.map((row) => row.workItemId).filter((id) => typeof id === "string" && id.length > 0);
20
+ compact.itemsCount = rows.length;
21
+ compact.ids = ids;
22
+ compact.itemsPreview = ids.slice(0, 3).map((id) => ({ id }));
23
+ compact.listArtifactHint = "items 已外置(truncatedKeys/omittedKeys 含 items):完整待办见 artifact;ids=本页全部 workItemId,itemsPreview=前 3 个 id 引用。";
24
+ }
25
+ return compact;
26
+ }
27
+ /**
28
+ * Conditional branch lines (round7). `routes[]` maps to the platform `Rule`
29
+ * DTO (Rule.java:28-59), which carries a structured branch condition
30
+ * `ruleConditionGroup = List<List<RuleConditionItem>>` (outer OR / inner AND).
31
+ * ActivityContext.getNextFormulaActivities:82-99 only consults it when
32
+ * popupType == EXPRESSION; a rule with utilizeElse=true is the else/fallback
33
+ * line and is never a condition line. These enums mirror ConditionType.java and
34
+ * MatchType.java (shared 8.6.26); a typo silently no-ops on the platform, so the
35
+ * write gate refuses it instead.
36
+ */
37
+ export const WORKFLOW_CONDITION_TYPES = new Set(["EQ", "NEQ", "GT", "LT", "GTEQ", "LTEQ", "CT", "NCT", "EP", "NEP", "OF", "NOF", "BETWEEN", "NOTBETWEEN", "CT_ALL", "NCT_ALL", "CT_ANY", "NCT_ANY", "EQ_ANY", "NEQ_ANY"]);
38
+ export const WORKFLOW_MATCH_TYPES = new Set(["ALL", "ANY"]);
39
+ /**
40
+ * `RuleConditionItem` (RuleConditionItem.java, shared 8.6.26) has EXACTLY four
41
+ * fields: currentDataItem, bizPropertyType, conditionType, value. Any extra key
42
+ * makes the platform's workflow/update deserialization fail and answer a
43
+ * **misleading `401001 流程不存在!`** — not a key error (live 2026-09-25: adding
44
+ * the business-rule condition keys targetDataItem/ruleValueType to a workflow
45
+ * route condition poisoned the whole update). Fail closed on unknown keys before
46
+ * the wire so the agent gets the real fix instead of chasing a phantom workflow.
47
+ */
48
+ export const WORKFLOW_RULE_CONDITION_ITEM_KEYS = new Set(["currentDataItem", "bizPropertyType", "conditionType", "value"]);
49
+ /**
50
+ * RuleConditionItem.bizPropertyType is a BizPropertyType whose fastjson
51
+ * deserializer (BizPropertyTypeDeserializer.deserialze) reads an INT index
52
+ * (`BizPropertyType.get(TypeUtils.castToInt(value))`) and whose serializer writes
53
+ * the same index. Sending the enum NAME ("NUMERICAL") makes castToInt coerce it
54
+ * to 0 (the wrong type) and the template conversion then fails with a MISLEADING
55
+ * `流程名称为空!` (live 101.96.203.196 / AI-Platform 1.1.22 — cost the sandbox
56
+ * agent the whole workflow write). Accept the name for ergonomics but emit the
57
+ * index on the wire.
58
+ */
59
+ const WORKFLOW_BIZ_PROPERTY_TYPE_INDEX = Object.freeze({
60
+ SHORT_TEXT: 0, LONG_TEXT: 1, NUMERICAL: 2, DATE: 3, LOGICAL: 4, SELECTION: 5,
61
+ ATTACHMENT: 6, COMMENT: 7, CHILD_TABLE: 8, WORK_SHEET: 9, ADDRESS: 10, MULT_WORK_SHEET: 11,
62
+ RADIO: 12, CHECKBOX: 13, DROPDOWN_BOX: 14, DROPDOWN_MULTI_BOX: 15, RELEVANCE_DATA: 16,
63
+ HYPER_LINK: 17, ID: 20, TIME: 28, STAFF_SELECTOR: 50, STAFF_MULTI_SELECTOR: 51,
64
+ DEPARTMENT_SELECTOR: 60, DEPARTMENT_MULTI_SELECTOR: 61, FORMULA: 100, OCR: 250,
65
+ ELECTRONIC_SIGN: 251, APPROVAL_INFO: 254,
66
+ });
67
+ const WORKFLOW_BIZ_PROPERTY_INDEX_SET = new Set(Object.values(WORKFLOW_BIZ_PROPERTY_TYPE_INDEX));
68
+ /** Resolve a caller-supplied bizPropertyType (index or enum name) to the wire index, or null if invalid. */
69
+ export function resolveBizPropertyTypeIndex(value) {
70
+ if (typeof value === "number" && Number.isInteger(value))
71
+ return WORKFLOW_BIZ_PROPERTY_INDEX_SET.has(value) ? value : null;
72
+ if (typeof value === "string")
73
+ return WORKFLOW_BIZ_PROPERTY_TYPE_INDEX[value.trim().toUpperCase()] ?? null;
74
+ return null;
75
+ }
76
+ /** Rewrite each RuleConditionItem.bizPropertyType to the numeric index the platform deserializes. */
77
+ export function normalizeRuleConditionGroup(groups) {
78
+ if (!Array.isArray(groups))
79
+ return groups;
80
+ return groups.map((group) => Array.isArray(group)
81
+ ? group.map((item) => {
82
+ const record = (item ?? {});
83
+ const index = resolveBizPropertyTypeIndex(record.bizPropertyType);
84
+ return index === null ? record : { ...record, bizPropertyType: index };
85
+ })
86
+ : group);
87
+ }
88
+ /** Route fields that describe the line's condition/behaviour (as opposed to geometry). */
89
+ const WORKFLOW_ROUTE_CONDITION_KEYS = ["text", "formula", "utilizeElse", "fixedPoint", "alternativeFlag", "childMatchType", "ruleConditionGroup"];
90
+ /**
91
+ * Fail closed on an unknown bindRule handler BEFORE any wire call. The MCP
92
+ * transport validates the zod schema, but `omc call` (the first-class live
93
+ * driver) invokes the handler directly, so the semantic gate lives here.
94
+ */
95
+ function resolveEventHandlerField(handler) {
96
+ const key = handler ?? "end";
97
+ const field = WORKFLOW_EVENT_HANDLER_FIELDS[key];
98
+ if (!field) {
99
+ throw new ToolRefusalError({
100
+ status: "refused",
101
+ blocker: "workflow-invalid-handler",
102
+ handler,
103
+ message: `handler must be one of ${Object.keys(WORKFLOW_EVENT_HANDLER_FIELDS).join("|")} (omit for end). 节点级事件不用 handler:改传 activityCode + nodeEvent(${Object.keys(WORKFLOW_NODE_EVENT_HANDLER_FIELDS).join("|")})`,
104
+ });
105
+ }
106
+ return { key: key, field };
107
+ }
108
+ export function resolveBindTarget(handler, nodeEvent, activityCode) {
109
+ const hasNode = nodeEvent !== undefined && nodeEvent !== null;
110
+ const hasActivity = activityCode !== undefined && activityCode !== null && String(activityCode).trim() !== "";
111
+ if (hasNode !== hasActivity) {
112
+ throw new ToolRefusalError({
113
+ status: "refused",
114
+ blocker: "workflow-invalid-handler",
115
+ message: hasNode
116
+ ? `nodeEvent=${String(nodeEvent)} 必须同时给 activityCode(节点级事件写在具体活动上)`
117
+ : `activityCode=${String(activityCode)} 必须同时给 nodeEvent(${Object.keys(WORKFLOW_NODE_EVENT_HANDLER_FIELDS).join("|")});只给 activityCode 不知道要绑该节点的哪个事件`,
118
+ });
119
+ }
120
+ if (hasNode && hasActivity) {
121
+ if (handler !== undefined && handler !== null)
122
+ throw new ToolRefusalError({
123
+ status: "refused",
124
+ blocker: "workflow-invalid-handler",
125
+ message: "handler(流程级)与 activityCode+nodeEvent(节点级)互斥:请只用一种形式",
126
+ });
127
+ const key = String(nodeEvent);
128
+ const field = WORKFLOW_NODE_EVENT_HANDLER_FIELDS[key];
129
+ if (!field)
130
+ throw new ToolRefusalError({
131
+ status: "refused",
132
+ blocker: "workflow-invalid-handler",
133
+ nodeEvent,
134
+ message: `nodeEvent must be one of ${Object.keys(WORKFLOW_NODE_EVENT_HANDLER_FIELDS).join("|")}`,
135
+ });
136
+ return { scope: "activity", key, activityCode: String(activityCode), field };
137
+ }
138
+ const resolved = resolveEventHandlerField(handler);
139
+ return { scope: "workflow", ...resolved };
140
+ }
141
+ /**
142
+ * Activity rows on a workflow template arrive EITHER as an array OR as an
143
+ * index-keyed object (the shape `workflow.get_draft` returns on 1.1.25). Node-
144
+ * level handler edits must preserve whichever shape the draft uses — rebinding a
145
+ * rule must not restructure the caller's stored template.
146
+ */
147
+ export function findTemplateActivity(template, activityCode) {
148
+ const raw = template?.activities;
149
+ if (Array.isArray(raw))
150
+ return raw.find((row) => String(row?.activityCode ?? "") === activityCode);
151
+ if (raw && typeof raw === "object")
152
+ return Object.values(raw).find((row) => String(row?.activityCode ?? "") === activityCode);
153
+ return undefined;
154
+ }
155
+ export function mapTemplateActivity(template, activityCode, update) {
156
+ const raw = template.activities;
157
+ if (Array.isArray(raw)) {
158
+ let found = false;
159
+ const activities = raw.map((entry) => {
160
+ const row = (entry ?? {});
161
+ if (String(row.activityCode ?? "") !== activityCode)
162
+ return entry;
163
+ found = true;
164
+ return update(row);
165
+ });
166
+ return { found, template: found ? { ...template, activities } : template };
167
+ }
168
+ if (raw && typeof raw === "object") {
169
+ const rows = raw;
170
+ const key = Object.keys(rows).find((name) => String((rows[name] ?? {}).activityCode ?? "") === activityCode);
171
+ if (key === undefined)
172
+ return { found: false, template };
173
+ return { found: true, template: { ...template, activities: { ...rows, [key]: update((rows[key] ?? {})) } } };
174
+ }
175
+ return { found: false, template };
176
+ }
177
+ export function templateActivityCodes(template) {
178
+ const raw = template?.activities;
179
+ const rows = Array.isArray(raw) ? raw : raw && typeof raw === "object" ? Object.values(raw) : [];
180
+ return rows.map((row) => String(row?.activityCode ?? "")).filter((code) => code !== "");
181
+ }
182
+ /**
183
+ * W1(2.1.5 真机 2026-11-25 契约不一致):既有节点的编辑行可以只给 activityCode
184
+ * ——类型在合并时从草稿同 code 节点补齐,调用方不必重复声明。
185
+ *
186
+ * 证据(前后端双侧):
187
+ * - 平台上送的**整行**必须有 activityType:`WorkflowTemplateUtil.convertActivity`
188
+ * 对每个活动做 `ActivityType.valueOf(activity.get("activityType"))`
189
+ * (2.1.5 launcher: :216-256 / 8.6.26: :249),缺类型抛异常被
190
+ * `convertWorkflowTemplateJsonToModel` 的 catch 吞成残缺模型(2.1.5 :135-140)
191
+ * → 保存链 50000。平台看到的是 OMC 合并后的草稿整行,不是调用方 delta。
192
+ * - 前端模板模型 `ActivitySchema.activityType: string` 是必填
193
+ * (frontend-src/frontend/packages/admin/src/typings/workflow.ts:26-28),
194
+ * 设计器从不发无类型节点 —— 「省 type」是 OMC 的合并能力,不是平台接受的形状,
195
+ * 所以只在草稿里**唯一**命中同 code 节点时成立(见
196
+ * uniqueDraftRowForTypelessEdit)。
197
+ *
198
+ * 编辑行判据是**形状**:这些键只可能是既有节点的子面(权限/改名/参与人/按钮),
199
+ * 新节点不会带。原先漏了 participant(0.8.1 真机:只给
200
+ * `{activityCode, participant}` 被本地拒),这里补齐。
201
+ */
202
+ const EXISTING_NODE_EDIT_KEYS = [
203
+ "propertyPermissions",
204
+ "subPropertyPermissions",
205
+ "activityName",
206
+ "name",
207
+ "i18nMessage",
208
+ "permittedAction",
209
+ "buttonPermission",
210
+ "btnConfigList",
211
+ "participant",
212
+ ];
213
+ export function editsExistingNodeShape(record) {
214
+ return EXISTING_NODE_EDIT_KEYS.some((key) => record[key] !== undefined);
215
+ }
216
+ /**
217
+ * Resolve the draft row a type-less caller edit inherits its activityType from.
218
+ * Only a UNIQUE same-code draft node qualifies: a miss means the caller is
219
+ * creating a new node (type is its identity — must be explicit), and duplicate
220
+ * codes cannot be resolved to one type. Both refuse BEFORE the wire with the
221
+ * draft's node list, because the platform swallows a typeless element into a
222
+ * partial model (50000).
223
+ */
224
+ export function draftNodeCandidateList(draftActivities) {
225
+ return draftActivities
226
+ .map((activity) => ({ activityCode: String(activity.activityCode ?? ""), activityType: String(activity.activityType ?? "") }))
227
+ .filter((row) => row.activityCode !== "")
228
+ .slice(0, 40);
229
+ }
230
+ export function uniqueDraftRowForTypelessEdit(tool, code, draftActivities) {
231
+ const matches = draftActivities.filter((activity) => String(activity.activityCode ?? "") === code);
232
+ if (matches.length === 1)
233
+ return matches[0];
234
+ const candidates = draftNodeCandidateList(draftActivities);
235
+ const listed = candidates.map((row) => `${row.activityCode}(${row.activityType})`).join("、");
236
+ throw new ToolRefusalError({
237
+ status: "refused",
238
+ blocker: "workflow-activity-type-missing",
239
+ activityCode: code,
240
+ ...(matches.length > 1 ? { ambiguousMatches: matches.length } : {}),
241
+ candidates,
242
+ message: matches.length > 1
243
+ ? `${tool}: 节点 ${code} 在草稿里命中 ${matches.length} 个同 code 节点,无法唯一继承类型——显式给 type/activityType。`
244
+ : `${tool}: 节点 ${code} 缺 type/activityType,且草稿里没有同 code 的既有节点可继承(新节点必须显式给 type;既有节点编辑行——participant/propertyPermissions/btnConfigList/改名——可省 type 仅当 activityCode 唯一命中草稿)。草稿现有节点:${listed || "(空)"}`,
245
+ });
246
+ }
247
+ /**
248
+ * Caller-side Activity aliases (input + the readback-only workflowSummary
249
+ * spelling) that must never ride the wire.
250
+ *
251
+ * r79-09: `permissions`/`formButtons`/`bizActions` are summary projections, not
252
+ * platform Activity fields (the wire uses `propertyPermissions` /
253
+ * `buttonPermission.customBtns` / per-event `ActivityEventHandler.bizActions`).
254
+ * ticket-112's contract is that `workflowSummary.activities` can be fed back to
255
+ * `workflow.update` verbatim, so every readback-only key must be stripped here.
256
+ */
257
+ const ACTIVITY_INPUT_ALIAS_KEYS = ["id", "type", "name", "code", "index", "permissions", "formButtons", "bizActions"];
258
+ /**
259
+ * r85(retro issue 05 深层病灶):`bizActions` 一键两义——
260
+ * ① summary 投影(`{<nodeEvent>:[ruleCode]}` 对象,r79-09,回喂必须剥);
261
+ * ② SYSTEM_ACTIVITY 的真实 wire 字段(`List<String>`,SystemActivity.java:19-21,
262
+ * 节点激活时执行)。此前无差别剥键,顶层绑定经 workflow.update 会被静默丢弃。
263
+ * 按形状区分:字符串数组=平台字段放行;对象=投影剥掉。
264
+ */
265
+ export function callerActivityWireEntries(record) {
266
+ return Object.entries(record).filter(([key, value]) => !ACTIVITY_INPUT_ALIAS_KEYS.includes(key) ||
267
+ (key === "bizActions" && Array.isArray(value) && value.every((item) => typeof item === "string")));
268
+ }
269
+ /**
270
+ * Workflow canonical node layout — the same lesson as the rule graph
271
+ * (CFG-26), freshly observed live 2026-09-17: mapCallerActivities merges an
272
+ * activity onto the draft row by code, else by TYPE. A caller who names TWO
273
+ * PARTICIPANT nodes has neither code in the draft, so BOTH inherit the single
274
+ * draft PARTICIPANT's box (x=327, y=116) and overlap — the designer then draws
275
+ * the fill→approve edge as a horizontal stub and the chain is unreadable. When
276
+ * the merged activities lack geometry or collide, lay the chain out in the
277
+ * platform's single column (x=327, 158×40, 80px apart) and re-derive the rule
278
+ * points. A graph the caller laid out deliberately (no missing box, no
279
+ * overlap) is preserved verbatim.
280
+ */
281
+ export function linearWorkflowOrder(activities, rules) {
282
+ const codes = activities.map((activity) => String(activity.activityCode ?? ""));
283
+ if (codes.some((code) => !code) || new Set(codes).size !== codes.length)
284
+ return [];
285
+ const outgoing = new Map();
286
+ for (const rule of rules) {
287
+ const pre = String(rule.preActivityCode ?? "");
288
+ const post = String(rule.postActivityCode ?? "");
289
+ if (!codes.includes(pre) || !codes.includes(post))
290
+ continue;
291
+ outgoing.set(pre, [...(outgoing.get(pre) ?? []), post]);
292
+ }
293
+ const starts = activities.filter((activity) => activity.activityType === "START").map((activity) => String(activity.activityCode));
294
+ if (starts.length !== 1 || [...outgoing.values()].some((targets) => targets.length > 1))
295
+ return [];
296
+ const order = [];
297
+ let cursor = starts[0];
298
+ while (cursor !== undefined && !order.includes(cursor)) {
299
+ order.push(cursor);
300
+ cursor = outgoing.get(cursor)?.[0];
301
+ }
302
+ return order.length === codes.length ? order : [];
303
+ }
304
+ export function canonicalizeWorkflowLayout(activities, rules) {
305
+ const numberOr = (value, fallback) => (Number.isFinite(Number(value)) ? Number(value) : fallback);
306
+ const boxOf = (activity) => ({
307
+ x: numberOr(activity.x, Number.NaN),
308
+ y: numberOr(activity.y, Number.NaN),
309
+ width: numberOr(activity.width, 158),
310
+ height: numberOr(activity.height, 40),
311
+ });
312
+ const boxes = activities.map(boxOf);
313
+ const missing = boxes.some((box) => Number.isNaN(box.x) || Number.isNaN(box.y));
314
+ const overlaps = boxes.some((a, ai) => boxes.some((b, bi) => bi > ai && !Number.isNaN(a.x) && !Number.isNaN(b.x) && a.x < b.x + b.width && b.x < a.x + a.width && a.y < b.y + b.height && b.y < a.y + a.height));
315
+ if (!missing && !overlaps)
316
+ return { activities, changed: false };
317
+ const order = linearWorkflowOrder(activities, rules);
318
+ const position = (code, index) => (order.length > 0 ? order.indexOf(code) : index);
319
+ return {
320
+ changed: true,
321
+ activities: activities.map((activity, index) => ({
322
+ ...activity,
323
+ x: 327,
324
+ y: 36 + 80 * position(String(activity.activityCode ?? ""), index),
325
+ width: 158,
326
+ height: 40,
327
+ })),
328
+ };
329
+ }
330
+ /** Ticket 112 — workflow rules carry designer-canvas `points` (same lesson as the rule graph): derive from the activity boxes. */
331
+ export function deriveRulePoints(pre, post, activities) {
332
+ const numberOr = (value, fallback) => (Number.isFinite(Number(value)) ? Number(value) : fallback);
333
+ const boxOf = (code, index) => {
334
+ const activity = activities.find((candidate) => String(candidate.activityCode ?? "") === code) ?? activities[index];
335
+ return {
336
+ x: numberOr(activity?.x, 327),
337
+ y: numberOr(activity?.y, 36 + 80 * index),
338
+ width: numberOr(activity?.width, 158),
339
+ height: numberOr(activity?.height, 40),
340
+ };
341
+ };
342
+ const preIndex = Math.max(0, activities.findIndex((candidate) => String(candidate.activityCode ?? "") === pre));
343
+ const postIndex = Math.max(0, activities.findIndex((candidate) => String(candidate.activityCode ?? "") === post));
344
+ const s = boxOf(pre, preIndex);
345
+ const t = boxOf(post, postIndex);
346
+ const scx = s.x + s.width / 2;
347
+ const tcx = t.x + t.width / 2;
348
+ if (t.y > s.y)
349
+ return [`${scx}, ${s.y + s.height}`, `${tcx}, ${t.y}`];
350
+ if (t.y < s.y)
351
+ return [`${scx}, ${s.y}`, `${tcx}, ${t.y + t.height}`];
352
+ if (t.x >= s.x)
353
+ return [`${s.x + s.width}, ${s.y + s.height / 2}`, `${t.x}, ${t.y + t.height / 2}`];
354
+ return [`${s.x}, ${s.y + s.height / 2}`, `${t.x + t.width}, ${t.y + t.height / 2}`];
355
+ }
356
+ /**
357
+ * The designer default OMC backfills is `rejectToStart:true` on approval nodes
358
+ * (see backfillDesignerDefaults). With that flag, rejecting returns the instance
359
+ * to the fill node and the flow keeps running: endEventHandler and
360
+ * cancelEventHandler never fire (live 2026-10-20, r5-asset — instance stayed
361
+ * PROCESSING, todo back at A2, status still 审批中). A rule bound to `cancel`
362
+ * therefore silently never runs. Advisory: reject-to-start is a legitimate
363
+ * choice, only "I bound a cancel rule and expect it to run" is broken.
364
+ */
365
+ /**
366
+ * A delta that omits `routes` keeps the draft's edges (mergeCallerDelta /
367
+ * completeWorkflowChain). That is the right default, but it is invisible: after
368
+ * 0.4.63's fix a branched draft survives an activities-only update, and a caller
369
+ * has no way to tell "I preserved 5 edges including the else fallback" from
370
+ * "the platform rebuilt a linear chain". Report the inherited branch edges.
371
+ */
372
+ export function inheritedBranchEdges(template) {
373
+ const rows = Array.isArray(template.activities) ? template.activities : [];
374
+ const rules = Array.isArray(template.rules) ? template.rules : [];
375
+ const outbound = new Map();
376
+ for (const rule of rules) {
377
+ const pre = String(rule.preActivityCode ?? "");
378
+ const post = String(rule.postActivityCode ?? "");
379
+ if (pre === "" || post === "")
380
+ continue;
381
+ outbound.set(pre, [...(outbound.get(pre) ?? []), post]);
382
+ }
383
+ const nameOf = new Map(rows.map((row) => [String(row.activityCode ?? ""), String(row.activityName ?? "")]));
384
+ return [...outbound.entries()]
385
+ .filter(([, targets]) => targets.length > 1)
386
+ .map(([pre, targets]) => `${pre}${nameOf.get(pre) ? `(${nameOf.get(pre)})` : ""} → ${targets.join(" | ")}`);
387
+ }
388
+ /**
389
+ * Round7 — the branch-relevant fields of a `Rule`, for readback. Without this
390
+ * the route condition is invisible: an agent could write a branch and never
391
+ * confirm which edge carries which condition.
392
+ *
393
+ * 2026-09-25 cost pass: the platform stores every optional rule key (`text`,
394
+ * `formula`, `childMatchType`, `ruleConditionGroup` as null; `utilizeElse`,
395
+ * `fixedPoint`, `alternativeFlag` as false; `popupType` as "FUNCTION"). Echoing
396
+ * those defaults repeated ~8 keys on EVERY edge of every workflow read (a 4-edge
397
+ * workflow carried ~890 B of edges, mostly defaults). Only meaningful values
398
+ * survive here; a default/absent key stays out. `full:true` still returns the
399
+ * raw stored row.
400
+ */
401
+ export function workflowRouteConditionView(rule) {
402
+ const view = {};
403
+ for (const key of ["text", "formula", "childMatchType", "ruleConditionGroup"]) {
404
+ const value = rule[key];
405
+ if (value !== undefined && value !== null)
406
+ view[key] = value;
407
+ }
408
+ for (const key of ["utilizeElse", "fixedPoint", "alternativeFlag"]) {
409
+ if (rule[key] === true)
410
+ view[key] = true;
411
+ }
412
+ if (rule.popupType !== undefined && rule.popupType !== null && rule.popupType !== "FUNCTION")
413
+ view.popupType = rule.popupType;
414
+ return view;
415
+ }
416
+ /** Activity type resolution shared by the merge + code reconcile (APPROVAL is a legacy alias; case-insensitive — "Participant"/"approval" are the same node type as the draft's "PARTICIPANT" and must not mint a fresh code). */
417
+ export function activityTypeOf(record) {
418
+ const rawType = String(record.activityType ?? record.type ?? "").trim().toUpperCase();
419
+ return rawType === "APPROVAL" ? "PARTICIPANT" : rawType;
420
+ }
421
+ /** Display name the caller asked for, in any accepted spelling. */
422
+ export function activityNameOf(record) {
423
+ const value = record.activityName ?? record.i18nMessage ?? record.name;
424
+ if (typeof value === "string" && value.length > 0)
425
+ return value;
426
+ // The participant shorthand `{type: Originator, name: 部门负责人}` carries the
427
+ // intended NODE label inside `participant.name`. The platform only resolves
428
+ // the participant keyword and defaults the activity name to 填写申请单, so
429
+ // without this the declared node name is silently lost (bench62: both approval
430
+ // nodes read back as 填写申请单). Promote it when the participant is the lone
431
+ // originator shorthand (the role-descriptor form keeps its own semantics).
432
+ const participant = record.participant;
433
+ if (participant && typeof participant === "object" && !Array.isArray(participant)) {
434
+ const descriptor = participant;
435
+ const typeValue = descriptor.type ?? descriptor.participantType;
436
+ if (typeof typeValue === "string" && /^originator$/i.test(typeValue.trim()) && typeof descriptor.name === "string" && descriptor.name.trim().length > 0)
437
+ return descriptor.name;
438
+ }
439
+ return undefined;
440
+ }
441
+ /**
442
+ * Activity code in any accepted spelling. `code` is what `workflowSummary`
443
+ * (get_draft/get_published compact) emits, so `get_draft → edit → update` — the
444
+ * documented "read back then send the delta" flow — round-trips: an activity the
445
+ * readback handed you is directly re-sendable.
446
+ */
447
+ export function activityCodeOf(record) {
448
+ return String(record.activityCode ?? record.id ?? record.code ?? "");
449
+ }
450
+ /**
451
+ * Rollback specs (git-revert semantics): before-state = the full draft row
452
+ * captured via get_draft; the restore replays workflow.update with the
453
+ * before template as a full-row replace (mergedTemplateBody echoes the draft
454
+ * verbatim when the caller template IS the draft row).
455
+ */
456
+ /**
457
+ * Restore-shaped snapshots come from the platform (`get_draft`), so they may
458
+ * carry spellings the WRITE gate refuses as malformed — notably
459
+ * `ruleConditionGroup: []` (8.x stores an empty outer array for a plain edge).
460
+ * Drop it before replaying a rollback: it means "no condition", and the strict
461
+ * input gate (round7) is right to refuse a caller-authored empty group.
462
+ */
463
+ export function sanitizeWorkflowSnapshotForReplay(row) {
464
+ const rules = row.rules;
465
+ if (!Array.isArray(rules))
466
+ return row;
467
+ return {
468
+ ...row,
469
+ rules: rules.map((rule) => {
470
+ const record = { ...(rule ?? {}) };
471
+ if (Array.isArray(record.ruleConditionGroup) && record.ruleConditionGroup.length === 0)
472
+ delete record.ruleConditionGroup;
473
+ return record;
474
+ }),
475
+ };
476
+ }
477
+ /**
478
+ * Round 4 (context-cost): keep the node structure in the default workflow
479
+ * readback. The full template row is 30–75 KB (activities ×4, originateActivity,
480
+ * notify config); without this projection the agent fetches the whole artifact
481
+ * just to see the node list. Reproduced benchmark: `artifact get` was 56% of a
482
+ * complex task's stdout, dominated by workflow.get_draft/get_published (75 KB +
483
+ * 52 KB). Full body stays reachable via detailArtifactId, `--jq`, or `--full`.
484
+ */
485
+ /**
486
+ * Round 16: compact, non-default field-permission summary for one activity.
487
+ * The full permission row carries ~10 keys per field (`propertyName`,
488
+ * `encryptVisible`, `decryptAble`, …); the caller only needs to confirm who can
489
+ * see/edit/require what, so keep `{code, visible, editable, required}` and drop
490
+ * the all-false rows that dominate the full body. Returns undefined when the
491
+ * activity declares no permission face or has no non-default row.
492
+ */
493
+ function activityPermissions(activity) {
494
+ const rows = activity.propertyPermissions;
495
+ if (!Array.isArray(rows))
496
+ return undefined;
497
+ const permissions = rows
498
+ .filter((row) => Boolean(row && typeof row === "object" && !Array.isArray(row)))
499
+ .map((row) => ({ code: row.propertyCode ?? null, visible: row.visible === true, editable: row.editable === true, required: row.required === true }))
500
+ .filter((row) => row.visible || row.editable || row.required);
501
+ return permissions.length > 0 ? { permissions } : undefined;
502
+ }
503
+ /**
504
+ * r79-09: node-level rule bindings come from the eight per-activity
505
+ * ActivityEventHandler fields (`{bizActions:[ruleCode], bizActionType:"BIZ_RULE"}`),
506
+ * **not** from a `bizActions` key on the activity row. The summary therefore
507
+ * projects `bizActions: {<nodeEvent>: [ruleCode]}` — the shape callers guessed
508
+ * as `activities[].bizActions` (issue 09) and the in-node version of the
509
+ * artifact face's `data.activities[code=X].<nodeEvent>.bizActions`.
510
+ *
511
+ * Single source of truth: `nodeRuleBindings` (the flat scan, kept) is derived
512
+ * from this helper too, so "which event counts as a binding" has one predicate.
513
+ * Unbound nodes carry no key (`--jq 'activities[].bizActions'` lists only bound
514
+ * nodes; the fan-out receipt's missedEntries explains the rest).
515
+ */
516
+ function activityBizActions(activity) {
517
+ const map = {};
518
+ for (const nodeEvent of Object.keys(WORKFLOW_NODE_EVENT_HANDLER_FIELDS)) {
519
+ const config = activity[nodeEvent];
520
+ const codes = Array.isArray(config?.bizActions) ? config.bizActions.filter((value) => typeof value === "string") : [];
521
+ if (codes.length > 0 && config?.bizActionType === "BIZ_RULE")
522
+ map[nodeEvent] = codes;
523
+ }
524
+ return Object.keys(map).length > 0 ? map : undefined;
525
+ }
526
+ /**
527
+ * r85(retro 2026-11-19 issue 05):SYSTEM_ACTIVITY 节点在活动行上还有**顶层**
528
+ * `bizActions` + `bizActionType`(SystemActivity.java:19-21「绑定的业务方法」,
529
+ * BIZ_METHOD/BIZ_RULE 二态)——与八个节点事件 handler 完全不同的第三个绑定面。
530
+ * 节点激活时执行它们(SystemActivityRuntime.java:54 processingBusiness),
531
+ * 发布校验按 BIZ_RULE 比对规则清单(WorkflowTemplateValidateUtility
532
+ * .validateSystemActivity:866-877)。客订规则绑在 Activity8 顶层 bizActions 而
533
+ * summary 看不到 → 用户得出「没绑」的错误结论。投影为独立键 systemBizActions
534
+ * (不占 activities[].bizActions——那个键是节点事件映射的既有投影)。
535
+ */
536
+ function activitySystemBizActions(activity) {
537
+ const raw = activity.bizActions;
538
+ if (!Array.isArray(raw))
539
+ return undefined;
540
+ const codes = raw.filter((value) => typeof value === "string" && value.length > 0);
541
+ if (codes.length === 0)
542
+ return undefined;
543
+ return { bizActionType: typeof activity.bizActionType === "string" ? activity.bizActionType : null, ruleCodes: codes };
544
+ }
545
+ export function workflowCompactProjection(result) {
546
+ const data = (result.data ?? null);
547
+ if (data === null)
548
+ return {};
549
+ const activities = (data.activities ?? {});
550
+ const nodes = Object.entries(activities).map(([index, activity]) => ({
551
+ index: Number(index),
552
+ code: activity.activityCode ?? null,
553
+ type: activity.activityType ?? null,
554
+ name: effectiveActivityName(activity),
555
+ ...(activity.participant !== undefined ? { participant: activity.participant } : {}),
556
+ // Round 16 (bench65 feedback): a participant node's field permissions were
557
+ // only visible in the 30–45 KB full body, so acceptance (and any "did my
558
+ // permission edit land?") required the artifact. Surface only the
559
+ // NON-DEFAULT rows (any of visible/editable/required true) so the summary
560
+ // stays small and names exactly what a readback should confirm.
561
+ ...(activityPermissions(activity) ?? {}),
562
+ // The designer's 「表单操作」 checkboxes live in buttonPermission.customBtns;
563
+ // surface the enabled codes so a readback answers "which buttons show on
564
+ // this node" without the 30–75 KB body.
565
+ ...(() => {
566
+ const bp = activity.buttonPermission;
567
+ const btns = Array.isArray(bp?.customBtns) ? bp.customBtns : [];
568
+ if (btns.length === 0)
569
+ return {};
570
+ const enabled = btns.filter((button) => button.enabled === true).map((button) => String(button.code ?? ""));
571
+ const disabled = btns.filter((button) => button.enabled !== true).map((button) => String(button.code ?? ""));
572
+ return { formButtons: { ...(enabled.length ? { enabled } : {}), ...(disabled.length ? { disabled } : {}) } };
573
+ })(),
574
+ // r79-09: node-level rule bindings, projected as bizActions:
575
+ // {<nodeEvent>: [ruleCode]} (same helper that drives nodeRuleBindings below).
576
+ ...(() => {
577
+ const bizActions = activityBizActions(activity);
578
+ return bizActions !== undefined ? { bizActions } : {};
579
+ })(),
580
+ // r85: TOP-LEVEL bizActions (SYSTEM_ACTIVITY's own binding surface — a rule
581
+ // here fires on node activation, not on a node event). Separate key so the
582
+ // node-event map above keeps its meaning.
583
+ ...(() => {
584
+ const system = activitySystemBizActions(activity);
585
+ return system !== undefined ? { systemBizActions: system } : {};
586
+ })(),
587
+ }));
588
+ const rules = data.rules;
589
+ const edges = Array.isArray(rules)
590
+ ? rules.map((rule) => {
591
+ const record = rule;
592
+ return { from: record.preActivityCode ?? null, to: record.postActivityCode ?? null, ...workflowRouteConditionView(record) };
593
+ })
594
+ : [];
595
+ // Round 15 (bench61 feedback): a count ("ruleBindings: 3") cannot be verified —
596
+ // show WHICH event handler binds WHICH rule codes, so a readback confirms the
597
+ // binding without pulling the full body. The platform's own originate node
598
+ // (填写申请单) and any injected participant are named too, so a caller does not
599
+ // mistake them for their declared nodes.
600
+ const ruleBindings = [];
601
+ for (const [handler, field] of Object.entries(WORKFLOW_EVENT_HANDLER_FIELDS)) {
602
+ const config = data[field];
603
+ const codes = Array.isArray(config?.bizActions) ? config.bizActions.filter((value) => typeof value === "string") : [];
604
+ if (codes.length > 0 && config?.bizActionType === "BIZ_RULE")
605
+ ruleBindings.push({ handler, field, ruleCodes: codes });
606
+ }
607
+ // Node-level bindings are invisible in the flow-level list above; surface the
608
+ // non-empty ones so a `get_draft`/`get_published` readback can confirm a
609
+ // `workflow.bindRule {activityCode,nodeEvent}` landing without `--full`.
610
+ // r79-09: flat scan VIEW of activities[].bizActions (same helper/predicate) —
611
+ // kept for "scan every node at once"; per-node reads should prefer the
612
+ // projected `activities[].bizActions`.
613
+ const nodeRuleBindings = [];
614
+ for (const row of Object.values(activities)) {
615
+ const activityCode = String(row?.activityCode ?? "");
616
+ if (activityCode === "")
617
+ continue;
618
+ for (const [nodeEvent, ruleCodes] of Object.entries(activityBizActions(row) ?? {}))
619
+ nodeRuleBindings.push({ activityCode, nodeEvent, ruleCodes });
620
+ }
621
+ // r85: the THIRD binding surface — SYSTEM_ACTIVITY's top-level bizActions.
622
+ // Same predicate as the per-node projection (activitySystemBizActions), so
623
+ // "what counts as a binding" stays single-sourced across the summary, the
624
+ // flat scans, and workflow.list's ruleBindingCount.
625
+ const systemRuleBindings = [];
626
+ for (const row of Object.values(activities)) {
627
+ const activityCode = String(row?.activityCode ?? "");
628
+ if (activityCode === "")
629
+ continue;
630
+ const system = activitySystemBizActions(row);
631
+ if (system !== undefined)
632
+ systemRuleBindings.push({ activityCode, bizActionType: system.bizActionType, ruleCodes: system.ruleCodes });
633
+ }
634
+ const originate = data.originateActivity;
635
+ // Count ALL propertyPermissions rows on the native template (including
636
+ // all-false), so --full/--jq can answer "did my visibility edit land?" even
637
+ // when the compact permissions face filters defaults out.
638
+ const propertyPermissionsCount = Object.values(activities).reduce((sum, activity) => {
639
+ const rows = activity.propertyPermissions;
640
+ return sum + (Array.isArray(rows) ? rows.length : 0);
641
+ }, 0);
642
+ // r30d F14: --full externalizes the native body; keep a projectable top-level
643
+ // activities summary so callers do not need four hops (describe → get --full
644
+ // → pathMiss → artifact get) just to see node codes / participants.
645
+ const activitySummaries = nodes.map((node) => ({
646
+ code: node.code,
647
+ name: node.name,
648
+ type: node.type,
649
+ ...(node.participant !== undefined ? { participants: node.participant } : {}),
650
+ ...(node.permissions !== undefined ? { propertyPermissions: node.permissions } : {}),
651
+ // r79-09: mirror the same node-level bindings on the top-level projection —
652
+ // `activities[].bizActions` is the literal path callers reach for (issue 09).
653
+ ...(node.bizActions !== undefined ? { bizActions: node.bizActions } : {}),
654
+ // r85: mirror the SYSTEM_ACTIVITY top-level face on the projectable row.
655
+ ...(node.systemBizActions !== undefined ? { systemBizActions: node.systemBizActions } : {}),
656
+ }));
657
+ return {
658
+ workflowSummary: {
659
+ workflowCode: data.workflowCode ?? result.workflowCode ?? null,
660
+ templateType: data.templateType ?? null,
661
+ activities: nodes,
662
+ edges,
663
+ ruleBindings,
664
+ ...(nodeRuleBindings.length > 0 ? { nodeRuleBindings } : {}),
665
+ ...(systemRuleBindings.length > 0 ? { systemRuleBindings } : {}),
666
+ ruleBindingCount: ruleBindings.reduce((sum, binding) => sum + binding.ruleCodes.length, 0) + systemRuleBindings.reduce((sum, binding) => sum + binding.ruleCodes.length, 0),
667
+ ...(originate ? { originateActivity: { code: originate.activityCode ?? null, type: originate.activityType ?? null, name: effectiveActivityName(originate), participant: originate.participant ?? null } } : {}),
668
+ },
669
+ // Projectable top-level face for --full / --jq (r30d F9/F14).
670
+ activities: activitySummaries,
671
+ propertyPermissionsCount,
672
+ version: data.workflowVersion ?? data.version ?? null,
673
+ // Editing needs only `activities` (array or index object) + `routes`: the tool
674
+ // merges onto the stored draft, connects added nodes through to END, fills
675
+ // sheetCode and geometry. Reading the 30–75 KB full body is NOT required —
676
+ // bench17 pulled 61 KB `full:true` just to edit two node names.
677
+ 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——规则绑在系统活动节点本身、激活时执行,别只看前两个面就下「没绑」结论)。",
678
+ };
679
+ }
680
+ /**
681
+ * A node's DISPLAY name: `name_i18n` (the rename carrier — the designer's
682
+ * rename writes the locale map and activityName keeps its first-created value,
683
+ * live 2026-10-17) wins over the first-created activityName/i18nMessage.
684
+ */
685
+ export function effectiveActivityName(activity) {
686
+ const i18n = activity.name_i18n;
687
+ // The rename carrier is normally a locale MAP, but some platform families
688
+ // answer it as a JSON STRING of that map (observed on a 1.1.x-compat
689
+ // endpoint: i18nMessage gets the new name, name_i18n comes back stringified).
690
+ // Without parsing it, a renamed node keeps reading its first-created
691
+ // activityName and every draft↔published diff would miss the rename.
692
+ const map = typeof i18n === "string" ? parseLocalizedMap(i18n) : i18n && typeof i18n === "object" ? i18n : undefined;
693
+ if (map !== undefined) {
694
+ const localized = map.zh ?? map.zh_TW ?? map.en;
695
+ if (localized !== undefined && String(localized) !== "")
696
+ return String(localized);
697
+ }
698
+ return (activity.activityName ?? activity.i18nMessage ?? null);
699
+ }
700
+ function parseLocalizedMap(value) {
701
+ const trimmed = value.trim();
702
+ if (!trimmed.startsWith("{"))
703
+ return undefined;
704
+ try {
705
+ const parsed = JSON.parse(trimmed);
706
+ return parsed !== null && typeof parsed === "object" && !Array.isArray(parsed) ? parsed : undefined;
707
+ }
708
+ catch {
709
+ return undefined;
710
+ }
711
+ }
712
+ /** 该 target(flow 级 handler / node 级事件)在模板上的 handler 对象。 */
713
+ export function bindTargetHandlerOf(template, target) {
714
+ if (target.scope === "workflow")
715
+ return (template?.[target.field] ?? {}) ?? {};
716
+ return (findTemplateActivity(template, target.activityCode)?.[target.field] ?? {}) ?? {};
717
+ }
718
+ /** Flatten a role-group/role row into the participant-construction fields. */
719
+ /**
720
+ * Role groups are CONTAINERS, not roles. The platform's own row marks them
721
+ * `group:true` (children carry `group:false`), so membership must be decided by
722
+ * that flag — never by `children.length`. Live 2026-10-21 (customer 8.2.96,
723
+ * 季度考评): every entry was a group with `children:[]`, so the old
724
+ * `children.length === 0 ? role : …` shape returned 19 "roles" that were all
725
+ * groups; the agent read `count:19` as "the 6 roles were never created" and
726
+ * reported a false blocker to the user. Groups also nest, so flatten
727
+ * recursively and keep them in a separate `groups` list.
728
+ */
729
+ const ROLE_CHILD_KEYS = ["children", "roles", "childRoles", "childList", "list"];
730
+ function roleChildren(row) {
731
+ for (const key of ROLE_CHILD_KEYS) {
732
+ const value = row[key];
733
+ if (Array.isArray(value))
734
+ return value;
735
+ }
736
+ return [];
737
+ }
738
+ function isRoleGroup(row) {
739
+ if (row.group === true)
740
+ return true;
741
+ // Older builds omit `group`; a container with children is still a container.
742
+ // A row that carries `groupId` is a leaf role even if it has an empty array.
743
+ if (row.groupId !== undefined && row.groupId !== null)
744
+ return false;
745
+ return roleChildren(row).length > 0;
746
+ }
747
+ export function flattenRoleTree(rows) {
748
+ const roles = [];
749
+ const groups = [];
750
+ const walk = (nodes, containers) => {
751
+ for (const node of nodes) {
752
+ if (!isRoleGroup(node)) {
753
+ const parent = containers.length > 0 ? containers[containers.length - 1] : null;
754
+ roles.push(roleOf(node, parent));
755
+ continue;
756
+ }
757
+ const name = String(node.name ?? "");
758
+ const id = String(node.id ?? "");
759
+ const code = node.code == null || node.code === "" ? null : String(node.code);
760
+ const path = [...containers.map((container) => container.name), name].filter((part) => part.length > 0).join(" / ");
761
+ const children = roleChildren(node);
762
+ const parent = containers.length > 0 ? containers[containers.length - 1] : null;
763
+ groups.push({
764
+ id: node.id ?? null,
765
+ name: node.name ?? null,
766
+ code: node.code ?? null,
767
+ corpId: node.corpId ?? null,
768
+ parentId: parent?.id ?? null,
769
+ path,
770
+ childCount: children.length,
771
+ });
772
+ if (children.length > 0)
773
+ walk(children, [...containers, { id, code, name }]);
774
+ }
775
+ };
776
+ walk(rows, []);
777
+ return {
778
+ // `count` stays role-only: it is what participant resolution consumes, and
779
+ // counting containers as roles is exactly the misread this fixes.
780
+ count: roles.length,
781
+ roleCount: roles.length,
782
+ groupCount: groups.length,
783
+ roles,
784
+ groups,
785
+ ...(roles.length === 0
786
+ ? {
787
+ hint: "本次返回里没有任何角色行(只有角色组或无数据)。角色组不是角色:不要据此断言「角色未创建」。若预期有角色,先看 groups[].childCount —— 组内为空说明该组下确实未建角色;若要验证某个 roleCode 在运行期可用,用业务数据反证(如 data.list 读取引用该 roleCode 的记录,或 org.user.search 找到人后用其角色字段)。",
788
+ }
789
+ : {}),
790
+ };
791
+ }
792
+ function roleOf(row, group) {
793
+ // r28h F6: roles used to carry only `group:<name>` — write faces need the
794
+ // group id/code. Keep `group` (name) for back-compat and add explicit FKs.
795
+ return {
796
+ id: row.id ?? null,
797
+ name: row.name ?? null,
798
+ code: row.code ?? null,
799
+ roleType: row.roleType ?? null,
800
+ corpId: row.corpId ?? null,
801
+ ...(group !== null
802
+ ? {
803
+ group: group.name,
804
+ groupId: group.id || null,
805
+ groupCode: group.code,
806
+ groupName: group.name,
807
+ }
808
+ : {}),
809
+ };
810
+ }
811
+ //# sourceMappingURL=shapes.js.map