@stalfh233/omc-cli 0.8.35 → 0.8.37

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.
@@ -1,7 +1,8 @@
1
1
  import { WireError, wireCall, wireRows } from "../../wire.js";
2
2
  import { ENDPOINTS } from "../../endpoints.js";
3
3
  import { ENGINE_OWNED_KEYS, RUNTIME_DATA_WIRE } from "../runtime-data-contract.js";
4
- import { choiceCodesFromFieldOptions, parseOptions } from "./field-options.js";
4
+ import { choiceValuesFromFieldOptions, optionValueKeyMap, parseOptions } from "./field-options.js";
5
+ import { dateFormatRegex } from "./date-format.js";
5
6
  import { RELATION_PROPERTY_TYPES, RUNTIME_SYSTEM_FIELD_CODES } from "./shapes.js";
6
7
  import { CHILD_TABLE_PROPERTY_TYPE } from "../../runtime-support.js";
7
8
  import { ToolRefusalError } from "../../tool-types.js";
@@ -375,7 +376,9 @@ export function unknownFieldDiagnostic(formData, fieldCodes, childCodes, schemaL
375
376
  const known = new Set(fieldCodes);
376
377
  const children = new Set(childCodes ?? []);
377
378
  const unknownFieldKeys = Object.entries(formData)
378
- .filter(([key, value]) => value !== null && !RUNTIME_SYSTEM_FIELD_CODES.has(key) && !key.endsWith("_") && !known.has(key) && !children.has(key) && !(value && typeof value === "object" && !Array.isArray(value) && key === "id"))
379
+ // `*_key` 是平台为选择字段生成的伴生列(DataModelConstants.SELECTION_KEY_SUFFIX),
380
+ // 不在 field.list 业务面里;手写/建议的 key 都必须豁免,否则一律误报 unknown。
381
+ .filter(([key, value]) => value !== null && !RUNTIME_SYSTEM_FIELD_CODES.has(key) && !key.endsWith("_") && !key.endsWith("_key") && !known.has(key) && !children.has(key) && !(value && typeof value === "object" && !Array.isArray(value) && key === "id"))
379
382
  .map(([key]) => key);
380
383
  return unknownFieldKeys.length > 0 ? {
381
384
  unknownFieldKeys,
@@ -388,6 +391,118 @@ export function readbackEmptyFields(formData, record) {
388
391
  .filter(([key, value]) => value !== null && value !== undefined && (source[key] === null || source[key] === undefined))
389
392
  .map(([key]) => key);
390
393
  }
394
+ function datePrefix(value) {
395
+ if (typeof value !== "string")
396
+ return undefined;
397
+ const match = /^(\d{4}-\d{2}-\d{2})(?:[T\s].*)?$/.exec(value.trim());
398
+ return match?.[1];
399
+ }
400
+ /** 只有「无前导零的规范数字串」才做数值归一,避免把 `007`/长编码当数字。 */
401
+ function canonicalNumber(value) {
402
+ const trimmed = value.trim();
403
+ if (!/^-?(?:0|[1-9]\d*)(?:\.\d+)?$/.test(trimmed))
404
+ return undefined;
405
+ return String(Number(trimmed));
406
+ }
407
+ /** 关联/人员/组织:写侧可能是 id 串或 `{id,...}`,读回常是对象。 */
408
+ function relationIdentity(value) {
409
+ if (value === null || typeof value !== "object" || Array.isArray(value))
410
+ return undefined;
411
+ const row = value;
412
+ const id = row.id ?? row.bizObjectId ?? row.objectId;
413
+ if (typeof id === "string" && id)
414
+ return id;
415
+ const display = row.displayCode ?? row.code;
416
+ return typeof display === "string" && display ? display : undefined;
417
+ }
418
+ function booleanValue(value) {
419
+ if (value === true || value === 1 || value === "1" || value === "true")
420
+ return true;
421
+ if (value === false || value === 0 || value === "0" || value === "false")
422
+ return false;
423
+ return undefined;
424
+ }
425
+ function fieldValueMatches(requested, stored) {
426
+ if (requested === stored)
427
+ return true;
428
+ // 关联对象 ↔ id 串 / 读回对象。
429
+ if (requested !== null && typeof requested === "object") {
430
+ const requestedId = relationIdentity(requested);
431
+ if (requestedId === undefined)
432
+ return false;
433
+ const storedId = relationIdentity(stored);
434
+ if (storedId !== undefined)
435
+ return requestedId === storedId;
436
+ return typeof stored === "string" && stored.trim() === requestedId;
437
+ }
438
+ if (stored !== null && typeof stored === "object") {
439
+ const storedId = relationIdentity(stored);
440
+ return storedId !== undefined && typeof requested === "string" && requested.trim() === storedId;
441
+ }
442
+ // 布尔:平台常按 0/1 或 "true"/"false" 落库。
443
+ if (typeof requested === "boolean" || typeof stored === "boolean") {
444
+ const left = booleanValue(requested);
445
+ const right = booleanValue(stored);
446
+ return left !== undefined && right !== undefined && left === right;
447
+ }
448
+ // 日期:写 "2026-12-02",读回 "2026-12-02 00:00:00" —— 按前 10 位比。
449
+ const requestedDate = datePrefix(requested);
450
+ const storedDate = datePrefix(stored);
451
+ if (requestedDate !== undefined && storedDate !== undefined)
452
+ return requestedDate === storedDate;
453
+ // 数字:number 与数字串互认(42 / "42" / "42.0")。
454
+ if (typeof requested === "number" || typeof stored === "number") {
455
+ const left = typeof requested === "number" ? requested : typeof requested === "string" ? Number(requested) : Number.NaN;
456
+ const right = typeof stored === "number" ? stored : typeof stored === "string" ? Number(stored) : Number.NaN;
457
+ if (!Number.isNaN(left) && !Number.isNaN(right))
458
+ return left === right;
459
+ }
460
+ if (typeof requested === "string" && typeof stored === "string") {
461
+ const left = requested.trim();
462
+ const right = stored.trim();
463
+ if (left === right)
464
+ return true;
465
+ const leftNumber = canonicalNumber(left);
466
+ const rightNumber = canonicalNumber(right);
467
+ return leftNumber !== undefined && rightNumber !== undefined && leftNumber === rightNumber;
468
+ }
469
+ return false;
470
+ }
471
+ export function fieldWriteMismatches(formData, record) {
472
+ if (record === null || typeof record !== "object" || Array.isArray(record))
473
+ return [];
474
+ const source = record;
475
+ const mismatches = [];
476
+ for (const [field, requested] of Object.entries(formData)) {
477
+ if (field === "id")
478
+ continue;
479
+ // `name` 是系统列但在数据面可写(数据标题规则会覆盖它)——它正是 issue #65
480
+ // 的现场,所以这里不能走 `submittedBusinessFields`(那份表把 name 当系统键滤掉)。
481
+ if (RUNTIME_SYSTEM_FIELD_CODES.has(field) && field !== "name")
482
+ continue;
483
+ if (field.endsWith("_") || field.endsWith("_key"))
484
+ continue;
485
+ if (requested === null || requested === undefined)
486
+ continue;
487
+ // 子表数组/多值不在此面(读回形状不同,且另有 childRowsNotDeletedWarnings)。
488
+ if (Array.isArray(requested))
489
+ continue;
490
+ const stored = source[field];
491
+ if (stored === null || stored === undefined)
492
+ continue;
493
+ // 多选关联写侧是分号串、读回是数组:形状不可直接对账,跳过(宁漏报不误报)。
494
+ if (Array.isArray(stored))
495
+ continue;
496
+ // 只能比对「标量 ↔ 标量」或「关联对象 ↔ 关联对象/id 串」;无身份的对象形状跳过。
497
+ if (requested !== null && typeof requested === "object" && relationIdentity(requested) === undefined)
498
+ continue;
499
+ if (stored !== null && typeof stored === "object" && relationIdentity(stored) === undefined)
500
+ continue;
501
+ if (!fieldValueMatches(requested, stored))
502
+ mismatches.push({ field, requested, stored });
503
+ }
504
+ return mismatches;
505
+ }
391
506
  export function readbackWarningFor(emptyFields, toolName) {
392
507
  if (emptyFields.length === 0)
393
508
  return undefined;
@@ -436,8 +551,9 @@ export async function runtimeDataWarnings(session, schemaCode, sheetCode, formDa
436
551
  warnings.push({ code: "required-empty", row, fieldCode: field, message: `字段 ${field} 声明必填但本行为空;平台照存,OMC 仅提示` });
437
552
  }
438
553
  const options = parseOptions(meta.options);
439
- const optionSet = options.optionsSet && typeof options.optionsSet === "object" ? options.optionsSet : {};
440
- const choiceCodes = choiceCodesFromFieldOptions(meta, options);
554
+ // 写面存的是选项 *value*(custom = optionsSet.custom[].value,字典 = name),
555
+ // 不是 code;用 code 集校验 custom 单选会整片误报(issue #100)。
556
+ const choiceCodes = choiceValuesFromFieldOptions(meta, options);
441
557
  if (choiceCodes.length > 0 && value !== null && value !== undefined && value !== "") {
442
558
  const allowed = new Set(choiceCodes);
443
559
  const values = Array.isArray(value) ? value : [value];
@@ -561,7 +677,7 @@ export async function loadPublishedFieldMeta(session, schemaCode) {
561
677
  }
562
678
  const options = parseOptions(row.options);
563
679
  serialNumber = serialNumber || options.formPropertyType === 100 || (Array.isArray(options.seqNoSetting) && options.seqNoSetting.length > 0);
564
- meta.set(code, { type, ...(format !== undefined ? { format } : {}), ...(serialNumber ? { serialNumber: true } : {}) });
680
+ meta.set(code, { type, ...(format !== undefined ? { format } : {}), ...(serialNumber ? { serialNumber: true } : {}), ...(Object.keys(options).length > 0 ? { options } : {}) });
565
681
  if (type === CHILD_TABLE_PROPERTY_TYPE)
566
682
  childCodes.push(code);
567
683
  }
@@ -578,7 +694,8 @@ export async function loadPublishedFieldMeta(session, schemaCode) {
578
694
  * 同序),而表单运行时保存路径不补 sortKey(`BizObjectInsertModel`/`BizObjectUpdateItem`
579
695
  * 无 sortKey 写入;补值只存在于导入合并 `IntegrationMergerUtils:34-37`、规则
580
696
  * `CreateServiceExecutor:166`/`BizObjectUtil:131`、流程结束 `EndActivityRuntime:277-278`)。
581
- * 所以新建保存/提交时,缺 sortKey 的子行按数组下标补 1..n;调用方显式值原样保留。
697
+ * 所以新建保存/提交时,缺 sortKey 的子行按数组下标补 **0..n-1**(与平台规则
698
+ * 创建/导入的 0 基一致,issue #106);调用方显式值原样保留。
582
699
  * 更新既有记录不补(既有行可能已有 sortKey,猜起点会撞号)。
583
700
  */
584
701
  export function stampChildSortKeys(formData, childCodes) {
@@ -598,7 +715,7 @@ export function stampChildSortKeys(formData, childCodes) {
598
715
  if (typeof row.rowStatus === "string" && row.rowStatus.trim().toLowerCase() === "deleted")
599
716
  return row;
600
717
  mutated = true;
601
- return { ...row, sortKey: index + 1 };
718
+ return { ...row, sortKey: index };
602
719
  });
603
720
  if (mutated) {
604
721
  next[code] = stamped;
@@ -607,6 +724,107 @@ export function stampChildSortKeys(formData, childCodes) {
607
724
  }
608
725
  return changed ? next : formData;
609
726
  }
727
+ /**
728
+ * Advisory only (issue #106): an explicit child `sortKey` outside the legal
729
+ * range still lands, but the platform's readback order (fixed `sortKey ASC`,
730
+ * BizObjectConverterImpl 8.6.26:1235,1247) then becomes surprising.
731
+ * - new record: legal `[0, n-1]` (the same 0-based slots OMC stamps);
732
+ * - update: `[0, E+A-1]` where E = existing rows, A = submitted rows that are
733
+ * not existing ids (appends). Pass the authoritative `existing` record.
734
+ * Never refuses — the platform is permissive here and a refusal would be a
735
+ * new failure mode for rows that currently work.
736
+ */
737
+ export function childSortKeyOutOfRangeWarnings(formData, childCodes, existingRecord) {
738
+ const warnings = [];
739
+ for (const code of childCodes) {
740
+ const rows = formData[code];
741
+ if (!Array.isArray(rows))
742
+ continue;
743
+ const existingRows = Array.isArray(existingRecord?.[code]) ? existingRecord[code] : undefined;
744
+ const existingIds = new Set((existingRows ?? [])
745
+ .map((row) => (row && typeof row === "object" && !Array.isArray(row) ? String(row.id ?? "").trim() : ""))
746
+ .filter((id) => id.length > 0));
747
+ const appended = existingRows === undefined
748
+ ? rows.length
749
+ : rows.filter((row) => !(row && typeof row === "object" && !Array.isArray(row) && existingIds.has(String(row.id ?? "").trim()))).length;
750
+ const max = (existingRows?.length ?? 0) + appended - 1;
751
+ if (max < 0)
752
+ continue;
753
+ rows.forEach((row, index) => {
754
+ if (!row || typeof row !== "object" || Array.isArray(row))
755
+ return;
756
+ const record = row;
757
+ const raw = record.sortKey;
758
+ if (raw === null || raw === undefined || String(raw).trim() === "")
759
+ return;
760
+ const value = Number(raw);
761
+ if (!Number.isFinite(value) || value < 0 || value > max) {
762
+ warnings.push({
763
+ code: "childSortKeyOutOfRange",
764
+ row: index,
765
+ fieldCode: code,
766
+ childTable: code,
767
+ sortKey: raw,
768
+ allowed: [0, max],
769
+ message: `子表 ${code} 第 ${index} 行显式 sortKey=${String(raw)} 超出合法范围 [0,${max}](新建记录 0..n-1;更新 E+A-1)——平台照样落库,但读回固定按 sortKey ASC,越界值会打乱顺序;缺省行已按数组下标补 0 基`,
770
+ });
771
+ }
772
+ });
773
+ }
774
+ return warnings;
775
+ }
776
+ /**
777
+ * Advisory only (issue #100): the platform mirrors every RADIO(12)/DROPDOWN(14)
778
+ * value into a `<field>_key` companion column through
779
+ * `OptionKeySupportImpl.getValueKeyMap` (8.6.26 :164-183). OMC does not write
780
+ * the companion key; it only tells the caller when a hand-built payload has a
781
+ * value without one (or a key that disagrees with the readable snapshot).
782
+ */
783
+ export function optionKeyWarnings(meta, formData, row = 1) {
784
+ if (!meta)
785
+ return [];
786
+ const warnings = [];
787
+ for (const [code, field] of meta) {
788
+ if (field.type !== 12 && field.type !== 14)
789
+ continue;
790
+ const value = formData[code];
791
+ if (value === null || value === undefined || value === "" || Array.isArray(value) || typeof value === "object")
792
+ continue;
793
+ const keyCode = `${code}_key`;
794
+ const suppliedKey = formData[keyCode];
795
+ const map = optionValueKeyMap({ options: field.options ?? {} });
796
+ const suggested = map.byValue.get(String(value));
797
+ const hasKey = !(suppliedKey === null || suppliedKey === undefined || String(suppliedKey).trim() === "");
798
+ if (!hasKey) {
799
+ warnings.push({
800
+ code: "optionKeyMissing",
801
+ row,
802
+ fieldCode: code,
803
+ keyField: keyCode,
804
+ value: String(value),
805
+ optionSource: map.source,
806
+ ...(suggested !== undefined ? { suggestedKey: suggested } : {}),
807
+ message: `字段 ${code} 传了值 "${String(value)}" 但没有伴生键 ${keyCode}。平台写面会按选项集反推并补写该键(OptionKeySupportImpl);` +
808
+ `本工具**不代写**。${suggested !== undefined ? `按当前${map.source === "snapshot" ? "字典快照" : "自定义选项"}可推出 ${keyCode}="${suggested}",需要就显式带上。` : map.source === "unresolved" ? `选项来源(businessModel)无法离线解析,本次给不出建议键。` : ""}`.trim(),
809
+ });
810
+ continue;
811
+ }
812
+ if (suggested !== undefined && String(suppliedKey).trim() !== suggested) {
813
+ warnings.push({
814
+ code: "optionKeyMismatch",
815
+ row,
816
+ fieldCode: code,
817
+ keyField: keyCode,
818
+ value: String(value),
819
+ suppliedKey: String(suppliedKey),
820
+ expectedKey: suggested,
821
+ optionSource: map.source,
822
+ message: `字段 ${code} 的值 "${String(value)}" 对应的 ${keyCode} 应为 "${suggested}",实际传了 "${String(suppliedKey)}"(按${map.source === "snapshot" ? "字典快照" : "自定义选项"}推导);平台写面会重算该伴生键,OMC 仅提示`,
823
+ });
824
+ }
825
+ }
826
+ return warnings;
827
+ }
610
828
  export async function stampChildRowStatuses(session, schemaCode, formData, preloaded) {
611
829
  const loaded = preloaded !== undefined ? preloaded : await loadPublishedFieldMeta(session, schemaCode);
612
830
  if (!loaded || loaded.childCodes.length === 0)
@@ -639,48 +857,21 @@ export async function stampChildRowStatuses(session, schemaCode, formData, prelo
639
857
  * `skipChildRowIdGate`:审批提交(workItemId/workflowInstanceId)先由
640
858
  * `submit-approval-child-rows` 统一拒——无 id 子行的 `child-rows-missing-id`
641
859
  * 教学会让调用方补 `rowStatus:"Added"`,然后再撞审批门(真机两道门互相打架)。
642
- * `assignChildSortKeys`:仅新建记录(save/submit)补 1..n,见 stampChildSortKeys。
860
+ * `assignChildSortKeys`:仅新建记录(save/submit)补 0..n-1,见 stampChildSortKeys。
643
861
  */
862
+ export function assertRuntimeFormShapeGate(loaded, formData, opts) {
863
+ assertRuntimeFieldValueShapes(loaded.meta, formData, loaded.childCodes, {
864
+ schemaCode: opts.schemaCode,
865
+ isUpdate: opts.isUpdate && opts.skipChildRowIdGate !== true,
866
+ });
867
+ }
644
868
  export async function prepareRuntimeFormData(session, schemaCode, formData, opts) {
645
869
  const loaded = await loadPublishedFieldMeta(session, schemaCode);
646
870
  if (loaded)
647
- assertRuntimeFieldValueShapes(loaded.meta, formData, loaded.childCodes, {
648
- schemaCode,
649
- isUpdate: opts.isUpdate && opts.skipChildRowIdGate !== true,
650
- });
871
+ assertRuntimeFormShapeGate(loaded, formData, { ...opts, schemaCode });
651
872
  const stamped = await stampChildRowStatuses(session, schemaCode, formData, loaded);
652
873
  const withSortKeys = opts.assignChildSortKeys === true ? stampChildSortKeys(stamped.formData, stamped.childCodes) : stamped.formData;
653
- return { formData: withSortKeys, childCodes: stamped.childCodes, serialNumberCodes: loaded ? [...loaded.meta].filter(([, field]) => field.serialNumber).map(([code]) => code) : [], fieldCodes: loaded ? [...loaded.meta.keys()] : undefined, schemaLoaded: loaded !== null };
654
- }
655
- /**
656
- * Translate a platform DATE options.format into a validator regex. The format
657
- * enum is UPPERCASE (`YYYY-MM-DD HH:mm:ss`), tokenized longest-first; literals
658
- * (`-`, `/`, `:`, space, 年/月/日) are escaped. Unknown formats return null —
659
- * the gate then stays silent rather than guessing.
660
- */
661
- export function dateFormatRegex(format) {
662
- const KNOWN = new Set([
663
- "YYYY", "YYYY-MM", "YYYY/MM", "YYYY-MM-DD", "YYYY/MM/DD",
664
- "YYYY-MM-DD HH:mm", "YYYY/MM/DD HH:mm", "YYYY-MM-DD HH:mm:ss", "YYYY/MM/DD HH:mm:ss",
665
- "YYYY-MM-DD CN-APM", "YYYY/MM/DD CN-APM", "YYYY-MM-DD CN-APM HH:mm", "YYYY/MM/DD CN-APM HH:mm",
666
- "YYYY-MM-DD EN-APM", "YYYY/MM/DD EN-APM", "YYYY-MM-DD EN-APM HH:mm", "YYYY/MM/DD EN-APM HH:mm",
667
- "YYYY年MM月DD日", "YYYY年MM月",
668
- ]);
669
- if (!KNOWN.has(format))
670
- return null;
671
- const pattern = format
672
- .split("CN-APM").join("\u0001")
673
- .split("EN-APM").join("\u0002")
674
- .split("YYYY").join("\\d{4}")
675
- .split("MM").join("\\d{2}")
676
- .split("DD").join("\\d{2}")
677
- .split("HH").join("\\d{2}")
678
- .split("mm").join("\\d{2}")
679
- .split("ss").join("\\d{2}")
680
- .split("\u0001").join("(?:上午|下午)")
681
- .split("\u0002").join("(?:AM|PM)")
682
- .replace(/[-/]/g, (ch) => `\\${ch}`);
683
- return new RegExp(`^${pattern}$`);
874
+ return { formData: withSortKeys, childCodes: stamped.childCodes, serialNumberCodes: loaded ? [...loaded.meta].filter(([, field]) => field.serialNumber).map(([code]) => code) : [], fieldCodes: loaded ? [...loaded.meta.keys()] : undefined, meta: loaded?.meta, schemaLoaded: loaded !== null };
684
875
  }
685
876
  /**
686
877
  * r17 (2026-10-26) live write-shape evidence on 1.1.25 — every case below was
@@ -704,7 +895,7 @@ export function assertRuntimeFieldValueShapes(meta, formData, childCodes, contex
704
895
  const field = meta.get(code);
705
896
  if (!field)
706
897
  continue;
707
- if (field.type === 3 && typeof value === "number") {
898
+ if ((field.type === 3 || field.type === 28) && typeof value === "number") {
708
899
  throw new ToolRefusalError({
709
900
  status: "refused",
710
901
  blocker: "submit-date-shape",
@@ -714,7 +905,7 @@ export function assertRuntimeFieldValueShapes(meta, formData, childCodes, contex
714
905
  `日期必须写成字段 format 对应的字符串(本字段 format=${field.format ?? "未知"}),如 "2026-10-26 11:00:00"。`,
715
906
  });
716
907
  }
717
- if (field.type === 3 && typeof value === "string" && field.format) {
908
+ if ((field.type === 3 || field.type === 28) && typeof value === "string" && field.format) {
718
909
  const re = dateFormatRegex(field.format);
719
910
  if (re && !re.test(value.trim())) {
720
911
  throw new ToolRefusalError({
@@ -723,7 +914,7 @@ export function assertRuntimeFieldValueShapes(meta, formData, childCodes, contex
723
914
  schemaCode: context.schemaCode,
724
915
  field: code,
725
916
  format: field.format,
726
- message: `日期字段 ${code} 的值 "${value}" 不匹配字段声明的 format "${field.format}"——平台直接回 50000 服务异常(r17 真机:仅日期串/ISO8601 带时区都打回)。` +
917
+ message: `${field.type === 28 ? "时间字段" : "日期字段"} ${code} 的值 "${value}" 不匹配字段声明的 format "${field.format}"——平台直接回 50000 服务异常(r17 真机:仅日期串/ISO8601 带时区都打回)。` +
727
918
  `按 format 逐位对齐;改格式走 field.update。`,
728
919
  });
729
920
  }
@@ -150,29 +150,112 @@ export async function resolveWorkflowArgWithFallback(session, args) {
150
150
  }
151
151
  return base;
152
152
  }
153
+ function headerRowsOf(value) {
154
+ if (value === null || value === undefined)
155
+ return [];
156
+ const rows = wireRows(value);
157
+ return rows
158
+ .map((row) => {
159
+ const workflowCode = typeof row.workflowCode === "string" ? row.workflowCode.trim() : "";
160
+ if (!workflowCode)
161
+ return null;
162
+ const published = row.published === true;
163
+ return {
164
+ workflowCode,
165
+ published,
166
+ draft: !published,
167
+ ...(typeof row.workflowName === "string" && row.workflowName.trim() ? { workflowName: row.workflowName } : {}),
168
+ };
169
+ })
170
+ .filter((row) => row !== null);
171
+ }
172
+ /** One header probe per model; only a 404 falls back to the legacy isworkflow path. */
173
+ async function probeWorkflowHeaders(session, schemaCode) {
174
+ try {
175
+ // issue #77.1(复审驳回):**显式**要「全部 header(含草稿)」,不依赖省略默认。
176
+ //
177
+ // 平台证据(8.6.26):
178
+ // - `WorkflowTemplateController.list`(decompiled-full/launcher-8.6.26/
179
+ // cloudpivot-engine-8.6.26/.../app/WorkflowTemplateController.java:842-849)
180
+ // GET /api/api/workflow/list 只声明 `schemaCode`,内部固定
181
+ // `getWorkflowTemplateHeadersBySchemaCode(schemaCode, Boolean.FALSE)`;
182
+ // - `WorkflowTemplateHeaderServiceImpl.getListBySchemaCode`(:97-106)只在
183
+ // `published == null || !published` 时返回全部 header,否则过滤掉草稿。
184
+ // 所以 8.6.26 的 HTTP 面其实没有 published 形参(未知 query 由 Spring 忽略);
185
+ // 这里仍显式带 `published=false`(HTTP query 是字符串,服务端 Boolean 绑定
186
+ // 大小写不敏感),让语义在「未来版本把该标志暴露成 query」时也保持「要全部」,
187
+ // 而不是把 draft 可见性押在省略默认上。
188
+ const result = await wireCall(session, { path: ENDPOINTS.workflowList, query: { schemaCode, published: "false" } });
189
+ const headers = headerRowsOf(result.data);
190
+ return { endpoint: `GET ${ENDPOINTS.workflowList}?schemaCode=&published=false`, headerCount: headers.length, headers };
191
+ }
192
+ catch (error) {
193
+ const absent = error instanceof WireError && error.kind === "http-status" && error.diagnostic?.httpStatus === 404;
194
+ if (!absent)
195
+ throw error;
196
+ }
197
+ // 老版本族没有 /workflow/list:回退 isworkflow→getWorkflow(只认已发布)。
198
+ const hasWorkflow = (await wireCall(session, { path: ENDPOINTS.workflowIsWorkflow, query: { schemaCode } })).data === true;
199
+ const linked = hasWorkflow ? (await wireCall(session, { path: ENDPOINTS.workflowGetBySchema, query: { schemaCode } })).data : null;
200
+ const workflowCode = linked && typeof linked.workflowCode === "string" && linked.workflowCode ? linked.workflowCode : "";
201
+ const linkedPublished = linked !== null && (linked.templateType === "PUBLISH" || linked.published === true);
202
+ const headers = workflowCode ? [{ workflowCode, published: linkedPublished, draft: !linkedPublished }] : [];
203
+ return {
204
+ endpoint: "legacy:isworkflow+getWorkflow",
205
+ headerCount: headers.length,
206
+ headers,
207
+ fallback: `平台没有 ${ENDPOINTS.workflowList}(HTTP 404)——已回退 isworkflow→getWorkflow;草稿流程/多流程可能不可见`,
208
+ };
209
+ }
153
210
  export async function scanModelWorkflowBindings(session, schemaCode) {
154
- const workflowCode = await resolveWorkflowArg(session, { schemaCode });
155
- if (!workflowCode)
211
+ const headerProbe = await probeWorkflowHeaders(session, schemaCode);
212
+ if (headerProbe.headers.length === 0)
156
213
  return null;
157
- let pub;
214
+ const publishedHeaders = headerProbe.headers.filter((header) => header.published);
215
+ const primary = publishedHeaders[0] ?? headerProbe.headers[0];
216
+ const workflowCode = primary.workflowCode;
217
+ let data = null;
158
218
  try {
159
- pub = await wireCall(session, { path: ENDPOINTS.workflowGetPublished, query: { workflowCode } });
219
+ const pub = await wireCall(session, { path: ENDPOINTS.workflowGetPublished, query: { workflowCode } });
220
+ data = (pub.data ?? null);
160
221
  }
161
222
  catch (error) {
162
- if (isWorkflowAbsent(error))
163
- return null;
164
- throw error;
223
+ // 401001 = 缺席信号(草稿未发布/流程刚删):不中断整轮扫描。
224
+ if (!isWorkflowAbsent(error))
225
+ throw error;
165
226
  }
166
- const data = (pub.data ?? null);
167
- const published = data !== null && (data.templateType === "PUBLISH" || data.published === true);
168
- const summary = workflowCompactProjection({ data: pub.data }).workflowSummary;
227
+ const bodyPublished = data !== null && (data.templateType === "PUBLISH" || data.published === true);
228
+ const probeMismatch = publishedHeaders.length > 0 && data === null
229
+ ? {
230
+ code: "published-header-read-empty",
231
+ message: `workflow/list 报 ${publishedHeaders.map((header) => header.workflowCode).join(", ")} 已发布(published:true),但 get_published 读回为空(401001/空载荷)——不静默当成 exists:false;先 workflow.get_published 点查并复核发布态`,
232
+ workflowCodes: publishedHeaders.map((header) => header.workflowCode),
233
+ }
234
+ : publishedHeaders.length > 0 && !bodyPublished
235
+ ? {
236
+ code: "published-header-body-draft",
237
+ message: `workflow/list 报 ${publishedHeaders.map((header) => header.workflowCode).join(", ")} 已发布,但 get_published 正文没有 PUBLISH 标记(templateType/published)——两面不一致,按未发布处理并复核发布态`,
238
+ workflowCodes: publishedHeaders.map((header) => header.workflowCode),
239
+ }
240
+ : undefined;
241
+ const summary = workflowCompactProjection({ data }).workflowSummary;
169
242
  const ruleBindings = summary?.ruleBindings ?? [];
170
243
  const nodeRuleBindings = summary?.nodeRuleBindings ?? [];
171
244
  const systemRuleBindings = summary?.systemRuleBindings ?? [];
172
245
  const ruleBindingCount = ruleBindings.reduce((sum, binding) => sum + binding.ruleCodes.length, 0) +
173
246
  nodeRuleBindings.reduce((sum, binding) => sum + binding.ruleCodes.length, 0) +
174
247
  systemRuleBindings.reduce((sum, binding) => sum + binding.ruleCodes.length, 0);
175
- return { workflowCode, published, ruleBindings, nodeRuleBindings, systemRuleBindings, ruleBindingCount };
248
+ return {
249
+ workflowCode,
250
+ workflowCodes: headerProbe.headers.map((header) => header.workflowCode),
251
+ published: bodyPublished,
252
+ headerProbe,
253
+ ...(probeMismatch !== undefined ? { probeMismatch } : {}),
254
+ ruleBindings,
255
+ nodeRuleBindings,
256
+ systemRuleBindings,
257
+ ruleBindingCount,
258
+ };
176
259
  }
177
260
  export async function getWorkflowHeaderOrNull(session, workflowCode) {
178
261
  try {
@@ -95,19 +95,30 @@ export function registerTemplateReadTools(tools) {
95
95
  // 单模型读失败不中断整轮清单;行级 readFailed 标注,不让一次失败
96
96
  // 变成整面错误(同 participantSearch 的容错口径)。
97
97
  readFailures += 1;
98
- workflows.push({ modelCode, workflowCode: null, exists: null, published: null, ruleBindingCount: null, readFailed: true });
98
+ workflows.push({ modelCode, workflowCode: null, workflowCodes: [], exists: null, published: null, ruleBindingCount: null, readFailed: true });
99
99
  return;
100
100
  }
101
101
  const face = outcome.value;
102
102
  if (face === null) {
103
103
  absentCount += 1;
104
- workflows.push({ modelCode, workflowCode: null, exists: false, published: false, ruleBindingCount: 0 });
104
+ // issue #77.1:absence 来自 header 探测为空。端点在上方 wire.plan 统一
105
+ // 说明;缺席行不带逐行 headerProbe(50 个空模型会把清单推过内联预算)。
106
+ workflows.push({ modelCode, workflowCode: null, workflowCodes: [], exists: false, published: false, ruleBindingCount: 0 });
105
107
  return;
106
108
  }
107
109
  withWorkflow += 1;
108
110
  if (face.published)
109
111
  publishedCount += 1;
110
- workflows.push({ modelCode, workflowCode: face.workflowCode, exists: true, published: face.published, ruleBindingCount: face.ruleBindingCount });
112
+ workflows.push({
113
+ modelCode,
114
+ workflowCode: face.workflowCode,
115
+ workflowCodes: face.workflowCodes,
116
+ headerProbe: face.headerProbe,
117
+ ...(face.probeMismatch !== undefined ? { probeMismatch: face.probeMismatch } : {}),
118
+ exists: true,
119
+ published: face.published,
120
+ ruleBindingCount: face.ruleBindingCount,
121
+ });
111
122
  });
112
123
  const schemaFilter = typeof args.schemaCode === "string" && args.schemaCode.trim() ? args.schemaCode.trim() : undefined;
113
124
  let resultWorkflows = workflows;
@@ -135,6 +146,12 @@ export function registerTemplateReadTools(tools) {
135
146
  readFailures: resultWorkflows.filter((row) => row.readFailed === true).length,
136
147
  };
137
148
  }
149
+ // issue #77.1:截断必须点名「漏了哪些模型」,只给数量无法补救。列表本身
150
+ // 也要有界:窗口很大时只回前 100 个 code(omittedModels 仍是全量计数)。
151
+ const OMITTED_MODEL_CODES_CAP = 100;
152
+ const omittedModelCodesAll = capped ? modelRows.slice(scanRows.length).map((row) => String(row.code)) : [];
153
+ const omittedModelCodes = omittedModelCodesAll.slice(0, OMITTED_MODEL_CODES_CAP);
154
+ const omittedModelCodesTruncated = omittedModelCodesAll.length > OMITTED_MODEL_CODES_CAP;
138
155
  return {
139
156
  applicationResolution: { ...applicationResolutionOf(scope), models: totalModels },
140
157
  modelsCount: totalModels,
@@ -144,20 +161,22 @@ export function registerTemplateReadTools(tools) {
144
161
  publishedCount: counts.publishedCount,
145
162
  absentCount: counts.absentCount,
146
163
  ...(counts.readFailures > 0 ? { readFailures: counts.readFailures } : {}),
147
- workflows: resultWorkflows,
148
- wire: {
149
- plan: "1 应用树 + 每模型 isworkflow(无流程即止,1 wire)→ 有流程再 getWorkflow + get_published(共 3 wire)",
150
- concurrency: scan.stats,
151
- },
152
164
  ...(capped
153
165
  ? {
154
166
  partial: true,
155
167
  omittedModels: totalModels - scanRows.length,
156
- note: `应用 ${scope.code} 共 ${totalModels} 个模型,超过 ${WORKFLOW_LIST_MODEL_CAP} 上限只扫前 ${WORKFLOW_LIST_MODEL_CAP} 个(按应用树序)——本清单不是全集`,
157
- nextCommand: `omc call workflow.get_published --args '{"schemaCode":"<模型code>"}'(点查未扫到的具体模型)`,
168
+ omittedModelCodes,
169
+ ...(omittedModelCodesTruncated ? { omittedModelCodesTruncated: true } : {}),
170
+ note: `应用 ${scope.code} 共 ${totalModels} 个模型,超过 ${WORKFLOW_LIST_MODEL_CAP} 上限只扫前 ${WORKFLOW_LIST_MODEL_CAP} 个(按应用树序)——本清单不是全集;omittedModelCodes 是未扫到的模型${omittedModelCodesTruncated ? `(只列前 ${OMITTED_MODEL_CODES_CAP} 个)` : ""},逐个用 workflow.get_published 点查`,
171
+ nextCommand: `omc call workflow.get_published --args '{"schemaCode":"${omittedModelCodes[0] ?? "<模型code>"}"}'(点查 omittedModelCodes 里的模型)`,
158
172
  }
159
173
  : {}),
160
- indexNote: "平台没有流程模板清单端点;本面以模型为索引(流程-模型一对一惯例,workflowCode 通常是 <模型code>_flow,以逐模型解析结果为准)——不在任何模型名下的流程不在本清单内",
174
+ workflows: resultWorkflows,
175
+ wire: {
176
+ plan: "1 应用树 + 每模型 workflow/list(一次拿 header:多流程/草稿 published 标记,1 wire)→ 有流程再 get_published(共 2 wire;workflow/list 404 的老版本族回退 isworkflow→getWorkflow)",
177
+ concurrency: scan.stats,
178
+ },
179
+ indexNote: "平台没有流程模板清单端点(无应用级清单,也没有 orphanWorkflows 面):本面以模型为索引、按 schemaCode 绑定——一个模型可挂多个流程(workflowCodes 全列),不属于任何模型的流程无法枚举;行内有 headerProbe,published header 与 get_published 正文不一致时另有 probeMismatch",
161
180
  };
162
181
  }, {
163
182
  target: `workflow.list:${args.applicationCode ?? "*"}`,
@@ -200,7 +200,7 @@ export const WORKFLOW_LANE_CONTRACT = Object.freeze({
200
200
  // markdown,首位必须是 workflow.get_draft 的 WORKFLOW_SCOPE)。
201
201
  "workflow.list": Object.freeze({
202
202
  scope: "application workflow inventory (model-indexed)",
203
- description: "应用内流程清单。平台**没有**流程模板清单端点——本面以模型为索引(workflowCode 通常为 `<模型code>_flow`,以逐模型解析为准):应用树取模型 → 逐模型解析流程(isworkflow→getWorkflow)→ 读 get_published 摘要。可选 `schemaCode` 客户端过滤(不伪造平台过滤;缺失回 workflow-list-model-not-found)。行 `{modelCode,workflowCode,exists,published,ruleBindingCount}`;无流程的模型如实列 exists:false(不是错误),ruleBindingCount 含 flow 级 handler 与节点级事件绑定的规则码总数。上限 50 模型:超出回 partial + omittedModels,点查用 workflow.get_published {schemaCode}。查某条规则被哪些流程绑定用 rule.references kind=rule。",
203
+ description: "应用内流程清单。平台**没有**流程模板清单端点——本面以模型为索引、按 schemaCode 绑定(多流程全列 workflowCodes):应用树取模型 → 每模型 workflow/list 探 header → 读 get_published 摘要。可选 `schemaCode` 客户端过滤(不伪造平台过滤;缺失回 workflow-list-model-not-found)。行 `{modelCode,workflowCode,workflowCodes,headerProbe,exists,published,ruleBindingCount}`;无流程模型如实列 exists:false;header 报已发布而正文空/草稿时行内 `probeMismatch`。ruleBindingCount 含 flow 级与节点级事件绑定的规则码总数。上限 50 模型:超出回 partial + omittedModels + omittedModelCodes,点查 workflow.get_published {schemaCode}。查规则绑定用 rule.references kind=rule。",
204
204
  }),
205
205
  "workflow.create": Object.freeze({
206
206
  scope: WORKFLOW_SCOPE,