@stalfh233/omc-cli 0.6.25 → 0.6.27

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.
@@ -349,6 +349,7 @@ const CAPABILITY_TOPICS = Object.freeze({
349
349
  "rule-lifecycle": ["app-scope", "omc-business-configuration", "omc-refusals"],
350
350
  workflow: ["omc-business-configuration", "omc-refusals"],
351
351
  onlinejs: ["omc-business-configuration", "omc-write-hazards"],
352
+ programming: ["omc-backend-online-coding", "omc-business-configuration", "omc-write-hazards"],
352
353
  bizservice: ["omc-business-configuration", "omc-write-hazards"],
353
354
  report: ["omc-business-configuration", "omc-write-hazards"],
354
355
  data: ["omc-business-configuration", "omc-refusals"],
@@ -35,6 +35,7 @@ export const CLI_STDOUT_OWNERS = {
35
35
  help: "envelope",
36
36
  graph: "envelope",
37
37
  residue: "envelope",
38
+ track: "envelope",
38
39
  programming: "envelope",
39
40
  rollback: "envelope",
40
41
  setup: "envelope",
package/dist/cli.js CHANGED
@@ -58,6 +58,7 @@ import { parseToolInput, ToolInputError } from "./tool-types.js";
58
58
  import { WireError, wireCall } from "./wire.js";
59
59
  import { DEFAULT_PULL_CONCURRENCY, GraphIndexAbsentError, GraphPullLockHeldError, MAX_PULL_CONCURRENCY, impactGraph, publishGraphPull, queryGraphReferences, queryGraphReferencesBatch, queryGraphEdges, readGraphStatus, searchGraphRules, } from "./graph.js";
60
60
  import { cmdResidue } from "./residue.js";
61
+ import { cmdTrack } from "./track.js";
61
62
  import { ENDPOINTS } from "./endpoints.js";
62
63
  import { makeToolContext } from "./context.js";
63
64
  import { cmdRollbackList, cmdRollbackPlan, cmdRollbackApply } from "./rollback.js";
@@ -2418,6 +2419,7 @@ async function main() {
2418
2419
  .option("--code <schemaCode>")
2419
2420
  .option("--fields <json>", "JSON 数组,每条是一个 field.create 参数(choices/字典 options 原样透传)")
2420
2421
  .option("--fields-json <json>")
2422
+ .option("--fields-file <path>", "从配置根内文件读字段 JSON 数组;与 --fields 互斥")
2421
2423
  .option("--env <environment>")
2422
2424
  .option("--environment <environment>")
2423
2425
  .option("--no-form", "跳过表单重建")
@@ -2436,6 +2438,7 @@ async function main() {
2436
2438
  ...(options.code ? ["--code", options.code] : []),
2437
2439
  ...(options.fields !== undefined ? ["--fields", options.fields] : []),
2438
2440
  ...(options.fieldsJson !== undefined ? ["--fields-json", options.fieldsJson] : []),
2441
+ ...(options.fieldsFile !== undefined ? ["--fields-file", options.fieldsFile] : []),
2439
2442
  ...(options.env ? ["--env", options.env] : []),
2440
2443
  ...(options.environment ? ["--environment", options.environment] : []),
2441
2444
  ...(options.form === false ? ["--no-form"] : []),
@@ -2533,6 +2536,7 @@ async function main() {
2533
2536
  });
2534
2537
  command.command("bench").option("--live-sample").option("--env <environment>").action(async (options) => { commandExitCode = await cmdBench([...(options.liveSample ? ["--live-sample"] : []), ...(options.env ? ["--env", options.env] : [])]); });
2535
2538
  command.command("residue <prefix>").description("跨面前缀残留扫描(model 全租户/folder/custompage;默认 deep 再查命中模型的 rule/datarule/onlinejs)——收尾「删净」一次证明,clean:true 即零残留。清理入口:omc model-purge --code <schemaCode>(按依赖倒序,默认 dry-run)。只读零写入;report 面暂停维护未扫描").option("--env <environment>", "环境名(默认按 cwd 的 .omc-env 解析)").option("--apps <codes>", "all(默认,全租户)或逗号分隔应用码").option("--no-deep", "只扫 model/folder/custompage,不深查命中模型").option("--all-faces", "列出全部应用×面(含 count:0;默认只回非零面+byFace/userResidues 紧凑形)").option("--max-output-bytes <bytes>").action(async (prefix, options) => { commandExitCode = await withTransport(options, request, (transport) => cmdResidue(prefix, { env: options.env, apps: options.apps, ...(options.deep === false ? { noDeep: true } : {}), ...(options.allFaces ? { allFaces: true } : {}) }, transport)); });
2539
+ command.command("track <schemaCode> <bizObjectId>").description("读取单条业务数据的行级变更留痕(只读;平台来源枚举含 BUSINESS_RULE 时原样回传)").option("--env <environment>").option("--property-code <code>").option("--max-output-bytes <bytes>").action(async (schemaCode, bizObjectId, options) => { commandExitCode = await withTransport(options, request, (transport) => cmdTrack(schemaCode, bizObjectId, { env: options.env, propertyCode: options.propertyCode }, transport)); });
2536
2540
  const jqOption = () => new Option("--jq [path]", "路径投影(与 call --jq 同 DSL;可逗号多路径;裸 --jq 列顶层键)").argParser((value, previous = []) => [...previous, value]).default([]);
2537
2541
  command.command("commands").option("--json").option("--compact").option("--filter <keyword>").option("--lane <id>").option("--max-output-bytes <bytes>").addOption(jqOption()).action(async (options) => { commandExitCode = await withTransport(options, request, (transport) => cmdDiscovery("commands", transport, undefined, { json: options.json === true, compact: options.compact === true, ...(options.filter ? { filter: options.filter } : {}), ...(options.lane ? { lane: options.lane } : {}), ...(options.jq !== undefined ? { jq: options.jq } : {}) })); });
2538
2542
  command.command("describe <tool>").option("--full").option("--cache-ok", "允许 --full 在同会话重复读时短路为 artifact 指针(默认每次回全文)").option("--schema-only").option("--param <name>").option("--example [id]").option("--max-output-bytes <bytes>").addOption(jqOption()).action(async (tool, options) => {
package/dist/endpoints.js CHANGED
@@ -110,6 +110,7 @@ export const ENDPOINTS = {
110
110
  ruleRuntimeExecuteBase: "/api/api/launcher/domain_service_runtime",
111
111
  ruleLogSearch: "/api/api/launcher/domain_service_runtime/{schemaCode}/search_rule_log",
112
112
  ruleActivityLog: "/api/api/launcher/domain_service_runtime/{schemaCode}/query_rule_activity_log",
113
+ dataTrackSearch: "/api/api/launcher/domain_service_runtime/{schemaCode}/search_data_track",
113
114
  /**
114
115
  * Form-toolbar button execution — a DIFFERENT face from the list-button one.
115
116
  * Live 2026-10-23 (1.1.25, Playwright capture of a `triggerType=FORM` button
package/dist/field-add.js CHANGED
@@ -17,6 +17,9 @@ import { argvValue } from "./args.js";
17
17
  import { runToolCall } from "./call.js";
18
18
  import { CLI_EXIT_CODES, classifyResult, envelope, refusalText, requestId } from "./cli-contract.js";
19
19
  import { writeEnvelope } from "./cli-output.js";
20
+ import { assertSafeInputPath } from "./artifacts.js";
21
+ import { readFileSync } from "node:fs";
22
+ import { resolve } from "node:path";
20
23
  /**
21
24
  * 字典简写展开(r30/r36 实证:字典字段要先 names 查 id、records 取记录、
22
25
  * 再拼 optionsSet.dictionary 三段 4–5 调;`dictCode` 把它折进 field-add 一步):
@@ -108,7 +111,9 @@ export async function cmdFieldAdd(args, contextForTest) {
108
111
  const request = requestId();
109
112
  const flag = (name) => argvValue(args, name);
110
113
  const schemaCode = flag("--schema") ?? flag("--schema-code") ?? flag("--code");
111
- const fieldsJson = flag("--fields") ?? flag("--fields-json");
114
+ const fieldsFile = flag("--fields-file");
115
+ const fieldsFlag = flag("--fields");
116
+ const fieldsJson = fieldsFlag === "-" ? readFileSync(0, "utf8") : fieldsFlag ?? flag("--fields-json");
112
117
  const environment = flag("--env") ?? flag("--environment");
113
118
  const apply = args.includes("--apply");
114
119
  const publishForm = !args.includes("--no-form");
@@ -117,7 +122,7 @@ export async function cmdFieldAdd(args, contextForTest) {
117
122
  const conditionsJson = flag("--conditions") ?? flag("--conditions-json");
118
123
  const demoRowsJson = flag("--demo-rows") ?? flag("--demo-rows-json");
119
124
  const usage = [
120
- "用法:omc field-add --schema <模型code> --fields '<JSON 数组>' [--apply]",
125
+ "用法:omc field-add --schema <模型code> --fields '<JSON 数组>' [--fields-file <路径>|--fields -] [--apply]",
121
126
  " --fields 每项是一个 field.create 的参数:{\"code\",\"name\",\"propertyType\",...}(choices/字典 options 原样透传);",
122
127
  " 字典简写:{\"dictCode\":\"<字典code>\"} 代替手拼 options.optionsSet(内部解析字典 id+启用记录,recipe 同形状)。",
123
128
  " 默认 dry-run;--apply 依次执行 建字段 → 发布字段 → 重建表单 → 列表追加列。",
@@ -125,6 +130,7 @@ export async function cmdFieldAdd(args, contextForTest) {
125
130
  " --no-form 跳过表单重建;--no-list 跳过列表加列(默认两者都做)。",
126
131
  " --conditions '<JSON 数组>' 列表固定过滤条件(listview.configure 契约;**整体替换**既有固定条件——要保留旧的须一并带上;不传则不动);需 --list(默认开)。",
127
132
  " --demo-rows '<JSON 数组>' 演示数据行(每项一份 formData,逐行 data.submit);非幂等——重复执行会重复插行。",
133
+ " --fields-file 从配置根内文件读 JSON 数组;--fields - 从 stdin 读 JSON 数组。",
128
134
  ].join("\n");
129
135
  const invalid = (message) => {
130
136
  writeEnvelope(envelope("error", {}, request, { code: "invalid-input", message: `${message}\n${usage}`, retryable: false }));
@@ -132,11 +138,23 @@ export async function cmdFieldAdd(args, contextForTest) {
132
138
  };
133
139
  if (!schemaCode)
134
140
  return invalid("--schema 必填(存量模型 code)");
135
- if (fieldsJson === undefined)
136
- return invalid("--fields 必填(JSON 数组)");
141
+ if (fieldsFile !== undefined && (fieldsFlag !== undefined || flag("--fields-json") !== undefined))
142
+ return invalid("--fields-file 不能与 --fields/--fields-json 同时使用");
143
+ let inputJson = fieldsJson;
144
+ if (fieldsFile !== undefined) {
145
+ try {
146
+ const root = resolve(process.env.OMC_CONFIG_HOME ?? process.cwd());
147
+ inputJson = readFileSync(assertSafeInputPath(root, fieldsFile, "--fields-file"), "utf8");
148
+ }
149
+ catch (error) {
150
+ return invalid(`--fields-file 读取失败:${error instanceof Error ? error.message : String(error)}`);
151
+ }
152
+ }
153
+ if (inputJson === undefined)
154
+ return invalid("--fields 必填(JSON 数组;或使用 --fields-file/--fields -)");
137
155
  let fields;
138
156
  try {
139
- const parsed = JSON.parse(fieldsJson);
157
+ const parsed = JSON.parse(inputJson);
140
158
  if (!Array.isArray(parsed) || parsed.length === 0)
141
159
  throw new Error("--fields 必须是非空 JSON 数组");
142
160
  fields = parsed;
@@ -938,14 +938,14 @@ export function assertSelectionChoicesAllowed(args) {
938
938
  }
939
939
  function refuseFieldOptions(reason, message) {
940
940
  const citation = {
941
- code: "capability-out-of-coverage",
941
+ code: "field-options-shape",
942
942
  lane: "field-families",
943
943
  capability: "field family full chain",
944
944
  status: "blocked",
945
945
  reason,
946
946
  message,
947
947
  };
948
- throw new ToolRefusalError({ status: "refused", blocker: "capability-out-of-coverage", citation });
948
+ throw new ToolRefusalError({ status: "refused", blocker: "field-options-shape", citation });
949
949
  }
950
950
  /**
951
951
  * Aggregation query conditions are deserialized by Jackson into Java enums that
@@ -30,6 +30,9 @@ export const FORMULA_FUNCTION_ALIASES = Object.freeze({
30
30
  STRCAT: "STRING",
31
31
  JOIN: "STRING",
32
32
  });
33
+ export const FORMULA_LINT_CODES = new Set([
34
+ "formula-function-unknown", "formula-function-alias", "formula-text-plus-concat",
35
+ ]);
33
36
  const TEXT_PLUS_CONCAT = /(\{[^{}]+\}|[A-Za-z_][A-Za-z0-9_]*\s*\([^()]*\))\s*\+\s*["']|["']\s*\+\s*(\{[^{}]+\}|[A-Za-z_][A-Za-z0-9_]*\s*\()/;
34
37
  /**
35
38
  * Lint one formula string. `where` names the carrier in the caller's own terms
@@ -75,6 +75,7 @@ const RULE_SAVE_DESCRIPTION = describeTool("保存业务规则(upsert):`ru
75
75
  "**EXPRESSION 值形状**:`ruleValueType:EXPRESSION` 时 `value` 必须是 {\"formula\":\"{字段A}+{字段B}\"}(大括号裸 code);门户设计器的 [code] 方括号式在这里不认。",
76
76
  "**幻影 schema 门(ticket 96 live 事故)**:rule.save 写前先以 bizmodels/get_all 探测模型存在(缺失 → refused `rule-schema-unresolved`,零规则面 wire 调用)——平台的 list/save 面会对任意 schemaCode 自动补建 7 条预置规则且 API 删除不可达(list 即重灌),幻影 schema 必须在写前拒绝。",
77
77
  "**输出回写排序(ticket 36 live 铁证)**:BIZ_ACTION 的 outputMappings 由 SYSTEM_CREATE/SYSTEM_UPDATE 持久化节点消费,动作节点必须排在系统节点之前(`Start→BizAction→SYSTEM_CREATE→End`);工具默认把系统节点补在 START 之后,有回写动作时须显式提供系统节点并置于动作之后,否则合并结果不落库(echoResult 恒 null)。",
78
+ "**跨模型 UPDATE 三段语义(1.1.25 反编译定案)**:`inputParam`=输入源(触发行或 QUERY 上游输出,`currentSchemaDataItem` 属此侧)→ `filterCondition` 按 `targetSchemaCode` 查目标行 → `dataActions` 把输入源值写入目标行。QUERY 目标行不自动成为输入源;child fan-out 保持 fail-closed(用显式中间字段/映射/二开)。",
78
79
  ]);
79
80
  export const BUSINESSRULE_LANE_CONTRACT = Object.freeze({
80
81
  lane: LANES.businessrule,
@@ -479,6 +479,7 @@ export function registerBusinessRuleLane(tools) {
479
479
  name: z.string().min(1),
480
480
  nodeGraph: ruleNodeGraphArg,
481
481
  publish: z.boolean().optional().describe("also publish the new version in this call (businessrule/publish) so the designer sees it; enabling stays with rule.enable — default false keeps the legacy draft-only save"),
482
+ allowAdvisory: z.boolean().optional().describe("调查逃生口;默认 false"),
482
483
  customTrigger: z.boolean().optional().describe("默认开:自定义 ruleCode + bizRuleType 0(非平台触发码 Create/Update/Delete/GetList/Load/Available/Cancel)即按钮/流程规则,工具在 START 后合成平台标准 CUSTOM_NODE「自定义按钮/流程触发」系统触发节点(nodeCode=ruleCode,live 布局 x558/y233);调用方已写 CUSTOM_NODE 则原样保留;显式 false 退回"),
483
484
  },
484
485
  execute: async (session, args) => executeRuleSaveWrite(session, args),
@@ -481,6 +481,11 @@ export function dataRuleFormulaWarnings(dataRuleType, options) {
481
481
  return [];
482
482
  return lintFormulaText(formula, "options.shortTextStitch.formula");
483
483
  }
484
+ function assertDataRuleFormulaLint(dataRuleType, options, allowAdvisory) {
485
+ const findings = dataRuleFormulaWarnings(dataRuleType, options);
486
+ if (findings.length > 0 && allowAdvisory !== true)
487
+ throw new ToolRefusalError({ status: "refused", blocker: "formula-lint-failed", validation: findings, nextCommand: "修正公式函数/字符串拼接;调查用途显式传 allowAdvisory:true", message: "公式写前校验拒绝:未知函数、平台别名或字符串 + 拼接。文本合并请使用 STRING()。" });
488
+ }
484
489
  /** Extract the expression of a type-2 CALCULATE rule (mirrors calcExpressionShapeError's carrier choice). */
485
490
  function type2FormulaText(options) {
486
491
  const raw = typeof options.shortTextStitch === "string" ? options.shortTextStitch : typeof options.value === "string" ? options.value : undefined;
@@ -872,9 +877,11 @@ export function registerDataRuleLane(tools) {
872
877
  childRule: z.boolean().optional().describe("true=子表列规则,propertyCode 为子表列 code;主表字段忽略"),
873
878
  name: z.string().optional(),
874
879
  sortKey: z.number().int().optional(),
880
+ allowAdvisory: z.boolean().optional().describe("调查逃生口;默认 false"),
875
881
  },
876
882
  execute: async (session, args) => {
877
883
  assertDataRuleOptions(args.dataRuleType, args.options, args.checkType);
884
+ assertDataRuleFormulaLint(args.dataRuleType, args.options, args.allowAdvisory);
878
885
  assertDataRuleCheckType(args.dataRuleType, args.checkType);
879
886
  assertDataRuleTarget(args);
880
887
  const codes = dataRuleTargetCodes(args);
@@ -957,6 +964,7 @@ export function registerDataRuleLane(tools) {
957
964
  propertyCodes: propertyCodesArg,
958
965
  dataRuleType: dataRuleTypeArg,
959
966
  options: dataRuleOptionsArg,
967
+ allowAdvisory: z.boolean().optional().describe("调查逃生口;默认 false"),
960
968
  checkType: checkTypeArg,
961
969
  childRule: z.boolean().optional().describe("true=子表列规则,propertyCode 为子表列 code;主表字段忽略"),
962
970
  name: z.string().optional(),
@@ -964,6 +972,7 @@ export function registerDataRuleLane(tools) {
964
972
  },
965
973
  execute: async (session, args) => {
966
974
  assertDataRuleOptions(args.dataRuleType, args.options, args.checkType);
975
+ assertDataRuleFormulaLint(args.dataRuleType, args.options, args.allowAdvisory);
967
976
  assertDataRuleCheckType(args.dataRuleType, args.checkType);
968
977
  const id = await locateDataRuleId(session, args, "update POST");
969
978
  const before = await listDataRules(session, args.schemaCode);
@@ -41,6 +41,61 @@ export async function modelSchemaCodes(session) {
41
41
  .map((row) => String(row.schemaCode ?? row.bizSchemaCode ?? row.code ?? ""))
42
42
  .filter((code) => code.length > 0);
43
43
  }
44
+ function relationTypeOf(row) {
45
+ const value = Number(row.type ?? row.propertyType);
46
+ return Number.isInteger(value) ? value : undefined;
47
+ }
48
+ /** Semantic relation gate: the designer only offers published business fields. */
49
+ async function assertRelationOptionsFields(session, schemaCode, propertyType, relativeCode, options) {
50
+ const type = typeof propertyType === "number" ? propertyType : FIELD_PROPERTY_TYPES[String(propertyType ?? "")];
51
+ if (type !== FIELD_PROPERTY_TYPES.WORK_SHEET && type !== FIELD_PROPERTY_TYPES.MULT_WORK_SHEET)
52
+ return;
53
+ const target = String(relativeCode ?? options.schemaCode ?? "").trim();
54
+ if (!target)
55
+ return;
56
+ const targetRows = wireRows((await wireCall(session, { path: ENDPOINTS.fieldList, query: { schemaCode: target, isPublish: "true" } })).data);
57
+ const ownRows = wireRows((await wireCall(session, { path: ENDPOINTS.fieldList, query: { schemaCode, isPublish: "true" } })).data);
58
+ const business = (rows) => rows
59
+ .map((row) => ({ code: String(row.code ?? row.propertyCode ?? "").trim(), type: relationTypeOf(row) }))
60
+ .filter((row) => row.code && !SYSTEM_FIELD_CODES.has(row.code));
61
+ const targetFields = business(targetRows);
62
+ const ownFields = business(ownRows);
63
+ // A compatibility/fake transport may expose an empty field face even though
64
+ // the model exists. Empty metadata is not proof that a requested field is
65
+ // absent; preserve the existing relation write path rather than rejecting a
66
+ // valid payload on an unavailable read face.
67
+ if (targetRows.length === 0 || ownRows.length === 0)
68
+ return;
69
+ const candidates = targetFields.map((row) => row.code).sort();
70
+ const display = typeof options.displayField === "string" ? options.displayField.trim() : "";
71
+ if (display) {
72
+ const field = targetFields.find((row) => row.code === display);
73
+ const declaredType = options.displayFieldType === undefined ? undefined : Number(options.displayFieldType);
74
+ if (!field || (declaredType !== undefined && Number.isInteger(declaredType) && field.type !== undefined && field.type !== declaredType)) {
75
+ throw new ToolRefusalError({ status: "refused", blocker: "relation-display-field-not-found", schemaCode, relationTarget: target, displayField: display, candidates, message: `关联显示字段 ${target}.${display} 不存在于发布面或类型不兼容;请从目标模型业务字段中选择。候选:${candidates.join("、") || "(无)"}` });
76
+ }
77
+ }
78
+ let mappings = options.mappings;
79
+ if (typeof mappings === "string" && mappings) {
80
+ try {
81
+ mappings = JSON.parse(mappings);
82
+ }
83
+ catch {
84
+ mappings = [];
85
+ }
86
+ }
87
+ if (!Array.isArray(mappings))
88
+ return;
89
+ const sourceCandidates = targetFields.map((row) => row.code).sort();
90
+ const targetCandidates = ownFields.map((row) => row.code).sort();
91
+ for (const [index, row] of mappings.entries()) {
92
+ const source = row && typeof row === "object" ? String(row.source ?? "").trim() : "";
93
+ const mappedTarget = row && typeof row === "object" ? String(row.target ?? "").trim() : "";
94
+ if (!sourceCandidates.includes(source) || !targetCandidates.includes(mappedTarget)) {
95
+ throw new ToolRefusalError({ status: "refused", blocker: "relation-mapping-field-not-found", schemaCode, relationTarget: target, mappingIndex: index, source, targetField: mappedTarget, sourceCandidates, targetCandidates, message: `关联映射第 ${index + 1} 行字段不存在:source=${source || "(空)"}(目标模型候选:${sourceCandidates.join("、") || "(无)"}),target=${mappedTarget || "(空)"}(本模型候选:${targetCandidates.join("、") || "(无)"})。请使用发布面业务字段 code。` });
96
+ }
97
+ }
98
+ }
44
99
  async function readFieldRollback(session, args) {
45
100
  for (const published of [false, true]) {
46
101
  const row = wireRows((await wireCall(session, { path: ENDPOINTS.fieldList, query: { schemaCode: String(args.schemaCode), isPublish: String(published) } })).data).find((entry) => String(entry.code ?? entry.propertyCode) === String(args.code));
@@ -314,7 +369,11 @@ export function registerFieldLane(tools) {
314
369
  ...(conditions.length > 0 ? { conditions } : {}),
315
370
  ...(field.shapeWarning !== undefined ? { shapeWarning: field.shapeWarning } : {}),
316
371
  ...(field.origin !== undefined ? { origin: field.origin } : {}),
317
- ...(args.full === true && "options" in field && field.options !== undefined ? { options: field.options, optionsPresent: true } : {}),
372
+ ...(args.full === true
373
+ ? ("options" in field && field.options !== undefined
374
+ ? { options: field.options, optionsPresent: true }
375
+ : { optionsPresent: false })
376
+ : {}),
318
377
  };
319
378
  });
320
379
  return {
@@ -373,6 +432,11 @@ export function registerFieldLane(tools) {
373
432
  ...(conditions.length > 0 ? { conditions } : {}),
374
433
  ...(field.shapeWarning !== undefined ? { shapeWarning: field.shapeWarning } : {}),
375
434
  ...(field.origin !== undefined ? { origin: field.origin } : {}),
435
+ // r46a 接线(2026-11-08,r45 普查 R5a):压缩占位行保留**标量判别键**
436
+ // optionsPresent——不然 >10 行的 full 读回内联面完全看不到 presence
437
+ // 信号,agent 误判「条件没写进去」(S1-G3 预言命中:通用层把「有值
438
+ // 但正文外置」和「确实没有」混在一起)。正文仍在 artifact。
439
+ ...(field.optionsPresent !== undefined ? { optionsPresent: field.optionsPresent } : {}),
376
440
  };
377
441
  }),
378
442
  hint: "字段详情(options/subSchema)用 omc call field.list --args '{\"schemaCode\":\"...\",\"published\":true,\"code\":\"<field>\"}'",
@@ -418,6 +482,7 @@ export function registerFieldLane(tools) {
418
482
  // (cpdocs issue #8:缺键让设计器选项弹窗硬崩)。
419
483
  const targetVersion = session.detectedVersion();
420
484
  const prepared = prepareFieldChange({ ...args, ...(targetVersion ? { targetVersion } : {}) });
485
+ await assertRelationOptionsFields(session, args.schemaCode, prepared.propertyType, args.relativeCode, prepared.options);
421
486
  let performed;
422
487
  try {
423
488
  performed = await wireCall(session, { path: ENDPOINTS.fieldCreate, method: "POST", body: fieldChangeWireBody(args, prepared) });
@@ -730,6 +795,7 @@ async function fieldUpdateDryRun(session, args) {
730
795
  ...(args.propertyEmpty !== undefined ? { propertyEmpty: args.propertyEmpty } : {}),
731
796
  };
732
797
  const prepared = prepareFieldUpdate(update);
798
+ await assertRelationOptionsFields(session, args.schemaCode, prepared.propertyType, args.relativeCode ?? record.relativeCode, prepared.options);
733
799
  const currentOptions = decodeJsonObjectColumn(record.options, { invalid: "throw", array: "accept", object: "accept" }) ?? {};
734
800
  const changes = [];
735
801
  const pushChange = (field, from, to) => {
@@ -554,8 +554,11 @@ export function registerOrganizationLane(tools) {
554
554
  // A 32-hex id absent from the tree may be a group created moments ago in
555
555
  // this same session; let it through and rely on the visibility backstop.
556
556
  if (!match && args.roleGroupCode) {
557
- throw new ToolInputError({
557
+ throw new ToolRefusalError({
558
+ status: "refused",
559
+ blocker: "role-group-not-found",
558
560
  message: `角色组 ${requested} 不存在。可用组:${groups.map((group) => `${group.code}(id=${group.id},${group.name})`).join(";")}`,
561
+ candidates: groups.map((group) => ({ code: group.code, id: group.id, name: group.name })),
559
562
  });
560
563
  }
561
564
  const roleGroupId = match?.id ?? String(requested);
@@ -57,11 +57,18 @@ export function registerRuleLogLane(tools) {
57
57
  const log = { ruleCode: row.code, name: row.name, triggerType: row.triggerType, status: row.status, triggerTime: row.triggerTime, finishTime: row.finishTime, ...(row.errMsg ? { errMsg: row.errMsg } : {}), ruleVersion: row.ruleVersion, traceId: row.traceId, triggerRows: Array.isArray(row.inputSummaries) ? row.inputSummaries.map((v) => ({ id: v.id, name: v.name })) : [] };
58
58
  if (args.includeNodes === true && index < 3) {
59
59
  const nodeData = (await wireCall(session, { path: path(ENDPOINTS.ruleActivityLog, args.schemaCode), method: "POST", body: { ruleLogId: row.id } })).data;
60
- log.nodes = Array.isArray(nodeData) ? nodeData.map((node) => ({ type: node.type, name: node.name, status: node.status, ...(node.targetSchemaCode ? { targetSchemaCode: node.targetSchemaCode } : {}), ...(node.errMsg ? { errMsg: node.errMsg } : {}) })) : [];
60
+ log.nodes = Array.isArray(nodeData) ? nodeData.map((node) => ({
61
+ type: node.type,
62
+ name: node.name,
63
+ status: node.status,
64
+ ...(String(node.type ?? "").toUpperCase() === "QUERY" ? { matchedUnknown: true } : {}),
65
+ ...(node.targetSchemaCode ? { targetSchemaCode: node.targetSchemaCode } : {}),
66
+ ...(node.errMsg ? { errMsg: node.errMsg } : {}),
67
+ })) : [];
61
68
  }
62
69
  return log;
63
70
  }));
64
- return { index: { schemaCode: args.schemaCode, page: requestedPage, size: requestedSize, totalElements: data.totalElements ?? logs.length, totalPages: data.totalPages ?? 0, ...(rowFilter ? { rowFilter } : {}) }, logs, notes: ["status=true 表示成功,status=false 表示失败", ...notes, ...(args.includeNodes === true ? ["节点 VO 不提供 targetBizObjectId,节点行级 id 不可得;仅前 3 条命中日志拉取节点链"] : [])] };
71
+ return { index: { schemaCode: args.schemaCode, page: requestedPage, size: requestedSize, totalElements: data.totalElements ?? logs.length, totalPages: data.totalPages ?? 0, ...(rowFilter ? { rowFilter } : {}) }, logs, notes: ["status=true 表示成功,status=false 表示失败", ...notes, ...(args.includeNodes === true ? ["节点 VO 不提供 targetBizObjectId,节点行级 id 不可得;仅前 3 条命中日志拉取节点链", "QUERY 节点日志不记录命中数:matchedUnknown=true;0 行与成功同形,请用 data.load 比对目标行"] : [])] };
65
72
  }, { target: `rulelog.search:${args.schemaCode}:${JSON.stringify(args)}` }),
66
73
  }));
67
74
  }
@@ -13,7 +13,6 @@ import { closestMatch } from "../closest-match.js";
13
13
  import { getReplayToken, listInstanceActivities, searchWorkItems, wireString } from "../workflow-support.js";
14
14
  import { PLATFORM_ADMIN_START_BYPASS, resolvePermissionActor } from "../identity.js";
15
15
  import { ENGINE_OWNED_KEYS, RUNTIME_DATA_LANE_CONTRACT, RUNTIME_DATA_WIRE, runtimeFormDataArg, } from "./runtime-data-contract.js";
16
- import { SYSTEM_FIELD_CODES } from "../field-families.js";
17
16
  import { applicationResolutionOf, resolveApplicationScope } from "../support.js";
18
17
  /** r29b F8: keep ids/itemsPreview through governedRead's compact diet. */
19
18
  const DATA_LIST_PREVIEW_LIMIT = 20;
@@ -1240,22 +1239,18 @@ export function registerRuntimeDataLane(tools) {
1240
1239
  const selected = fields ?? Object.keys(data).filter((field) => !["id", "bizObjectId", "schemaCode", "sequenceStatus", "createdTime", "updatedTime", "creator", "updater"].includes(field));
1241
1240
  return { id: row.bizObjectId ?? row.id ?? data.id, fields: Object.fromEntries(selected.map((field) => [field, data[field] ?? null])) };
1242
1241
  });
1243
- // A6(GitLab #15):all:true 路径此前完全没有 projectionHint——未配置列
1244
- // 的 null/省略同样要点名,防「全量拉取却被投影坑」(实测 orderChange)。
1245
- let allHint;
1246
- if (items.length > 0) {
1242
+ const preview = dataListItemPreview(items);
1243
+ const nullProjection = items.some((item) => Object.values(item.fields).some((value) => value === null));
1244
+ let viewColumnsCount;
1245
+ if (nullProjection) {
1247
1246
  try {
1248
- const typeByCode = await publishedTypeByCode();
1249
- const returnedKeys = new Set(Object.keys(items[0]?.fields ?? {}));
1250
- const hintColumns = [...typeByCode.keys()].filter((field) => !SYSTEM_FIELD_CODES.has(field) && (!returnedKeys.has(field) || items.every((item) => item.fields[field] === null)));
1251
- if (hintColumns.length > 0)
1252
- allHint = `这些列在默认视图未配置(值可能存在但列表投影为 null 或整列省略):${hintColumns.join("、")};先用 listview.configure 配置列,或用 data.load 读单条权威值`;
1247
+ const view = (await wireCall(session, { path: ENDPOINTS.listQueryGet, query: { schemaCode: args.schemaCode, code: args.queryCode ?? args.schemaCode, clientType: "PC" } })).data;
1248
+ viewColumnsCount = Array.isArray(view?.queryColumns) ? view.queryColumns.length : 0;
1253
1249
  }
1254
1250
  catch {
1255
- // 元数据读失败不阻断数据返回
1251
+ // Projection diagnostics must never make data.list fail.
1256
1252
  }
1257
1253
  }
1258
- const preview = dataListItemPreview(items);
1259
1254
  return {
1260
1255
  schemaCode: args.schemaCode,
1261
1256
  ...application,
@@ -1292,7 +1287,7 @@ export function registerRuntimeDataLane(tools) {
1292
1287
  capNotice: `已取前 ${collected.length} 条 / 共 ${total} 条(安全上限 ${CAP})——还差 ${total - collected.length} 条没返回。不要把它当全集:加 filters 分片(如按日期/业务键)分别拉取,或去掉 all 用 page/size 手动翻页。`,
1293
1288
  }
1294
1289
  : {}),
1295
- ...(allHint ? { projectionHint: allHint } : {}),
1290
+ ...(nullProjection ? { projectionHint: { hint: "null 可能=未投影进视图列,判真值用 data.load --args {schemaCode,bizObjectId}", ...(viewColumnsCount !== undefined ? { viewColumnsCount } : {}) } } : {}),
1296
1291
  items,
1297
1292
  };
1298
1293
  }
@@ -1404,6 +1399,17 @@ export function registerRuntimeDataLane(tools) {
1404
1399
  const data = row.data && typeof row.data === "object" ? row.data : row;
1405
1400
  return String(data.sequenceStatus ?? row.sequenceStatus ?? "") === "DRAFT";
1406
1401
  }).length;
1402
+ let viewColumnsCount;
1403
+ const hasNullValue = items.some((item) => Object.values(item.fields).some((value) => value === null));
1404
+ if (hasNullValue) {
1405
+ try {
1406
+ const view = (await wireCall(session, { path: ENDPOINTS.listQueryGet, query: { schemaCode: args.schemaCode, code: args.queryCode ?? args.schemaCode, clientType: "PC" } })).data;
1407
+ viewColumnsCount = Array.isArray(view?.queryColumns) ? view.queryColumns.length : 0;
1408
+ }
1409
+ catch {
1410
+ // Keep the data read authoritative if the optional diagnostic read fails.
1411
+ }
1412
+ }
1407
1413
  const readback = {
1408
1414
  schemaCode: args.schemaCode,
1409
1415
  ...application,
@@ -1433,6 +1439,7 @@ export function registerRuntimeDataLane(tools) {
1433
1439
  return { filter: policy };
1434
1440
  })(),
1435
1441
  ...(choiceFilterFields.length > 0 && Number(total ?? 0) === 0 ? { filterValueHint: choiceFilterValueHint(choiceFilterFields) } : {}),
1442
+ ...(hasNullValue ? { projectionHint: { hint: "null 可能=未投影进视图列,判真值用 data.load --args {schemaCode,bizObjectId}", ...(viewColumnsCount !== undefined ? { viewColumnsCount } : {}) } } : {}),
1436
1443
  totalPages,
1437
1444
  itemsCount: items.length,
1438
1445
  itemsReturned: items.length,
@@ -1444,59 +1451,6 @@ export function registerRuntimeDataLane(tools) {
1444
1451
  // r29b F8 的 ids/itemsPreview 由 compact(外置时)现算,见 dataListCompactProjection。
1445
1452
  items,
1446
1453
  };
1447
- // A model's unconfigured default list view projects business columns as
1448
- // null even though the stored values exist (ticket 07). Only when the
1449
- // caller explicitly projected columns, EVERY returned row yielded null
1450
- // for EVERY selected column, and the published metadata confirms those
1451
- // are real model fields, surface the recovery hint. `items` is never
1452
- // reshaped — the hint is a sibling readback field.
1453
- // Candidate keys first (pure — zero wires); metadata only when there is
1454
- // at least one all-null column to classify (preserves the rawCondition
1455
- // path's zero-extra-wire contract when there is nothing to hint).
1456
- const businessNullColumns = async () => {
1457
- const candidates = Object.keys(items[0]?.fields ?? {}).filter((field) => !SYSTEM_FIELD_CODES.has(field) && items.every((item) => item.fields[field] === null));
1458
- if (candidates.length === 0)
1459
- return [];
1460
- const typeByCode = await publishedTypeByCode();
1461
- return candidates.filter((field) => typeByCode.has(field));
1462
- };
1463
- // A6(GitLab #15,2026-11-04):未配置列有两种投影形态——值为 null,或
1464
- // **整键省略**(orderChange 实测:sequenceNo 在 data.list 里根本不出现,
1465
- // data.load 却有值,被误读成「单号为空」)。省略检测需要发布元数据
1466
- // (fieldList 有 60s wire 缓存,DSL 过滤路径本就已取);两种形态合并进 hint。
1467
- const projectionHintFor = async () => {
1468
- if (items.length === 0)
1469
- return undefined;
1470
- const typeByCode = await publishedTypeByCode();
1471
- const returnedKeys = new Set(Object.keys(items[0]?.fields ?? {}));
1472
- const nullColumns = fields && fields.length > 0
1473
- ? fields.filter((field) => typeByCode.has(field) && items.every((item) => item.fields[field] === null))
1474
- : [...returnedKeys].filter((field) => !SYSTEM_FIELD_CODES.has(field) && typeByCode.has(field) && items.every((item) => item.fields[field] === null));
1475
- const omittedColumns = !fields
1476
- ? [...typeByCode.keys()].filter((field) => !SYSTEM_FIELD_CODES.has(field) && !returnedKeys.has(field))
1477
- : [];
1478
- const hintColumns = [...new Set([...nullColumns, ...omittedColumns])];
1479
- if (hintColumns.length === 0)
1480
- return undefined;
1481
- return `这些列在默认视图未配置(值可能存在但列表投影为 null 或整列省略):${hintColumns.join("、")};先用 listview.configure 配置列,或用 data.load 读单条权威值`;
1482
- };
1483
- if (fields &&
1484
- fields.length > 0 &&
1485
- items.length > 0 &&
1486
- items.every((item) => fields.every((field) => item.fields[field] === null))) {
1487
- const typeByCode = await publishedTypeByCode();
1488
- if (fields.every((field) => typeByCode.has(field)))
1489
- readback.projectionHint = RUNTIME_DATA_WIRE.projectionHint;
1490
- }
1491
- else if (!fields && items.length > 0) {
1492
- // r17 finding: BOTH delegated agents tripped on implicit projection —
1493
- // business fields absent from the list view render as null in every
1494
- // row with no explanation. Name the null'd business columns so the
1495
- // agent reads data.load instead of misdiagnosing "data lost".
1496
- const hint = await projectionHintFor();
1497
- if (hint)
1498
- readback.projectionHint = hint;
1499
- }
1500
1454
  // r29b F8: ids/itemsPreview 已在同信封;artifact 提示由 compact 外置后的
1501
1455
  // fetch/detailArtifactId 承担。这里不改既有 projectionHint 主句(契约测试
1502
1456
  // 钉死 RUNTIME_DATA_WIRE.projectionHint 原文)。
@@ -878,7 +878,15 @@ async function assertRoleParticipantScopes(session, body) {
878
878
  if (String(activity.activityType ?? "") !== "PARTICIPANT")
879
879
  continue;
880
880
  const participant = typeof activity.participant === "string" ? activity.participant.trim() : "";
881
- const match = /^FindUserByRole\s*\(\s*[^,]+?\s*,\s*("(?:\\.|[^"\\])*"|'(?:\\.|[^'\\])*')\s*,\s*("(?:\\.|[^"\\])*"|'(?:\\.|[^'\\])*')\s*\)\s*$/.exec(participant);
881
+ if (/^FindUserByRole\s*\(/i.test(participant)) {
882
+ const strict = /^FindUserByRole\s*\(\s*\{Originator\.OU\}\s*,\s*("(?:\\.|[^"\\])*"|'(?:\\.|[^'\\])*')\s*,\s*("(?:\\.|[^"\\])*"|'(?:\\.|[^'\\])*')\s*\)\s*$/i.exec(participant);
883
+ if (!strict)
884
+ throw new ToolRefusalError({ status: "refused", blocker: "workflow-find-user-by-role-parameters-invalid", activityCode: String(activity.activityCode ?? ""), nextCommand: "使用 FindUserByRole({Originator.OU},\"<真实角色code>\",\"random\");组织范围不得手填 id", message: `节点 ${String(activity.activityCode ?? "")} 的 FindUserByRole 参数不合法:x 必须是单一 {Originator.OU},不得手填 id;y 必须是带引号的单一角色 code。` });
885
+ const order = strict[2].slice(1, -1);
886
+ if (!new Set(["dept", "sortKey", "random"]).has(order))
887
+ throw new ToolRefusalError({ status: "refused", blocker: "workflow-find-user-by-role-order-invalid", activityCode: String(activity.activityCode ?? ""), order, candidates: ["dept", "sortKey", "random"], nextCommand: "将第三参数改为 dept、sortKey 或 random", message: `FindUserByRole 第三参数 ${order} 不在允许枚举 dept/sortKey/random。` });
888
+ }
889
+ const match = /^FindUserByRole\s*\(\s*\{Originator\.OU\}\s*,\s*("(?:\\.|[^"\\])*"|'(?:\\.|[^'\\])*')\s*,\s*("(?:\\.|[^"\\])*"|'(?:\\.|[^'\\])*')\s*\)\s*$/.exec(participant);
882
890
  if (!match)
883
891
  continue;
884
892
  const quoted = match[1];
@@ -902,9 +910,7 @@ async function assertRoleParticipantScopes(session, body) {
902
910
  roleListAvailable = true;
903
911
  }
904
912
  catch {
905
- // Role existence is advisory when the organization read face is unavailable.
906
- // Do not turn a transient read failure into a blanket workflow write outage.
907
- roleListAvailable = false;
913
+ throw new ToolRefusalError({ status: "refused", blocker: "workflow-participant-role-read-failed", nextCommand: "omc call org.role.list --args '{}'", message: "无法读取真实角色树,不能确认 FindUserByRole 的 role code;为避免流程静默回退发起人,已 fail-closed 拒绝写入。请恢复组织读面后重试。" });
908
914
  }
909
915
  if (roleListAvailable) {
910
916
  const byCode = new Map(listedRoles
@@ -385,6 +385,7 @@ const ruleCrossModelCreate = Object.freeze({
385
385
  "**`originatorValueType:\"DYNAMIC\"` 的 `originatorValue` 必须指向人员字段**(STAFF_SELECTOR 等);指向文本/编号字段会致发起人错误或为空。",
386
386
  "「当前时间」不是规则的 value 类型:`ruleValueType:\"SYSTEM\"` 不会填 now(真机 2026-10-08 落 null)。要让下游日期=生成时刻,把该**日期字段的默认值**设为「当前时间」(平台 `{value:\"current\"}`),或走二开;纯规则映射填不出 now。",
387
387
  "上游是 QUERY 时 `inputParam=\"_<QUERY节点code>_output\"`(QUERY 查 N 行→CREATE 逐条生成即 N→N 扇出,真机验证支持,同/跨模型均可);否则 `\"_input\"`。",
388
+ "跨模型 UPDATE 三段:`inputParam`/`currentSchemaDataItem`=输入源(触发行或 QUERY 输出)→ `filterCondition` 查 `targetSchemaCode` 目标行 → `dataActions` 写入。QUERY 目标行非隐式输入源;child fan-out 保持 fail-closed。",
388
389
  "`QUERY` 节点只能查**主模型行**:查子表 schema(`parent.child` 或子 schema 名)空条件返回 0 行、带条件 550018(真机 2026-10-08)——逐子表明细扇出才需要二开。",
389
390
  "跨模型 CREATE/UPDATE 真机验证支持(2026-09-28 / 2026-10-08);承载规则的触发时机要对(Create 在提交时触发、Update 只在 data.update 触发、TIMING 定时触发)。",
390
391
  "**CREATE 目标是已发布流程的模型时**(2026-10-27 真机四格矩阵):不传 startWorkflow → 建行**不发起流程**;要发起必须 startWorkflow:true + targetWorkflowCode:<该流程> + originatorValue 用户对象数组 [{\"id\":\"<userId>\",\"name\":\"<名>\"}](传对象 {} → 触发提交 50000 expect '[';无效 id → 50000 发起人不存在);设计器手工编辑可打开该开关,API 与设计器配置会漂移,rule.get 回读核对。",
@@ -107,7 +107,7 @@ const numericTwoDecimals = Object.freeze({
107
107
  priorToolReferences: [{ tool: "discover_environment", args: { environment }, purpose: "确认目标模型已存在" }],
108
108
  dryRun: { supported: true, command: `omc call field.create --env ${environment} --dry-run --args '<recipe.args>'`, notes: "dry-run 校验 propertyType/scale/治理,不创建" },
109
109
  expectedReadback: { readback: { draftFieldPresent: true }, next: ["field.publish"] },
110
- refusalRecovery: [{ code: "capability-out-of-coverage", action: "NUMERICAL 必须带 options.scale;金额两位小数用 scale:2,整数用 scale:0" }, ...commonRecovery],
110
+ refusalRecovery: [{ code: "field-options-shape", action: "NUMERICAL 必须带 options.scale;金额两位小数用 scale:2,整数用 scale:0" }, ...commonRecovery],
111
111
  requiresEnvironmentDerivedIds: false,
112
112
  });
113
113
  const dictionarySelection = Object.freeze({
@@ -6,8 +6,10 @@ import { ToolRefusalError } from "./tool-types.js";
6
6
  import { decodeJsonColumn, JSON_COLUMN_NULL_COALESCE } from "./json-column.js";
7
7
  import { RULE_BIZ_RULE_TYPE_DESCRIPTION, RULE_CREATE_BODY, RULE_ROUTES_DESCRIPTION, ruleNodeGraphDescription, schedulerSettingDescription, } from "./lanes/businessrule-contract.js";
8
8
  import { validateRuleNodeGraph, prepareRuleGraph, PLATFORM_TRIGGER_RULE_CODES, DEFAULT_SYSTEM_NODE_BY_RULE_CODE } from "./lanes/rule-graph.js";
9
+ import { FORMULA_LINT_CODES } from "./formula-lint.js";
9
10
  import { compileMethodConfigPlain } from "./bizservice-config.js";
10
11
  import { RESERVED_CODES } from "./code-rules.js";
12
+ import { SYSTEM_FIELD_CODES } from "./field-families.js";
11
13
  import { FIELD_PROPERTY_TYPES } from "./field-families.js";
12
14
  /** Business-rule node graph. Platform trigger rules are addressed by ruleCode: Create / Update / Delete / Available / Cancel / GetList / Load. */
13
15
  export const ruleNodeGraphArg = z
@@ -341,6 +343,111 @@ function collectBizMethodRefs(nodes) {
341
343
  * error (the platform requires the field to be PUBLISHED, not merely drafted).
342
344
  */
343
345
  const RULE_RESERVED_MAPPING_CODES = RESERVED_CODES;
346
+ const RULE_GRAPH_FIELD_OWNERSHIP_EXEMPT = (code) => code === "_input" || /^_QN_.*_output$/u.test(code) || SYSTEM_FIELD_CODES.has(code) || RESERVED_CODES.has(code.toLowerCase());
347
+ function fieldCodeParts(raw) {
348
+ const parts = raw.split(".").map((part) => part.trim()).filter(Boolean);
349
+ return parts.length > 1 ? { child: parts[0], field: parts[1] } : { field: parts[0] ?? "" };
350
+ }
351
+ function collectRuleGraphFieldRefs(schemaCode, nodes) {
352
+ const refs = [];
353
+ const queryModels = new Map();
354
+ for (const entry of nodes) {
355
+ if (!entry || typeof entry !== "object")
356
+ continue;
357
+ const node = entry;
358
+ if (String(node.nodeType ?? "") === "QUERY" && typeof node.nodeCode === "string" && typeof node.targetSchemaCode === "string")
359
+ queryModels.set(node.nodeCode, node.targetSchemaCode.trim());
360
+ }
361
+ const sourceModel = (node) => {
362
+ const input = typeof node.inputParam === "string" ? /^_(.+)_output$/u.exec(node.inputParam) : undefined;
363
+ return input?.[1] && queryModels.get(input[1]) ? queryModels.get(input[1]) : schemaCode;
364
+ };
365
+ const add = (node, side, raw, model, where) => {
366
+ if (typeof raw !== "string")
367
+ return;
368
+ const value = raw.trim();
369
+ if (!value || RULE_GRAPH_FIELD_OWNERSHIP_EXEMPT(value))
370
+ return;
371
+ const { field, child } = fieldCodeParts(value);
372
+ if (!field || RULE_GRAPH_FIELD_OWNERSHIP_EXEMPT(field))
373
+ return;
374
+ // A dotted child path is addressed by the child schema itself. The gate
375
+ // intentionally checks the child code/field set only; parent fan-out and
376
+ // child-row execution remain the separate rule-graph semantics gate.
377
+ refs.push({ nodeCode: String(node.nodeCode ?? ""), side, code: value, model: child ?? model, where });
378
+ };
379
+ const walkFormula = (node, formula, model, where) => {
380
+ if (typeof formula !== "string")
381
+ return;
382
+ for (const match of formula.matchAll(/\{([^{}]+)\}/gu))
383
+ add(node, "input", match[1], model, `${where}.formula`);
384
+ };
385
+ const walkConditions = (node, value, targetModel, inputModel, where) => {
386
+ if (Array.isArray(value))
387
+ return value.forEach((item, index) => walkConditions(node, item, targetModel, inputModel, `${where}[${index}]`));
388
+ if (!value || typeof value !== "object")
389
+ return;
390
+ const record = value;
391
+ if (record.targetSchemaDataItem !== undefined)
392
+ add(node, "target", record.targetSchemaDataItem, targetModel, `${where}.targetSchemaDataItem`);
393
+ if (record.currentSchemaDataItem !== undefined)
394
+ add(node, "input", record.currentSchemaDataItem, inputModel, `${where}.currentSchemaDataItem`);
395
+ if (String(record.ruleValueType ?? "").toUpperCase() === "EXPRESSION")
396
+ walkFormula(node, record.value, inputModel, `${where}.value`);
397
+ for (const [key, item] of Object.entries(record))
398
+ if (["mainConditions", "sheetConditions", "conditionGroup", "targetConditionGroups", "exitConditionGroups", "dataCondition", "execConditionGroups", "sourceConditionGroups"].includes(key))
399
+ walkConditions(node, item, targetModel, inputModel, `${where}.${key}`);
400
+ };
401
+ for (const entry of nodes) {
402
+ if (!entry || typeof entry !== "object")
403
+ continue;
404
+ const node = entry;
405
+ const type = String(node.nodeType ?? "");
406
+ const targetModel = type === "QUERY" ? String(node.targetSchemaCode ?? "") : String(node.targetObjectCode ?? schemaCode);
407
+ const inputModel = sourceModel(node);
408
+ walkConditions(node, node.filterCondition, targetModel, inputModel, "filterCondition");
409
+ walkConditions(node, node.targetConditionGroups, targetModel, inputModel, "targetConditionGroups");
410
+ walkConditions(node, node.exitConditionGroups, targetModel, inputModel, "exitConditionGroups");
411
+ if (Array.isArray(node.dataActions))
412
+ for (const [index, action] of node.dataActions.entries()) {
413
+ if (!action || typeof action !== "object")
414
+ continue;
415
+ const record = action;
416
+ add(node, "target", record.targetDataItem, targetModel, `dataActions[${index}].targetDataItem`);
417
+ add(node, "input", record.currentDataItemValue ?? record.currentSchemaDataItem, inputModel, `dataActions[${index}].currentDataItemValue`);
418
+ const formula = record.value && typeof record.value === "object" ? record.value.formula : undefined;
419
+ walkFormula(node, formula, inputModel, `dataActions[${index}].value`);
420
+ }
421
+ }
422
+ return refs;
423
+ }
424
+ async function assertRuleGraphFieldOwnership(session, schemaCode, nodes, allowAdvisory = false) {
425
+ const refs = collectRuleGraphFieldRefs(schemaCode, nodes);
426
+ if (refs.length === 0)
427
+ return [];
428
+ const models = [...new Set(refs.map((ref) => ref.model))].filter(Boolean).slice(0, 3);
429
+ const fieldSets = new Map();
430
+ await Promise.all(models.map(async (model) => {
431
+ const fields = wireRows((await wireCall(session, { path: ENDPOINTS.fieldList, query: { schemaCode: model, isPublish: "true" } })).data);
432
+ fieldSets.set(model, new Set(fields.map((field) => String(field.code ?? field.propertyCode ?? "").trim()).filter(Boolean)));
433
+ }));
434
+ // An unseeded model has no published-field evidence on the fake platform;
435
+ // retain legacy round-trip behavior there. Once a field set is observable,
436
+ // every referenced code is checked fail-closed (real environments always
437
+ // expose the published field list, including an empty list for a model).
438
+ const missing = refs.filter((ref) => {
439
+ const fields = fieldSets.get(ref.model);
440
+ return fields !== undefined && fields.size > 0 && !fields.has(fieldCodeParts(ref.code).field);
441
+ });
442
+ if (missing.length === 0)
443
+ return [];
444
+ const first = missing[0];
445
+ const candidates = [...(fieldSets.get(first.model) ?? [])].sort().slice(0, 50);
446
+ const message = `规则节点 ${first.nodeCode} 的${first.side === "target" ? "目标" : "输入源"}字段 ${first.model}.${first.code} 不存在或未发布;请从该模型已发布字段中选择。候选:${candidates.join("、") || "(无)"}`;
447
+ if (allowAdvisory)
448
+ return [{ code: "rule-graph-field-not-in-model", nodeCode: first.nodeCode, key: first.where, severity: "warning", message: `${message}(allowAdvisory:true,仅调查放行)` }];
449
+ 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
+ }
344
451
  async function assertBizActionMappingFieldsExist(session, schemaCode, nodes) {
345
452
  const rows = [];
346
453
  for (const entry of nodes) {
@@ -757,6 +864,16 @@ export async function executeRuleSaveWrite(session, args) {
757
864
  // plain advisory.
758
865
  const lintWarnings = warningFindings.filter((blocker) => blocker.hazard !== true);
759
866
  const lintHazards = warningFindings.filter((blocker) => blocker.hazard === true);
867
+ const formulaWarnings = lintWarnings.filter((finding) => FORMULA_LINT_CODES.has(finding.code));
868
+ if (formulaWarnings.length > 0 && args.allowAdvisory !== true) {
869
+ throw new ToolRefusalError({
870
+ status: "refused",
871
+ blocker: "formula-lint-failed",
872
+ validation: formulaWarnings,
873
+ nextCommand: "将未知函数改为平台注册函数(文本拼接使用 STRING),仅调查时显式传 allowAdvisory:true",
874
+ message: "公式写前校验拒绝:发现未知函数、平台别名或字符串 + 拼接。请修正公式;调查用途可显式 allowAdvisory:true(默认 fail-closed)。",
875
+ });
876
+ }
760
877
  if (blockers.some((blocker) => blocker.severity !== "warning")) {
761
878
  throw new ToolRefusalError({
762
879
  status: "refused",
@@ -780,6 +897,10 @@ export async function executeRuleSaveWrite(session, args) {
780
897
  });
781
898
  await assertCreateSelectionCompatibility(session, args.schemaCode, Array.isArray(nodes) ? nodes : []);
782
899
  await assertBizActionMappingFieldsExist(session, args.schemaCode, Array.isArray(nodes) ? nodes : []);
900
+ // r47a: ordinary UPDATE/CREATE/EXPRESSION references use two distinct
901
+ // ownership sides. Read each involved published field set once (at most the
902
+ // rule model plus two target/query models) and refuse before rule.save.
903
+ blockers.push(...(await assertRuleGraphFieldOwnership(session, args.schemaCode, Array.isArray(nodes) ? nodes : [], args.allowAdvisory === true)));
783
904
  // Ticket 96: phantom-schema gate — BEFORE the first businessrule wire call
784
905
  // (the rule list itself auto-creates preset rows for unknown schemas).
785
906
  await assertRuleSchemaExists(session, args.schemaCode);
package/dist/skills.js CHANGED
@@ -276,6 +276,8 @@ export function readSkillSection(name, requested) {
276
276
  const matches = (heading) => {
277
277
  if (heading === normalized)
278
278
  return true;
279
+ if (heading.replace(/\s+`[^`]+`\s*$/, "").trim() === normalized)
280
+ return true;
279
281
  if (heading.replace(/[^\p{L}\p{N}]+/gu, "-").toLowerCase() === normalized)
280
282
  return true;
281
283
  if (requestedOrdinal !== undefined) {
package/dist/track.js ADDED
@@ -0,0 +1,70 @@
1
+ import { ConfigStore, defaultPaths } from "./config-store.js";
2
+ import { SessionManager } from "./session-manager.js";
3
+ import { makeToolContext } from "./context.js";
4
+ import { ENDPOINTS } from "./endpoints.js";
5
+ import { wireCall } from "./wire.js";
6
+ import { emitInvalid, emitResult } from "./command-transport.js";
7
+ const trackPath = (schemaCode) => ENDPOINTS.dataTrackSearch.replace("{schemaCode}", encodeURIComponent(schemaCode));
8
+ function asRows(data) {
9
+ if (!data || typeof data !== "object")
10
+ return [];
11
+ const record = data;
12
+ return Array.isArray(record.content) ? record.content.filter((row) => Boolean(row && typeof row === "object")) : [];
13
+ }
14
+ function project(row) {
15
+ const source = row.sourceOperateType ?? row.operateType ?? row.sourceUserType;
16
+ return {
17
+ id: row.id ?? null,
18
+ time: row.createdTime ?? row.operateTime ?? row.updateTime ?? null,
19
+ operateType: row.operateType ?? null,
20
+ sourceOperateType: row.sourceOperateType ?? null,
21
+ sourceUserType: row.sourceUserType ?? null,
22
+ source: source ?? null,
23
+ operator: row.userName ?? row.operatorName ?? row.userId ?? row.creator ?? null,
24
+ propertyCodes: Array.isArray(row.propertyCodes)
25
+ ? row.propertyCodes
26
+ : Array.isArray(row.propertyCodeList)
27
+ ? row.propertyCodeList
28
+ : Object.keys((row.beforeRowData ?? row.afterRowData ?? {})),
29
+ ...(row.beforeRowData !== undefined ? { beforeRowData: row.beforeRowData } : {}),
30
+ ...(row.afterRowData !== undefined ? { afterRowData: row.afterRowData } : {}),
31
+ };
32
+ }
33
+ export async function searchTrack(session, schemaCode, bizObjectId, propertyCode) {
34
+ const body = {
35
+ // DataTrackSearchAssembler uses PageRequest.of(page - 1, size).
36
+ page: 1,
37
+ size: 100,
38
+ bizObjectIds: [bizObjectId],
39
+ ...(propertyCode ? { propertyCodes: [propertyCode] } : {}),
40
+ };
41
+ const data = (await wireCall(session, { path: trackPath(schemaCode), method: "POST", body })).data;
42
+ const rows = asRows(data);
43
+ const raw = data && typeof data === "object" ? data : {};
44
+ return {
45
+ schemaCode,
46
+ bizObjectId,
47
+ page: 1,
48
+ size: 100,
49
+ total: raw.totalElements ?? rows.length,
50
+ entries: rows.map(project),
51
+ notes: [
52
+ "sourceOperateType/source 为平台留痕来源;BUSINESS_RULE 表示业务规则来源(若平台返回该枚举)",
53
+ "平台回执未提供 before/after 时不补造旧值;本命令只报告平台实际返回的字段",
54
+ ...(rows.length === 100 ? ["本次最多取 100 条;需要更早历史时当前命令尚未提供分页参数"] : []),
55
+ ],
56
+ };
57
+ }
58
+ export async function cmdTrack(schemaCode, bizObjectId, options, transport) {
59
+ if (!schemaCode || !bizObjectId)
60
+ return emitInvalid(transport, { message: "track 需要 schemaCode 和 bizObjectId" });
61
+ try {
62
+ const context = makeToolContext({ sessions: new SessionManager(new ConfigStore(defaultPaths())) });
63
+ const session = await context.sessions.session(options.env);
64
+ return emitResult(await searchTrack(session, schemaCode, bizObjectId, options.propertyCode), transport);
65
+ }
66
+ catch (error) {
67
+ return emitResult({ status: "error", blocker: "track-search-failed", message: error instanceof Error ? error.message : String(error) }, transport);
68
+ }
69
+ }
70
+ //# sourceMappingURL=track.js.map
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@stalfh233/omc-cli",
3
- "version": "0.6.25",
3
+ "version": "0.6.27",
4
4
  "description": "CloudPivot 8.6 configuration capability CLI — governed, fail-closed, coverage-manifest bounded.",
5
5
  "type": "module",
6
6
  "bin": {
@@ -55,7 +55,7 @@
55
55
  },
56
56
  "dependencies": {
57
57
  "commander": "14.0.3",
58
- "omc-core": "0.6.25",
58
+ "omc-core": "0.6.27",
59
59
  "proper-lockfile": "4.1.2",
60
60
  "write-file-atomic": "6.0.0",
61
61
  "zod": "^3.23.8",
@@ -73,6 +73,6 @@
73
73
  "directory": "packages/omc-cli"
74
74
  },
75
75
  "optionalDependencies": {
76
- "@stalfh233/omc-fake-platform": "0.6.25"
76
+ "@stalfh233/omc-fake-platform": "0.6.27"
77
77
  }
78
78
  }
@@ -13,6 +13,7 @@ description: 一页纸业务场景步骤清单(采购申请 / 请假审批 /
13
13
 
14
14
  1. `omc next "从零做采购申请:主子表、合计、条件审批、列表、按钮"` → `omc intent schema`
15
15
  2. `omc model-scaffold --app <app> --code <code> --name 采购申请 --fields '<JSON数组>' --apply`(字段含 `amount` NUMERICAL scale=2、`<主表code>_details` CHILD_TABLE 及 item/qty/price/lineAmount 子列;子表 code 必须全局唯一)
16
+ 3. (`model-scaffold` 已在第 2 步完成字段发布与表单发布;无需另起命令)
16
17
  4. `omc compute --schema <code> --target amount --formula 'SUM({<主表code>_details.lineAmount})' --apply`(⚠️ 只在门户算,REST 不回填)
17
18
  5. 条件审批(金额>50000 两级):**不要** `approval-flow --condition`(无此参数)。线性先:`omc approval-flow --schema <code> --steps '经理@role:<mgr>' --steps '总监@role:<dir>' --apply`;条件分流改 `omc describe workflow.update --example workflow-conditional-branch` 后 `workflow.update`。
18
19
  6. 发起权限:`omc call workflow.addPermission --args '{"workflowCode":"<code>_wf","unitId":"<deptOrRoleId>","unitType":1}'`(这是**谁能发起**,不是行级可见范围)