@stalfh233/omc-cli 0.8.36 → 0.8.38

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,
@@ -548,8 +551,9 @@ export async function runtimeDataWarnings(session, schemaCode, sheetCode, formDa
548
551
  warnings.push({ code: "required-empty", row, fieldCode: field, message: `字段 ${field} 声明必填但本行为空;平台照存,OMC 仅提示` });
549
552
  }
550
553
  const options = parseOptions(meta.options);
551
- const optionSet = options.optionsSet && typeof options.optionsSet === "object" ? options.optionsSet : {};
552
- const choiceCodes = choiceCodesFromFieldOptions(meta, options);
554
+ // 写面存的是选项 *value*(custom = optionsSet.custom[].value,字典 = name),
555
+ // 不是 code;用 code 集校验 custom 单选会整片误报(issue #100)。
556
+ const choiceCodes = choiceValuesFromFieldOptions(meta, options);
553
557
  if (choiceCodes.length > 0 && value !== null && value !== undefined && value !== "") {
554
558
  const allowed = new Set(choiceCodes);
555
559
  const values = Array.isArray(value) ? value : [value];
@@ -673,7 +677,7 @@ export async function loadPublishedFieldMeta(session, schemaCode) {
673
677
  }
674
678
  const options = parseOptions(row.options);
675
679
  serialNumber = serialNumber || options.formPropertyType === 100 || (Array.isArray(options.seqNoSetting) && options.seqNoSetting.length > 0);
676
- 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 } : {}) });
677
681
  if (type === CHILD_TABLE_PROPERTY_TYPE)
678
682
  childCodes.push(code);
679
683
  }
@@ -690,7 +694,8 @@ export async function loadPublishedFieldMeta(session, schemaCode) {
690
694
  * 同序),而表单运行时保存路径不补 sortKey(`BizObjectInsertModel`/`BizObjectUpdateItem`
691
695
  * 无 sortKey 写入;补值只存在于导入合并 `IntegrationMergerUtils:34-37`、规则
692
696
  * `CreateServiceExecutor:166`/`BizObjectUtil:131`、流程结束 `EndActivityRuntime:277-278`)。
693
- * 所以新建保存/提交时,缺 sortKey 的子行按数组下标补 1..n;调用方显式值原样保留。
697
+ * 所以新建保存/提交时,缺 sortKey 的子行按数组下标补 **0..n-1**(与平台规则
698
+ * 创建/导入的 0 基一致,issue #106);调用方显式值原样保留。
694
699
  * 更新既有记录不补(既有行可能已有 sortKey,猜起点会撞号)。
695
700
  */
696
701
  export function stampChildSortKeys(formData, childCodes) {
@@ -710,7 +715,7 @@ export function stampChildSortKeys(formData, childCodes) {
710
715
  if (typeof row.rowStatus === "string" && row.rowStatus.trim().toLowerCase() === "deleted")
711
716
  return row;
712
717
  mutated = true;
713
- return { ...row, sortKey: index + 1 };
718
+ return { ...row, sortKey: index };
714
719
  });
715
720
  if (mutated) {
716
721
  next[code] = stamped;
@@ -719,6 +724,110 @@ export function stampChildSortKeys(formData, childCodes) {
719
724
  }
720
725
  return changed ? next : formData;
721
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): 8.6 mirrors every RADIO(12)/DROPDOWN(14) value into
778
+ * a `<field>_key` companion column through
779
+ * `OptionKeySupportImpl.getValueKeyMap` (8.6.26 :164-183). 2.1.5 live (w53,
780
+ * 2026-12-05) does NOT recompute that key on a Facade write — a supplied wrong
781
+ * key is persisted as-is (save readback + data.load both returned the wrong
782
+ * key). OMC never writes the companion key; it only tells the caller when a
783
+ * hand-built payload has a value without one (or a key that disagrees with the
784
+ * readable snapshot).
785
+ */
786
+ export function optionKeyWarnings(meta, formData, row = 1) {
787
+ if (!meta)
788
+ return [];
789
+ const warnings = [];
790
+ for (const [code, field] of meta) {
791
+ if (field.type !== 12 && field.type !== 14)
792
+ continue;
793
+ const value = formData[code];
794
+ if (value === null || value === undefined || value === "" || Array.isArray(value) || typeof value === "object")
795
+ continue;
796
+ const keyCode = `${code}_key`;
797
+ const suppliedKey = formData[keyCode];
798
+ const map = optionValueKeyMap({ options: field.options ?? {} });
799
+ const suggested = map.byValue.get(String(value));
800
+ const hasKey = !(suppliedKey === null || suppliedKey === undefined || String(suppliedKey).trim() === "");
801
+ if (!hasKey) {
802
+ warnings.push({
803
+ code: "optionKeyMissing",
804
+ row,
805
+ fieldCode: code,
806
+ keyField: keyCode,
807
+ value: String(value),
808
+ optionSource: map.source,
809
+ ...(suggested !== undefined ? { suggestedKey: suggested } : {}),
810
+ message: `字段 ${code} 传了值 "${String(value)}" 但没有伴生键 ${keyCode}。平台写面会按选项集反推并补写该键(OptionKeySupportImpl);` +
811
+ `本工具**不代写**。${suggested !== undefined ? `按当前${map.source === "snapshot" ? "字典快照" : "自定义选项"}可推出 ${keyCode}="${suggested}",需要就显式带上。` : map.source === "unresolved" ? `选项来源(businessModel)无法离线解析,本次给不出建议键。` : ""}`.trim(),
812
+ });
813
+ continue;
814
+ }
815
+ if (suggested !== undefined && String(suppliedKey).trim() !== suggested) {
816
+ warnings.push({
817
+ code: "optionKeyMismatch",
818
+ row,
819
+ fieldCode: code,
820
+ keyField: keyCode,
821
+ value: String(value),
822
+ suppliedKey: String(suppliedKey),
823
+ expectedKey: suggested,
824
+ optionSource: map.source,
825
+ message: `字段 ${code} 的值 "${String(value)}" 与伴生键 ${keyCode} 不匹配:按${map.source === "snapshot" ? "字典快照" : "自定义选项"}推导应为 "${suggested}",实际传了 "${String(suppliedKey)}"。8.6 平台保存时可能重算该键;2.1.5 实测走 Facade 直接写入时不会自动重算,会保留传入的错误 key(2.1.7 待采样)。请显式写正确的 ${keyCode},不要依赖平台补偿。`,
826
+ });
827
+ }
828
+ }
829
+ return warnings;
830
+ }
722
831
  export async function stampChildRowStatuses(session, schemaCode, formData, preloaded) {
723
832
  const loaded = preloaded !== undefined ? preloaded : await loadPublishedFieldMeta(session, schemaCode);
724
833
  if (!loaded || loaded.childCodes.length === 0)
@@ -751,48 +860,21 @@ export async function stampChildRowStatuses(session, schemaCode, formData, prelo
751
860
  * `skipChildRowIdGate`:审批提交(workItemId/workflowInstanceId)先由
752
861
  * `submit-approval-child-rows` 统一拒——无 id 子行的 `child-rows-missing-id`
753
862
  * 教学会让调用方补 `rowStatus:"Added"`,然后再撞审批门(真机两道门互相打架)。
754
- * `assignChildSortKeys`:仅新建记录(save/submit)补 1..n,见 stampChildSortKeys。
863
+ * `assignChildSortKeys`:仅新建记录(save/submit)补 0..n-1,见 stampChildSortKeys。
755
864
  */
865
+ export function assertRuntimeFormShapeGate(loaded, formData, opts) {
866
+ assertRuntimeFieldValueShapes(loaded.meta, formData, loaded.childCodes, {
867
+ schemaCode: opts.schemaCode,
868
+ isUpdate: opts.isUpdate && opts.skipChildRowIdGate !== true,
869
+ });
870
+ }
756
871
  export async function prepareRuntimeFormData(session, schemaCode, formData, opts) {
757
872
  const loaded = await loadPublishedFieldMeta(session, schemaCode);
758
873
  if (loaded)
759
- assertRuntimeFieldValueShapes(loaded.meta, formData, loaded.childCodes, {
760
- schemaCode,
761
- isUpdate: opts.isUpdate && opts.skipChildRowIdGate !== true,
762
- });
874
+ assertRuntimeFormShapeGate(loaded, formData, { ...opts, schemaCode });
763
875
  const stamped = await stampChildRowStatuses(session, schemaCode, formData, loaded);
764
876
  const withSortKeys = opts.assignChildSortKeys === true ? stampChildSortKeys(stamped.formData, stamped.childCodes) : stamped.formData;
765
- 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 };
766
- }
767
- /**
768
- * Translate a platform DATE options.format into a validator regex. The format
769
- * enum is UPPERCASE (`YYYY-MM-DD HH:mm:ss`), tokenized longest-first; literals
770
- * (`-`, `/`, `:`, space, 年/月/日) are escaped. Unknown formats return null —
771
- * the gate then stays silent rather than guessing.
772
- */
773
- export function dateFormatRegex(format) {
774
- const KNOWN = new Set([
775
- "YYYY", "YYYY-MM", "YYYY/MM", "YYYY-MM-DD", "YYYY/MM/DD",
776
- "YYYY-MM-DD HH:mm", "YYYY/MM/DD HH:mm", "YYYY-MM-DD HH:mm:ss", "YYYY/MM/DD HH:mm:ss",
777
- "YYYY-MM-DD CN-APM", "YYYY/MM/DD CN-APM", "YYYY-MM-DD CN-APM HH:mm", "YYYY/MM/DD CN-APM HH:mm",
778
- "YYYY-MM-DD EN-APM", "YYYY/MM/DD EN-APM", "YYYY-MM-DD EN-APM HH:mm", "YYYY/MM/DD EN-APM HH:mm",
779
- "YYYY年MM月DD日", "YYYY年MM月",
780
- ]);
781
- if (!KNOWN.has(format))
782
- return null;
783
- const pattern = format
784
- .split("CN-APM").join("\u0001")
785
- .split("EN-APM").join("\u0002")
786
- .split("YYYY").join("\\d{4}")
787
- .split("MM").join("\\d{2}")
788
- .split("DD").join("\\d{2}")
789
- .split("HH").join("\\d{2}")
790
- .split("mm").join("\\d{2}")
791
- .split("ss").join("\\d{2}")
792
- .split("\u0001").join("(?:上午|下午)")
793
- .split("\u0002").join("(?:AM|PM)")
794
- .replace(/[-/]/g, (ch) => `\\${ch}`);
795
- return new RegExp(`^${pattern}$`);
877
+ 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 };
796
878
  }
797
879
  /**
798
880
  * r17 (2026-10-26) live write-shape evidence on 1.1.25 — every case below was
@@ -816,7 +898,7 @@ export function assertRuntimeFieldValueShapes(meta, formData, childCodes, contex
816
898
  const field = meta.get(code);
817
899
  if (!field)
818
900
  continue;
819
- if (field.type === 3 && typeof value === "number") {
901
+ if ((field.type === 3 || field.type === 28) && typeof value === "number") {
820
902
  throw new ToolRefusalError({
821
903
  status: "refused",
822
904
  blocker: "submit-date-shape",
@@ -826,7 +908,7 @@ export function assertRuntimeFieldValueShapes(meta, formData, childCodes, contex
826
908
  `日期必须写成字段 format 对应的字符串(本字段 format=${field.format ?? "未知"}),如 "2026-10-26 11:00:00"。`,
827
909
  });
828
910
  }
829
- if (field.type === 3 && typeof value === "string" && field.format) {
911
+ if ((field.type === 3 || field.type === 28) && typeof value === "string" && field.format) {
830
912
  const re = dateFormatRegex(field.format);
831
913
  if (re && !re.test(value.trim())) {
832
914
  throw new ToolRefusalError({
@@ -835,7 +917,7 @@ export function assertRuntimeFieldValueShapes(meta, formData, childCodes, contex
835
917
  schemaCode: context.schemaCode,
836
918
  field: code,
837
919
  format: field.format,
838
- message: `日期字段 ${code} 的值 "${value}" 不匹配字段声明的 format "${field.format}"——平台直接回 50000 服务异常(r17 真机:仅日期串/ISO8601 带时区都打回)。` +
920
+ message: `${field.type === 28 ? "时间字段" : "日期字段"} ${code} 的值 "${value}" 不匹配字段声明的 format "${field.format}"——平台直接回 50000 服务异常(r17 真机:仅日期串/ISO8601 带时区都打回)。` +
839
921
  `按 format 逐位对齐;改格式走 field.update。`,
840
922
  });
841
923
  }
@@ -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,
@@ -82,6 +82,9 @@ const ALWAYS_INLINE_KEYS = new Map([
82
82
  // 为什么)。≤2KB 原样内联;更大的失败清单仍在 artifact 里。
83
83
  ["failed", 2000],
84
84
  ["failures", 2000],
85
+ // #77.2:withDraft 的「app 面会补建 7 条预置」披露是教学键——compact 折叠
86
+ // 成 {length,sha256,omitted} 后,调用方看不到自己多出来的预置行是怎么来的。
87
+ ["draftNote", 1200],
85
88
  ]);
86
89
  /** Config-inventory keys that compact to a code list (not a bare count). */
87
90
  const CODE_LIST_KEYS = new Set(["fields", "columns", "conditions", "sorts", "datarules", "buttons", "views", "sheets"]);
@@ -205,6 +208,20 @@ function slimRuleRow(rule) {
205
208
  name: typeof rule.name === "string" ? rule.name : null,
206
209
  ...(rule.enabled !== undefined ? { enabled: rule.enabled } : {}),
207
210
  ...(rule.defaultRule !== undefined ? { defaultRule: rule.defaultRule } : {}),
211
+ // #77.3:`rule.list --withDraft` 的判定面(publishEnabled/draftEnabled/
212
+ // draftStatus/executable/executableBasis)是显式开关的唯一答案——compact
213
+ // 若把它瘦身掉,开了 withDraft 反而看不到可执行性(默认行没有这些键,
214
+ // 投影逐字节不变)。
215
+ ...(rule.executable !== undefined
216
+ ? {
217
+ publishEnabled: rule.publishEnabled ?? null,
218
+ draftEnabled: rule.draftEnabled ?? null,
219
+ draftStatus: rule.draftStatus ?? null,
220
+ executable: rule.executable,
221
+ ...(rule.executableBasis !== undefined ? { executableBasis: rule.executableBasis } : {}),
222
+ ...(rule.draftOnly === true ? { draftOnly: true } : {}),
223
+ }
224
+ : {}),
208
225
  // r83:rule.list --withMappings 的映射摘要随行保留(否则 >2048B 的常见
209
226
  // 7 条预置规则会「开了 withMappings 却在默认面看不到映射」)。
210
227
  ...(Array.isArray(rule.mappings) ? { mappings: rule.mappings } : {}),
@@ -154,8 +154,8 @@ const READ_SHAPES = {
154
154
  // artifact get --shape 先看骨架再 --jq)。published/draft 两面同形,仅 templateType
155
155
  // 与 published 键不同。
156
156
  "workflow.list": {
157
- keys: ["applicationResolution", "modelsCount", "scannedModels", "filteredBy?{schemaCode}", "filteredModelScanned?", "filteredModelNote?", "withWorkflow", "publishedCount", "absentCount", "workflows:array<{modelCode,workflowCode,exists,published,ruleBindingCount,readFailed?}>", "wire", "partial?", "omittedModels?", "nextCommand?", "indexNote", "environmentFingerprint"],
158
- notes: ["无流程的模型 workflowCode:null + exists:false(不是错误);平台无流程清单端点,本面按模型索引(流程-模型一对一惯例,workflowCode 常为 <模型code>_flow)", "ruleBindingCount = flow 级 handler + 节点级事件 + SYSTEM_ACTIVITY 顶层绑定的规则码总数(比 get_published 摘要里的同名键多算节点级)", "schemaCode 是**客户端过滤**(先按应用扫描再过滤该模型,不伪造平台过滤);模型不在应用内 → workflow-list-model-not-found + availableModels"],
157
+ keys: ["applicationResolution", "modelsCount", "scannedModels", "filteredBy?{schemaCode}", "filteredModelScanned?", "filteredModelNote?", "withWorkflow", "publishedCount", "absentCount", "workflows:array<{modelCode,workflowCode,workflowCodes,headerProbe,probeMismatch?,exists,published,ruleBindingCount,readFailed?}>", "wire", "partial?", "omittedModels?", "omittedModelCodes?", "omittedModelCodesTruncated?", "nextCommand?", "indexNote", "environmentFingerprint"],
158
+ notes: ["无流程的模型 workflowCode:null + exists:false(不是错误);平台无应用级流程清单端点,本面按 schemaCode 绑定、一个模型可挂多个流程(workflowCodes 全列,headerProbe 如实回 header)", "ruleBindingCount = flow 级 handler + 节点级事件 + SYSTEM_ACTIVITY 顶层绑定的规则码总数(比 get_published 摘要里的同名键多算节点级)", "schemaCode 是**客户端过滤**(先按应用扫描再过滤该模型,不伪造平台过滤);模型不在应用内 → workflow-list-model-not-found + availableModels"],
159
159
  },
160
160
  "workflow.get_published": {
161
161
  // A2 locator:模板摘要 activities[].code ↔ 实例/待办 activityCode(Activity.java:26-30
@@ -178,10 +178,11 @@ const READ_SHAPES = {
178
178
  ],
179
179
  },
180
180
  "rule.list": {
181
- keys: ["rules:array<{code,name,enabled,status,ruleVersion,defaultRule,preset,mappings?,mappingsUnavailable?}>", "rulesCount", "modelPresent", "source", "executableHint", "mappingsWireNote?", "schemaCodes?/modelsCount?/models?:array<每模型同单模型回执>/partial?/failed?:array<{schemaCode,code,message}>/absentModels?"],
181
+ keys: ["rules:array<{code,name,enabled,status,ruleVersion,defaultRule,preset,mappings?,mappingsUnavailable?,publishEnabled?,draftEnabled?,draftStatus?,executable?,executableBasis?,draftOnly?}>", "rulesCount", "modelPresent", "source", "executableHint", "draftFace?/draftRowsCount?/draftNote?", "mappingsWireNote?", "schemaCodes?/modelsCount?/models?/partial?/failed?/absentModels?"],
182
182
  notes: [
183
183
  "入参/他面叫 ruleCode,本面返回 rules[].code",
184
184
  "source=published-list:enabled/status 来自 PUBLISH 投影;可执行性看 rule.get / rule.enable.verified",
185
+ "withDraft:true 追加 app DRAFT 面(+1 wire,规则<7 时平台可能补建 7 条预置;回执 draftNote 披露):逐行 publishEnabled/draftEnabled/draftStatus/executable/executableBasis,并补入 PUBLISH 清单看不到的禁用/草稿行(draftOnly:true,enabled/status 为 null)。executable 按平台 getExecutableBySchemaCodeAndCode:DEFAULT 需 DRAFT enabled=true、status!=DISABLED、至少 1 条 latestPublished;CODING/DECISION 只要求 DRAFT 存在",
185
186
  "modelPresent:false 时未发 list(避免幻影 schema 补建 7 条预置)",
186
187
  "withMappings:true 时每行带 mappings[]={nodeCode,serviceCode,serviceMethodCode,inputCount,outputCount}(摘要,正文 inputMappings/outputMappings 用 rule.get);行里读不到图 → mappingsUnavailable:true(≠没有映射)",
187
188
  "schemaCodes[] 跨模型清单:models[] 每元素与单模型回执同形(含 modelPresent:false/rulesCount;三句提示抬到顶层 crossModelNotes,逐模型相同不重复),失败汇总在 failed[](partial:true);上限 20 个模型",
package/dist/read.js CHANGED
@@ -2,7 +2,7 @@ import { assertWithinCoverage } from "./coverage.js";
2
2
  import { wireErrorKind, isUncertainWireError, refusalFromCoverage, sha256, writeArtifact } from "./support.js";
3
3
  import { READ_FULL_INLINE_CEILING_BYTES, omittedScalarKeys, passthroughScalars, projectReadResult, projectReadSemantics, } from "./read-projection.js";
4
4
  import { plannableArgsRaw } from "./plan.js";
5
- import { WireError } from "./wire.js";
5
+ import { WireError, PLATFORM_API_UP_ROUTE_NOT_FOUND, PLATFORM_API_DOWN } from "./wire.js";
6
6
  import { describeWireFailure, isRetryableTransportKind } from "./wire-failure.js";
7
7
  /**
8
8
  * B3(0.8.4,2026-11-25 真机):幂等读的有界重试。
@@ -210,6 +210,14 @@ export async function governedRead(ctx, tool, args, execute, options = {}) {
210
210
  // 端点、尝试次数、失败分类、可执行回退都在这里(判定不变)。
211
211
  attempts: Math.max(1, attempts),
212
212
  ...transportDiagnostics(tool.name, error, sessionRef?.environmentName ?? args.environment, Math.max(0, attempts - 1), facts),
213
+ // issue #77.6:网关 HTML 404 的判定子类(healthz 探测结果)随回执带出,
214
+ // 调用方据此区分「平台在线但路由没到」与「平台不可用」。
215
+ ...(error instanceof WireError && error.diagnostic?.health !== undefined
216
+ ? {
217
+ healthProbe: error.diagnostic.health,
218
+ gateway404Class: error.diagnostic.health.up ? PLATFORM_API_UP_ROUTE_NOT_FOUND : PLATFORM_API_DOWN,
219
+ }
220
+ : {}),
213
221
  // issue 2026-11 F5:传输失败时把「到底打的是哪台」一起回出来——真机会话里
214
222
  // env list 是 cwd 作用域,agent 静默落到全局 default 的另一台主机,只看
215
223
  // detail 无从判断。configRoot/项目根用 `omc env list` 复核。
@@ -11,7 +11,7 @@ const workflowSave = Object.freeze({
11
11
  preconditions: ["模型默认表单/字段和 workflow 已发布;应用可用;formData 不带已存在 id"],
12
12
  conditionalRequirements: [
13
13
  "workflow draft-save 总是 INSERT;不要把已存在记录 id 放进 formData",
14
- "子表新建行缺 sortKey 时工具按数组下标补 1..n(平台读回固定 sortKey ASC;更新既有记录请显式带 sortKey)",
14
+ "子表新建行缺 sortKey 时工具按数组下标补 0..n-1(平台读回固定 sortKey ASC;更新既有记录请显式带 sortKey)",
15
15
  "关联字段(WORK_SHEET)在 formData 里写 `\"<relationField>\":\"<bizObjectId>\"`(`{id}` 也接受;读回是 `{schemaCode,id,displayCode}`);子表行内关联列同理。人员/组织字段写数组 `[{id,type,name}]`。",
16
16
  "**50000 疑应用未发布**:某些环境里模型所在应用未发布时运行时写稳定 50000(工具反推拒 app-not-published;同调用在已发布应用成功);非普遍规律——另有一类环境未发布也能写(2026-09-19 实测,案卷 docs/issues/omc-cli-findings-2026-09-19.md B17)。遇 50000 先只读核对,别仅凭「应用未发布」放弃运行时验证。",
17
17
  ],
@@ -90,7 +90,7 @@ const workflowSubmit = Object.freeze({
90
90
  conditionalRequirements: [
91
91
  "workItemId 或 workflowInstanceId 出现时必须传 bizObjectId;身份只能复制 data.save 的 authoritative readback",
92
92
  "**审批提交(workItemId/workflowInstanceId)只传主表字段**:formData 里不要带子表数组——平台按「追加行」再插一份(真机 2→6 行),CLI 默认拒 `submit-approval-child-rows`。子表数组只在保存/首次提交时带;确要在审批中追加子行才显式传 allowChildRowAppend:true",
93
- "子表读回顺序按 sortKey ASC(平台固定排序):**新建**保存/提交时 CLI 会给缺 sortKey 的子行按数组下标补 1..n(显式值保留);更新既有记录请显式带 sortKey,否则 null 排序不保证",
93
+ "子表读回顺序按 sortKey ASC(平台固定排序):**新建**保存/提交时 CLI 会给缺 sortKey 的子行按数组下标补 0..n-1(显式值保留);更新既有记录请显式带 sortKey,否则 null 排序不保证",
94
94
  "节点字段权限(editable/visible)只是门户读面膜:REST 提交/普通更新都不校验(回执 nodeFieldPermissionNote)",
95
95
  ],
96
96
  priorToolReferences: [
@@ -159,7 +159,7 @@ const childRowsUpsert = Object.freeze({
159
159
  refusalRecovery: [
160
160
  { code: "child-rows-missing-id", action: "无 id 的行补 id 或改 rowStatus:Added" },
161
161
  ],
162
- notes: "data.save 新建时子行可不带 id(工具 stamp Added,并按数组下标补缺省 sortKey 1..n);本配方指 update/既有记录——更新既有行请显式带 sortKey(平台读回按 sortKey ASC,null 顺序不保证)",
162
+ notes: "data.save 新建时子行可不带 id(工具 stamp Added,并按数组下标补缺省 sortKey 0..n-1);本配方指 update/既有记录——更新既有行请显式带 sortKey(平台读回按 sortKey ASC,null 顺序不保证)",
163
163
  requiresEnvironmentDerivedIds: true,
164
164
  });
165
165
  const dataDeleteSweep = Object.freeze({