@stalfh233/omc-cli 0.8.7 → 0.8.8

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.
@@ -39,6 +39,41 @@ export function propagateRelationOptions(attributesJson, fields) {
39
39
  return JSON.stringify(attributes);
40
40
  }
41
41
  export const propagateRelationMappings = propagateRelationOptions;
42
+ /**
43
+ * The platform stores a form with NO custom HTML in one of several "empty"
44
+ * shapes, not just `undefined`:
45
+ * - `""` — the legacy designer's initial value (frontend-dist/admin/js/12404:
46
+ * `publishedHtmlJson:""` in the new-sheet default object);
47
+ * - `"{}"` — what a live 2.1.5 form returned from `form.get` for a published
48
+ * default form (0.8.7 real-machine probe C/F2);
49
+ * - `"[]"` — the designer's Save-cleared draft (Ticket 74) and the fake
50
+ * platform's publish default.
51
+ * The runtime renderer treats all of them as "no custom html": it parses and
52
+ * then guards `if (s && s.length > 0)` (frontend-dist/admin/js/19497,
53
+ * template.ebdab9f4, mobile/js/60404) — `{}` has no `.length`, so the block is
54
+ * skipped without touching `element.tagName`. Reporting them as a render
55
+ * violation was a false alarm: the published form renders fine.
56
+ */
57
+ function isEmptyHtmlShape(trimmed) {
58
+ if (trimmed === "" || trimmed === "[]" || trimmed === "{}")
59
+ return true;
60
+ try {
61
+ const parsed = JSON.parse(trimmed);
62
+ if (Array.isArray(parsed))
63
+ return parsed.length === 0;
64
+ return parsed !== null && typeof parsed === "object" && !Array.isArray(parsed) && Object.keys(parsed).length === 0;
65
+ }
66
+ catch {
67
+ return false;
68
+ }
69
+ }
70
+ function jsonTopLevelType(value) {
71
+ if (value === null)
72
+ return "null";
73
+ if (Array.isArray(value))
74
+ return "array";
75
+ return typeof value;
76
+ }
42
77
  /**
43
78
  * Parse-only JavaScript check for a `<script>` element body.
44
79
  *
@@ -68,18 +103,23 @@ function scriptSyntaxProblem(source) {
68
103
  export function validateHtmlRender(value, requirePlatformSkeleton = false) {
69
104
  if (value === undefined || value === null)
70
105
  return { ok: true, skipped: true };
71
- if (typeof value !== "string" || value.trim() === "") {
72
- return { ok: false, violations: [{ index: -1, problem: "html must be a non-empty JSON element array" }] };
106
+ if (typeof value !== "string") {
107
+ return { ok: false, violations: [{ index: -1, path: "html", problem: `html must be a JSON element array; got ${jsonTopLevelType(value)}` }] };
73
108
  }
109
+ const trimmed = value.trim();
110
+ // No custom HTML: `""` / `"{}"` / `"[]"` (and their parse-equivalents) are
111
+ // platform defaults, not a broken published form.
112
+ if (isEmptyHtmlShape(trimmed))
113
+ return { ok: true, skipped: true };
74
114
  let parsed;
75
115
  try {
76
- parsed = JSON.parse(value);
116
+ parsed = JSON.parse(trimmed);
77
117
  }
78
118
  catch {
79
- return { ok: false, violations: [{ index: -1, problem: "html must be valid JSON" }] };
119
+ return { ok: false, violations: [{ index: -1, path: "html", problem: "html must be valid JSON" }] };
80
120
  }
81
- if (!Array.isArray(parsed) || parsed.length === 0) {
82
- return { ok: false, violations: [{ index: -1, problem: "html must be a non-empty JSON element array" }] };
121
+ if (!Array.isArray(parsed)) {
122
+ return { ok: false, violations: [{ index: -1, path: "html", problem: `html must be a JSON element array; got ${jsonTopLevelType(parsed)}` }] };
83
123
  }
84
124
  const violations = [];
85
125
  const ids = new Set();
@@ -267,7 +267,7 @@ export const FIELD_LANE_CONTRACT = Object.freeze({
267
267
  controlEmissionPolicy: "ticket 101: controls PHONE(24)/PHOTO(10) are blocked for creation (no BizPropertyType maps to them — BizPropertyType.java:27-54); Tab(500) is a layout container (DataModelInitUtils.java:61-75 recurses panels, never a field); CreatedDeptId(102) is a system-field projection (DefaultPropertyType.java:18-21 → DEPARTMENT_SELECTOR 60, BizMainSystemPropertyRegistry.java:88-101); the scaffold SKIPS any field type without a control mapping — unknown/blocked control types are never auto-created (fail-closed)",
268
268
  fieldRowDefaultPolicy: "ticket 108 determination (live 8.6.26 write+read 2026-09-15 + fwb 8.6.39 readback): the 2026-09-14 key unions are MULTI-FIELD UNIONS of designer rows, not per-field required keys — the platform accepts-and-persists minimal rows, so the minimal default + caller passthrough is the INTENTIONAL boundary. Selection families 12/13/14/15 MUST-FIXED to omit dictionaryData (designer rows carry none; live proves the platform merely accepts the extra key — omc_mcp_t108dd readback carried it only because we sent it). Families 0/1/2/9/11/17 keep the designer-carried {dictionaryData:\"\"}; DATE(3) keeps required format (BizObjectFacadeImpl.java:2949); ATTACHMENT(6) stays intentionally empty (system rows often have no options)",
269
269
  orgSelectorFieldRowOptions: "org-selector families STAFF_SELECTOR / STAFF_MULTI_SELECTOR / DEPARTMENT_SELECTOR / DEPARTMENT_MULTI_SELECTOR (5/50/51/60/61): the field-row options are a publish-safe shape observed on the yst/fwb publish face (2656 rows) — null or {defaultValue, mappings, virtualField[, noRepeat]}; single-select defaultValue \"\" and multi-select []; deptVisible/multi are FORM-CONTROL discriminator keys (read from control.options via disposeUpdateType/updateSelectionType) and never appear on the field row",
270
- relationMappingsSource: "the field row's options.mappings is the source of truth for relation carry-through; editing a form control's mappings is recomputed from the field and does not survive readback (live 2026-10-14 中冶). Update chain: field.update with the full options (change only mappings, keep queryCode/displayField/schemaCode/conditions… as-is) → field.publish → form.draft rebuild:false (keeps the existing layout and any online JS) → form.publish → readback. Do NOT use cascadeRepublish on a form that already carries a custom layout or online JS — it re-scaffolds the default form",
270
+ relationMappingsSource: "`options.mappings` 形如 `[{source:<关联目标字段/父模型字段>,target:<本模型字段>}]`(裸 code),是关联填充的事实源(字段行,不是表单控件:改控件映射会被重算覆盖,live 2026-10-14 中冶)。Update chain: field.update with the full options (change only mappings, keep queryCode/displayField/schemaCode/conditions… as-is) → field.publish → form.draft rebuild:false (keeps the existing layout and any online JS) → form.publish → readback. Do NOT use cascadeRepublish on a form that already carries a custom layout or online JS — it re-scaffolds the default form. 子表关联列取主表字段的完整配方:`omc describe field.create --example child-map-fill`",
271
271
  propertyEmptyReadback: "propertyEmpty overrides the data-model not-null declaration; false reopens a field the platform previously created wrongly (required/readonly belong to the form and workflow nodes). bizproperty/list rows do NOT carry propertyEmpty, so readback.propertyEmpty appears only when the draft face returns it — the CLI never fabricates it; readback.committed lists what actually went on the wire",
272
272
  listFace: "field.list default face inlines code/name/type(+typeName)/conditions signal/shapeWarning only; the whole choices package is not inlined (a selection field measured ~500B/row) — verify options/subSchema with the code/fields selectors or full:true",
273
273
  }),
@@ -409,21 +409,88 @@ export function decodeButtonScript(input) {
409
409
  * 306103(删除后将无可用视图)。平台要求**每个模型至少保留一个 PC 可见视图和
410
410
  * 一个 MOBILE 可见视图**;该码只在 2.1.5 出现(`ErrorCode.java:383`),8.6.26
411
411
  * 无 306103。导出以便回执文案被测试钉住(PC/MOBILE 各一条 + 正确出路)。
412
+ *
413
+ * `detail.localPrecheck:true` 表示本判定来自**写前本地预检**(零 wire 写入):
414
+ * 平台判据由两族源码合并而来 —— 2.1.5 BizQueryController.delete:215-227
415
+ * (扣掉目标后剩余视图里必须仍有 showOnPc=true 与 showOnMobile=true 各一条,
416
+ * null/false 都算不可见);8.6.26 同方法 :297-311 只禁删**第一行**视图
417
+ * (BIZ_QUERY_DEFAULT 303025)。两者取并集,宁拒绝不误删。
412
418
  */
413
- export function listviewLastVisibleRefusal(schemaCode, code) {
419
+ export function listviewLastVisibleRefusal(schemaCode, code, detail) {
420
+ const local = detail?.localPrecheck === true;
421
+ const reasons = detail?.reasons ?? [];
422
+ const platformRule = reasons.includes("default-view")
423
+ ? "8.6.26 BizQueryController.delete:297-311(bizList.get(0) 不可删,BIZ_QUERY_DEFAULT 303025)"
424
+ : "2.1.5 BizQueryController.delete:215-227(扣掉目标后 PC/MOBILE 各需至少一条可见视图,BIZ_QUERY_DELETE_LACK_PC_MOBILE_VIEWS 306103)";
414
425
  return new ToolRefusalError({
415
426
  status: "refused",
416
427
  blocker: "listview-last-visible",
417
428
  schemaCode,
418
429
  code,
430
+ ...(local
431
+ ? {
432
+ localPrecheck: true,
433
+ reasons,
434
+ platformRule,
435
+ ...(detail?.firstViewCode !== undefined ? { firstViewCode: detail.firstViewCode } : {}),
436
+ ...(detail?.remainingViewCodes !== undefined ? { remainingViewCodes: detail.remainingViewCodes } : {}),
437
+ }
438
+ : {}),
419
439
  nextCommand: `omc model-purge --code ${schemaCode}`,
420
440
  cleanupGuidance: `删视图在平台上不是独立清理步骤:要清视图就删模型(model-purge / model.delete 级联删除它的全部视图,含这条);` +
421
441
  `listview.delete 只用于替换视图(先建/配好替代视图再删旧的),最后一条可见视图不可单删。`,
422
- message: `不能删除视图 ${code}:平台要求**至少保留一个 PC 可见视图和一个 MOBILE 可见视图**(PC + MOBILE 各一条,306103)。` +
442
+ message: (local && !reasons.includes("last-visible")
443
+ ? `不能删除视图 ${code}:8.6.26 平台禁止删除默认(第一行)视图(BIZ_QUERY_DEFAULT 303025)。`
444
+ : `不能删除视图 ${code}:平台要求**至少保留一个 PC 可见视图和一个 MOBILE 可见视图**(PC + MOBILE 各一条,306103)。`) +
445
+ (local
446
+ ? `本条是**写前本地预检**(零写入,未发 delete wire):${reasons.includes("default-view") ? "目标是默认(第一行)视图,8.6.26 直接禁删;" : ""}${reasons.includes("last-visible") ? "扣掉它之后 PC/MOBILE 的可见视图不足各一条。" : ""}`
447
+ : "") +
423
448
  `单独删最后一条视图没有意义——删模型会级联删除它的所有视图。要继续用这个模型就**就地改**(listview.configure 省略 code 即改默认视图),` +
424
449
  `要整体清理就用 model-purge(默认 dry-run,先看计划)。`,
425
450
  });
426
451
  }
452
+ /**
453
+ * Local mirror of the platform delete gate (F8 0.8.8). Returns null when the
454
+ * delete is NOT locally known to be blocked — including whenever the read face
455
+ * cannot prove visibility (list wire failed / visibility keys not projected) or
456
+ * the target is absent from the list. In those cases the caller must keep the
457
+ * existing behaviour and let the platform refuse (never a false local allow).
458
+ */
459
+ export async function listviewDeleteLocalBlock(session, schemaCode, code) {
460
+ let rows;
461
+ try {
462
+ rows = wireRows((await wireCall(session, { path: ENDPOINTS.listQueryList, query: { schemaCode, clientType: "PC" } })).data);
463
+ }
464
+ catch {
465
+ return null;
466
+ }
467
+ if (rows.length === 0)
468
+ return null;
469
+ const index = rows.findIndex((row) => String(row.code ?? "") === code);
470
+ if (index < 0)
471
+ return null;
472
+ // Both flags must be projected by the read face. An ABSENT key is "unknown"
473
+ // (e.g. a proxy projection) — do not read it as false. A present null IS the
474
+ // platform's "not visible" (2.1.5 uses Boolean.TRUE.equals).
475
+ const known = (row, key) => key in row && (typeof row[key] === "boolean" || row[key] === null);
476
+ if (!rows.every((row) => known(row, "showOnPc") && known(row, "showOnMobile")))
477
+ return null;
478
+ const remaining = rows.filter((_, position) => position !== index);
479
+ const pcLeft = remaining.some((row) => row.showOnPc === true);
480
+ const mobileLeft = remaining.some((row) => row.showOnMobile === true);
481
+ const reasons = [];
482
+ if (index === 0)
483
+ reasons.push("default-view");
484
+ if (remaining.length === 0 || !pcLeft || !mobileLeft)
485
+ reasons.push("last-visible");
486
+ if (reasons.length === 0)
487
+ return null;
488
+ return {
489
+ reasons,
490
+ firstViewCode: String(rows[0]?.code ?? ""),
491
+ remainingViewCodes: remaining.map((row) => String(row.code ?? "")).filter(Boolean),
492
+ };
493
+ }
427
494
  export function registerListViewLane(tools) {
428
495
  tools.push(defineTool({
429
496
  name: "listview.get",
@@ -1299,10 +1366,43 @@ export function registerListViewLane(tools) {
1299
1366
  scope: LIST_VIEW_TOOLS["listview.delete"].scope,
1300
1367
  description: LIST_VIEW_TOOLS["listview.delete"].description,
1301
1368
  inputSchema: { schemaCode: z.string().min(1), code: z.string().min(1) },
1369
+ // F8(0.8.8):写前本地预检——平台在删「最后一条可见视图 / 默认视图」时拒绝
1370
+ // (2.1.5 :215-227 / 8.6.26 :297-311),本工具先读视图清单就地拒绝,零写入。
1371
+ // dry-run 与真写共用这一个函数;读面不足时返回 null → 照旧走平台 wire 拒绝。
1372
+ writeLint: async (session, args) => {
1373
+ const blocked = await listviewDeleteLocalBlock(session, args.schemaCode, args.code);
1374
+ if (blocked !== null)
1375
+ throw listviewLastVisibleRefusal(args.schemaCode, args.code, {
1376
+ localPrecheck: true,
1377
+ reasons: blocked.reasons,
1378
+ firstViewCode: blocked.firstViewCode,
1379
+ remainingViewCodes: blocked.remainingViewCodes,
1380
+ });
1381
+ return {
1382
+ wouldChange: true,
1383
+ summary: `即将删除列表视图 ${args.schemaCode}/${args.code}`,
1384
+ visibilityPrecheck: {
1385
+ locallyBlocked: false,
1386
+ note: "本地未命中「最后一条可见视图/默认视图」判据;平台 306103/303025 仍是最终门(读面不足时不做本地判定)",
1387
+ },
1388
+ };
1389
+ },
1302
1390
  execute: async (session, args) => {
1303
1391
  const before = await wireCall(session, { path: ENDPOINTS.listQueryGetHeader, query: { schemaCode: args.schemaCode, code: args.code } });
1304
1392
  if (before.data == null)
1305
1393
  return { performed: { skipped: "already-absent" }, readback: { absent: true, header: null } };
1394
+ // Local precheck (zero write): the platform refuses the last visible view
1395
+ // (2.1.5) / the default first-row view (8.6.26) with 306103/303025. When
1396
+ // the read face cannot prove visibility this returns null and the delete
1397
+ // proceeds to the platform wire, preserving today's refusal path.
1398
+ const blocked = await listviewDeleteLocalBlock(session, args.schemaCode, args.code);
1399
+ if (blocked !== null)
1400
+ throw listviewLastVisibleRefusal(args.schemaCode, args.code, {
1401
+ localPrecheck: true,
1402
+ reasons: blocked.reasons,
1403
+ firstViewCode: blocked.firstViewCode,
1404
+ remainingViewCodes: blocked.remainingViewCodes,
1405
+ });
1306
1406
  let performed;
1307
1407
  try {
1308
1408
  performed = await wireCall(session, { path: ENDPOINTS.listQueryDelete, method: "POST", query: { schemaCode: args.schemaCode, code: args.code } });
@@ -5,7 +5,7 @@ export { RUNTIME_DATA_WIRE, RUNTIME_QUERY_OPERATORS, ENGINE_OWNED_KEYS, SUBMIT_S
5
5
  import { RUNTIME_DATA_WIRE } from "omc-core/wire-facts";
6
6
  export function dataListDescription() {
7
7
  const wire = RUNTIME_DATA_WIRE;
8
- return `按简化过滤 DSL 查询业务对象(runtime/query/list);DSL 在 CLI 内翻译为平台 queryCondition(${wire.dslShape}),并按发布字段元数据为每个条件注入 propertyType(未知过滤字段将被拒绝,可用 rawCondition 逃生);响应行在 items[],业务字段在 items[].fields.<code>(不是 rows[],也不是 item 顶层——--jq 常用 items[].fields.sku);空模型返回空列表;未配列的自定义字段投影为 null——这是显示面缺列配置、不是数据缺失(data.load 有值),显式选列在结果中全为 null 而发布字段元数据显示其存在时,readback 追加 projectionHint(先用 listview.configure 配置该模型的默认视图列,或用 data.load 读单条权威值)。键缺席=字段不存在;键在值 null=未投影或真空值(见 projectionHint.unprojected);逐行未投影看 items[].unprojected(nullSemantics 说明两者都不是「字段不存在」)。`;
8
+ return `按简化过滤 DSL 查询业务对象(runtime/query/list);DSL 在 CLI 内翻译为平台 queryCondition(${wire.dslShape}),并按发布字段元数据为每个条件注入 propertyType(未知过滤字段将被拒绝,可用 rawCondition 逃生);响应行在 items[],业务字段在 items[].fields.<code>(不是 rows[],也不是 item 顶层——--jq 常用 items[].fields.sku);空模型返回空列表;列表只投影视图列:**已判定未投影的列会从 items[].fields 省略键**(items[].unprojected 点名;不是数据丢失——data.load 有值;显式选列在结果中全为 null 而发布字段元数据显示其存在时,readback 追加 projectionHint,先用 listview.configure 配置该模型的默认视图列或用 data.load 读单条权威值)。键缺席=字段不存在或该行已判定未投影(见 items[].unprojected);键在且值 null=真空值(未投影或真空值不再同形;nullSemantics 说明口径)。`;
9
9
  }
10
10
  export function dataAggregateDescription() {
11
11
  return `临时计数与数值聚合(纯读)。count:runtime/query/list size:1 读 totalElements(服务端精确、不受 cap 影响;带 filter +1 field.list)。sum/avg/min/max:field 必填且已发布 propertyType=2(NUMERICAL);无 GET_LIST 改源时优先 /sum ALL_DATA(coverage.mode=server-aggregate,全量精确),否则/失败/键不符回退本地折叠(strategyFallback;size:200 翻页至 cap 1000,null 不进聚合、avg=sum/非 null 行数,nonNullCount=0→value:null)。complete 看 rowsScanned>=total,否则 missingCount+capNotice,绝不外推。groupBy 单列:count 值域可枚举(options/字典)→值域×count(V+3 wire),分桶并发窗口 4(限流退化 2,见 wire.concurrency),桶序稳定;按 count 降序取 topN(默认 10/上限 20),截断给 truncatedBuckets/bucketsTruncatedCount,null 单列 nullBucket;不可枚举或数值指标→本地扫描(coverage.mode=paged-local-scan/local-scan),数值桶 {key,count,nonNullCount,value} 按 value 降序、并列按 key,null 行进 nullBucket。filter.draftPolicy:count+groupBy 默认 includeDrafts:false 注入 sequenceStatus≠DRAFT;数值指标不默认排除;count 省略=平台默认(无条件含草稿、带条件排草稿);显式 false 强制排除。边界:临时问句用本工具;持久图表/看板用 report.chartdata,视图汇总列用 sumType,写时计算用 datarule type2。子表计数/求和用 child(主表 schemaCode + childSchemaCode/bizObjectId)。`;
@@ -133,7 +133,7 @@ export const RUNTIME_DATA_LANE_CONTRACT = Object.freeze({
133
133
  tools: Object.freeze({
134
134
  "data.list": Object.freeze({ scope: "filtered list field projection", description: dataListDescription() }),
135
135
  "data.aggregate": Object.freeze({ scope: "aggregate count and grouped distribution via query/list totals", description: dataAggregateDescription() }),
136
- "data.load": Object.freeze({ scope: "authoritative readback form load", description: "M2 authoritative readback: form/load one business object by id. **返回形状:业务字段值在 `result.data`(非 readback.authoritative);大结果 stdout 只回 detailArtifactId + fetch 提示,用 `omc artifact get <id>` 取回;`fields:[...]` 可投影只取所需键**。" }),
136
+ "data.load": Object.freeze({ scope: "authoritative readback form load", description: "M2 authoritative readback: form/load one business object by id. **返回形状:业务字段值在 `result.data`(非 readback.authoritative);大结果 stdout 只回 detailArtifactId + fetch 提示,用 `omc artifact get <id>` 取回;`fields:[...]` 可投影只取所需键**。DATE 字段读回固定 `YYYY-MM-DD HH:mm:ss`(后端 DateBizField.toDisplayValue 恒用秒级格式;表单 load 序列化同口径),字段 options.format 只影响门户显示,不要按 format 断言读回字符串。" }),
137
137
  "data.save": Object.freeze({
138
138
  scope: "write authoritative readback form save",
139
139
  description: dataSaveDescription(),
@@ -144,7 +144,7 @@ export const RUNTIME_DATA_LANE_CONTRACT = Object.freeze({
144
144
  }),
145
145
  "data.delete": Object.freeze({
146
146
  scope: "write authoritative readback form save",
147
- description: desc("M2 runtime data delete (runtime/form/delete) with absence readback."),
147
+ description: desc("M2 runtime data delete (runtime/form/delete) with absence readback. 批量回执按 absent / deleted[].absent / deletionVerified / undeletedIds 判成功;**没有 `present` 键**(旧版与 absent 并列会出现 present:true+absent:true,无法判断读哪条);remainingRows/modelRowsRemaining/modelClean 只描述整表状态,不用于判批量删除成败。"),
148
148
  }),
149
149
  "data.submit": Object.freeze({ scope: "write authoritative readback form save", description: dataSubmitDescription() }),
150
150
  }),
@@ -423,7 +423,7 @@ export function itemUnprojectedFields(fields, projectionMiss, viewColumnCodes) {
423
423
  })
424
424
  .map(([code]) => code);
425
425
  }
426
- /** 行级 `unprojected` 是加法:既有 `fields` 的键与 null 值逐字保留。 */
426
+ /** 行级 `unprojected` 只在有已判定未投影列时加键(空数组没有信息量,也会涨字节)。 */
427
427
  export function attachItemUnprojected(items, projectionMiss, viewColumnCodes) {
428
428
  // 键只在**该行真的**有已判定未投影列时出现:无标注的行不加 `unprojected: []`
429
429
  // ——每行多 ~20B 会把 25 行的小结果顶过 compact 外置阈值(0.8.7 全量实测
@@ -433,8 +433,27 @@ export function attachItemUnprojected(items, projectionMiss, viewColumnCodes) {
433
433
  return unprojected.length > 0 ? { ...item, unprojected } : { ...item };
434
434
  });
435
435
  }
436
+ /**
437
+ * F5(w53,2026-11-26 真机):已判定未投影的列**从 `items[].fields` 省略键**,
438
+ * 不再回 `null`——0.8.7 真机里 `faultDesc/repairDate/version:null` 与真实空值
439
+ * 同形,脚本会当成「值丢了」。`unprojected` 仍逐行点名同一批 code(键缺席 =
440
+ * 未投影/不适用;键在且 null 才是真空值)。
441
+ *
442
+ * 只删**该行 unprojected 点名的键**:无证据的 null(真空值)逐字保留;系统列 /
443
+ * `*_` / `*_key` 本来就不进 unprojected,也不会被误删。
444
+ */
445
+ export function omitUnprojectedFields(items) {
446
+ return items.map((item) => {
447
+ if (item.unprojected === undefined || item.unprojected.length === 0)
448
+ return item;
449
+ const fields = { ...item.fields };
450
+ for (const code of item.unprojected)
451
+ delete fields[code];
452
+ return { ...item, fields };
453
+ });
454
+ }
436
455
  /** 人类/脚本读 null 的唯一权威口径;与行级 `unprojected` 同时出现才完整。 */
437
- export const DATA_LIST_NULL_SEMANTICS = "items[].fields.<code> 键在且值为 null 可能是未投影进视图列(也可能本就是空值),不是「字段不存在」;items[].unprojected 只在该行有已判定的未投影列时出现(列出的 code 值必为 null),键缺席表示本行没有已判定的未投影列;判真值用 data.load。";
456
+ export const DATA_LIST_NULL_SEMANTICS = "items[].fields.<code> 键缺席=字段不存在或该行已判定未投影(items[].unprojected 已省略该键);键在且值为 null 才是真空值;判真值用 data.load。";
438
457
  /**
439
458
  * B2(issue 2026-11-25,真机 `milestone_ledger`):`data.list` 对关联字段静默回
440
459
  * null,而同一条记录 `data.load` 有真实值(`{id, displayCode, <显示字段>}`)。
@@ -494,6 +513,92 @@ export function relationColumnsNotProjected(codes, relationCodes, schemaCode, sa
494
513
  nextCommand: `omc call data.load --env <env> --args '{"schemaCode":"${schemaCode}","bizObjectId":"${id}"}'`,
495
514
  }));
496
515
  }
516
+ /**
517
+ * F4(w53,2026-11-26 真机):`options.mappings` 只在**门户表单运行时**用户选中
518
+ * 关联值时回填副本/快照列;`data.save` / `data.update` / `data.submit` 的服务端
519
+ * 写路径不执行映射(子表 `repairRef` 有 mappings,save 后快照仍为空)。
520
+ *
521
+ * 平台证据(8.6.26):门户 `runtime/form/save` 链路
522
+ * `FormRuntimeController.save:806-843` → `saveBizSheet:932-970` →
523
+ * `RuntimeController.saveBizObject:926-934` → `BizObjectFacadeImpl.saveBizObject`
524
+ * **没有** mapping 调用;表单运行时另走显式的
525
+ * `BaseController.executeDataRuleValidationAndMapping:1088-1103`(mappingList),
526
+ * 其调用方是 OpenAPI v2/v3(`OpenApiFormController.java:290` /
527
+ * `OpenApiBizObjectController.java:260`),不是本工具使用的 runtime 表单保存面。
528
+ * `options.mappings` 的消费实现见 `WorkSheetMappingServiceImpl.executeChildMapping`
529
+ * (bizdata `:207-230`)——只在被显式调用的 mapping 面执行。
530
+ * 「后端会不会代跑映射」如需逐版本闭环,仍需真机采样复核。
531
+ *
532
+ * 只在本次 formData 真的带了子表数组时才读子表 schema 的已发布字段(零数组 =
533
+ * 零 wire);读失败静默跳过,绝不阻断写。
534
+ */
535
+ const MAPPING_NOTE_LIMIT = 5;
536
+ const MAPPING_NOTE_TARGET_LIMIT = 3;
537
+ function relationMappingsOf(row) {
538
+ const options = parseOptions(row.options);
539
+ let raw = options.mappings ?? row.mappings;
540
+ if (typeof raw === "string") {
541
+ if (raw.trim() === "")
542
+ return { declared: false, targets: [] };
543
+ try {
544
+ raw = JSON.parse(raw);
545
+ }
546
+ catch {
547
+ // 非空字符串仍是「声明了映射」(损坏 JSON 可能被平台原样保存)。
548
+ return { declared: true, targets: [] };
549
+ }
550
+ }
551
+ if (!Array.isArray(raw))
552
+ return { declared: raw !== undefined && raw !== null, targets: [] };
553
+ const targets = raw
554
+ .map((entry) => entry && typeof entry === "object" && !Array.isArray(entry)
555
+ ? String(entry.target ?? "").trim()
556
+ : "")
557
+ .filter((target) => target.length > 0);
558
+ return { declared: raw.length > 0, targets };
559
+ }
560
+ async function childTableMappingHits(session, formData, childCodes) {
561
+ const present = childCodes.filter((code) => Array.isArray(formData[code]));
562
+ if (present.length === 0)
563
+ return [];
564
+ const hits = [];
565
+ for (const childTable of present) {
566
+ let rows;
567
+ try {
568
+ // 子表 schemaCode = 父模型 CHILD_TABLE 字段的 code(平台同源)。
569
+ rows = wireRows((await wireCall(session, { path: ENDPOINTS.fieldList, query: { schemaCode: childTable, isPublish: "true" } })).data);
570
+ }
571
+ catch {
572
+ // 元数据读不到就不提示(读面副作用不能阻断写)。
573
+ continue;
574
+ }
575
+ for (const row of rows) {
576
+ const type = Number(row.propertyType ?? row.type);
577
+ if (!RELATION_PROPERTY_TYPES.has(type))
578
+ continue;
579
+ const mapping = relationMappingsOf(row);
580
+ if (!mapping.declared)
581
+ continue;
582
+ const relationField = String(row.code ?? row.propertyCode ?? "");
583
+ if (relationField)
584
+ hits.push({ childTable, relationField, targets: mapping.targets });
585
+ }
586
+ }
587
+ return hits;
588
+ }
589
+ function mappingRuntimeNoteFor(hits) {
590
+ if (hits.length === 0)
591
+ return undefined;
592
+ const shown = hits.slice(0, MAPPING_NOTE_LIMIT);
593
+ const detail = shown
594
+ .map((hit) => {
595
+ const targets = hit.targets.slice(0, MAPPING_NOTE_TARGET_LIMIT).join("/");
596
+ const suffix = targets.length > 0 ? `→${targets}${hit.targets.length > MAPPING_NOTE_TARGET_LIMIT ? "…" : ""}` : "";
597
+ return `${hit.childTable}.${hit.relationField}${suffix}`;
598
+ })
599
+ .join("、");
600
+ return `REST 写不执行关联映射(options.mappings 只在门户选值时由表单运行时回填):${detail}${hits.length > shown.length ? ` 等 ${hits.length} 处` : ""};快照/映射目标字段需调用方在 formData 里自填,映射配置以 field.get 的 options 为准。`;
601
+ }
497
602
  /**
498
603
  * data.list 的视图证据读取(query/get 失败/无视图 → undefined = 无证据)。
499
604
  * 拿到 queryColumns 数组才算可判定证据;视图对象在但 queryColumns 非数组 →
@@ -1976,7 +2081,10 @@ export function registerRuntimeDataLane(tools) {
1976
2081
  const projectionHintAll = projectionHintWithMiss(projectionHintFace(items, viewEvidence), projectionMissAll);
1977
2082
  const columnsNotProjected = await relationNotProjectedOf(items, projectionMissAll, viewEvidence?.viewColumnCodes);
1978
2083
  const itemsWithProjection = attachItemUnprojected(items, projectionMissAll, viewEvidence?.viewColumnCodes);
1979
- const anyNullField = items.some((item) => Object.values(item.fields).some((value) => value === null));
2084
+ // F5(w53):已判定未投影的列从 fields 省略键(unprojected 仍是证据);
2085
+ // 无证据的 null(真空值)保留。诊断都已用带 null 的 items 算完再省略。
2086
+ const itemsFinal = omitUnprojectedFields(itemsWithProjection);
2087
+ const anyNullField = itemsFinal.some((item) => Object.values(item.fields).some((value) => value === null));
1980
2088
  return {
1981
2089
  schemaCode: args.schemaCode,
1982
2090
  ...application,
@@ -2027,7 +2135,7 @@ export function registerRuntimeDataLane(tools) {
2027
2135
  ...(anyNullField ? { nullSemantics: DATA_LIST_NULL_SEMANTICS } : {}),
2028
2136
  ...(projectionMissAll.length > 0 ? { projectionMiss: projectionMissAll } : {}),
2029
2137
  ...(columnsNotProjected.length > 0 ? { columnsNotProjected } : {}),
2030
- items: itemsWithProjection,
2138
+ items: itemsFinal,
2031
2139
  };
2032
2140
  }
2033
2141
  let result;
@@ -2168,10 +2276,12 @@ export function registerRuntimeDataLane(tools) {
2168
2276
  const projectionHintPaged = projectionHintWithMiss(projectionHintFace(items, viewEvidence), projectionMissPaged);
2169
2277
  const columnsNotProjected = await relationNotProjectedOf(items, projectionMissPaged, viewEvidence?.viewColumnCodes);
2170
2278
  const itemsWithProjection = attachItemUnprojected(items, projectionMissPaged, viewEvidence?.viewColumnCodes);
2171
- const anyNullField = items.some((item) => Object.values(item.fields).some((value) => value === null));
2279
+ // F5(w53):已判定未投影的列从 fields 省略键;无证据的 null 保留。
2280
+ const itemsFinal = omitUnprojectedFields(itemsWithProjection);
2281
+ const anyNullField = itemsFinal.some((item) => Object.values(item.fields).some((value) => value === null));
2172
2282
  // F6 工单 05b:只有本页行真的内联了子表数组才给一句(否则零字节);
2173
2283
  // 取第一条命中行,命令里的 schemaCode/childSchemaCode/bizObjectId 都是真值。
2174
- const inlineChild = items
2284
+ const inlineChild = itemsFinal
2175
2285
  .map((item) => inlineChildRowsOf(item.fields, item.id))
2176
2286
  .find((hit) => hit !== undefined);
2177
2287
  const readback = {
@@ -2220,7 +2330,7 @@ export function registerRuntimeDataLane(tools) {
2220
2330
  size: page.size ?? args.size ?? 20,
2221
2331
  ...(pageOutOfRange ? { pageOutOfRange: true, emptyPage: true, hint: `page 从 0 开始,当前传了 ${requestedPage};合法范围 0..${Math.max(0, totalPages - 1)}。` } : {}),
2222
2332
  // r29b F8 的 ids/itemsPreview 由 compact(外置时)现算,见 dataListCompactProjection。
2223
- items: itemsWithProjection,
2333
+ items: itemsFinal,
2224
2334
  };
2225
2335
  // r29b F8: ids/itemsPreview 已在同信封;artifact 提示由 compact 外置后的
2226
2336
  // fetch/detailArtifactId 承担。这里不改既有 projectionHint 主句(契约测试
@@ -3118,9 +3228,12 @@ export function registerRuntimeDataLane(tools) {
3118
3228
  let sequenceStatus = null;
3119
3229
  readbackData = (await wireCall(session, { path: ENDPOINTS.runtimeFormLoad, query: { schemaCode: args.schemaCode, sheetCode, objectId: returnedId } })).data;
3120
3230
  sequenceStatus = extractSequenceStatus((readbackData ?? {}));
3231
+ // F4(w53):本次 formData 真带子表数组时才读子表字段元数据;无数组/读不到
3232
+ // 元数据 → 零提示(读失败不阻断写)。
3233
+ const mappingRuntimeNote = mappingRuntimeNoteFor(await childTableMappingHits(session, formData, prepared.childCodes));
3121
3234
  return {
3122
3235
  performed: { errcode: performed.errcode, ...application, bizObjectId: returnedId, workflowInstanceId, workItemId, workItemSource, sheetCode, resolvedFrom, formType: "save-draft-workflow" },
3123
- readback: { ...application, ...writeDiagnostics, authoritative: projectReadbackRecord(normalizeLoadedRecord((readbackData ?? {})), args), sequenceStatus, expectedSequenceStatus: "DRAFT" },
3236
+ readback: { ...application, ...writeDiagnostics, ...(mappingRuntimeNote !== undefined ? { mappingRuntimeNote } : {}), authoritative: projectReadbackRecord(normalizeLoadedRecord((readbackData ?? {})), args), sequenceStatus, expectedSequenceStatus: "DRAFT" },
3124
3237
  };
3125
3238
  }
3126
3239
  // 券商 issue 1.3(cpdocs 2026-10-27):带 formData.id 的 save 是更新语义;
@@ -3173,9 +3286,13 @@ export function registerRuntimeDataLane(tools) {
3173
3286
  const workflowDraftHint = publishedWorkflow
3174
3287
  ? `本模型有已发布流程 ${publishedWorkflow},不能用 submit:true 一调完成态;要走三段:① data.save {schemaCode:"${args.schemaCode}", workflowCode:"${publishedWorkflow}", formData:{...}} 新建流程草稿 → ② 从回执 performed 取 bizObjectId / workItemId / workflowInstanceId → ③ data.submit {schemaCode:"${args.schemaCode}", bizObjectId:"<bizObjectId>", workItemId:"<workItemId>", workflowInstanceId:"<workflowInstanceId>"} 提交起始待办(后续审批用 workitem 面;不保证立即完成态);本次无实例草稿不能原地起流程`
3175
3288
  : null;
3289
+ // F4(w53):仅在本次 formData 含子表数组时读该子表字段元数据;没有数组 /
3290
+ // 读不到元数据 → 零提示、零额外 wire(读失败不阻断写)。
3291
+ const mappingRuntimeNote = mappingRuntimeNoteFor(await childTableMappingHits(session, formData, prepared.childCodes));
3176
3292
  const plainReadback = {
3177
3293
  ...application,
3178
3294
  ...writeDiagnostics,
3295
+ ...(mappingRuntimeNote !== undefined ? { mappingRuntimeNote } : {}),
3179
3296
  authoritative: projectReadbackRecord(savedRecord, args),
3180
3297
  ...(savedEmptyFields.length > 0 ? { readbackWarning: readbackWarningFor(savedEmptyFields, "data.save") } : {}),
3181
3298
  ...(dataWarnings.length > 0 ? { warnings: dataWarnings } : {}),
@@ -3502,13 +3619,15 @@ export function registerRuntimeDataLane(tools) {
3502
3619
  : undefined;
3503
3620
  // `deleted`/`count` ride `readback` — the write envelope surfaces only
3504
3621
  // performed/readback inline (extra top-level keys are artifact-only).
3505
- // `present:false` downgrades deliveryState to WRITE_UNVERIFIED in the
3506
- // shared write pipeline, so an ineffective batch is never DELIVERED.
3622
+ // F10(w53,2026-11-26):不再回 `present`——它和 `absent` 是同一条判据
3623
+ // (batchDeleteIneffective===undefined),真机出现过 present:true+absent:true
3624
+ // 并列,读者只能二选一猜。成功判据保持 absent/deleted[].absent/
3625
+ // deletionVerified/undeletedIds;「整表是否还在」看 modelRowsRemaining/modelClean
3626
+ // (失败时 absent:false 仍由共享写门降级 WRITE_UNVERIFIED)。
3507
3627
  const residue = await remainingRows(session, args.schemaCode, sheetCode);
3508
3628
  return {
3509
3629
  performed: { sheetCode, resolvedFrom },
3510
3630
  readback: {
3511
- present: batchDeleteIneffective === undefined,
3512
3631
  absent: batchDeleteIneffective === undefined && deleted.every((entry) => entry.absent === true),
3513
3632
  count: deleted.length,
3514
3633
  deletedCount,
@@ -3843,8 +3843,114 @@ export function registerWorkflowLane(tools) {
3843
3843
  lane: WORKFLOW_LANE,
3844
3844
  scope: WORKFLOW_TOOLS["workflow.delete"].scope,
3845
3845
  description: WORKFLOW_TOOLS["workflow.delete"].description,
3846
- inputSchema: { schemaCode: z.string().min(1), code: z.string().min(1).describe("流程编码——本参数名是 code") },
3846
+ inputSchema: {
3847
+ schemaCode: z.string().min(1),
3848
+ code: z.string().min(1).describe("流程编码——本参数名是 code"),
3849
+ unbindListviews: z
3850
+ .boolean()
3851
+ .optional()
3852
+ .describe("先解绑列表视图再删流程:true 时对本模型每个绑定了本流程的列表视图执行 listview.configure(actions:[] + replaceActions:true,保留原列 fieldCodes),成功后才删流程;任一步解绑失败即停、不删流程。**会改动视图配置(移除该视图 add 动作的平台关联),必须显式确认才做。** 默认 false 只删流程,遇 303024 仍拒绝并给 nextCommand"),
3853
+ },
3854
+ // F7(0.8.8):dry-run 与真写共用同一份只读扫描——预览列出会被解绑的视图,
3855
+ // 真写在任何写 wire 之前也先跑这里。两者都不写。
3856
+ writeLint: async (session, args) => {
3857
+ if (args.unbindListviews !== true) {
3858
+ return {
3859
+ wouldChange: true,
3860
+ summary: `即将删除流程 ${args.code}(未请求解绑列表视图)`,
3861
+ listviewUnbind: {
3862
+ requested: false,
3863
+ note: "未传 unbindListviews;不改任何视图配置。若平台回 303024,重发时带 unbindListviews:true 让本工具先解绑。",
3864
+ },
3865
+ };
3866
+ }
3867
+ const scan = await scanListviewsBoundToWorkflow(session, args.schemaCode, args.code);
3868
+ return {
3869
+ wouldChange: true,
3870
+ summary: scan.bound.length > 0
3871
+ ? `先解绑 ${scan.bound.length} 个列表视图,再删除流程 ${args.code}`
3872
+ : `未发现绑定本流程的列表视图;将直接删除流程 ${args.code}`,
3873
+ listviewUnbind: {
3874
+ requested: true,
3875
+ readable: scan.readable,
3876
+ ...(scan.bound.length > 0
3877
+ ? {
3878
+ views: scan.bound.map(({ code, name, fieldCodes }) => ({
3879
+ code,
3880
+ name,
3881
+ ...(fieldCodes.length > 0 ? { fieldCodes } : {}),
3882
+ action: "listview.configure actions:[] + replaceActions:true",
3883
+ })),
3884
+ }
3885
+ : {}),
3886
+ ...(scan.unreadableViews.length > 0 ? { unreadableViews: scan.unreadableViews } : {}),
3887
+ then: "workflow.delete",
3888
+ ...(scan.readable
3889
+ ? {}
3890
+ : { note: "视图清单读取失败:真写仍会先读;读不到绑定时只删流程,平台 303024 会挡住,不误放行。" }),
3891
+ },
3892
+ };
3893
+ },
3847
3894
  execute: async (session, args) => {
3895
+ const steps = [];
3896
+ // Opt-in unbind (F7): the workflow.publish side effect binds every list
3897
+ // view's `add` action to this workflow, and workflow.delete then answers
3898
+ // 303024 until those associations are gone. Unbind FIRST, and stop
3899
+ // before the delete if any view cannot be cleared (never half-delete).
3900
+ if (args.unbindListviews === true) {
3901
+ const scan = await scanListviewsBoundToWorkflow(session, args.schemaCode, args.code);
3902
+ const configure = siblings.find((tool) => tool.name === "listview.configure");
3903
+ if (scan.bound.length > 0 && configure?.writeExecute === undefined)
3904
+ throw new ToolRefusalError({
3905
+ status: "refused",
3906
+ blocker: "workflow-unbind-step-unavailable",
3907
+ workflowCode: args.code,
3908
+ message: "workflow.delete 需要 listview.configure 来解绑视图,但它未注册写执行;零写入停止",
3909
+ });
3910
+ for (const view of scan.bound) {
3911
+ const fieldCodes = view.fieldCodes.length > 0 ? view.fieldCodes : ["createdTime", "creater", "name", "sequenceNo"];
3912
+ try {
3913
+ const outcome = await configure.writeExecute(session, {
3914
+ schemaCode: args.schemaCode,
3915
+ code: view.code,
3916
+ fieldCodes,
3917
+ actions: [],
3918
+ replaceActions: true,
3919
+ });
3920
+ if ("status" in outcome)
3921
+ throw new ToolRefusalError({
3922
+ status: "refused",
3923
+ blocker: "workflow-unbind-step-stopped",
3924
+ workflowCode: args.code,
3925
+ viewCode: view.code,
3926
+ message: `解绑视图 ${view.code} 中途停止(${String(outcome.envelope?.message ?? outcome.status)})`,
3927
+ });
3928
+ steps.push({
3929
+ step: "listview.configure",
3930
+ status: "ok",
3931
+ viewCode: view.code,
3932
+ viewName: view.name,
3933
+ actions: "cleared",
3934
+ replaceActions: true,
3935
+ readback: outcome.readback,
3936
+ });
3937
+ }
3938
+ catch (error) {
3939
+ const cause = error instanceof Error ? error.message : String(error);
3940
+ throw new ToolRefusalError({
3941
+ status: "refused",
3942
+ blocker: "workflow-unbind-failed",
3943
+ workflowCode: args.code,
3944
+ schemaCode: args.schemaCode,
3945
+ viewCode: view.code,
3946
+ steps,
3947
+ nextCommand: `omc call listview.configure --env <env> --args '${JSON.stringify({ schemaCode: args.schemaCode, code: view.code, fieldCodes, actions: [], replaceActions: true })}'`,
3948
+ message: `解绑列表视图 ${view.code} 失败,已停止:**流程 ${args.code} 未删除**(不半删)。原因:${cause}。` +
3949
+ `按 nextCommand 修好该视图后重发 workflow.delete(仍带 unbindListviews:true);已成功解绑的视图在 steps 里。`,
3950
+ });
3951
+ }
3952
+ }
3953
+ }
3848
3954
  let performed;
3849
3955
  try {
3850
3956
  performed = await wireCall(session, { path: ENDPOINTS.workflowDelete, method: "POST", query: { workflowCode: args.code } });
@@ -3909,13 +4015,35 @@ export function registerWorkflowLane(tools) {
3909
4015
  ? `绑在:${bound.map((view) => `${view.code}(${view.name})action=${view.actionCode ?? "?"}`).join("、")}。`
3910
4016
  : `默认视图多半是 ${args.schemaCode}(workflow.create 会自动绑)。`) +
3911
4017
  `先解绑再删:粘贴 nextCommand(listview.configure:actions:[] + replaceActions:true + 现有 fieldCodes),再重试 workflow.delete。` +
4018
+ (args.unbindListviews === true
4019
+ ? `本次已带 unbindListviews:true,但仍有绑定未被清掉(见 boundListviews / unreadableViews);按 nextCommand 处理后重试。`
4020
+ : `也可以重发 workflow.delete 并带 unbindListviews:true,让本工具先逐个视图解绑再删。`) +
3912
4021
  `整体清理也可用 omc model-purge --code ${args.schemaCode}(级联带走流程模板与视图)。`,
3913
4022
  });
3914
4023
  }
3915
4024
  throw error;
3916
4025
  }
3917
4026
  const header = await wireCall(session, { path: ENDPOINTS.workflowGetHeader, query: { workflowCode: args.code } }).catch(() => ({ data: null }));
3918
- return { performed: { errcode: performed.errcode }, readback: { workflowCode: args.code, absent: header.data === null || header.data === undefined } };
4027
+ const absent = header.data === null || header.data === undefined;
4028
+ if (args.unbindListviews === true) {
4029
+ steps.push({ step: "workflow.delete", status: "ok", workflowCode: args.code, errcode: performed.errcode, absent });
4030
+ }
4031
+ return {
4032
+ performed: { errcode: performed.errcode },
4033
+ readback: {
4034
+ workflowCode: args.code,
4035
+ absent,
4036
+ ...(args.unbindListviews === true
4037
+ ? {
4038
+ listviewUnbind: {
4039
+ requested: true,
4040
+ unboundViews: steps.filter((step) => step.step === "listview.configure").map((step) => step.viewCode),
4041
+ },
4042
+ }
4043
+ : {}),
4044
+ },
4045
+ ...(steps.length > 0 ? { steps } : {}),
4046
+ };
3919
4047
  },
3920
4048
  rollback: workflowRollbackSpec("workflow.delete"),
3921
4049
  });
@@ -4329,53 +4457,68 @@ export function registerWorkflowLane(tools) {
4329
4457
  }
4330
4458
  return { bound, readable };
4331
4459
  }
4332
- /** Best-effort: which list views still bind this workflow (303024 recovery). */
4333
- async function findListviewsBoundToWorkflow(session, schemaCode, workflowCode) {
4460
+ /**
4461
+ * Which list views bind this workflow, plus whether the READ succeeded.
4462
+ * `readable:false` means "could not list views" (NOT "none bound") — callers
4463
+ * must fail open to the platform's 303024 rather than deleting blind
4464
+ * (F7 0.8.8). Bindings are only ever created on the `add` action by
4465
+ * workflow.publish → updateBizQueryAddAction (8.6.26
4466
+ * WorkflowTemplateController.java:791,818-846; 2.1.5 :695-711,741-761).
4467
+ */
4468
+ async function scanListviewsBoundToWorkflow(session, schemaCode, workflowCode) {
4334
4469
  const bound = [];
4470
+ const unreadableViews = [];
4471
+ let listed;
4335
4472
  try {
4336
- const listed = wireRows((await wireCall(session, { path: ENDPOINTS.listQueryList, query: { schemaCode, clientType: "PC" } })).data);
4337
- for (const row of listed) {
4338
- const code = String(row.code ?? "");
4339
- if (!code)
4473
+ listed = wireRows((await wireCall(session, { path: ENDPOINTS.listQueryList, query: { schemaCode, clientType: "PC" } })).data);
4474
+ }
4475
+ catch {
4476
+ return { bound, readable: false, unreadableViews };
4477
+ }
4478
+ for (const row of listed) {
4479
+ const code = String(row.code ?? "");
4480
+ if (!code)
4481
+ continue;
4482
+ try {
4483
+ const got = await wireCall(session, { path: ENDPOINTS.listQueryGet, query: { schemaCode, code, clientType: "PC" } });
4484
+ const model = (got.data ?? null);
4485
+ if (!model)
4340
4486
  continue;
4341
- try {
4342
- const got = await wireCall(session, { path: ENDPOINTS.listQueryGet, query: { schemaCode, code, clientType: "PC" } });
4343
- const model = (got.data ?? null);
4344
- if (!model)
4487
+ const actions = Array.isArray(model.queryActions) ? model.queryActions : [];
4488
+ const fieldCodes = (Array.isArray(model.queryColumns) ? model.queryColumns : [])
4489
+ .map((column) => String(column.propertyCode ?? ""))
4490
+ .filter(Boolean);
4491
+ for (const action of actions) {
4492
+ const association = action.associationType ?? action.queryActionRelativeType;
4493
+ const associationCode = String(action.associationCode ?? action.relativeCode ?? "");
4494
+ const isWorkflow = association === 1 ||
4495
+ association === "1" ||
4496
+ association === "WORKFLOW" ||
4497
+ String(association).toUpperCase() === "WORKFLOW";
4498
+ if (!isWorkflow)
4345
4499
  continue;
4346
- const actions = Array.isArray(model.queryActions) ? model.queryActions : [];
4347
- const fieldCodes = (Array.isArray(model.queryColumns) ? model.queryColumns : [])
4348
- .map((column) => String(column.propertyCode ?? ""))
4349
- .filter(Boolean);
4350
- for (const action of actions) {
4351
- const association = action.associationType ?? action.queryActionRelativeType;
4352
- const associationCode = String(action.associationCode ?? action.relativeCode ?? "");
4353
- const isWorkflow = association === 1 ||
4354
- association === "1" ||
4355
- association === "WORKFLOW" ||
4356
- String(association).toUpperCase() === "WORKFLOW";
4357
- if (!isWorkflow)
4358
- continue;
4359
- if (associationCode && associationCode !== workflowCode && associationCode !== schemaCode)
4360
- continue;
4361
- bound.push({
4362
- code,
4363
- name: String(row.name ?? model.name ?? code),
4364
- actionCode: action.actionCode === undefined || action.actionCode === null ? null : String(action.actionCode),
4365
- associationCode: associationCode || null,
4366
- fieldCodes,
4367
- });
4368
- }
4369
- }
4370
- catch {
4371
- // one view unreadable — keep scanning
4500
+ if (associationCode && associationCode !== workflowCode && associationCode !== schemaCode)
4501
+ continue;
4502
+ bound.push({
4503
+ code,
4504
+ name: String(row.name ?? model.name ?? code),
4505
+ actionCode: action.actionCode === undefined || action.actionCode === null ? null : String(action.actionCode),
4506
+ associationCode: associationCode || null,
4507
+ fieldCodes,
4508
+ });
4372
4509
  }
4373
4510
  }
4511
+ catch {
4512
+ // one view unreadable — keep scanning, but remember it: it may still
4513
+ // carry the binding, so an opted-in delete must not claim "clean".
4514
+ unreadableViews.push(code);
4515
+ }
4374
4516
  }
4375
- catch {
4376
- // list unreadable — caller still gets a generic detach recipe
4377
- }
4378
- return bound;
4517
+ return { bound, readable: true, unreadableViews };
4518
+ }
4519
+ /** Best-effort: which list views still bind this workflow (303024 recovery). */
4520
+ async function findListviewsBoundToWorkflow(session, schemaCode, workflowCode) {
4521
+ return (await scanListviewsBoundToWorkflow(session, schemaCode, workflowCode)).bound;
4379
4522
  }
4380
4523
  // `list_permission` echoes the PERMISSION row id plus the unit's display name
4381
4524
  // and code — never the unitId (WorkflowTemplateController.getPermissionMap).
@@ -28,6 +28,8 @@ import { writeEnvelope } from "./cli-output.js";
28
28
  import { ENDPOINTS } from "./endpoints.js";
29
29
  import { wireCall, wireRows } from "./wire.js";
30
30
  import { readModelRecord } from "./model-record.js";
31
+ import { inboundModelReferences, inboundReferenceRefusal } from "./lanes/model-references.js";
32
+ import { resolveModelTreeNode } from "./lanes/model.js";
31
33
  import { SessionManager } from "./session-manager.js";
32
34
  import { ConfigStore, defaultPaths } from "./config-store.js";
33
35
  async function sessionFor(environment) {
@@ -35,6 +37,29 @@ async function sessionFor(environment) {
35
37
  const sessions = new SessionManager(store);
36
38
  return sessions.session(environment);
37
39
  }
40
+ /**
41
+ * Map the inner refusal's executable steps to an ordered list of prerequisite
42
+ * targets, e.g. `["field.delete:items.repairRef", "field.publish:m",
43
+ * "model.delete:m"]`. The old purge receipt built this from
44
+ * `referencingModels` codes and produced `["m", "m"]` for a self-reference
45
+ * (the child column resolves back to the parent) — a list with no executable
46
+ * prerequisite and the target twice. Deriving it from the shared
47
+ * `deletionSteps` keeps the order and never repeats an entry.
48
+ */
49
+ export function purgeDeletionOrder(steps) {
50
+ const seen = new Set();
51
+ const order = [];
52
+ for (const step of steps) {
53
+ const schemaCode = String(step.args.schemaCode ?? "");
54
+ const code = typeof step.args.code === "string" ? step.args.code : "";
55
+ const target = step.tool === "field.delete" ? `field.delete:${schemaCode}.${code}` : `${step.tool}:${schemaCode}`;
56
+ if (seen.has(target))
57
+ continue;
58
+ seen.add(target);
59
+ order.push(target);
60
+ }
61
+ return order;
62
+ }
38
63
  /**
39
64
  * Read-only discovery: everything the purge would remove, in dependency order.
40
65
  * `session` is injectable so tests can plan against a fake platform; the CLI
@@ -146,6 +171,31 @@ export async function planPurge(options, injected) {
146
171
  const steps = [];
147
172
  if (instanceCount > 0)
148
173
  steps.push(options.purgeInstances ? `workflow.delete_instance ×${instanceCount}` : `⛔ ${instanceCount} 个流程实例(需 --purge-instances)`);
174
+ // Inbound-reference pre-scan: the SAME shared scan model.delete runs before
175
+ // physically_delete (src/lanes/model-references.ts). Read-only; a failure of
176
+ // the scan must not block the plan — the write path re-scans and refuses.
177
+ let referencePreview = {};
178
+ if (modelExists) {
179
+ try {
180
+ const resolved = await resolveModelTreeNode(session, options.schemaCode);
181
+ const references = resolved.treeRows.length > 0 ? await inboundModelReferences(session, [options.schemaCode], resolved.treeRows) : [];
182
+ if (references.length > 0) {
183
+ const refusal = inboundReferenceRefusal(options.schemaCode, references);
184
+ referencePreview = {
185
+ inboundReferences: references,
186
+ deletionSteps: refusal.deletionSteps,
187
+ deletionOrder: purgeDeletionOrder(refusal.deletionSteps),
188
+ nextCommand: refusal.nextCommand,
189
+ referenceNotice: `${options.schemaCode} 有入站引用(${refusal.referencingModels.map((model) => model.schemaCode).join("、")};` +
190
+ `子表列经 parentCode 解析回本模型时属于自引用)。--apply 的 model.delete 会零写入拒绝;先按 deletionSteps 逐条拆引用(nextCommand 是第一条),再重跑本命令。`,
191
+ };
192
+ steps.push(`⛔ 入站引用:先执行 deletionSteps(${refusal.deletionSteps[0]?.command ?? ""}),再删模型`);
193
+ }
194
+ }
195
+ catch {
196
+ // A scan error is reported by the write path's own gate; the plan stays useful.
197
+ }
198
+ }
149
199
  steps.push(`model.delete ${options.schemaCode}(级联带走:${[
150
200
  workflowCode ? `流程 ${workflowCode}` : undefined,
151
201
  listViews.length > 0 ? `${listViews.length} 个列表视图` : undefined,
@@ -173,6 +223,7 @@ export async function planPurge(options, injected) {
173
223
  instanceIds: [...instanceIds].slice(0, 50),
174
224
  steps,
175
225
  blockers,
226
+ ...referencePreview,
176
227
  };
177
228
  }
178
229
  /**
@@ -265,12 +316,13 @@ export async function cmdModelPurge(args) {
265
316
  return CLI_EXIT_CODES.internal;
266
317
  }
267
318
  if (!apply) {
319
+ const referenced = plan.inboundReferences !== undefined && plan.inboundReferences.length > 0;
268
320
  writeEnvelope(envelope("ok", {
269
- status: plan.blockers.length > 0 ? "blocked" : "dry-run",
321
+ status: plan.blockers.length > 0 || referenced ? "blocked" : "dry-run",
270
322
  ...plan,
271
323
  ...(plan.blockers.length > 0
272
324
  ? {}
273
- : { note: "dry-run 只列计划、不写。--apply 按上面的顺序执行;每步回读确认。" }),
325
+ : { note: `dry-run 只列计划、不写。--apply 按上面的顺序执行;每步回读确认。${referenced ? "入站引用已预扫(与 model.delete 同一份 gate):model.delete 会零写入拒绝,先按 deletionSteps 拆引用。" : ""}` }),
274
326
  }, request));
275
327
  return CLI_EXIT_CODES.ok;
276
328
  }
@@ -284,12 +336,28 @@ export async function cmdModelPurge(args) {
284
336
  }));
285
337
  return CLI_EXIT_CODES.policyRefused;
286
338
  }
287
- const steps = [];
288
339
  const session = await sessionFor(environment);
289
340
  const call = async (tool, toolArgs) => {
290
341
  const outcome = await runToolCall(tool, { args: toolArgs, requestId: request, ...(environment !== undefined ? { environment } : {}), print: () => undefined });
291
342
  return { ok: outcome.exitCode === 0, result: outcome.result };
292
343
  };
344
+ const execution = await executePurge(plan, session, call);
345
+ const result = execution.result;
346
+ const steps = Array.isArray(result.steps) ? result.steps : [];
347
+ const classified = classifyResult(execution.failed ? { ...result, requested: steps.length, succeeded: steps.filter((step) => step.status !== "failed").length } : result);
348
+ writeEnvelope(envelope(classified.status, result, request, classified.error));
349
+ return execution.failed ? 1 : 0;
350
+ }
351
+ /**
352
+ * Write phase: instances → `model.delete`, then build the receipt. Split from
353
+ * `cmdModelPurge` so the failure pass-through can be exercised without a live
354
+ * environment (the old code inline-built the receipt, so the F9 regression —
355
+ * dropping the inner `deletionSteps` and pointing `nextCommand` at the same
356
+ * command — had no test surface).
357
+ */
358
+ export async function executePurge(plan, session, call) {
359
+ const schemaCode = plan.schemaCode;
360
+ const steps = [];
293
361
  const record = (step, ok, detail) => {
294
362
  steps.push({ step, status: ok ? "ok" : "failed", ...(detail ? { detail } : {}) });
295
363
  };
@@ -316,6 +384,11 @@ export async function cmdModelPurge(args) {
316
384
  const unremovableInstances = instanceOutcome.unremovableInstances;
317
385
  // 2) the model — everything else cascades with it.
318
386
  let referrers = [];
387
+ // F9(0.8.8,探针 C):内层 model.delete 的零写入拒绝已带 inboundReferences /
388
+ // deletionSteps(可复制 command)。旧 purge 把它们压成 referrers 字符串,再用
389
+ // referrers 拼 deletionOrder/nextCommand:自引用(子表列 parentCode 解析回自身)
390
+ // 时得到 ["m","m"],nextCommand 只是重跑同一条命令——照做必再撞同一拒绝。
391
+ let deleteRefusal;
319
392
  if (!failed) {
320
393
  const outcome = await call("model.delete", { schemaCode });
321
394
  const readback = outcome.result.readback;
@@ -323,13 +396,39 @@ export async function cmdModelPurge(args) {
323
396
  referrers = Array.isArray(outcome.result.referencingModels)
324
397
  ? outcome.result.referencingModels.map((row) => String(row.schemaCode ?? "")).filter((code) => code.length > 0)
325
398
  : [];
399
+ const refusalMessage = typeof outcome.result.message === "string" && outcome.result.message.length > 0 ? outcome.result.message : refusalText(outcome.result);
326
400
  record(`model.delete:${schemaCode}`, outcome.ok || absent, outcome.ok || absent
327
401
  ? (readback ? { cascades: true, absent: readback.absent ?? null } : undefined)
328
- : { message: refusalText(outcome.result), ...(referrers.length > 0 ? { referencedBy: referrers } : {}) });
329
- if (!outcome.ok && !absent)
402
+ : { message: refusalMessage, ...(referrers.length > 0 ? { referencedBy: referrers } : {}) });
403
+ if (!outcome.ok && !absent) {
330
404
  failed = true;
405
+ const inboundReferences = Array.isArray(outcome.result.inboundReferences) ? outcome.result.inboundReferences : [];
406
+ const deletionSteps = Array.isArray(outcome.result.deletionSteps) ? outcome.result.deletionSteps : [];
407
+ if (inboundReferences.length > 0)
408
+ deleteRefusal = { inboundReferences, deletionSteps, message: refusalMessage };
409
+ }
331
410
  }
332
411
  const status = failed ? "partial" : "ok";
412
+ // Pass the inner refusal through verbatim; the purge-level receipt must not
413
+ // promise keys it dropped (F9: message named deletionSteps that were absent).
414
+ const failureFields = deleteRefusal !== undefined
415
+ ? {
416
+ nextAction: "execute-deletion-steps",
417
+ inboundReferences: deleteRefusal.inboundReferences,
418
+ deletionSteps: deleteRefusal.deletionSteps,
419
+ deletionOrder: purgeDeletionOrder(deleteRefusal.deletionSteps),
420
+ nextCommand: deleteRefusal.deletionSteps[0]?.command ?? `omc model-purge --code ${schemaCode}`,
421
+ ...(referrers.length > 0 ? { blockedBy: referrers } : {}),
422
+ message: `${schemaCode} 未删除(零写入拒绝,未启动平台删除任务)。${deleteRefusal.message} ` +
423
+ `按 deletionSteps 逐条执行(nextCommand 是第一条可复制命令);拆完引用后重跑 omc model-purge --code ${schemaCode} --apply(本命令会先删流程实例、再让 model.delete 级联)。`,
424
+ }
425
+ : {
426
+ nextAction: "fix-and-rerun",
427
+ ...(referrers.length > 0 ? { blockedBy: referrers } : {}),
428
+ message: referrers.length > 0
429
+ ? `${schemaCode} 仍被 ${referrers.join("、")} 的关联字段引用,模型不能删。先跑 omc model-purge --code ${schemaCode}(dry-run)拿 inboundReferences / deletionSteps,逐条拆引用后再 --apply。`
430
+ : "在失败的这一步停下(幂等,可修好后重跑同一条命令)。已成功的步骤不会重复破坏。",
431
+ };
333
432
  const result = {
334
433
  status,
335
434
  schemaCode,
@@ -339,19 +438,7 @@ export async function cmdModelPurge(args) {
339
438
  ...(unremovableInstances.length > 0 ? { unremovableInstances } : {}),
340
439
  steps,
341
440
  ...(failed
342
- ? {
343
- nextAction: "fix-and-rerun",
344
- ...(referrers.length > 0
345
- ? {
346
- blockedBy: referrers,
347
- deletionOrder: [...referrers, schemaCode],
348
- nextCommand: `omc model-purge --code ${referrers[0]} --purge-instances --apply`,
349
- }
350
- : {}),
351
- message: referrers.length > 0
352
- ? `${schemaCode} 仍被 ${referrers.join("、")} 的关联字段引用,模型不能删(平台 deleteFunctions 的异步拒绝已提前到调用时)。按 deletionOrder 先清引用方,再重跑本命令。`
353
- : "在失败的这一步停下(幂等,可修好后重跑同一条命令)。已成功的步骤不会重复破坏。",
354
- }
441
+ ? failureFields
355
442
  : unremovableInstances.length > 0
356
443
  ? {
357
444
  cleanupWarning: `${unremovableInstances.length} 条停滞实例无法通过平台 REST 删除(delete_instance 50000:业务对象已不存在,平台 NPE)。` +
@@ -365,8 +452,6 @@ export async function cmdModelPurge(args) {
365
452
  "**这就是 r12–r14 三次脏沙盒的根治**:实例先走,就不会留下指向空模板的待办。",
366
453
  }),
367
454
  };
368
- const classified = classifyResult(status === "partial" ? { ...result, requested: steps.length, succeeded: steps.filter((step) => step.status !== "failed").length } : result);
369
- writeEnvelope(envelope(classified.status, result, request, classified.error));
370
- return failed ? 1 : 0;
455
+ return { failed, result };
371
456
  }
372
457
  //# sourceMappingURL=model-purge.js.map
@@ -233,30 +233,47 @@ export async function cmdModelScaffold(args) {
233
233
  steps.push({ step: "model.create", status: created.ok ? "ok" : "skipped", ...(modelExists ? { detail: { reason: "already-present" } } : {}) });
234
234
  // 2) 字段:逐条,duplicate 记 skipped,其余失败继续跑完(一次看全)。
235
235
  const failedFields = [];
236
+ // F3(0.8.8,探针 C):回执计数必须解释得通。字段写入分两条路:
237
+ // - 顶层字段:一次 field.create 写一个字段;
238
+ // - CHILD_TABLE:平台在同一次 save 里把子表字段 **和声明的子列** 一起写进去
239
+ // (BizPropertyFacadeImpl.save:87-89:isSubTable() → ensureBizObjectSchema
240
+ // (property.getCode()).addProperty(subProperties)),因此 attach 成功之后
241
+ // 逐条 child:field.create 回 already-present 的子列,是「本次刚建出来」,
242
+ // 不是「本次开始前就在」。旧回执把两者都算 skipped(真机 13/6/6)。
243
+ let createdFieldCount = 0;
244
+ let alreadyPresentFieldCount = 0;
245
+ let childColumnsCreated = 0;
236
246
  // Only the PARENT publishes. A CHILD_TABLE's columns live under the parent's
237
247
  // schema (the platform answers 300004 数据模型不存在 for
238
248
  // bizproperty/publish on a child schema), and the parent's publish already
239
249
  // verifies them — r12's "checked 21/20/21" counts include child columns.
240
250
  const publishTargets = new Set([code]);
241
251
  const createFields = async (schemaCode, list, label) => {
252
+ const counts = { created: 0, alreadyPresent: 0, failed: 0 };
242
253
  for (const field of list) {
243
254
  const outcome = await call("field.create", scaffoldFieldArgs(schemaCode, field));
244
255
  const message = String(outcome.result.message ?? "");
245
256
  if (outcome.ok) {
257
+ counts.created += 1;
246
258
  steps.push({ step: `${label}:field.create`, status: "ok", detail: { schemaCode, code: field.code } });
247
259
  }
248
260
  else if (/已存在|duplicate/i.test(message)) {
261
+ counts.alreadyPresent += 1;
249
262
  steps.push({ step: `${label}:field.create`, status: "skipped", detail: { schemaCode, code: field.code, reason: "already-present" } });
250
263
  }
251
264
  else {
265
+ counts.failed += 1;
252
266
  const reason = refusalText(outcome.result);
253
267
  failedFields.push({ code: field.code, message: reason });
254
268
  steps.push({ step: `${label}:field.create`, status: "failed", detail: { schemaCode, code: field.code, message: reason } });
255
269
  }
256
270
  }
271
+ return counts;
257
272
  };
258
273
  const topLevel = fields.filter((field) => scaffoldChildrenOf(field).length === 0);
259
- await createFields(code, topLevel, "model");
274
+ const topCounts = await createFields(code, topLevel, "model");
275
+ createdFieldCount += topCounts.created;
276
+ alreadyPresentFieldCount += topCounts.alreadyPresent;
260
277
  // 3) 子表:先挂子表字段(CHILD_TABLE 建在父模型上),再往子表 schema 建子列。
261
278
  for (const child of fields.filter((field) => scaffoldChildrenOf(field).length > 0)) {
262
279
  const parentOutcome = await call("field.create", scaffoldFieldArgs(code, { ...child }));
@@ -267,6 +284,7 @@ export async function cmdModelScaffold(args) {
267
284
  steps.push({ step: "child:attach", status: "failed", detail: { parent: code, child: child.code, message: reason } });
268
285
  continue;
269
286
  }
287
+ const children = scaffoldChildrenOf(child);
270
288
  steps.push({
271
289
  step: "child:attach",
272
290
  status: parentOutcome.ok ? "ok" : "skipped",
@@ -276,10 +294,26 @@ export async function cmdModelScaffold(args) {
276
294
  detail: {
277
295
  parent: code,
278
296
  child: child.code,
279
- note: parentOutcome.ok ? "子表字段与子列在这一次 attach 中一起建立;随后的 child:field.create 返回 already-present 是正常的" : "子表已存在(含子列),跳过",
297
+ note: parentOutcome.ok
298
+ ? "子表字段与子列在这一次 attach 中一起建立(BizPropertyFacadeImpl.save 的 isSubTable 分支);随后的 child:field.create 返回 already-present 是正常的"
299
+ : "子表已存在(含子列),跳过",
280
300
  },
281
301
  });
282
- await createFields(child.code, scaffoldChildrenOf(child), "child");
302
+ const childCounts = await createFields(child.code, children, "child");
303
+ if (parentOutcome.ok) {
304
+ // The attach created the CHILD_TABLE field AND every declared column in one
305
+ // platform save; a follow-up already-present is THIS RUN's write, so it
306
+ // belongs to created (never to skipped). A column whose follow-up create
307
+ // really failed is counted as failed, not created.
308
+ const built = Math.max(0, children.length - childCounts.failed);
309
+ createdFieldCount += 1 + built;
310
+ childColumnsCreated += built;
311
+ }
312
+ else {
313
+ createdFieldCount += childCounts.created;
314
+ alreadyPresentFieldCount += 1 + childCounts.alreadyPresent;
315
+ childColumnsCreated += childCounts.created;
316
+ }
283
317
  }
284
318
  // 4) 发布字段:半成品不发布(比不发布更难查)。
285
319
  const publishFieldSteps = [];
@@ -327,21 +361,29 @@ export async function cmdModelScaffold(args) {
327
361
  }
328
362
  const failedSteps = steps.filter((step) => step.status === "failed");
329
363
  const status = failedSteps.length > 0 ? "partial" : "ok";
330
- const fieldCount = fields.reduce((sum, field) => sum + 1 + scaffoldChildrenOf(field).length, 0);
331
- // NOTE: renamed locally to unblock tsx (parallel agent redeclared `created`
332
- // in this same scope). Keep semantics identical.
333
- const fieldsCreated = steps.filter((step) => step.step.endsWith("field.create") && step.status === "ok").length;
364
+ const childColumnCount = fields.reduce((sum, field) => sum + scaffoldChildrenOf(field).length, 0);
365
+ // `fieldCount` 是历史键,语义是「最终业务字段总数」(顶层声明 + 子列);
366
+ // 落库计数改用显式键名(F3,0.8.8):created/skipped 旧键保留为别名,但取值
367
+ // 以「本次真的写入」为准,不再把 attach 一起建出的子列记成 skipped。
368
+ const fieldCount = fields.length + childColumnCount;
334
369
  const publishActions = publishFieldSteps.filter((step) => step.status === "ok").length;
335
370
  // r28g F5:旧键 publishedFields 实际是「发布动作次数/目标 schema 数」(常=1),
336
371
  // 与 fieldCount 量级不符。保留旧键作兼容别名,同时给 publishActions + 字段计数。
337
- const fieldsPublishedEstimate = publishingBlocked || fieldPublishFailed ? 0 : fieldsCreated;
372
+ const fieldsPublishedEstimate = publishingBlocked || fieldPublishFailed ? 0 : createdFieldCount;
338
373
  const result = {
339
374
  status,
340
375
  model: code,
341
376
  name,
342
377
  fieldCount,
343
- created: fieldsCreated,
344
- skipped: steps.filter((step) => step.step.endsWith("field.create") && step.status === "skipped").length,
378
+ declaredFieldCount: fields.length,
379
+ createdFieldCount,
380
+ alreadyPresentFieldCount,
381
+ childColumnCount,
382
+ childColumnsCreated,
383
+ failedFieldCount: failedFields.length,
384
+ countsNote: "declaredFieldCount = 本次 --fields 声明的顶层字段数;createdFieldCount = 本次真正新写入的业务字段数(子表 attach 一并建出的子列计入 created,不记 skipped);alreadyPresentFieldCount = 本次开始前就已存在的字段数;fieldCount = 最终业务字段总数(declaredFieldCount + childColumnCount)。旧键 created/skipped 分别是 createdFieldCount/alreadyPresentFieldCount 的别名。",
385
+ created: createdFieldCount,
386
+ skipped: alreadyPresentFieldCount,
345
387
  failed: failedFields.length,
346
388
  publishActions,
347
389
  publishedFields: publishActions,
@@ -228,6 +228,49 @@ const childTable = Object.freeze({
228
228
  ],
229
229
  requiresEnvironmentDerivedIds: false,
230
230
  });
231
+ /**
232
+ * 探针 C F1(0.8.8):子表列取主表字段的快照填充。
233
+ *
234
+ * 平台执行面(file:line 见交付报告):mappings 的 `{source,target}` 就是
235
+ * `WorkSheetPropertyMapping.linkageCode/assignmentCode`(2.1.5 :45-54)——
236
+ * source=关联目标(本例=父模型)字段,target=本模型(子表)字段;
237
+ * `WorkSheetMappingServiceImpl` 只在表单映射链里 `assignChildData`,CLI
238
+ * `data.save` 走的 `/api/runtime/form/save` 不调用 mappingList(探针 C F4)。
239
+ */
240
+ const childTableParentFieldFill = Object.freeze({
241
+ id: "child-map-fill",
242
+ title: "子表取主表",
243
+ aliases: ["取主表", "关联填充"],
244
+ status: "requires-prior-readback",
245
+ tool: "field.create",
246
+ args: {
247
+ environment,
248
+ schemaCode: "<model>_items",
249
+ code: "refParent",
250
+ name: "关联",
251
+ propertyType: "WORK_SHEET",
252
+ relativeCode: "<model>",
253
+ options: {
254
+ schemaCode: "<model>",
255
+ queryCode: "<model>",
256
+ displayField: "<父字段>",
257
+ mappings: [{ source: "<父字段>", target: "<快照列>" }],
258
+ },
259
+ },
260
+ preconditions: [
261
+ "子表 code 全局唯一;先建并发布快照标量列,再建关联列。",
262
+ "映射只在门户选值时回填:CLI data.save 不跑映射,API 写入须自带快照值。",
263
+ ],
264
+ conditionalRequirements: [
265
+ "关联列必须带 relativeCode(=options.schemaCode=主模型);source=主模型字段、target=本子表列,均裸 code。",
266
+ "关联列不能是 CHILD_TABLE/OCR/ELECTRONIC_SIGN/MULT_WORK_SHEET/RELEVANCE_DATA/FORMULA;field.publish 后 field.get 读回 options.mappings。",
267
+ ],
268
+ priorToolReferences: [],
269
+ dryRun: { supported: true, command: `omc call field.create --env ${environment} --dry-run --args '<args>'`, notes: "" },
270
+ expectedReadback: { readback: { fieldPresent: true }, next: ["field.publish", "field.get 读回映射"] },
271
+ refusalRecovery: [{ code: "relation-mapping-field-not-found", action: "source 用主模型字段、target 用本子表列,均裸 code" }],
272
+ requiresEnvironmentDerivedIds: true,
273
+ });
231
274
  const businessModelDropdown = Object.freeze({
232
275
  id: "business-model-dropdown",
233
276
  title: "用另一个模型的数据作下拉来源(businessModel)",
@@ -420,6 +463,6 @@ const externalLookupModel = Object.freeze({
420
463
  });
421
464
  export const FIELD_METADATA = Object.freeze({
422
465
  "field.update": Object.freeze({ recipes: [formConditionalRequired, formAlwaysReadonly, formConditionalReadonly], relatedTools: ["field.list", "field.publish", "form.draft", "form.publish"] }),
423
- "field.create": Object.freeze({ recipes: [fieldSerialNumber, numericTwoDecimals, numericPercent, dictionarySelection, dictionaryMultiSelection, childTable, businessModelDropdown, formulaAggregationCrossModel, formulaExpressionSameModel, externalLookupModel], relatedTools: ["dictionary.names", "dictionary.records", "discover_environment", "field.list", "field.publish", "form.draft", "configure_form", "form.publish"] }),
466
+ "field.create": Object.freeze({ recipes: [fieldSerialNumber, numericTwoDecimals, numericPercent, dictionarySelection, dictionaryMultiSelection, childTable, childTableParentFieldFill, businessModelDropdown, formulaAggregationCrossModel, formulaExpressionSameModel, externalLookupModel], relatedTools: ["dictionary.names", "dictionary.records", "discover_environment", "field.list", "field.publish", "form.draft", "configure_form", "form.publish"] }),
424
467
  });
425
468
  //# sourceMappingURL=field.js.map
@@ -9,7 +9,7 @@ const listViewConfigure = Object.freeze({
9
9
  conditionalRequirements: [
10
10
  "**省略 `code` 即配置默认视图(code = schemaCode);不要先 listview.create——那会多出一个自定义视图。** 只有确实需要第二个视图时才 listview.create。案卷:r60a-F13 真机对齐 2026-11-13;r73 #6 真机对齐 2026-11-17;8.6.41 实测默认视图同样可 configure(改默认视图影响所有用户)。",
11
11
  "`fieldCodes` 只列业务字段,可给 propertyCode 或字段显示名;系统列由平台决定。未知引用被拒(listview-columns-unknown-field)。",
12
- "数值列 displayFormat 由字段 0 基 `options.scale` 推导(0=整数,1=1位,2=2位…;真机:scale 2 → displayFormat 3 = 两位小数);本工具会原地修正既有列的 displayFormat。",
12
+ "**`displayFormat` 是平台数值格式枚举,不是字段 `scale`**(scale 只决定小数位,currency/percent 会覆盖位数)。平台 `QueryRuntimeController.parseNumber`(8.6.26 :1830,case 1/2/3/11/12/23..26 小数、case 4/5/6/13/14/27..30 百分比、case 7/15/16/31..34 货币¥、case 8/17/18/35..38 美元、case 9/19/20/39..42 欧元;前端枚举同值:`RMB.percentile=7`、`ratio.percentile=6`,admin bundle 19497.069256cf.js)。枚举表:**1=0 位小数、2=1 位、3=2 位、11=3 位、12=4 位、23..26=5..8 位**(`1..n=小数位` 这一族;真机 scale 2 → displayFormat 3);**6=百分比(2 位)**、4/5/13/14/27..30 为百分比其它位数;**7=货币 ¥(2 位)**、15/16/31..34 为货币其它位数。金额列(NUMERICAL scale=2 + format=RMB.percentile)回读 7,不是 3。本工具会原地修正既有列的 displayFormat。",
13
13
  "**列汇总**:数值列 `sumType` wire 为整数——0=不统计/1=求和/2=平均/3=最小/4=最大/5=计数,写进 `presentation.columnsJson` 的列对象(8.6.26 反编译 SumType 实证)。",
14
14
  "`query/update` 自动 publish=TRUE——视图无草稿/发布两态,无需独立发布步骤。",
15
15
  ],
@@ -28,6 +28,8 @@ const KEY_RULES = Object.freeze({
28
28
  workflowCode: { cls: "registry", source: "workflow.get_published → code" },
29
29
  sheetCode: { cls: "registry", source: "form.get / model.inspect → 默认表单槽位" },
30
30
  propertyCode: { cls: "registry", source: "field.list → fields[].code(名称匹配,可能歧义)" },
31
+ // 0.8.8(探针 C F1):子表关联列的 relativeCode = 关联目标模型 code(model.list 可查)。
32
+ relativeCode: { cls: "registry", source: "model.list → models[].schemaCode(关联目标模型)" },
31
33
  serviceCode: { cls: "registry", source: "service.list → serviceCode" },
32
34
  methodCode: { cls: "registry", source: "method.get / service.get → methodCode" },
33
35
  serviceCategoryId: { cls: "registry", source: "service.category.list → id(「全部」空 id 不可用)" },
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@stalfh233/omc-cli",
3
- "version": "0.8.7",
3
+ "version": "0.8.8",
4
4
  "description": "CloudPivot 8.6 configuration capability CLI — governed, fail-closed, coverage-manifest bounded.",
5
5
  "type": "module",
6
6
  "bin": {
@@ -58,7 +58,7 @@
58
58
  },
59
59
  "dependencies": {
60
60
  "commander": "14.0.3",
61
- "omc-core": "0.8.7",
61
+ "omc-core": "0.8.8",
62
62
  "proper-lockfile": "4.1.2",
63
63
  "write-file-atomic": "6.0.0",
64
64
  "zod": "^3.23.8",
@@ -76,6 +76,6 @@
76
76
  "directory": "packages/omc-cli"
77
77
  },
78
78
  "optionalDependencies": {
79
- "@stalfh233/omc-fake-platform": "0.8.7"
79
+ "@stalfh233/omc-fake-platform": "0.8.8"
80
80
  }
81
81
  }
@@ -39,6 +39,19 @@ capability's coverage/tools/boundaries from `omc-capabilities`.
39
39
  | 集成、接口、服务、回调、对接外部系统 | B2 业务集成服务 (`service.register`);二开接口 = 扩展模块写 REST 接口 + RESTFUL 服务指向它;自定义协议适配器 SPI 非常规、不在支持面 |
40
40
  | 数据、提交、保存、删除、查记录 | M2 runtime data |
41
41
 
42
+ ## 子表关联列取主表字段(options.mappings 字段映射)
43
+
44
+ 需求原话常是「子表列指向主模型,把 `pb_repair.repairNo` 映射到 `pb_repair_items.repairNoSnapshot`」——这是**子表 schema 上的 WORK_SHEET 关联列 + `options.mappings`**,不是业务规则 `dataActions`。
45
+
46
+ 1. 先在子表 schema 建快照标量列(如 `repairNoSnapshot` SHORT_TEXT)并发布。
47
+ 2. 再建关联列,形状照抄配方 `omc describe field.create --example child-map-fill`:
48
+ `field.create {schemaCode:"<model>_items", code:"refParent", propertyType:"WORK_SHEET", relativeCode:"<model>", options:{schemaCode:"<model>", queryCode:"<model>", displayField:"<父字段>", mappings:[{source:"<父字段>",target:"<快照列>"}]}}`。
49
+ 3. `field.publish`(整模型一次)→ `field.get` 读回核对 `options.mappings`。
50
+
51
+ - **字段映射**的事实源是字段行 `options.mappings`(`source`=关联目标/父模型字段,`target`=本子表列,都是裸 code);改表单控件属性里的映射会被平台按字段重算覆盖。
52
+ - **关联填充只在门户选值时由表单运行时回填**:CLI `data.save`(`/api/runtime/form/save`)**不跑映射**,API 写入必须自己带快照列值,否则读回为空——这不是映射配置失败。
53
+ - 子表 code 是全局唯一子 schema;关联列必须带 `relativeCode`,且不能是 CHILD_TABLE / OCR / ELECTRONIC_SIGN / MULT_WORK_SHEET / RELEVANCE_DATA / FORMULA。
54
+
42
55
  ## 横切面 — landscape and boundaries
43
56
 
44
57
  Coverage status and boundaries for every capability (including 权限/子表/聚合/