@stalfh233/omc-cli 0.6.81 → 0.6.83

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,5 +1,5 @@
1
1
  import { z } from "zod";
2
- import { wireCall, wireRows, WireError } from "./wire.js";
2
+ import { wireCall, wireCallWith404Fallback, wireRows, WireError } from "./wire.js";
3
3
  import { ENDPOINTS } from "./endpoints.js";
4
4
  import { readModelRecord } from "./model-record.js";
5
5
  import { ToolRefusalError } from "./tool-types.js";
@@ -8,6 +8,7 @@ import { RULE_BIZ_RULE_TYPE_DESCRIPTION, RULE_CREATE_BODY, RULE_ROUTES_DESCRIPTI
8
8
  import { validateRuleNodeGraph, prepareRuleGraph, PLATFORM_TRIGGER_RULE_CODES, DEFAULT_SYSTEM_NODE_BY_RULE_CODE } from "./lanes/rule-graph.js";
9
9
  import { FORMULA_LINT_CODES } from "./formula-lint.js";
10
10
  import { compileMethodConfigPlain } from "./bizservice-config.js";
11
+ import { closestMatches } from "./closest-match.js";
11
12
  import { RESERVED_CODES } from "./code-rules.js";
12
13
  import { SYSTEM_FIELD_CODES } from "./field-families.js";
13
14
  import { FIELD_PROPERTY_TYPES } from "./field-families.js";
@@ -448,8 +449,24 @@ async function assertRuleGraphFieldOwnership(session, schemaCode, nodes, allowAd
448
449
  return [{ code: "rule-graph-field-not-in-model", nodeCode: first.nodeCode, key: first.where, severity: "warning", message: `${message}(allowAdvisory:true,仅调查放行)` }];
449
450
  throw new ToolRefusalError({ status: "refused", blocker: "rule-graph-field-not-in-model", nodeCode: first.nodeCode, side: first.side, model: first.model, field: first.code, where: first.where, missing, candidates, message });
450
451
  }
451
- async function assertBizActionMappingFieldsExist(session, schemaCode, nodes) {
452
+ /** BIZ_ACTION/GET_LIST(BIZ_SERVICE) 节点映射的来源模型解析(与条件叶归属同款:QUERY 上游优先)。 */
453
+ function mappingSourceModelResolver(schemaCode, nodes) {
454
+ const queryModels = new Map();
455
+ for (const entry of nodes) {
456
+ if (!entry || typeof entry !== "object")
457
+ continue;
458
+ const node = entry;
459
+ if (String(node.nodeType ?? "") === "QUERY" && typeof node.nodeCode === "string" && typeof node.targetSchemaCode === "string")
460
+ queryModels.set(node.nodeCode, node.targetSchemaCode.trim());
461
+ }
462
+ return (node) => {
463
+ const input = typeof node.inputParam === "string" ? /^_(.+)_output$/u.exec(node.inputParam) : undefined;
464
+ return input?.[1] && queryModels.get(input[1]) ? queryModels.get(input[1]) : schemaCode;
465
+ };
466
+ }
467
+ async function assertRuleMappingFieldsPublished(session, schemaCode, nodes, options = {}) {
452
468
  const rows = [];
469
+ const modelOf = mappingSourceModelResolver(schemaCode, nodes);
453
470
  for (const entry of nodes) {
454
471
  if (!entry || typeof entry !== "object")
455
472
  continue;
@@ -474,28 +491,61 @@ async function assertBizActionMappingFieldsExist(session, schemaCode, nodes) {
474
491
  continue; // only PROPERTY mappings resolve to a schema field
475
492
  const bizCode = typeof row.bizCode === "string" ? row.bizCode.trim() : "";
476
493
  if (!bizCode)
477
- continue; // missing bizCode is a shape-lint concern
478
- rows.push({ nodeCode: String(node.nodeCode ?? ""), listKey, serviceMethodParameterCode: typeof row.serviceMethodParameterCode === "string" ? row.serviceMethodParameterCode : "", bizCode });
494
+ continue; // r85 issue 04:显式空映射(bizCode:"")不指向字段,运行时参数不传
495
+ rows.push({ nodeCode: String(node.nodeCode ?? ""), listKey, serviceMethodParameterCode: typeof row.serviceMethodParameterCode === "string" ? row.serviceMethodParameterCode : "", bizCode, model: modelOf(node) });
479
496
  }
480
497
  }
481
498
  }
482
499
  if (rows.length === 0)
483
- return;
484
- const fields = wireRows((await wireCall(session, { path: ENDPOINTS.fieldList, query: { schemaCode, isPublish: "true" } })).data);
485
- const known = new Set(fields.map((field) => String(field.code ?? field.propertyCode ?? "").trim()).filter((code) => code.length > 0));
486
- for (const code of RULE_RESERVED_MAPPING_CODES)
487
- known.add(code);
488
- const missing = rows.filter((row) => !known.has(row.bizCode));
489
- if (missing.length > 0) {
490
- throw new ToolRefusalError({
491
- status: "refused",
492
- blocker: "rule-graph-bizaction-mapping-field-missing",
493
- schemaCode,
494
- missing,
495
- message: "methodMapping 的 PROPERTY(codeType:1) 映射 bizCode 指向该模型上不存在(或未发布)的字段——平台 publish 会只回一个无明细的 550018「规则存在异常」。先 field.create 建字段并 field.publish 发布,或把映射改到已发布的真实字段 code",
496
- recovery: [{ code: "create-and-publish-mapped-field", action: "field.create 建该字段 → field.publish 发布 → 重试 rule.save;或先 field.list(published:true) 核对字段 code" }],
497
- });
500
+ return { checkedModels: 0 };
501
+ const fieldLists = new Map();
502
+ for (const model of [...new Set(rows.map((row) => row.model))]) {
503
+ const fields = wireRows((await wireCall(session, { path: ENDPOINTS.fieldList, query: { schemaCode: model, isPublish: "true" } })).data);
504
+ const codes = fields.map((field) => String(field.code ?? field.propertyCode ?? "").trim()).filter((code) => code.length > 0);
505
+ for (const code of RULE_RESERVED_MAPPING_CODES)
506
+ codes.push(code);
507
+ fieldLists.set(model, codes);
498
508
  }
509
+ const missing = rows.filter((row) => {
510
+ const known = fieldLists.get(row.model);
511
+ if (known === undefined)
512
+ return false;
513
+ // 子表路径 `sheetCode.field`:父字段清单只含 sheet 列本身——前缀在册即视为
514
+ // 子列引用(子列清单不在本面,不猜)。整串命中同样放行(与 r21 门同口径)。
515
+ if (row.bizCode.includes(".")) {
516
+ const prefix = row.bizCode.slice(0, row.bizCode.indexOf("."));
517
+ return !known.includes(prefix) && !known.includes(row.bizCode);
518
+ }
519
+ return !known.includes(row.bizCode);
520
+ });
521
+ if (missing.length === 0)
522
+ return { checkedModels: fieldLists.size };
523
+ const detail = missing.map((row) => {
524
+ const known = fieldLists.get(row.model) ?? [];
525
+ return {
526
+ nodeCode: row.nodeCode,
527
+ listKey: row.listKey,
528
+ serviceMethodParameterCode: row.serviceMethodParameterCode,
529
+ bizCode: row.bizCode,
530
+ model: row.model,
531
+ modelFieldCount: known.length,
532
+ modelFieldSample: [...new Set(known)].sort().slice(0, 20),
533
+ didYouMean: closestMatches(row.bizCode, known, 3).map((match) => match.name),
534
+ };
535
+ });
536
+ if (options.allowAbsent === true)
537
+ return { checkedModels: fieldLists.size, absent: detail.map(({ nodeCode, serviceMethodParameterCode, bizCode, model }) => ({ nodeCode, serviceMethodParameterCode, bizCode, model })) };
538
+ throw new ToolRefusalError({
539
+ status: "refused",
540
+ blocker: "rule-mapping-field-absent",
541
+ schemaCode,
542
+ missing: detail,
543
+ message: "methodMapping 的 PROPERTY(codeType:1) 映射 bizCode 不在来源模型(本模型或 QUERY 上游模型)的已发布字段清单——平台侧不保证拦截(2026-11-19 联调实证:保存/发布通过、运行时参数静默 null → 10005)。先 field.create+field.publish 建字段,或改映射到 didYouMean 给出的已发布字段;确知不存在仍要保存:显式 allowAbsentMappingFields:true",
544
+ recovery: [
545
+ { code: "create-and-publish-mapped-field", action: "field.create 建该字段 → field.publish 发布 → 重试 rule.save;或先 field.list(published:true) 核对字段 code" },
546
+ { code: "allow-absent-mapping-fields", action: "确知字段不存在仍要保存:rule.save 传 allowAbsentMappingFields:true(回执 absentMappingFieldsAllowed 点名放行项)" },
547
+ ],
548
+ });
499
549
  }
500
550
  /**
501
551
  * Ticket 96 live incident fix — fail-closed schema-existence gate for every
@@ -867,7 +917,7 @@ export async function lintRuleGraphForWrite(session, args, options = {}) {
867
917
  throw new ToolRefusalError({
868
918
  status: "refused",
869
919
  blocker: "rule-graph-routes-empty",
870
- message: `图有 ${nodes.length} 个节点但 0 条 routes——平台发布会判「孤立节点」(550014)。边用 routes:[{preNode:"Start",postNode:"UPDATE_1"},...](不是 edges/from/to,那会被静默剥掉)`,
920
+ message: `图有 ${nodes.length} 个节点但 0 条 routes——平台发布会判「孤立节点」(550014)。边用 routes:[{preNode:"Start",postNode:"UPDATE_1"},...](不是 edges/from/to,那会被静默剥掉);更新既有规则可整个省略 routes,工具会读现行连线沿用(回执 routesSource:"existing")`,
871
921
  });
872
922
  return { preparedGraph, blockers, lintWarnings, lintHazards, nodes, routes };
873
923
  }
@@ -970,20 +1020,228 @@ function normalizeRuleJsonColumn(value, fallback) {
970
1020
  return JSON.stringify(value);
971
1021
  return fallback;
972
1022
  }
1023
+ /** r85(retro 2026-11-19 issue 11):`<field-xxx>` 是设计器富文本标记;运行时只读 formula。 */
1024
+ export const DESIGNER_FIELD_TAG = "<field-";
1025
+ /** 图里是否存在 codeType:7 表达式映射(决定是否需要读现存映射做设计器文本保读)。 */
1026
+ function nodeGraphHasExpressionMappings(graph) {
1027
+ const nodes = graph.nodes;
1028
+ if (typeof nodes === "string") {
1029
+ try {
1030
+ return nodeGraphHasExpressionMappings({ nodes: JSON.parse(nodes) });
1031
+ }
1032
+ catch {
1033
+ return false;
1034
+ }
1035
+ }
1036
+ if (!Array.isArray(nodes))
1037
+ return false;
1038
+ for (const entry of nodes) {
1039
+ if (!entry || typeof entry !== "object")
1040
+ continue;
1041
+ const mapping = entry.methodMapping;
1042
+ if (!mapping || typeof mapping !== "object" || Array.isArray(mapping))
1043
+ continue;
1044
+ const m = mapping;
1045
+ for (const listKey of ["inputMappings", "outputMappings"])
1046
+ if (Array.isArray(m[listKey]) && m[listKey].some((element) => element && typeof element === "object" && Number(element.codeType) === 7))
1047
+ return true;
1048
+ }
1049
+ return false;
1050
+ }
1051
+ /** 解析 codeType:7 的 bizCode JSON;非对象/坏串返回 null。 */
1052
+ function parseExpressionBizCode(bizCode) {
1053
+ if (typeof bizCode !== "string" || !bizCode.trim())
1054
+ return null;
1055
+ try {
1056
+ const parsed = JSON.parse(bizCode);
1057
+ return parsed && typeof parsed === "object" && !Array.isArray(parsed) ? parsed : null;
1058
+ }
1059
+ catch {
1060
+ return null;
1061
+ }
1062
+ }
1063
+ /** 现存映射值带设计器痕迹:editorText 含 `<field-` 或 editorMark 非空。 */
1064
+ function hasDesignerText(expression) {
1065
+ const editorText = typeof expression.editorText === "string" ? expression.editorText : "";
1066
+ const editorMark = typeof expression.editorMark === "string" ? expression.editorMark : "";
1067
+ return editorText.includes(DESIGNER_FIELD_TAG) || editorMark !== "";
1068
+ }
1069
+ /**
1070
+ * r85(retro 2026-11-19 issue 11):codeType:7 的保守 partial 合并。
1071
+ *
1072
+ * 设计器把公式存成两份文本:`formula`(`{code}` 形,运行时唯一求值源)与
1073
+ * `editorText`(`<field-xxx>code</field-xxx>` 富文本 + editorMark=标记名;xxx 是
1074
+ * 设计器端 Math.random 生成的 8 位 nonce——admin/js/12404.1675d362.js
1075
+ * setEditorMark:"field-"+random(8),**不是字段/控件 id,不可从字段读回面推导**)。
1076
+ * CLI 生成的 editorText 设计器标红,覆盖会丢用户在设计器里改好的渲染。
1077
+ *
1078
+ * 语义:目标映射的**现存值**带设计器痕迹、调用方**未显式传 editorText** 时,默认
1079
+ * 保留现存 editorText/editorMark 只更新 formula(preservedDesignerText 点名);
1080
+ * 调用方显式传了 editorText、或逃生阀 allowDesignerTextOverwrite:true,才覆盖
1081
+ * (designerTextOverwritten 警示)。无设计器痕迹时零注记(不加噪音)。
1082
+ */
1083
+ async function preserveDesignerFormulaText(nodes, loadCurrentRow, allowOverwrite) {
1084
+ const preserved = [];
1085
+ const overwritten = [];
1086
+ if (!nodes.some((node) => {
1087
+ const type = String(node.nodeType ?? "");
1088
+ return type === "BIZ_ACTION" || (type === "GET_LIST" && String(node.dataSourceType ?? "") === "BIZ_SERVICE");
1089
+ }))
1090
+ return { preserved, overwritten };
1091
+ const row = await loadCurrentRow();
1092
+ if (!row || typeof row.node !== "string")
1093
+ return { preserved, overwritten };
1094
+ const existingNodes = parseJsonColumn(row.node);
1095
+ if (!Array.isArray(existingNodes))
1096
+ return { preserved, overwritten };
1097
+ const designerByText = new Map();
1098
+ for (const entry of existingNodes) {
1099
+ if (!entry || typeof entry !== "object")
1100
+ continue;
1101
+ const node = entry;
1102
+ const mapping = node.methodMapping;
1103
+ if (!mapping || typeof mapping !== "object" || Array.isArray(mapping))
1104
+ continue;
1105
+ const m = mapping;
1106
+ for (const listKey of ["inputMappings", "outputMappings"]) {
1107
+ if (!Array.isArray(m[listKey]))
1108
+ continue;
1109
+ for (const element of m[listKey]) {
1110
+ if (!element || typeof element !== "object")
1111
+ continue;
1112
+ const elementRow = element;
1113
+ if (Number(elementRow.codeType) !== 7)
1114
+ continue;
1115
+ const expression = parseExpressionBizCode(elementRow.bizCode);
1116
+ if (!expression || !hasDesignerText(expression))
1117
+ continue;
1118
+ designerByText.set(`${String(node.nodeCode ?? "")}#${listKey}#${String(elementRow.serviceMethodParameterCode ?? "")}`, {
1119
+ editorText: typeof expression.editorText === "string" ? expression.editorText : "",
1120
+ editorMark: typeof expression.editorMark === "string" ? expression.editorMark : "",
1121
+ });
1122
+ }
1123
+ }
1124
+ }
1125
+ if (designerByText.size === 0)
1126
+ return { preserved, overwritten };
1127
+ for (const node of nodes) {
1128
+ const type = String(node.nodeType ?? "");
1129
+ if (type !== "BIZ_ACTION" && !(type === "GET_LIST" && String(node.dataSourceType ?? "") === "BIZ_SERVICE"))
1130
+ continue;
1131
+ const mapping = node.methodMapping;
1132
+ if (!mapping || typeof mapping !== "object" || Array.isArray(mapping))
1133
+ continue;
1134
+ const m = mapping;
1135
+ for (const listKey of ["inputMappings", "outputMappings"]) {
1136
+ if (!Array.isArray(m[listKey]))
1137
+ continue;
1138
+ for (const element of m[listKey]) {
1139
+ if (!element || typeof element !== "object")
1140
+ continue;
1141
+ const elementRow = element;
1142
+ if (Number(elementRow.codeType) !== 7)
1143
+ continue;
1144
+ const expression = parseExpressionBizCode(elementRow.bizCode);
1145
+ if (!expression)
1146
+ continue;
1147
+ const key = `${String(node.nodeCode ?? "")}#${listKey}#${String(elementRow.serviceMethodParameterCode ?? "")}`;
1148
+ const existing = designerByText.get(key);
1149
+ if (!existing)
1150
+ continue;
1151
+ const where = `${String(node.nodeCode ?? "")}/${String(elementRow.serviceMethodParameterCode ?? "")}`;
1152
+ const callerHasText = typeof expression.editorText === "string" && expression.editorText.trim() !== "";
1153
+ if (callerHasText || allowOverwrite) {
1154
+ overwritten.push(where);
1155
+ continue;
1156
+ }
1157
+ expression.editorText = existing.editorText;
1158
+ expression.editorMark = existing.editorMark;
1159
+ elementRow.bizCode = JSON.stringify(expression);
1160
+ preserved.push(where);
1161
+ }
1162
+ }
1163
+ }
1164
+ return { preserved, overwritten };
1165
+ }
1166
+ /** r85(retro 2026-11-19 issue 04):显式空映射(bizCode:"",PROPERTY/CONST 归一后同形)点名。 */
1167
+ function collectEmptyMappings(nodes) {
1168
+ const empty = [];
1169
+ for (const node of nodes) {
1170
+ const mapping = node.methodMapping;
1171
+ if (!mapping || typeof mapping !== "object" || Array.isArray(mapping))
1172
+ continue;
1173
+ const m = mapping;
1174
+ for (const listKey of ["inputMappings", "outputMappings"]) {
1175
+ if (!Array.isArray(m[listKey]))
1176
+ continue;
1177
+ for (const element of m[listKey]) {
1178
+ if (!element || typeof element !== "object")
1179
+ continue;
1180
+ const row = element;
1181
+ if (row.bizCode !== "")
1182
+ continue;
1183
+ if (Number(row.codeType) !== 1 && Number(row.codeType) !== 0)
1184
+ continue;
1185
+ empty.push(`${String(node.nodeCode ?? "")}/${String(row.serviceMethodParameterCode ?? "")}`);
1186
+ }
1187
+ }
1188
+ }
1189
+ return empty;
1190
+ }
973
1191
  export async function lintRuleSaveWrite(session, args) {
1192
+ // r85(issue 03/08):幻影 schema 门提前到一切规则面 wire 之前(原在图 lint 后,
1193
+ // 而 computeCarriedNodeCodes 已会 list——提前只收紧不放松;后续 routes 沿用
1194
+ // 读取/设计器保读都以 schema 已证存在为前提)。
1195
+ await assertRuleSchemaExists(session, args.schemaCode);
1196
+ // r85(issue 03):省略 routes 的沿用读取需要现存行;issue 11 的设计器文本
1197
+ // 保读需要现存映射。list 一趟同时服务 existing 定位与原有 upsert 语义。
1198
+ const list = await wireCall(session, { path: ENDPOINTS.businessRuleListBySchemaCode, query: { schemaCode: args.schemaCode } });
1199
+ const existing = wireRows(list.data).find((row) => row.code === args.ruleCode);
1200
+ let cachedCurrentRow = undefined;
1201
+ const loadCurrentRow = async () => {
1202
+ if (cachedCurrentRow !== undefined)
1203
+ return cachedCurrentRow;
1204
+ if (!existing?.id) {
1205
+ cachedCurrentRow = null;
1206
+ return null;
1207
+ }
1208
+ try {
1209
+ cachedCurrentRow = (await wireCall(session, { path: ENDPOINTS.businessRuleGet, query: { id: String(existing.id) } })).data;
1210
+ }
1211
+ catch {
1212
+ cachedCurrentRow = null;
1213
+ }
1214
+ return cachedCurrentRow;
1215
+ };
1216
+ // r85(issue 03):nodeGraph.routes 省略 + 规则已存在 → 读现行连线沿用
1217
+ // (businessrule/get +1 wire,回执 routesSource:"existing")。读不到 route 列
1218
+ // 不猜连线:落回 routes-empty/缺边 lint(新建路径本就必须显式给 routes)。
1219
+ let routesSource;
1220
+ let graph = args.nodeGraph;
1221
+ const routesOmitted = graph.routes === undefined;
1222
+ if (existing?.id && (routesOmitted || nodeGraphHasExpressionMappings(graph))) {
1223
+ const currentRow = await loadCurrentRow();
1224
+ if (routesOmitted && currentRow && typeof currentRow.route === "string") {
1225
+ const routes = parseJsonColumn(currentRow.route);
1226
+ if (Array.isArray(routes)) {
1227
+ graph = { ...graph, routes: routes };
1228
+ routesSource = "existing";
1229
+ }
1230
+ }
1231
+ }
974
1232
  // Pre-flight dry lint (ticket 14) lives in lintRuleGraphForWrite (r73 #1):
975
1233
  // the SAME lint now serves the real write AND `rule.node.update`'s
976
1234
  // dryRunPayload, so a dry-run answers the same 能写/不能写 question.
977
- const { preparedGraph, blockers, lintWarnings, lintHazards, nodes, routes } = await lintRuleGraphForWrite(session, args);
1235
+ const { preparedGraph, blockers, lintWarnings, lintHazards, nodes, routes } = await lintRuleGraphForWrite(session, { ...args, nodeGraph: graph });
978
1236
  await assertCreateSelectionCompatibility(session, args.schemaCode, Array.isArray(nodes) ? nodes : []);
979
- await assertBizActionMappingFieldsExist(session, args.schemaCode, Array.isArray(nodes) ? nodes : []);
1237
+ // r85(issue 08):codeType:1 映射字段预检(QUERY 上游模型解析 + did-you-mean
1238
+ // + allowAbsentMappingFields 逃生阀)。r21 的同模型门已并入本门。
1239
+ const mappingPreflight = await assertRuleMappingFieldsPublished(session, args.schemaCode, Array.isArray(nodes) ? nodes : [], { allowAbsent: args.allowAbsentMappingFields === true });
980
1240
  // r47a: ordinary UPDATE/CREATE/EXPRESSION references use two distinct
981
1241
  // ownership sides. Read each involved published field set once (at most the
982
1242
  // rule model plus two target/query models) and refuse before rule.save.
983
1243
  blockers.push(...(await assertRuleGraphFieldOwnership(session, args.schemaCode, Array.isArray(nodes) ? nodes : [], args.allowAdvisory === true)));
984
- // Ticket 96: phantom-schema gate — BEFORE the first businessrule wire call
985
- // (the rule list itself auto-creates preset rows for unknown schemas).
986
- await assertRuleSchemaExists(session, args.schemaCode);
1244
+ // Ticket 96: phantom-schema gate — r85 起已提前到函数首(一切规则面 wire 之前)。
987
1245
  // ASSIGN shape is version-dependent (see isModernAssignVersion).
988
1246
  const assignCodes = assignNodes(nodes);
989
1247
  if (assignCodes.length > 0) {
@@ -1072,8 +1330,7 @@ export async function lintRuleSaveWrite(session, args) {
1072
1330
  : typeof schedulerInput === "string"
1073
1331
  ? schedulerInput
1074
1332
  : JSON.stringify(schedulerInput);
1075
- const list = await wireCall(session, { path: ENDPOINTS.businessRuleListBySchemaCode, query: { schemaCode: args.schemaCode } });
1076
- const existing = wireRows(list.data).find((row) => row.code === args.ruleCode);
1333
+ // r85:existing 定位已提前到函数首(与 routes 沿用读取共用一趟 list)。
1077
1334
  // Persistence nodes belong to the PLATFORM, not to us and not to the caller.
1078
1335
  // The preset row already carries its own (Start → Create(SYSTEM_CREATE) →
1079
1336
  // End). Copy that node verbatim instead of fabricating our own: nodeCode,
@@ -1084,7 +1341,7 @@ export async function lintRuleSaveWrite(session, args) {
1084
1341
  const systemSpec = DEFAULT_SYSTEM_NODE_BY_RULE_CODE[args.ruleCode];
1085
1342
  if (existing?.id && systemSpec) {
1086
1343
  try {
1087
- const baselineRow = (await wireCall(session, { path: ENDPOINTS.businessRuleGet, query: { id: String(existing.id) } })).data;
1344
+ const baselineRow = await loadCurrentRow();
1088
1345
  const baselineNodes = parseJsonColumn(baselineRow?.node);
1089
1346
  const platformNode = Array.isArray(baselineNodes)
1090
1347
  ? baselineNodes.find((node) => String(node.nodeType ?? "") === systemSpec.nodeType)
@@ -1104,6 +1361,11 @@ export async function lintRuleSaveWrite(session, args) {
1104
1361
  // synthesized the platform CUSTOM_NODE (rule.run then 550001s). Echo the
1105
1362
  // observed trigger shape instead of the request.
1106
1363
  const customTriggerApplied = nodes.some((node) => String(node.nodeType ?? "") === "CUSTOM_NODE");
1364
+ // r85(issue 11):设计器公式文本保守合并(保留现存 editorText/editorMark,
1365
+ // 只更新 formula;在 nodeJson 序列化前就地改写映射元素)。
1366
+ const designerText = await preserveDesignerFormulaText(nodes, loadCurrentRow, args.allowDesignerTextOverwrite === true);
1367
+ // r85(issue 04):显式空映射点名(归一后 bizCode:"" 的 PROPERTY/CONST 映射)。
1368
+ const emptyMappings = collectEmptyMappings(nodes);
1107
1369
  const nodeJson = typeof nodes === "string" ? nodes : JSON.stringify(nodes);
1108
1370
  const routeJson = typeof routes === "string" ? routes : JSON.stringify(routes);
1109
1371
  const schedulerField = schedulerSetting === undefined ? {} : { schedulerSetting };
@@ -1137,11 +1399,95 @@ export async function lintRuleSaveWrite(session, args) {
1137
1399
  nodeJson,
1138
1400
  routeJson,
1139
1401
  schedulerField,
1402
+ // r85(retro 2026-11-19)
1403
+ ...(routesSource !== undefined ? { routesSource } : {}),
1404
+ emptyMappings,
1405
+ preservedDesignerText: designerText.preserved,
1406
+ designerTextOverwritten: designerText.overwritten,
1407
+ mappingFieldChecks: mappingPreflight.checkedModels,
1408
+ ...(mappingPreflight.absent !== undefined ? { absentMappingFields: mappingPreflight.absent } : {}),
1409
+ };
1410
+ }
1411
+ async function verifyRulePublish(session, schemaCode, ruleCode, publishResponse) {
1412
+ const verifyWire = "发布后经 runtime/business_rule/list_by_schemacode 读回验证(+1 wire,替换原先读不到发布事实的 app/DRAFT 面读回——app 面只投影 DRAFT 行,读它验证不了发布)";
1413
+ const responseVersion = publishResponse !== null && typeof publishResponse.ruleVersion === "number" ? publishResponse.ruleVersion : undefined;
1414
+ let rows;
1415
+ try {
1416
+ rows = wireRows((await wireCallWith404Fallback(session, [
1417
+ { path: ENDPOINTS.runtimeBusinessRuleListBySchemaCode, query: { schemaCode } },
1418
+ { path: ENDPOINTS.businessRuleListBySchemaCode, query: { schemaCode } },
1419
+ ])).data);
1420
+ }
1421
+ catch (error) {
1422
+ // 读回异常:发布请求本身已成功(wireCall errcode 0 才走到这里),验证失败 ≠ 未发布。
1423
+ return {
1424
+ publishedVerified: false,
1425
+ latestPublished: false,
1426
+ detail: {
1427
+ verifyWire,
1428
+ verifyFailed: "read-error",
1429
+ verifyError: error instanceof Error ? error.message.slice(0, 200) : String(error).slice(0, 200),
1430
+ verifyNote: "发布请求已成功(performed.errcode 0),但发布后读回验证读失败——不要据此重复 save(会造新记录);用 rule.list 复核 latestPublished/ruleVersion",
1431
+ nextCommand: `omc call rule.list --args '${JSON.stringify({ schemaCode })}' --env <env>(读 latestPublished/ruleVersion 复核发布)`,
1432
+ },
1433
+ };
1434
+ }
1435
+ const publishedRow = rows.find((row) => row.code === ruleCode && row.latestPublished === true);
1436
+ if (publishedRow !== undefined) {
1437
+ const listedVersion = typeof publishedRow.ruleVersion === "number" ? publishedRow.ruleVersion : undefined;
1438
+ const version = listedVersion ?? responseVersion ?? null;
1439
+ return {
1440
+ publishedVerified: true,
1441
+ verifiedBy: "published-list",
1442
+ ruleVersion: version,
1443
+ latestPublished: true,
1444
+ detail: {
1445
+ verifyWire,
1446
+ ...(listedVersion !== undefined && responseVersion !== undefined && listedVersion !== responseVersion
1447
+ ? { versionMismatchNote: `列表验证版本 ${listedVersion} ≠ 发布响应版本 ${responseVersion}(以列表为准——发布响应是 DRAFT 行模型 + facade 回填的版本号)` }
1448
+ : {}),
1449
+ },
1450
+ };
1451
+ }
1452
+ if (responseVersion !== undefined) {
1453
+ // 列表读不到但发布响应带了新版本号:runtime 面按 DRAFT 行 enabled 过滤
1454
+ // (草稿未启用则 PUBLISH 行不出现),或 8.1 族 runtime 面缺席下探到的 app 面
1455
+ // 只回 DRAFT 行——发布本身有服务端同步证据。
1456
+ return {
1457
+ publishedVerified: true,
1458
+ verifiedBy: "publish-response",
1459
+ ruleVersion: responseVersion,
1460
+ latestPublished: false,
1461
+ detail: {
1462
+ verifyWire,
1463
+ latestPublishedUncheckedNote: "发布响应已带新 ruleVersion(facade 同步铸 PUBLISH 行的证据),但列表面读不到 latestPublished 行——runtime 面按 DRAFT 行 enabled 过滤(未启用则不显示)或本版本族走的是 app/DRAFT 面。latestPublished 未经列表证实,故不给该键",
1464
+ },
1465
+ };
1466
+ }
1467
+ return {
1468
+ publishedVerified: false,
1469
+ latestPublished: false,
1470
+ detail: {
1471
+ verifyWire,
1472
+ verifyFailed: "not-visible",
1473
+ verifyNote: "发布请求已发出,但列表面与发布响应都没给出可验证的版本证据(可能仍在传播或该版本族的发布响应不带 ruleVersion)——不要据此重复 save;用 rule.list 复核",
1474
+ nextCommand: `omc call rule.list --args '${JSON.stringify({ schemaCode })}' --env <env>(读 latestPublished/ruleVersion 复核发布)`,
1475
+ },
1140
1476
  };
1141
1477
  }
1142
1478
  export async function executeRuleSaveWrite(session, args) {
1143
1479
  // 与 dry-run 同源:同一套只读门先跑,然后才写。
1144
- const { lintWarnings, lintHazards, bizMethodChecks, existing, customTriggerApplied, isPresetRule, bizRuleType, nodeJson, routeJson, schedulerField, schedulerSetting, nodes, } = await lintRuleSaveWrite(session, args);
1480
+ const { lintWarnings, lintHazards, bizMethodChecks, existing, customTriggerApplied, isPresetRule, bizRuleType, nodeJson, routeJson, schedulerField, schedulerSetting, nodes, routesSource, emptyMappings, preservedDesignerText, designerTextOverwritten, mappingFieldChecks, absentMappingFields, } = await lintRuleSaveWrite(session, args);
1481
+ // r85(retro 2026-11-19):dry-run 与真写共用的回执增量(routes 沿用 / 空映射 /
1482
+ // 设计器文本保读 / 映射字段预检)。
1483
+ const r85Readback = {
1484
+ ...(routesSource !== undefined ? { routesSource, routesNote: "本次未传 routes:已读现行连线沿用(businessrule/get +1 wire)" } : {}),
1485
+ ...(emptyMappings.length > 0 ? { emptyMappings, emptyMappingNote: "显式空映射(bizCode:\"\"):平台运行时跳过该参数、不传值(MapOps.java:490-496),服务侧按 null/缺省收到" } : {}),
1486
+ ...(preservedDesignerText.length > 0 ? { preservedDesignerText, designerTextNote: "这些映射现存设计器公式文本(editorText/editorMark)已保留,只更新了 formula——不传 editorText 时工具不覆盖设计器渲染;要覆盖显式传 editorText 或 allowDesignerTextOverwrite:true" } : {}),
1487
+ ...(designerTextOverwritten.length > 0 ? { designerTextOverwritten, designerTextOverwriteNote: "这些映射的设计器公式文本被本次写入覆盖(调用方显式传了 editorText 或 allowDesignerTextOverwrite:true);设计器打开若标红,用 rule.get formulaNotes 核对两份文本" } : {}),
1488
+ ...(mappingFieldChecks > 0 ? { mappingFieldChecks } : {}),
1489
+ ...(absentMappingFields !== undefined ? { absentMappingFieldsAllowed: absentMappingFields } : {}),
1490
+ };
1145
1491
  const performed = existing?.id
1146
1492
  ? await wireCall(session, { path: ENDPOINTS.businessRuleUpdate, method: "POST", body: {
1147
1493
  ...existing,
@@ -1182,6 +1528,14 @@ export async function executeRuleSaveWrite(session, args) {
1182
1528
  const currentLintWarnings = lintWarnings.filter((warning) => warning.nodeCode === undefined || graphNodeCodes.has(warning.nodeCode) || warning.code === "rule-graph-system-node-tool-owned");
1183
1529
  if (args.publish === true) {
1184
1530
  const row = await currentRow();
1531
+ // Publish-response evidence (r86 issue 14): the platform's publish answer is
1532
+ // itself synchronous proof — the facade mints the PUBLISH row inside a lock
1533
+ // (templateType=PUBLISH, latestPublished=TRUE, ruleVersion=max+1, status
1534
+ // ENABLED) and RETURNS the model with the minted ruleVersion
1535
+ // (BusinessRuleFacadeImpl.publishBusinessRule:337-352 →
1536
+ // BusinessRuleServiceImpl.publish:483-536). Keep the body; verification
1537
+ // falls back to it when the list face cannot show the row.
1538
+ let publishResponse = null;
1185
1539
  if (row?.id) {
1186
1540
  // Publish the FULL model, not the list-projection row: `list_by_schemacode`
1187
1541
  // omits `node`/`route`/`schedulerSetting`, so publishing it drops the
@@ -1189,7 +1543,8 @@ export async function executeRuleSaveWrite(session, args) {
1189
1543
  // the authoritative `businessrule/get?id` model (same as rule.get/enable).
1190
1544
  const full = (await wireCall(session, { path: ENDPOINTS.businessRuleGet, query: { id: String(row.id) } })).data;
1191
1545
  try {
1192
- await wireCall(session, { path: ENDPOINTS.businessRulePublish, method: "POST", body: full ?? row });
1546
+ const publishedCall = await wireCall(session, { path: ENDPOINTS.businessRulePublish, method: "POST", body: full ?? row });
1547
+ publishResponse = (publishedCall.data ?? null);
1193
1548
  }
1194
1549
  catch (error) {
1195
1550
  if (error instanceof WireError && error.errcode === RULE_SELF_CHECK_ERRCODE) {
@@ -1206,15 +1561,20 @@ export async function executeRuleSaveWrite(session, args) {
1206
1561
  throw error;
1207
1562
  }
1208
1563
  }
1209
- const effective = await currentRow();
1210
- // Live 8.6.26 (2026-09-17): businessrule/publish mints a version but does
1211
- // NOT flip a publish marker that this readback can see — the working row
1212
- // keeps templateType DRAFT and the list projection reports
1213
- // latestPublished:false even for the platform's own ENABLED presets. So
1214
- // `published` must be DERIVED from the effective row, never assumed; a
1215
- // hardcoded true made a draft rule look live and a workflow end-event
1216
- // binding on it was silently dead. Liveness itself is `rule.enable`.
1217
- const published = effective?.status === "ENABLED" || effective?.latestPublished === true || effective?.templateType === "PUBLISH";
1564
+ // r86(retro issue 14):发布后必须用「能看见 PUBLISH 行的面」验证。旧的
1565
+ // currentRow() 走 app 面 list_by_schemacode,而平台用 **DRAFT 行**服务它
1566
+ // (BusinessRuleController.list → listViewsBySchemaCode →
1567
+ // listDraftBySchemaCode,BusinessRuleFacadeImpl.java:143-150 /
1568
+ // BusinessRuleServiceImpl.java:175-177)——DRAFT 行结构上不可能携带
1569
+ // latestPublished,于是发布成功后回执仍报 latestPublished:false /
1570
+ // ruleVersion:null(retro 实证:紧接着 rule.list 却读到 latestPublished:true、
1571
+ // ruleVersion:4),agent 以为没发布成功而重复 save,每次都铸造新规则记录 ID。
1572
+ // runtime 面 list_by_schemacode 才投影 PUBLISH 行
1573
+ // (BusinessRuleRuntimeController.java:71-77 → listLatestRulesBySchemaCode),
1574
+ // 与 rule.list 同源;发布后经它读回验证(+1 wire),列表读不到时回落发布
1575
+ // 响应体的 ruleVersion。绝不把「验证不了」谎报成 latestPublished:false。
1576
+ const verification = await verifyRulePublish(session, args.schemaCode, args.ruleCode, publishResponse);
1577
+ const published = verification.publishedVerified;
1218
1578
  const effectiveNow = published && enabled;
1219
1579
  const effectiveBasis = effectiveNow ? "本次图已发布且规则 enabled:true,当前运行面可用" : "本次图未同时满足 publish + enabled;仍需 rule.enable 才是当前运行图";
1220
1580
  const previousRuleVersion = existing?.ruleVersion;
@@ -1223,8 +1583,16 @@ export async function executeRuleSaveWrite(session, args) {
1223
1583
  readback: {
1224
1584
  rulePresent: true,
1225
1585
  published,
1586
+ // r86 issue 14:publishedVerified/verifiedBy 是发布成败的判定键;ruleVersion
1587
+ // 只报验证过的版本(列表验证值优先,回落发布响应值)。latestPublished 仅在
1588
+ // 列表验证成立时出现,否则 latestPublishedUnchecked——不再谎报 false。
1589
+ publishedVerified: verification.publishedVerified,
1590
+ ...(verification.verifiedBy !== undefined ? { verifiedBy: verification.verifiedBy } : {}),
1591
+ ...(verification.ruleVersion !== undefined ? { ruleVersion: verification.ruleVersion } : {}),
1592
+ ...(verification.latestPublished === true ? { latestPublished: true } : { latestPublishedUnchecked: true }),
1593
+ ...verification.detail,
1226
1594
  enabled,
1227
- status: effective?.status,
1595
+ status: row?.status,
1228
1596
  ...(currentLintWarnings.length > 0 ? { lintWarnings: currentLintWarnings } : {}),
1229
1597
  ...(lintHazards.length > 0 ? { lintHazards } : {}),
1230
1598
  customTrigger: customTriggerApplied,
@@ -1237,14 +1605,16 @@ export async function executeRuleSaveWrite(session, args) {
1237
1605
  executableRequires: "rule.enable",
1238
1606
  executableHint: "publish 只写 PUBLISH 行,不等于可执行:运行时按 DRAFT 行的 enabled + status 判定(BusinessRuleTableImpl#getExecutableBySchemaCodeAndCode),而 list 面显示的是 PUBLISH 行。用 rule.run / domain_service_runtime 前先 rule.enable(它 publish 后再调平台 /enable,把 DRAFT 行 status 置 ENABLED)。",
1239
1607
  ...(customTriggerApplied ? {} : { customTriggerHint: "图中没有 CUSTOM_NODE 触发节点:门户按钮/流程按钮调用该规则时会按各自的触发面执行;rule.run 也能执行(它不要求 CUSTOM_NODE),执行时以 BUTTON 触发类型跑同一张图" }),
1240
- id: effective?.id ?? undefined,
1241
- ruleVersion: effective?.ruleVersion,
1608
+ id: row?.id ?? undefined,
1242
1609
  previousRuleVersion,
1243
1610
  effectiveNow,
1244
1611
  effectiveBasis,
1245
- latestPublished: effective?.latestPublished,
1612
+ ...r85Readback,
1246
1613
  ...(await modelWorkflowDispatchWarning(session, args.schemaCode)),
1247
1614
  ...(existing?.id ? { versionNote } : {}),
1615
+ // r86 issue 14:防重复保存警示——看错 latestPublished 而重复 save 的代价是
1616
+ // 每次都铸造新规则记录 ID(同 code 旧行仍可读,见 versionNote)。
1617
+ repeatSaveWarning: `发布是否成功看 publishedVerified(本次 ${verification.publishedVerified ? `verifiedBy:${verification.verifiedBy}` : "未验证通过"});同一 ruleCode 每次保存都会造新规则记录 ID,不要因 latestPublished 缺席/未验证而重复 save`,
1248
1618
  ...(enabled ? {} : { nextAction: "rule.enable(businessrule/publish + businessrule/enable 两步)后规则才会分发并对流程/按钮可见;publish:true 只写入版本" }),
1249
1619
  },
1250
1620
  };
@@ -1271,6 +1641,7 @@ export async function executeRuleSaveWrite(session, args) {
1271
1641
  previousRuleVersion,
1272
1642
  effectiveNow: false,
1273
1643
  effectiveBasis: "本次只写 DRAFT,未发布;rule.enable(或 publish:true 后再 enable)才会让本次图成为当前运行图",
1644
+ ...r85Readback,
1274
1645
  ...(await modelWorkflowDispatchWarning(session, args.schemaCode)),
1275
1646
  latestPublished: effective?.latestPublished,
1276
1647
  ...(existing?.id ? { versionNote } : {}),