@stalfh233/omc-cli 0.8.3 → 0.8.5

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.
@@ -1227,17 +1227,120 @@ export function customButtonJsonStoredShape(options) {
1227
1227
  return "absent";
1228
1228
  }
1229
1229
  export const CUSTOM_BUTTON_JSON_STRING_SHAPE_WARNING = "customButtonJson 被存为字符串(双重编码)——前端按钮不渲染,设计器形状=数组+actionConfig 对象(线上 #38);用 form.draft/form.publish 重写 buttons 即自愈";
1230
+ /**
1231
+ * B5-2(issue 2026-11-25 真机 2.1.5):`faces.inSync` 原先只比
1232
+ * `draftViewJson === publishedViewJson`,于是「草稿改了字段标签
1233
+ * (attributesJson.options.name)」仍旧回 `inSync:true / effectiveFace:"published"`,
1234
+ * 结论句还写「与发布面一致」。
1235
+ *
1236
+ * 平台自己的「有没有未发布草稿」判定比的是**四对**面(对:
1237
+ * attributes/view/actions/html,任一不同即 existDraft):
1238
+ * - 8.6.26:`AppIntegrationFacadeImpl.java:2670`(decompiled-full/launcher-8.6.26/
1239
+ * cloudpivot-engine)同式在 `decompiled-engine/.../AppIntegrationFacadeImpl.java:2725`;
1240
+ * 随后的提拔分支把 draft 四份逐份拷进 published(:2681-2684 / :2726-2730)。
1241
+ * - 设计器发布把四面写成同一份内存值:`publishedAttributesJson`/`publishedViewJson`
1242
+ * 由布局生成后回填 draft,`draftActionsJson=publishedActionsJson`、
1243
+ * `draftHtmlJson=publishedHtmlJson`(frontend-dist/admin/js/4280.cfa75764.js
1244
+ * `initLayout` 后的发布分支;同文件保存分支只写 draft)。
1245
+ * - 运行时面只认 published 四份:`getPublishBizForm` 把 draft 四份置 null 后交付
1246
+ * (ModelManagementFacadeImpl.java:626-640 / 2.1.5 :624-639,B5 已引)。
1247
+ *
1248
+ * 比较用**规范化后的语义等值**,不是字符串:平台两种写法(null vs "[]" vs "{}"、
1249
+ * 顶层 JSON 串、嵌套 stringified JSON、对象键序)表示同一个面时不应制造差异
1250
+ * (同一口径见 lanes/config-diff.ts 的 FORM_FACE_PAIRS / normalizeEmptyPair)。
1251
+ */
1252
+ export const FORM_FACE_PAIRS = [
1253
+ { key: "view", draftKey: "draftViewJson", publishedKey: "publishedViewJson" },
1254
+ { key: "attributes", draftKey: "draftAttributesJson", publishedKey: "publishedAttributesJson" },
1255
+ { key: "html", draftKey: "draftHtmlJson", publishedKey: "publishedHtmlJson" },
1256
+ { key: "actions", draftKey: "draftActionsJson", publishedKey: "publishedActionsJson" },
1257
+ ];
1258
+ const EMPTY_FORM_FACE = { __emptyFormFace: true };
1259
+ /**
1260
+ * Canonical value for one face: object keys sorted (order-insensitive), arrays
1261
+ * kept in order (row/button order is meaningful), and stringified JSON parsed
1262
+ * so `{options:"{\"name\":\"A\"}"}` and `{options:{name:"A"}}` compare equal.
1263
+ * null / "" / "[]" / "{}" all canonicalise to the same empty sentinel: the
1264
+ * platform stores "no face" in any of those spellings (config-diff
1265
+ * normalizeEmptyPair has the same rule for the diff face).
1266
+ */
1267
+ function canonicalFormFaceValue(value) {
1268
+ if (Array.isArray(value)) {
1269
+ if (value.length === 0)
1270
+ return EMPTY_FORM_FACE;
1271
+ return value.map((item) => canonicalFormFaceValue(item));
1272
+ }
1273
+ if (value !== null && typeof value === "object") {
1274
+ const entries = Object.entries(value)
1275
+ .filter(([, item]) => item !== undefined)
1276
+ .sort(([left], [right]) => (left < right ? -1 : left > right ? 1 : 0));
1277
+ if (entries.length === 0)
1278
+ return EMPTY_FORM_FACE;
1279
+ return Object.fromEntries(entries.map(([key, item]) => [key, canonicalFormFaceValue(item)]));
1280
+ }
1281
+ if (typeof value === "string") {
1282
+ const trimmed = value.trim();
1283
+ if (trimmed.startsWith("{") || trimmed.startsWith("[")) {
1284
+ try {
1285
+ return canonicalFormFaceValue(JSON.parse(trimmed));
1286
+ }
1287
+ catch {
1288
+ return value;
1289
+ }
1290
+ }
1291
+ return value;
1292
+ }
1293
+ return value;
1294
+ }
1295
+ /** Canonical signature of a stored face column (dirty/unparsable columns stay opaque text). */
1296
+ function formFaceSignature(value) {
1297
+ if (value === undefined || value === null)
1298
+ return JSON.stringify(EMPTY_FORM_FACE);
1299
+ if (typeof value !== "string")
1300
+ return JSON.stringify(canonicalFormFaceValue(value));
1301
+ const trimmed = value.trim();
1302
+ if (trimmed === "")
1303
+ return JSON.stringify(EMPTY_FORM_FACE);
1304
+ if (!trimmed.startsWith("{") && !trimmed.startsWith("["))
1305
+ return JSON.stringify(trimmed);
1306
+ try {
1307
+ return JSON.stringify(canonicalFormFaceValue(JSON.parse(trimmed)));
1308
+ }
1309
+ catch {
1310
+ return JSON.stringify(trimmed);
1311
+ }
1312
+ }
1313
+ /**
1314
+ * Compare the draft face against the published face ACROSS all four published
1315
+ * columns. `draftPresent`/`publishedPresent` are the caller's content-derived
1316
+ * presence booleans (same rule as `faces.*.present`); when either side is
1317
+ * absent the faces are not comparable and `inSync` stays null.
1318
+ */
1319
+ export function compareFormFaces(sheet, presence) {
1320
+ if (!presence.draftPresent || !presence.publishedPresent)
1321
+ return { inSync: null, differingFaces: [] };
1322
+ const differingFaces = [];
1323
+ for (const pair of FORM_FACE_PAIRS) {
1324
+ if (formFaceSignature(sheet[pair.draftKey]) !== formFaceSignature(sheet[pair.publishedKey]))
1325
+ differingFaces.push(pair.key);
1326
+ }
1327
+ return { inSync: differingFaces.length === 0, differingFaces };
1328
+ }
1230
1329
  export function resolveEffectiveFormFace(input) {
1231
1330
  const { draftPresent, publishedPresent, inSync } = input;
1232
1331
  if (publishedPresent) {
1233
- if (draftPresent && inSync === false)
1332
+ if (draftPresent && inSync === false) {
1333
+ const where = input.differingFaces && input.differingFaces.length > 0 ? `(${input.differingFaces.join("/")} 面不同)` : "";
1234
1334
  return {
1235
1335
  effectiveFace: "both",
1236
- effectiveFaceNote: "线上=published 面;draft 有未发布改动,发布后才生效",
1336
+ effectiveFaceNote: `线上=published 面;draft 是另一份未发布草稿,有未发布改动${where},form.publish 后才生效`,
1237
1337
  };
1338
+ }
1238
1339
  return {
1239
1340
  effectiveFace: "published",
1240
- effectiveFaceNote: "线上=published 面(draft 为空或与发布面一致)",
1341
+ effectiveFaceNote: draftPresent
1342
+ ? "线上=published 面(draft 内容与发布面语义一致,没有未发布改动)"
1343
+ : "线上=published 面(没有草稿面)",
1241
1344
  };
1242
1345
  }
1243
1346
  if (draftPresent)
@@ -2,6 +2,8 @@ import { validateBusinessCode } from "../../code-rules.js";
2
2
  import { fieldSemanticDescriptor, prepareFieldChange } from "../../field-change.js";
3
3
  import { CHILD_TABLE_SCALAR_PROPERTY_TYPES, FIELD_PROPERTY_TYPES, OUT_OF_COVERAGE_FIELD_TYPES, isNumericalScale } from "../../field-families.js";
4
4
  import { ENDPOINTS } from "../../endpoints.js";
5
+ import { lintFieldCreateWrite, modelSchemaCodes } from "../../lanes/field.js";
6
+ import { ToolRefusalError } from "../../tool-types.js";
5
7
  import { wireCall, wireRows } from "../../wire.js";
6
8
  import { canonicalJson } from "../dsl.js";
7
9
  import { refuse } from "../capability.js";
@@ -171,6 +173,102 @@ async function readFields(session, schemaCode) {
171
173
  }
172
174
  return [...fields.values()];
173
175
  }
176
+ /**
177
+ * 0.8.4 P0 同类收尾(W21):intent 逐字段调用 `field.create`,语义门确实会跑;
178
+ * 但**新模型**此刻发布面为空,而共享门 `assertRelationOptionsFields` 的既有设计是
179
+ * 「空读面不判」(避免读面不可用时误拒)。于是同一 `models[].fields[]` 内、映射
180
+ * target 指向同包字段、或聚合指向同包裸子表 code 的声明会落回那个逃生口——与
181
+ * `configure_model` 修前的 P0 同类。
182
+ *
183
+ * 这里把**本次 plan 里该模型声明的全部字段**整理成 overlay(code + 字段族),
184
+ * apply 时交给同一个 `lintFieldCreateWrite`。只取同一意图同一模型的声明:
185
+ * 不读上一次 plan、不跨模型借字段、不把声明 absent 的字段并进来。
186
+ */
187
+ export function intentOwnFieldOverlays(intent) {
188
+ const overlays = new Map();
189
+ for (const model of intent.models) {
190
+ if (model.absent === true)
191
+ continue;
192
+ // Model schema: every declared-present field is a mapping target candidate.
193
+ const ownFields = model.fields
194
+ .filter((field) => field.absent !== true)
195
+ .map((field) => ({ code: field.code, propertyType: field.type }));
196
+ if (ownFields.length > 0)
197
+ overlays.set(model.code, ownFields);
198
+ // Child schema: `field.create` for a child column carries schemaCode = the
199
+ // parent field code, and its own face is the declared child columns. A child
200
+ // code shares the platform's global schema namespace with models, so never
201
+ // overwrite a model entry.
202
+ for (const field of model.fields) {
203
+ if (field.absent === true || field.type !== "CHILD_TABLE")
204
+ continue;
205
+ const columns = (field.subFields ?? []).map((sub) => ({ code: sub.code, propertyType: sub.type }));
206
+ if (columns.length > 0 && !overlays.has(field.code))
207
+ overlays.set(field.code, columns);
208
+ }
209
+ }
210
+ return overlays;
211
+ }
212
+ /** One planned `field.create` as the shared gate's input (the plan's args are the tool shape). */
213
+ function gateInputOf(schemaCode, args, targetVersion) {
214
+ return {
215
+ schemaCode,
216
+ code: String(args.code ?? ""),
217
+ name: String(args.name ?? ""),
218
+ propertyType: args.propertyType,
219
+ ...(args.options !== null && typeof args.options === "object" ? { options: args.options } : {}),
220
+ ...(Array.isArray(args.choices) ? { choices: args.choices } : {}),
221
+ ...(typeof args.relativeCode === "string" ? { relativeCode: args.relativeCode } : {}),
222
+ ...(Array.isArray(args.subFields) ? { subFields: args.subFields } : {}),
223
+ ...(typeof args.propertyEmpty === "boolean" ? { propertyEmpty: args.propertyEmpty } : {}),
224
+ ...(targetVersion ? { targetVersion } : {}),
225
+ };
226
+ }
227
+ /**
228
+ * `intent apply` 的字段写前语义门:在**任何写 wire 之前**把本次 plan 的字段
229
+ * 创建整包过一遍 `field.create` 的同门 `lintFieldCreateWrite`,并附上同包声明
230
+ * 字段作为本模型读面 overlay。只发 GET(发布面读 + 租户模型清单)。
231
+ *
232
+ * 判定不在这里重写:blocker / 诊断字段与 `field.create` 逐字同形(同门产物),
233
+ * 另加 `intentField` 定位到 plan 里的具体字段。
234
+ */
235
+ export async function lintIntentFieldCreateChanges(session, intent, changes) {
236
+ const overlays = intentOwnFieldOverlays(intent);
237
+ if (overlays.size === 0)
238
+ return undefined;
239
+ const relevant = changes.filter((change) => change.tool === "field.create" && overlays.has(String(change.args.schemaCode ?? "")));
240
+ if (relevant.length === 0)
241
+ return undefined;
242
+ // One model-list read for the whole plan (field.create would read it per field).
243
+ const relationCandidates = await modelSchemaCodes(session);
244
+ const targetVersion = session.detectedVersion();
245
+ for (const change of relevant) {
246
+ const schemaCode = String(change.args.schemaCode ?? "");
247
+ try {
248
+ await lintFieldCreateWrite(session, gateInputOf(schemaCode, change.args, targetVersion), {
249
+ relationCandidates,
250
+ pendingOwnFields: overlays.get(schemaCode),
251
+ });
252
+ }
253
+ catch (error) {
254
+ if (!(error instanceof ToolRefusalError))
255
+ throw error;
256
+ const { status: _status, ...detail } = error.payload;
257
+ return {
258
+ status: "refused",
259
+ ...detail,
260
+ intentField: {
261
+ schemaCode,
262
+ code: String(change.args.code ?? ""),
263
+ ...(change.resource !== undefined ? { resource: change.resource } : {}),
264
+ },
265
+ message: `${String(detail.message ?? "字段写前语义门拒绝")};intent apply 在任何写 wire 之前按整包字段面判定,本次零写入——修正意图后重新 intent plan`,
266
+ nextAction: "fix the declared fields/mappings in the intent, then re-run intent plan + apply",
267
+ };
268
+ }
269
+ }
270
+ return undefined;
271
+ }
174
272
  /**
175
273
  * The field capability (field families + CHILD_TABLE columns). It owns the
176
274
  * whole field lifecycle on the intent face: declaration validation, the
@@ -21,6 +21,7 @@ import { jsonBytes, sha256, writeArtifact } from "../support.js";
21
21
  import { INTENT_COMPILER_VERSION, intentConfigRoot, readIntentFile } from "./cli.js";
22
22
  import { validateRuleNodeGraph, PLATFORM_TRIGGER_RULE_CODES, walkConditionLeaves } from "../lanes/rule-graph.js";
23
23
  import { expectedRuleGraph } from "./capabilities/businessrule.js";
24
+ import { lintIntentFieldCreateChanges } from "./capabilities/field.js";
24
25
  import { readBaseline, baselineFingerprintOf } from "./baseline.js";
25
26
  import { compileIntent } from "./compiler.js";
26
27
  import { buildPlan, verifyPlan } from "./plan-file.js";
@@ -510,6 +511,14 @@ export async function applyIntent(planPath, options, ports) {
510
511
  environment: session.environmentName,
511
512
  message: "plan 之后环境已变化(baseline fingerprint 不一致)——按配置基线契约,写入前必须重新 intent plan;绝不盲用过期 plan",
512
513
  });
514
+ // 0.8.4 P0 同类收尾(W21):intent 的字段创建走 field.create,门会跑,但新模型
515
+ // 此刻发布面为空——共享门的「空读面不判」会让同包关系映射/裸子表聚合落回逃生
516
+ // 口。用本次 plan 的整包字段声明作 overlay,在**任何写 wire 之前**补判(只 GET)。
517
+ const fieldGateRefusal = await lintIntentFieldCreateChanges(session, plan.intent, plan.changes);
518
+ if (fieldGateRefusal !== undefined) {
519
+ console.error(`intent apply ${planId}:字段写前语义门拒绝(${String(fieldGateRefusal.blocker)})——零写入`);
520
+ return emit(fieldGateRefusal);
521
+ }
513
522
  // Ticket 123 — the final confirmation: after the writes (or on an
514
523
  // already-converged no-op) decode the authoritative live state back into
515
524
  // intent shape and compare. A mismatch is NEVER reported as plain success
@@ -86,8 +86,55 @@ function propertyTypeName(type) {
86
86
  return name;
87
87
  return String(type);
88
88
  }
89
+ function pendingOwnFieldRows(pending) {
90
+ return pending.flatMap((field) => {
91
+ const raw = field.propertyType;
92
+ const type = typeof raw === "number" ? raw : FIELD_PROPERTY_TYPES[String(raw)];
93
+ return field.code ? [{ code: field.code, ...(type !== undefined ? { type } : {}) }] : [];
94
+ });
95
+ }
96
+ /**
97
+ * 平台「**模型不存在**」的 errcode 白名单——只有这一类允许把本模型发布面读成
98
+ * 空读面。白名单之外的任何失败(50000 / 权限 / 超时 / 404 端点缺席)都必须原样
99
+ * 抛出去:吞掉它们等于「无证据不判」,会把写前门变成逃生口。
100
+ *
101
+ * 证据(双版本 ErrorCode 枚举逐字一致):
102
+ * - 8.6.26 `backend/decompiled-full/launcher-8.6.26/cloudpivot-shared-8.6.26/
103
+ * com/authine/cloudpivot/engine/ErrorCode.java:183`
104
+ * `BIZ_SCHEMA_MODEL_NOT_EXIST(300004L, "数据模型不存在!")`
105
+ * - 2.1.5 `backend/decompiled-full/launcher-2.1.5/cloudpivot-contracts-AI-Platform-v2.1.5/
106
+ * com/authine/cloudpivot/engine/ErrorCode.java:199` 同值
107
+ * - 抛点:`BizPropertyController.getPropertyList`(2.1.5 `cloudpivot-engine-AI-Platform-v2.1.5/
108
+ * .../app/BizPropertyController.java:232`,方法体 :225;8.6.26 同文件:346,方法体 :339)
109
+ * —— `getBizSchemaBySchemaCode` 回 null(schema 不存在)即抛该码。
110
+ *
111
+ * **300010 刻意不在白名单**:同枚举里它是 `BIZ_SCHEMA_CODE_EMPTY`
112
+ * 「数据模型编码不能为空!」(8.6.26:188 / 2.1.5:204),语义是「入参 schemaCode
113
+ * 为空」,不是「模型不存在」;吞它会掩盖入参错误。HTTP 404 属网关/端点缺席
114
+ * (wire.ts 的 http-status 家族),也不是同一类。
115
+ */
116
+ const MODEL_ABSENT_ERRCODES = new Set([300004]);
117
+ /**
118
+ * 本模型发布面读:模型不存在(300004)时退化为**空读面**,与
119
+ * `assertRelationOptionsFields` 内 `rowsOf` 的 `.catch(() => [])` 同口径。
120
+ *
121
+ * 0.8.5 P0 回归:`configure_model` 新建模型时本读面必然 300004,0.8.4 让它无兜底
122
+ * 抛上来,整条新建路径 100% 不可用(2.1.5 真机)。空读面 + `pendingOwnFields`
123
+ * overlay 仍参与判定(overlay 就是本模型字段面);没有 overlay 时由下游沿用
124
+ * 既有「空读面不判」的保守规则。
125
+ */
126
+ async function readPublishedFieldFace(session, schemaCode) {
127
+ try {
128
+ return wireRows((await wireCall(session, { path: ENDPOINTS.fieldList, query: { schemaCode, isPublish: "true" } })).data);
129
+ }
130
+ catch (error) {
131
+ if (error instanceof WireError && error.kind === "business" && error.errcode !== undefined && MODEL_ABSENT_ERRCODES.has(error.errcode))
132
+ return [];
133
+ throw error;
134
+ }
135
+ }
89
136
  /** Semantic relation gate: the designer only offers published business fields. */
90
- async function assertRelationOptionsFields(session, schemaCode, propertyType, relativeCode, options) {
137
+ async function assertRelationOptionsFields(session, schemaCode, propertyType, relativeCode, options, pendingOwnFields = []) {
91
138
  const type = typeof propertyType === "number" ? propertyType : FIELD_PROPERTY_TYPES[String(propertyType ?? "")];
92
139
  if (type !== FIELD_PROPERTY_TYPES.WORK_SHEET && type !== FIELD_PROPERTY_TYPES.MULT_WORK_SHEET)
93
140
  return;
@@ -109,7 +156,8 @@ async function assertRelationOptionsFields(session, schemaCode, propertyType, re
109
156
  return pending;
110
157
  };
111
158
  const targetRows = await rowsOf(target);
112
- const ownRows = await rowsOf(schemaCode);
159
+ // 同包声明、尚未落库的本模型字段并进本模型读面(configure_model 的 P0 缝)。
160
+ const ownRows = [...(await rowsOf(schemaCode)), ...pendingOwnFieldRows(pendingOwnFields)];
113
161
  // 设计器把「关联目标 = 某模型的子表」存成 options.mainTableCode(主表模型)
114
162
  // + options.schemaCode(子表)。前端 getSourceDataItems(bundle
115
163
  // admin/js/79850.2b085fc5.js@byte25582,mainTableCode 分支@25858)把主表字段与
@@ -135,6 +183,11 @@ async function assertRelationOptionsFields(session, schemaCode, propertyType, re
135
183
  const targetFields = business(targetRows);
136
184
  const ownFields = business(ownRows);
137
185
  const mainFields = business(mainRows);
186
+ // 候选清单按 field.list 的业务字段口径(businessOnly)过滤:`parentId`/`sortKey`
187
+ // 是平台注入子表的系统列,业务字段面板不显示,提示里也不该出现(0.8.3 真机 §5.4)。
188
+ // **判定**仍用上面未过滤的字段集——系统列确实存在于模型,把它们从解析/存在性里
189
+ // 摘掉会把指向系统列的合法映射误判成「字段不存在」。
190
+ const listedFields = (fields) => fields.filter((row) => !isSystemFieldCode(row.code));
138
191
  // A compatibility/fake transport may expose an empty field face even though
139
192
  // the model exists. Empty metadata is not proof that a requested field is
140
193
  // absent; preserve the existing relation write path rather than rejecting a
@@ -210,7 +263,7 @@ async function assertRelationOptionsFields(session, schemaCode, propertyType, re
210
263
  return undefined;
211
264
  return business(sheetRows).find((row) => row.code === column);
212
265
  };
213
- const linkedCandidates = [...new Set([...targetFields, ...mainFields].map((row) => row.code))].sort();
266
+ const linkedCandidates = [...new Set(listedFields([...targetFields, ...mainFields]).map((row) => row.code))].sort();
214
267
  const display = typeof options.displayField === "string" ? options.displayField.trim() : "";
215
268
  if (display) {
216
269
  // 子表目标下显示字段来自主表模型(前端 getRelativeDataItem(mainTableCode))。
@@ -231,7 +284,7 @@ async function assertRelationOptionsFields(session, schemaCode, propertyType, re
231
284
  }
232
285
  if (!Array.isArray(mappings))
233
286
  return;
234
- const targetCandidates = ownFields.map((row) => row.code).sort();
287
+ const targetCandidates = listedFields(ownFields).map((row) => row.code).sort();
235
288
  for (const [index, row] of mappings.entries()) {
236
289
  const source = row && typeof row === "object" ? String(row.source ?? "").trim() : "";
237
290
  const mappedTarget = row && typeof row === "object" ? String(row.target ?? "").trim() : "";
@@ -241,7 +294,7 @@ async function assertRelationOptionsFields(session, schemaCode, propertyType, re
241
294
  // Diagnosis must be actionable: name the linked side(s) actually consulted.
242
295
  if (!sourceField)
243
296
  await loadTargetParent();
244
- const linkedCodes = [...new Set([...targetFields, ...mainFields, ...targetParentFields].map((entry) => entry.code))].sort();
297
+ const linkedCodes = [...new Set(listedFields([...targetFields, ...mainFields, ...targetParentFields]).map((entry) => entry.code))].sort();
245
298
  const side = !sourceField && !targetField ? "both" : !sourceField ? "source" : "target";
246
299
  const linkedHint = mainTableCode
247
300
  ? `关联模型 ${target} / 主表 ${mainTableCode}`
@@ -363,6 +416,23 @@ function isSystemFieldCode(code) {
363
416
  const value = String(code ?? "");
364
417
  return SYSTEM_FIELD_CODES.has(value) || value === "parentId" || value === "sortKey";
365
418
  }
419
+ /**
420
+ * 子表 schema(`bizmodels/get_all.parentCode` 非空)没有独立表单槽位:表单/在线 JS
421
+ * 都挂在父模型的 `bizsheet` 上。把子表 code 当 `form.get` 的入参只会固定回 50000
422
+ * 「服务异常」——那是噪音,不是「表单里没有这个字段」(0.8.3 真机 §5.6)。
423
+ * 判据读一次模型记录(与关联语义门同一个 parentCode 面);读不到就按「不是子表」
424
+ * 继续既有扫描,不因判定面不可用而扩大跳过范围。
425
+ */
426
+ async function schemaIsChildTable(session, schemaCode) {
427
+ try {
428
+ const record = await readModelRecord(session, schemaCode);
429
+ const parentCode = typeof record?.parentCode === "string" ? record.parentCode.trim() : "";
430
+ return parentCode !== "" && parentCode !== schemaCode;
431
+ }
432
+ catch {
433
+ return false;
434
+ }
435
+ }
366
436
  /**
367
437
  * 线上 #40 第 8 条(2026-11-17):field.list 只有 code/type/typeName/name,
368
438
  * 无法判断字段何时被删除/改名(探针只能用业务数据的时间反推)。
@@ -396,7 +466,7 @@ function pickFieldTimestamps(row) {
396
466
  * from an external model without a read. The create path already reads the
397
467
  * published field list, so resolve it here for free and refuse before the write.
398
468
  */
399
- function assertNoSelfSchemaAggregation(args, published) {
469
+ function assertNoSelfSchemaAggregation(args, published, pendingOwnFields = []) {
400
470
  const raw = args.propertyType;
401
471
  const propertyType = typeof raw === "number" ? raw : FIELD_PROPERTY_TYPES[String(raw)];
402
472
  if (propertyType !== FIELD_PROPERTY_TYPES.FORMULA)
@@ -409,9 +479,14 @@ function assertNoSelfSchemaAggregation(args, published) {
409
479
  const target = typeof agg?.schemaCode === "string" ? agg.schemaCode.trim() : "";
410
480
  if (!target)
411
481
  return;
412
- const childCodes = published
413
- .filter((row) => Number(row.type ?? row.propertyType) === FIELD_PROPERTY_TYPES.CHILD_TABLE)
414
- .map((row) => String(row.code ?? row.propertyCode ?? ""));
482
+ const childCodes = [
483
+ ...published
484
+ .filter((row) => Number(row.type ?? row.propertyType) === FIELD_PROPERTY_TYPES.CHILD_TABLE)
485
+ .map((row) => String(row.code ?? row.propertyCode ?? "")),
486
+ ...pendingOwnFieldRows(pendingOwnFields)
487
+ .filter((row) => row.type === FIELD_PROPERTY_TYPES.CHILD_TABLE)
488
+ .map((row) => String(row.code)),
489
+ ];
415
490
  const resolvesToSelf = aggregationTargetsOwnSchema(args.schemaCode, target) || childCodes.includes(stripAggregationPrefix(target));
416
491
  if (!resolvesToSelf)
417
492
  return;
@@ -461,6 +536,32 @@ async function assertNoChildSchemaAggregation(session, schemaCode, propertyType,
461
536
  `(门户计算规则 / 写入方维护),再用 AGGREGATION 聚合该标量。配方:omc describe field.create --example formula-aggregation-cross-model。`,
462
537
  });
463
538
  }
539
+ /**
540
+ * `field.create` 的**唯一**写前语义门(0.8.4 P0,2.1.5/8.6.26 双侧证据见
541
+ * assertRelationOptionsFields / assertNoSelfSchemaAggregation 的注释):
542
+ *
543
+ * 1. 聚合自引用/本模型子表(305003 死循环);
544
+ * 2. 聚合目标是子表 schema(目标模型从此不可写 40000);
545
+ * 3. 关联目标模型不存在(发布 300010 毒模型);
546
+ * 4. 关联映射的 source/target 合法性(运行期 50000 / 静默丢值)。
547
+ *
548
+ * `field.create` 与 `configure_model` 的 `fields[]` 都调这一个函数:编排(写锁、
549
+ * 顺序、续跑)留在各自 lane,判定只在这里。**不要**在别处再内联其中任何一道。
550
+ */
551
+ export async function lintFieldCreateWrite(session, input, options = {}) {
552
+ const published = options.publishedRows
553
+ ?? await readPublishedFieldFace(session, input.schemaCode);
554
+ const pendingOwnFields = options.pendingOwnFields ?? [];
555
+ assertNoSelfSchemaAggregation({ schemaCode: input.schemaCode, propertyType: input.propertyType, options: input.options }, published, pendingOwnFields);
556
+ await assertNoChildSchemaAggregation(session, input.schemaCode, input.propertyType, input.options ?? {});
557
+ assertRelationTargetExists({ ...input }, options.relationCandidates ?? await modelSchemaCodes(session));
558
+ // 目标版本决定 optionsSet 形状:8.2 以下要补 optionStructure/treeSelect
559
+ // (cpdocs issue #8:缺键让设计器选项弹窗硬崩)。
560
+ const targetVersion = input.targetVersion ?? session.detectedVersion();
561
+ const prepared = prepareFieldChange({ ...input, ...(targetVersion ? { targetVersion } : {}) });
562
+ await assertRelationOptionsFields(session, input.schemaCode, prepared.propertyType, input.relativeCode, prepared.options, pendingOwnFields);
563
+ return prepared;
564
+ }
464
565
  export function registerFieldLane(tools) {
465
566
  tools.push(defineTool({
466
567
  name: "field.list",
@@ -717,15 +818,10 @@ export function registerFieldLane(tools) {
717
818
  }
718
819
  // One seam owns field-change normalization, every reproduced gate, and the
719
820
  // wire body (src/field-change.ts), so configure_model and intent share it.
720
- assertNoSelfSchemaAggregation(args, published);
721
- await assertNoChildSchemaAggregation(session, args.schemaCode, args.propertyType, args.options ?? {});
722
- const models = await modelSchemaCodes(session);
723
- assertRelationTargetExists({ ...args }, models);
724
- // 目标版本决定 optionsSet 形状:8.2 以下要补 optionStructure/treeSelect
725
- // (cpdocs issue #8:缺键让设计器选项弹窗硬崩)。
821
+ // 0.8.4 P0: the three semantic gates live in lintFieldCreateWrite, which
822
+ // configure_model calls too — never inline a subset here again.
726
823
  const targetVersion = session.detectedVersion();
727
- const prepared = prepareFieldChange({ ...args, ...(targetVersion ? { targetVersion } : {}) });
728
- await assertRelationOptionsFields(session, args.schemaCode, prepared.propertyType, args.relativeCode, prepared.options);
824
+ const prepared = await lintFieldCreateWrite(session, { ...args, ...(targetVersion ? { targetVersion } : {}) }, { publishedRows: published });
729
825
  let performed;
730
826
  try {
731
827
  performed = await wireCall(session, { path: ENDPOINTS.fieldCreate, method: "POST", body: fieldChangeWireBody(args, prepared) });
@@ -832,6 +928,16 @@ export function registerFieldLane(tools) {
832
928
  },
833
929
  preflight: (args) => assertNameI18nArg(args.name_i18n),
834
930
  dryRunPayload: fieldUpdateDryRun,
931
+ // 0.8.4 P0:真写与 dry-run 同门。此前 field.update 只有 dryRunPayload——
932
+ // 关联映射/显示字段的发布面语义门只在预览路径,真写把非法 mappings 原样
933
+ // 写进平台(2.1.5 真机:dry-run refused relation-mapping-field-not-found,
934
+ // 真写 ok/DELIVERED)。writeLint 在 lease 内、任何写 wire 之前跑
935
+ // lintFieldUpdateWrite(与 dry-run 同一个函数),拒绝即零 wire。
936
+ writeLint: async (session, args) => {
937
+ await lintFieldUpdateWrite(session, args);
938
+ },
939
+ lintScope: "partial",
940
+ lintUnchecked: ["sync-dictionary-binding", "platform-side-validation", "post-write-readback"],
835
941
  rollback: fieldRollbackSpec("field.update"),
836
942
  });
837
943
  writeTool({
@@ -895,7 +1001,7 @@ export function registerFieldLane(tools) {
895
1001
  const impact = await collectFieldDeleteImpact(session, args, { full: true });
896
1002
  return { wouldChange: true, impact, schemaCode: args.schemaCode, code: args.code };
897
1003
  },
898
- lintScope: "full",
1004
+ lintScope: "partial",
899
1005
  lintUnchecked: ["platform-side-validation", "post-write-readback"],
900
1006
  rollback: fieldRollbackSpec("field.delete"),
901
1007
  });
@@ -1073,10 +1179,17 @@ function assertNoImmutableOptionChanges(schemaCode, code, changedOptionKeys) {
1073
1179
  });
1074
1180
  }
1075
1181
  /**
1076
- * Session-aware dry-run for field.update: structured from→to changes (only real
1077
- * diffs), plus an honest dataImpact note when storage-shape keys move.
1182
+ * `field.update` 的唯一写前门(R75-B 同门缝)。
1183
+ *
1184
+ * 0.8.4 P0(2026-11-26,2.1.5 真机):关联映射语义门只在 `dryRunPayload` 里,
1185
+ * 真写 `runFieldUpdate` 没跑它——同一份 args `--dry-run` 回
1186
+ * `relation-mapping-field-not-found`,真写却 ok/DELIVERED 并把
1187
+ * `{"source":"no_such_field","target":"bm"}` 写进平台。本函数把「读字段行 →
1188
+ * 聚合自引用门 → prepareFieldUpdate → 关联映射/显示字段发布面门」收成一个
1189
+ * 只读函数,dry-run、`writeLint`(真写路径,lease 内、写 wire 之前)与
1190
+ * `runFieldUpdate` 都调它,不复制判定。
1078
1191
  */
1079
- async function fieldUpdateDryRun(session, args) {
1192
+ async function lintFieldUpdateWrite(session, args) {
1080
1193
  const record = await loadFieldRowForUpdate(session, args.schemaCode, args.code);
1081
1194
  if (args.options !== undefined) {
1082
1195
  const publishedRows = await wireCall(session, { path: ENDPOINTS.fieldList, query: { schemaCode: args.schemaCode, isPublish: "true" } })
@@ -1100,7 +1213,40 @@ async function fieldUpdateDryRun(session, args) {
1100
1213
  ...(args.propertyEmpty !== undefined ? { propertyEmpty: args.propertyEmpty } : {}),
1101
1214
  };
1102
1215
  const prepared = prepareFieldUpdate(update);
1216
+ await assertFieldUpdateRelationTarget(session, record, prepared, args);
1103
1217
  await assertRelationOptionsFields(session, args.schemaCode, prepared.propertyType, args.relativeCode ?? record.relativeCode, prepared.options);
1218
+ return { record, prepared };
1219
+ }
1220
+ /**
1221
+ * 审计 #2(W17):`field.update` 也能把关联列指向**不存在的模型**——`field.create`
1222
+ * 有 `assertRelationTargetExists`,update 的 dry-run 与真写两条路都没有。
1223
+ *
1224
+ * 只在调用方**改变了**关联目标(relativeCode / options.schemaCode 与存量不同)时
1225
+ * 校验。纯改名、只改别的 options 键不校验:目标模型已被平台删除后字段行仍在,
1226
+ * 若连改名都要求目标存在,这些历史字段就再也维护不了。判定复用 field.create 的
1227
+ * 同一个 assertRelationTargetExists(候选 = 租户模型 code 清单)。
1228
+ */
1229
+ async function assertFieldUpdateRelationTarget(session, record, prepared, args) {
1230
+ const type = typeof prepared.propertyType === "number" ? prepared.propertyType : FIELD_PROPERTY_TYPES[String(prepared.propertyType ?? "")];
1231
+ if (type !== FIELD_PROPERTY_TYPES.WORK_SHEET && type !== FIELD_PROPERTY_TYPES.MULT_WORK_SHEET)
1232
+ return;
1233
+ const requestedCandidate = typeof args.relativeCode === "string" ? args.relativeCode : prepared.options.schemaCode;
1234
+ const requested = typeof requestedCandidate === "string" ? requestedCandidate.trim() : "";
1235
+ if (!requested)
1236
+ return;
1237
+ const previousCandidate = record.relativeCode ?? optionsObjectOf(record.options).schemaCode;
1238
+ const previous = typeof previousCandidate === "string" ? previousCandidate.trim() : "";
1239
+ if (requested === previous)
1240
+ return;
1241
+ assertRelationTargetExists({ propertyType: type, options: prepared.options, relativeCode: args.relativeCode }, await modelSchemaCodes(session));
1242
+ }
1243
+ /**
1244
+ * Session-aware dry-run for field.update: structured from→to changes (only real
1245
+ * diffs), plus an honest dataImpact note when storage-shape keys move.
1246
+ */
1247
+ async function fieldUpdateDryRun(session, args) {
1248
+ // Same gate as the real write (writeLint → lintFieldUpdateWrite).
1249
+ const { record, prepared } = await lintFieldUpdateWrite(session, args);
1104
1250
  const currentOptions = decodeJsonObjectColumn(record.options, { invalid: "throw", array: "accept", object: "accept" }) ?? {};
1105
1251
  const changes = [];
1106
1252
  const pushChange = (field, from, to) => {
@@ -1240,76 +1386,85 @@ async function scanFieldRuleReferences(session, schemaCode, code) {
1240
1386
  }
1241
1387
  return { references };
1242
1388
  }
1243
- async function scanFieldFormListviewOnlineJs(session, schemaCode, code) {
1389
+ async function scanFieldFormListviewOnlineJs(session, schemaCode, code, options = {}) {
1244
1390
  const references = [];
1245
1391
  const dependentUpdates = {};
1246
- // form.get 面:控件码清单
1247
- try {
1248
- const sheet = (await wireCall(session, { path: ENDPOINTS.sheetGet, query: { schemaCode, sheetCode: schemaCode } })).data;
1249
- if (!sheet) {
1250
- dependentUpdates.form = { present: false, note: "默认表单不存在(sheetGet 空)" };
1251
- }
1252
- else {
1253
- const draftControls = formControlCodes(sheet.draftAttributesJson);
1254
- const publishedControls = formControlCodes(sheet.publishedAttributesJson);
1255
- const inDraft = draftControls.includes(code);
1256
- const inPublished = publishedControls.includes(code);
1257
- dependentUpdates.form = {
1258
- present: true,
1259
- inDraft,
1260
- inPublished,
1261
- note: inDraft || inPublished
1262
- ? "删除字段后表单控件会残留;需 form.draft(rebuild)/form.publish 清理"
1263
- : "默认表单控件码未引用该字段",
1264
- };
1265
- if (inDraft || inPublished) {
1266
- references.push({
1267
- kind: "form",
1268
- code: schemaCode,
1269
- name: String(sheet.name ?? schemaCode),
1270
- via: inDraft && inPublished ? "draft+published controls" : inDraft ? "draft controls" : "published controls",
1271
- schemaCode,
1272
- });
1392
+ const childSchema = options.childSchema === true;
1393
+ // 子表 code 没有独立表单面(表单/在线 JS 挂在父模型上):不把子表 code 当
1394
+ // form.get 的入参,否则每次影响面扫描都固定回一条 50000 噪音(0.8.3 真机 §5.6)。
1395
+ if (childSchema) {
1396
+ dependentUpdates.form = { skipped: true, note: "子表 code 没有独立表单面(表单/在线 JS 在父模型上),未调用 form.get" };
1397
+ dependentUpdates.onlineJs = { skipped: true, note: "随表单面跳过:子表 code 没有独立表单/在线 JS 槽位" };
1398
+ }
1399
+ else {
1400
+ // form.get 面:控件码清单
1401
+ try {
1402
+ const sheet = (await wireCall(session, { path: ENDPOINTS.sheetGet, query: { schemaCode, sheetCode: schemaCode } })).data;
1403
+ if (!sheet) {
1404
+ dependentUpdates.form = { present: false, note: "默认表单不存在(sheetGet 空)" };
1273
1405
  }
1274
- // online JS:扫 customScript 原文是否提及字段 code
1275
- const scripts = [];
1276
- for (const face of [sheet.draftHtmlJson, sheet.publishedHtmlJson]) {
1277
- if (typeof face !== "string" || !face.trim())
1278
- continue;
1279
- try {
1280
- const parsed = JSON.parse(face);
1281
- if (!Array.isArray(parsed))
1406
+ else {
1407
+ const draftControls = formControlCodes(sheet.draftAttributesJson);
1408
+ const publishedControls = formControlCodes(sheet.publishedAttributesJson);
1409
+ const inDraft = draftControls.includes(code);
1410
+ const inPublished = publishedControls.includes(code);
1411
+ dependentUpdates.form = {
1412
+ present: true,
1413
+ inDraft,
1414
+ inPublished,
1415
+ note: inDraft || inPublished
1416
+ ? "删除字段后表单控件会残留;需 form.draft(rebuild)/form.publish 清理"
1417
+ : "默认表单控件码未引用该字段",
1418
+ };
1419
+ if (inDraft || inPublished) {
1420
+ references.push({
1421
+ kind: "form",
1422
+ code: schemaCode,
1423
+ name: String(sheet.name ?? schemaCode),
1424
+ via: inDraft && inPublished ? "draft+published controls" : inDraft ? "draft controls" : "published controls",
1425
+ schemaCode,
1426
+ });
1427
+ }
1428
+ // online JS:扫 customScript 原文是否提及字段 code
1429
+ const scripts = [];
1430
+ for (const face of [sheet.draftHtmlJson, sheet.publishedHtmlJson]) {
1431
+ if (typeof face !== "string" || !face.trim())
1282
1432
  continue;
1283
- const custom = parsed.find((element) => element?.id === "customScript");
1284
- if (typeof custom?.innerHTML === "string" && custom.innerHTML.trim())
1285
- scripts.push(custom.innerHTML);
1433
+ try {
1434
+ const parsed = JSON.parse(face);
1435
+ if (!Array.isArray(parsed))
1436
+ continue;
1437
+ const custom = parsed.find((element) => element?.id === "customScript");
1438
+ if (typeof custom?.innerHTML === "string" && custom.innerHTML.trim())
1439
+ scripts.push(custom.innerHTML);
1440
+ }
1441
+ catch {
1442
+ // ignore malformed html face
1443
+ }
1286
1444
  }
1287
- catch {
1288
- // ignore malformed html face
1445
+ const mentioned = scripts.some((script) => scriptMentionsField(script, code));
1446
+ dependentUpdates.onlineJs = {
1447
+ scanned: true,
1448
+ mentioned,
1449
+ note: mentioned
1450
+ ? "在线 JS 原文仍包含该字段 code;删除后脚本引用会静默残留,需 onlinejs.compose 清理"
1451
+ : "在线 JS 原文未匹配到该字段 code(按词边界扫描,不含间接引用)",
1452
+ };
1453
+ if (mentioned) {
1454
+ references.push({
1455
+ kind: "onlineJs",
1456
+ code: schemaCode,
1457
+ name: String(sheet.name ?? schemaCode),
1458
+ via: "customScript.innerHTML",
1459
+ schemaCode,
1460
+ });
1289
1461
  }
1290
1462
  }
1291
- const mentioned = scripts.some((script) => scriptMentionsField(script, code));
1292
- dependentUpdates.onlineJs = {
1293
- scanned: true,
1294
- mentioned,
1295
- note: mentioned
1296
- ? "在线 JS 原文仍包含该字段 code;删除后脚本引用会静默残留,需 onlinejs.compose 清理"
1297
- : "在线 JS 原文未匹配到该字段 code(按词边界扫描,不含间接引用)",
1298
- };
1299
- if (mentioned) {
1300
- references.push({
1301
- kind: "onlineJs",
1302
- code: schemaCode,
1303
- name: String(sheet.name ?? schemaCode),
1304
- via: "customScript.innerHTML",
1305
- schemaCode,
1306
- });
1307
- }
1308
1463
  }
1309
- }
1310
- catch (error) {
1311
- dependentUpdates.form = { unknown: true, note: `form.get 不可用:${error instanceof Error ? error.message : String(error)}` };
1312
- dependentUpdates.onlineJs = { unknown: true, note: `onlinejs 扫描跳过:form 面读取失败` };
1464
+ catch (error) {
1465
+ dependentUpdates.form = { unknown: true, note: `form.get 不可用:${error instanceof Error ? error.message : String(error)}` };
1466
+ dependentUpdates.onlineJs = { unknown: true, note: `onlinejs 扫描跳过:form 面读取失败` };
1467
+ }
1313
1468
  }
1314
1469
  // listview.get 面:列/条件
1315
1470
  try {
@@ -1365,22 +1520,39 @@ async function collectFieldDeleteImpact(session, args, options) {
1365
1520
  else {
1366
1521
  unknowns.push("真写回执未扫业务规则引用(成本高);完整引用面请先 --dry-run");
1367
1522
  }
1368
- const surfaces = await scanFieldFormListviewOnlineJs(session, args.schemaCode, args.code);
1523
+ const childSchema = await schemaIsChildTable(session, args.schemaCode);
1524
+ const surfaces = await scanFieldFormListviewOnlineJs(session, args.schemaCode, args.code, { childSchema });
1369
1525
  references.push(...surfaces.references);
1370
1526
  for (const key of ["form", "listview", "onlineJs"]) {
1371
1527
  const face = surfaces.dependentUpdates[key];
1372
1528
  if (face?.unknown === true && typeof face.note === "string")
1373
1529
  unknowns.push(face.note);
1374
1530
  }
1531
+ // 子表 code 无独立表单面:整面对不上就不算「扫过」,归入 notScanned 并说明原因。
1532
+ const skipped = new Set();
1533
+ if (surfaces.dependentUpdates.form?.skipped === true)
1534
+ skipped.add("form");
1535
+ if (surfaces.dependentUpdates.onlineJs?.skipped === true)
1536
+ skipped.add("onlinejs");
1537
+ const scanned = (options.full
1538
+ ? ["businessrule", "form", "listview", "onlinejs", "data"]
1539
+ : ["form", "listview", "onlinejs", "data"]).filter((key) => !skipped.has(key));
1540
+ const notScanned = [
1541
+ ...(options.full
1542
+ ? ["workflow.permissions", "workflow.bindings", "rule.conditions"]
1543
+ : ["businessrule", "workflow.permissions", "workflow.bindings", "rule.conditions"]),
1544
+ ...(skipped.has("form") ? ["form(子表 code 无独立表单面,未调用 form.get)"] : []),
1545
+ ...(skipped.has("onlinejs") ? ["onlinejs(随表单面跳过:子表 code 无独立槽位)"] : []),
1546
+ ];
1375
1547
  return {
1376
1548
  dataRows: counted.dataRows,
1377
1549
  ...(counted.note ? { dataRowsNote: counted.note } : counted.dataRows === "unknown" ? { dataRowsNote: "拿不到行数:data.list total 不可用" } : {}),
1378
1550
  references,
1379
1551
  dependentUpdates: surfaces.dependentUpdates,
1380
1552
  coverage: {
1381
- scanned: options.full ? ["businessrule", "form", "listview", "onlinejs", "data"] : ["form", "listview", "onlinejs", "data"],
1382
- notScanned: options.full ? ["workflow.permissions", "workflow.bindings", "rule.conditions"] : ["businessrule", "workflow.permissions", "workflow.bindings", "rule.conditions"],
1383
- coveredSurfaces: options.full ? ["businessrule", "form", "listview", "onlinejs", "data"] : ["form", "listview", "onlinejs", "data"],
1553
+ scanned,
1554
+ notScanned,
1555
+ coveredSurfaces: scanned,
1384
1556
  },
1385
1557
  ...(unknowns.length > 0 ? { unknown: unknowns } : {}),
1386
1558
  note: options.full
@@ -1451,6 +1623,14 @@ async function runFieldUpdate(session, args) {
1451
1623
  ...(args.propertyEmpty !== undefined ? { propertyEmpty: args.propertyEmpty } : {}),
1452
1624
  };
1453
1625
  const prepared = prepareFieldUpdate(update);
1626
+ // 0.8.4 P0:真写自己的这道门(与 writeLint/dry-run 同一个 assertRelationOptionsFields)。
1627
+ // writeLint 已经在前置跑过一遍;这里保留 execute 内的同函数调用,保证
1628
+ // runFieldUpdate 被任何未经过 writeLint 的入口复用时也不会把非法 mappings
1629
+ // 写进平台。propertyType/relativeCode 取 prepareFieldUpdate 的归一结果 +
1630
+ // 存量行回退,与 dry-run 逐字一致。
1631
+ await assertRelationOptionsFields(session, args.schemaCode, prepared.propertyType, args.relativeCode ?? record.relativeCode, prepared.options);
1632
+ // 审计 #2:目标变更时校验关联目标存在(与 dry-run/writeLint 同一个函数)。
1633
+ await assertFieldUpdateRelationTarget(session, record, prepared, args);
1454
1634
  const currentOptions = decodeJsonObjectColumn(record.options, { invalid: "throw", array: "accept", object: "accept" }) ?? {};
1455
1635
  const requestedChanges = [];
1456
1636
  const same = (left, right) => JSON.stringify(left) === JSON.stringify(right);
@@ -1,7 +1,7 @@
1
1
  import { z } from "zod";
2
2
  import { ENDPOINTS } from "../endpoints.js";
3
3
  import { decodeButtonScript } from "./list-view.js";
4
- import { executeFormDraftWrite, executeFormPublishWrite, executeFormRunButtonWrite, lintFormPublishReadOnly, readFormButtons, readFormOrNull, refuseEmptyCallerLayout, validateHtmlRender, customButtonJsonStoredShape, CUSTOM_BUTTON_JSON_STRING_SHAPE_WARNING, FORM_FLAG_AUTHORITY_NOTE, resolveEffectiveFormFace } from "../form-support.js";
4
+ import { executeFormDraftWrite, executeFormPublishWrite, executeFormRunButtonWrite, lintFormPublishReadOnly, readFormButtons, readFormOrNull, refuseEmptyCallerLayout, validateHtmlRender, customButtonJsonStoredShape, CUSTOM_BUTTON_JSON_STRING_SHAPE_WARNING, FORM_FLAG_AUTHORITY_NOTE, compareFormFaces, resolveEffectiveFormFace } from "../form-support.js";
5
5
  import { capabilityArg, environmentArg } from "../args.js";
6
6
  import { governedRead } from "../read.js";
7
7
  import { writeTool } from "../write.js";
@@ -186,10 +186,15 @@ export function registerFormLane(tools) {
186
186
  // B5(issue 2026-11-25):两套口径(旗标 vs faces)并列时调用方还得二次推理
187
187
  // 「到底发布没发布」。给单一结论字段(规则与证据见 form-support 的
188
188
  // resolveEffectiveFormFace),旗标矛盾时再补一句「以谁为准」。
189
+ // B5-2(真机 2.1.5):inSync 必须比**四对**面(view/attributes/html/actions,
190
+ // 平台 AppIntegrationFacadeImpl:2670 同口径);只比 view 时「草稿改了字段标签」
191
+ // 会误判成 published。比较用规范化语义等值,见 compareFormFaces。
192
+ const faceSync = compareFormFaces(sheet, { draftPresent, publishedPresent });
189
193
  const faceVerdict = resolveEffectiveFormFace({
190
194
  draftPresent,
191
195
  publishedPresent,
192
- inSync: draftPresent && publishedPresent ? sheet.draftViewJson === sheet.publishedViewJson : null,
196
+ inSync: faceSync.inSync,
197
+ differingFaces: faceSync.differingFaces,
193
198
  });
194
199
  const base = {
195
200
  schemaCode: args.schemaCode,
@@ -202,12 +207,13 @@ export function registerFormLane(tools) {
202
207
  faces: {
203
208
  draft: { present: draftPresent, controlCount: draftCodes.length },
204
209
  published: { present: publishedPresent, controlCount: publishedCodes.length },
205
- inSync: draftPresent && publishedPresent ? sheet.draftViewJson === sheet.publishedViewJson : null,
210
+ inSync: faceSync.inSync,
211
+ ...(faceSync.inSync === false ? { differingFaces: faceSync.differingFaces } : {}),
206
212
  },
207
213
  ...(flagMismatch
208
214
  ? {
209
215
  flagMismatch: true,
210
- flagNote: "平台布尔与内容不一致:published/existDraft 来自 bizsheet/get 的标记位,faces 由 draft/published 两份布局内容推导。判「现在有几面」以 faces 为准;判「能否被运行时读到」以 published 为准(平台可能未刷新标记)。" +
216
+ flagNote: "平台布尔与内容不一致:published/existDraft 来自 bizsheet/get 的标记位,faces 由 draft/published 的 view/attributes/html/actions 四份布局面内容规范化比较推导。判「现在有几面」以 faces 为准;判「能否被运行时读到」以 published 为准(平台可能未刷新标记)。" +
211
217
  FORM_FLAG_AUTHORITY_NOTE,
212
218
  }
213
219
  : {}),
@@ -504,8 +510,9 @@ export function registerFormLane(tools) {
504
510
  const buttons = readFormButtons(record.options) ?? [];
505
511
  const publishedActions = parseActionEntries(record.publishedActionsJson);
506
512
  const flagMismatch = (record.published === true) !== publishedPresent || (record.existDraft === true) !== draftPresent;
507
- const inSync = draftPresent && publishedPresent ? record.draftViewJson === record.publishedViewJson : null;
508
- const faceVerdict = resolveEffectiveFormFace({ draftPresent, publishedPresent, inSync });
513
+ // B5-2:与 form.get 同源(四对面语义比较),列表 detail 面不得另有一套判据。
514
+ const faceSync = compareFormFaces(record, { draftPresent, publishedPresent });
515
+ const faceVerdict = resolveEffectiveFormFace({ draftPresent, publishedPresent, inSync: faceSync.inSync, differingFaces: faceSync.differingFaces });
509
516
  detailed.push({
510
517
  ...publicSheet,
511
518
  present: true,
@@ -518,12 +525,13 @@ export function registerFormLane(tools) {
518
525
  faces: {
519
526
  draft: { present: draftPresent, controlCount: draftCodes.length },
520
527
  published: { present: publishedPresent, controlCount: publishedCodes.length },
521
- inSync,
528
+ inSync: faceSync.inSync,
529
+ ...(faceSync.inSync === false ? { differingFaces: faceSync.differingFaces } : {}),
522
530
  },
523
531
  ...(flagMismatch
524
532
  ? {
525
533
  flagMismatch: true,
526
- flagNote: "平台旗标与内容不一致:published/existDraft 来自 bizsheet/get 的标记位,faces 由两份布局内容推导。判「现在有几面」以 faces 为准;判「运行时能否读到」以 published 为准。" + FORM_FLAG_AUTHORITY_NOTE,
534
+ flagNote: "平台旗标与内容不一致:published/existDraft 来自 bizsheet/get 的标记位,faces 由 view/attributes/html/actions 四份布局面内容规范化比较推导。判「现在有几面」以 faces 为准;判「运行时能否读到」以 published 为准。" + FORM_FLAG_AUTHORITY_NOTE,
527
535
  }
528
536
  : {}),
529
537
  });
@@ -1,7 +1,7 @@
1
1
  import { z } from "zod";
2
2
  import { ENDPOINTS } from "../endpoints.js";
3
- import { assertFieldFamilyAllowed, assertSelectionChoicesAllowed, choicesArg, fieldOptionsArg, nameI18nJson, propertyTypeArg, relationTargetOf, relativeCodeArg, SYSTEM_FIELD_CODES, subFieldArg, assertRelationTargetExists, } from "../field-families.js";
4
- import { modelSchemaCodes } from "./field.js";
3
+ import { assertFieldFamilyAllowed, assertSelectionChoicesAllowed, choicesArg, fieldOptionsArg, nameI18nJson, propertyTypeArg, relationTargetOf, relativeCodeArg, SYSTEM_FIELD_CODES, subFieldArg, } from "../field-families.js";
4
+ import { modelSchemaCodes, lintFieldCreateWrite } from "./field.js";
5
5
  import { fieldChangeWireBody, prepareFieldChange, sameFieldChange } from "../field-change.js";
6
6
  import { executeFormDraftWrite, executeFormPublishWrite } from "../form-support.js";
7
7
  import { mapBounded } from "../support.js";
@@ -1518,12 +1518,26 @@ export function registerModelLane(tools) {
1518
1518
  execute: async (session, args) => {
1519
1519
  const results = [];
1520
1520
  const entries = fieldEntriesOf(args);
1521
- // r37 跨路接线(同扇门):field.create 单独调用已对关联字段目标写前拒
1522
- // (relation-target-not-found),configure_model 的字段包不能是例外——
1523
- // 否则混合包仍会落到裸 300010 把整个模型毒住。
1521
+ // 0.8.4 P0(W17 审计):configure_model 的 fields[] 曾只跑
1522
+ // assertRelationTargetExists,于是非法关联 mappings 与自引用/子表聚合
1523
+ // 绕过了 field.create 的语义门,直接写进平台。现在整包在**任何写 wire
1524
+ // 之前**走同一个 lintFieldCreateWrite;同包声明但尚未落库的字段作为
1525
+ // 本模型读面一起参与判定(新模型的发布面此时还是空的)。
1524
1526
  const relationCandidates = await modelSchemaCodes(session);
1525
- for (const entry of entries)
1526
- assertRelationTargetExists(entry, relationCandidates);
1527
+ const gateTargetVersion = session.detectedVersion();
1528
+ const pendingOwnFields = entries.map((entry) => ({ code: entry.code, propertyType: entry.propertyType }));
1529
+ const preparedEntries = [];
1530
+ for (const [index, entry] of entries.entries()) {
1531
+ const input = fieldChangeInputOf(args.code, entry, { targetVersion: gateTargetVersion });
1532
+ try {
1533
+ preparedEntries.push(await lintFieldCreateWrite(session, input, { relationCandidates, pendingOwnFields }));
1534
+ }
1535
+ catch (error) {
1536
+ if (!(error instanceof ToolRefusalError))
1537
+ throw error;
1538
+ throw configureModelFieldGateRefusal(index, entry, error);
1539
+ }
1540
+ }
1527
1541
  const stop = (index, tool, error) => {
1528
1542
  const envelope = error instanceof ToolRefusalError
1529
1543
  ? Object.fromEntries(Object.entries(error.payload).filter(([key]) => key !== "status"))
@@ -1594,9 +1608,8 @@ export function registerModelLane(tools) {
1594
1608
  draftFields.set(code, row);
1595
1609
  }
1596
1610
  }
1597
- const configureTargetVersion = session.detectedVersion();
1598
- for (const entry of entries) {
1599
- const input = fieldChangeInputOf(args.code, entry, { targetVersion: configureTargetVersion });
1611
+ for (const [index, entry] of entries.entries()) {
1612
+ const input = fieldChangeInputOf(args.code, entry, { targetVersion: gateTargetVersion });
1600
1613
  failed = await run(results.length, "field.create", async () => {
1601
1614
  const existing = existingFields.get(entry.code);
1602
1615
  if (existing !== undefined) {
@@ -1612,7 +1625,7 @@ export function registerModelLane(tools) {
1612
1625
  message: `字段 ${args.code}.${entry.code} 已存在且形状与请求不同;configure_model 只创建缺失字段,不改写既有字段。先核对既有形状(omc call field.list --args '{"schemaCode":"${args.code}","published":false,"code":"${entry.code}"}'),要改写走 field.update,要新字段就换 code`,
1613
1626
  });
1614
1627
  }
1615
- const prepared = prepareFieldChange(input);
1628
+ const prepared = preparedEntries[index];
1616
1629
  const performed = await wireCall(session, { path: ENDPOINTS.fieldCreate, method: "POST", body: fieldChangeWireBody(input, prepared) });
1617
1630
  createdOptions.set(entry.code, prepared.options);
1618
1631
  const after = wireRows((await wireCall(session, { path: ENDPOINTS.fieldList, query: { schemaCode: args.code, isPublish: "false" } })).data);
@@ -1744,4 +1757,22 @@ function fieldChangeInputOf(schemaCode, entry, scope = {}) {
1744
1757
  ...(entry.propertyEmpty !== undefined ? { propertyEmpty: entry.propertyEmpty } : {}),
1745
1758
  };
1746
1759
  }
1760
+ /**
1761
+ * 0.8.4 P0:`configure_model` 的字段包未过 `field.create` 同一道语义门时,
1762
+ * 回执要能直接定位到包里的哪一项。blocker 与 field.create 完全同形(同门产物,
1763
+ * 不另造一套),另加 `fields[{index,code}]` + `fieldIndex/fieldCode`。
1764
+ */
1765
+ function configureModelFieldGateRefusal(index, entry, error) {
1766
+ const { status: _status, ...detail } = error.payload;
1767
+ const blocker = String(error.payload.blocker ?? "configure-model-field-gate-refused");
1768
+ return new ToolRefusalError({
1769
+ ...detail,
1770
+ status: "refused",
1771
+ blocker,
1772
+ fieldIndex: index,
1773
+ fieldCode: entry.code,
1774
+ fields: [{ index, code: entry.code, blocker }],
1775
+ message: `configure_model fields[${index}](${entry.code})未过 field.create 同一道写前语义门:${String(error.payload.message ?? "")}`,
1776
+ });
1777
+ }
1747
1778
  //# sourceMappingURL=model.js.map
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@stalfh233/omc-cli",
3
- "version": "0.8.3",
3
+ "version": "0.8.5",
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.3",
61
+ "omc-core": "0.8.5",
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.3"
79
+ "@stalfh233/omc-fake-platform": "0.8.5"
80
80
  }
81
81
  }