@stalfh233/omc-cli 0.6.88 → 0.6.89

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.
package/dist/endpoints.js CHANGED
@@ -172,6 +172,20 @@ export const ENDPOINTS = {
172
172
  dataRuleDelete: "/api/api/app/bizdatarule/delete",
173
173
  runtimeFormSave: "/api/api/runtime/form/save",
174
174
  runtimeFormLoad: "/api/api/runtime/form/load",
175
+ /**
176
+ * 子表专用查询面(filter + 列投影 + 分页 + 服务端总数)。
177
+ * FormRuntimeController.list_child
178
+ * (cloudpivot-engine-8.6.26/.../runtime/FormRuntimeController.java:1901-1928)
179
+ * 校验 schemaCode/childSchemaCode/bizObjectId 后走
180
+ * BizObjectFacadeImpl.queryChildBizObjects
181
+ * (cloudpivot-bizdata-8.6.26/.../bizobject/BizObjectFacadeImpl.java:7594-7639),
182
+ * 强制 AND parentId=bizObjectId,回 PageVO<Map<String,Object>>
183
+ * (content 是扁平行 map,不是 query/list 的 {bizObjectId,data} 包装)。
184
+ * 坑:QueryDataVO.getSize() 在 size 为空/0 时返回 Integer.MAX_VALUE
185
+ * (cloudpivot-engine-8.6.26/.../view/runtime/QueryDataVO.java:186-191)——
186
+ * 调用方**必须显式传 size**,否则退化成全量。
187
+ */
188
+ runtimeFormListChild: "/api/api/runtime/form/list_child",
175
189
  runtimeFormReplayToken: "/api/api/runtime/form/getReplayToken",
176
190
  runtimeQueryList: "/api/api/runtime/query/list",
177
191
  /** 平台服务端聚合(QueryRuntimeController.sum,POST /runtime/query/sum;数值/公式列,ALL_DATA)。 */
@@ -1,5 +1,6 @@
1
1
  import { ENDPOINTS } from "../../endpoints.js";
2
2
  import { assertBizServiceAdapterWhitelisted, compileMethodConfigPlain, compileParameterFace, compileServiceConfig, normalizeMethodConfigReadback, normalizeParameterFaceReadback } from "../../bizservice-config.js";
3
+ import { countMethodMapping, methodReferencedCoreMessage, methodReferenceIdentity, scanMethodReferenceSites } from "../../method-references.js";
3
4
  import { wireCall, wireRows, WireError } from "../../wire.js";
4
5
  import { refuse } from "../capability.js";
5
6
  import { sameValue } from "../compare.js";
@@ -163,92 +164,19 @@ function serviceFromRow(service, adapterCode, rowsByCode, declared) {
163
164
  } : {}),
164
165
  };
165
166
  }
166
- /** Platform reference count (F12): GET /app/bizmethod/count_mapping → Integer. */
167
+ /** Platform reference count (F12) — shared with `method.delete` (src/method-references.ts). */
167
168
  async function countMapping(session, serviceCode, methodCode) {
168
- const response = await wireCall(session, {
169
- path: ENDPOINTS.bizMethodCountMapping,
170
- query: { serviceCode, ...(methodCode !== undefined ? { serviceMethodCode: methodCode } : {}) },
171
- });
172
- const value = response.data;
173
- if (typeof value === "number" && Number.isFinite(value))
174
- return value;
175
- const parsed = Number(value);
176
- return Number.isFinite(parsed) ? parsed : 0;
177
- }
178
- /** Cap the identity scan: only DECLARED-ABSENT methods that the platform already counts get here. */
179
- const REFERENCE_SCAN_MODELS = 25;
180
- const REFERENCE_SCAN_RULES = 50;
181
- const REFERENCE_SITES_RETURNED = 8;
182
- function mappedNodeCodes(nodeColumn, serviceCode, methodCode) {
183
- const decoded = decodeColumn(nodeColumn);
184
- if (!Array.isArray(decoded))
185
- return [];
186
- const nodeCodes = [];
187
- for (const entry of decoded) {
188
- if (!entry || typeof entry !== "object" || Array.isArray(entry))
189
- continue;
190
- const node = entry;
191
- const mapping = node.methodMapping;
192
- if (!mapping || typeof mapping !== "object" || Array.isArray(mapping))
193
- continue;
194
- const mapped = mapping;
195
- if (String(mapped.serviceCode ?? "") !== serviceCode || String(mapped.serviceMethodCode ?? "") !== methodCode)
196
- continue;
197
- const nodeCode = String(node.nodeCode ?? "");
198
- if (nodeCode !== "")
199
- nodeCodes.push(nodeCode);
200
- }
201
- return nodeCodes;
169
+ return countMethodMapping(session, serviceCode, methodCode);
202
170
  }
203
171
  /**
204
172
  * Readable identity of a reference (ruleCode/nodeCode) for the method-delete
205
173
  * warning. `count_mapping` is the authoritative count; this is only the label —
206
174
  * every read is best-effort and a failure degrades to a pointer at
207
- * `rule.references kind=service`, never to a wrong claim.
175
+ * `rule.references kind=service`, never to a wrong claim. The scan itself lives
176
+ * in the shared module so `method.delete` and intent never drift apart.
208
177
  */
209
178
  async function referenceSitesOf(session, serviceCode, methodCode) {
210
- let schemaCodes = [];
211
- try {
212
- const rows = wireRows((await wireCall(session, {
213
- path: ENDPOINTS.bizServiceMethodViewReference,
214
- query: { serviceCode, serviceMethodCode: methodCode },
215
- })).data);
216
- schemaCodes = [...new Set(rows.map((row) => String(row.schemaCode ?? "")).filter((code) => code !== ""))].slice(0, REFERENCE_SCAN_MODELS);
217
- }
218
- catch {
219
- return [];
220
- }
221
- const sites = [];
222
- for (const schemaCode of schemaCodes) {
223
- let rules = [];
224
- try {
225
- rules = wireRows((await wireCall(session, { path: ENDPOINTS.businessRuleListBySchemaCode, query: { schemaCode } })).data);
226
- }
227
- catch {
228
- continue;
229
- }
230
- for (const rule of rules.slice(0, REFERENCE_SCAN_RULES)) {
231
- const ruleCode = String(rule.code ?? "");
232
- const id = rule.id;
233
- if (ruleCode === "" || typeof id !== "string" || id === "")
234
- continue;
235
- let record = null;
236
- try {
237
- record = (await wireCall(session, { path: ENDPOINTS.businessRuleGet, query: { id } })).data;
238
- }
239
- catch {
240
- continue;
241
- }
242
- if (!record)
243
- continue;
244
- for (const nodeCode of mappedNodeCodes(record.node, serviceCode, methodCode)) {
245
- sites.push({ schemaCode, ruleCode, nodeCode });
246
- if (sites.length >= REFERENCE_SITES_RETURNED)
247
- return sites;
248
- }
249
- }
250
- }
251
- return sites;
179
+ return (await scanMethodReferenceSites(session, serviceCode, methodCode)).sites;
252
180
  }
253
181
  function validateServiceNode(serviceNode, index, draft, validation) {
254
182
  const base = `services[${index}]`;
@@ -638,10 +566,7 @@ function liveMethodOf(service, declared, methodCode) {
638
566
  function methodReferencedWarning(serviceCode, methodCode, liveMethod) {
639
567
  const count = liveMethod.referenceCount ?? 0;
640
568
  const sites = liveMethod.referenceSites ?? [];
641
- const identity = sites.length > 0
642
- ? `;引用点:${sites.slice(0, 3).map((site) => `${site.schemaCode}/${site.ruleCode}#${site.nodeCode}`).join("、")}${sites.length > 3 ? ` 等 ${sites.length} 处` : ""}`
643
- : `;定位:omc call rule.references --args '{"kind":"service","code":"${serviceCode}"}'`;
644
- return `业务方法 ${serviceCode}/${methodCode} 仍被 ${count} 条规则映射引用——平台删除会回 500108「业务方法已绑定默认方法,不可删除」(BizServiceMethodController.java:248-281),apply 会在该步原样失败且不删任何东西。先解绑引用规则(rule.save 去掉对应 BIZ_ACTION 节点)并 apply,再删方法${identity}`;
569
+ return methodReferencedCoreMessage(serviceCode, methodCode, count) + methodReferenceIdentity(sites, serviceCode);
645
570
  }
646
571
  /** Attach method-level reference counts (+ readable sites) to declared-absent methods of a present service. */
647
572
  async function withMethodReferences(session, entry, declared, absentCodes) {
@@ -7,6 +7,7 @@ import { capabilityArg, environmentArg } from "../args.js";
7
7
  import { governedRead } from "../read.js";
8
8
  import { writeTool } from "../write.js";
9
9
  import { decodeJsonColumn as decodeSharedJsonColumn, JSON_COLUMN_NULL_COALESCE } from "../json-column.js";
10
+ import { countMethodMapping, methodReferencedCoreMessage, methodReferenceIdentity, scanMethodReferenceSites } from "../method-references.js";
10
11
  import { defineTool, ToolRefusalError } from "../tool-types.js";
11
12
  import { wireCall, wireRows, wireDownloadBuffer, wireUploadFile, WireError } from "../wire.js";
12
13
  import { parameterFaceCovers, serviceStatusSegment } from "../service-support.js";
@@ -803,10 +804,39 @@ export function registerB2Lane(tools) {
803
804
  serviceStatus: serviceStatusSegment({ operation: "method.delete", serviceCode: args.serviceCode, methodCode: args.methodCode, servicePresent, methodPresent: false }),
804
805
  };
805
806
  // A referenced method answers 500108 业务方法已绑定默认方法,不可删除
806
- // (BizServiceMethodController.java:246-272) — governedWrite surfaces the
807
- // platform refusal verbatim with errcode + message; the rule and its
808
- // binding stay untouched.
809
- const performed = await wireCall(session, { path: ENDPOINTS.bizServiceMethodDelete, method: "POST", query: { id } });
807
+ // (BizServiceMethodController.java:248-281). The writeLint pre-check makes
808
+ // that refusal local (zero writes, references + two confirmed options);
809
+ // this catch is the RACE fallback: something got bound between the lint
810
+ // and the delete, or h_biz_method_mapping kept a residue. Only the count
811
+ // is re-read here — never the rule scan.
812
+ let performed;
813
+ try {
814
+ performed = await wireCall(session, { path: ENDPOINTS.bizServiceMethodDelete, method: "POST", query: { id } });
815
+ }
816
+ catch (error) {
817
+ if (!(error instanceof WireError) || error.errcode !== 500108)
818
+ throw error;
819
+ let count;
820
+ try {
821
+ count = await countMethodMapping(session, args.serviceCode, args.methodCode);
822
+ }
823
+ catch {
824
+ count = undefined;
825
+ }
826
+ throw new ToolRefusalError({
827
+ status: "refused",
828
+ blocker: "method-referenced",
829
+ errcode: 500108,
830
+ serviceCode: args.serviceCode,
831
+ methodCode: args.methodCode,
832
+ ...(count !== undefined
833
+ ? { referenceCount: count }
834
+ : { referenceCountNote: "count_mapping 在 500108 之后重读失败:方法级引用计数未知(平台 500108 仍是权威删除门)" }),
835
+ message: `${methodReferencedCoreMessage(args.serviceCode, args.methodCode, count ?? 0)}(预检计数为 0,但平台仍返回 500108:竞态或 h_biz_method_mapping 残留)`,
836
+ doNot: "不要自行解绑规则、不要改调度生效时间后再删方法;解绑属于高危写入,必须用户确认",
837
+ nextCommand: `omc call rule.references --args '{"kind":"service","code":"${args.serviceCode}"}'`,
838
+ });
839
+ }
810
840
  const afterRows = wireRows((await wireCall(session, { path: ENDPOINTS.bizServiceMethodList, query: { serviceCode: args.serviceCode, filterFlag: "false" } })).data);
811
841
  const after = afterRows.find((row) => row.code === args.methodCode);
812
842
  return {
@@ -815,6 +845,69 @@ export function registerB2Lane(tools) {
815
845
  serviceStatus: serviceStatusSegment({ operation: "method.delete", serviceCode: args.serviceCode, methodCode: args.methodCode, servicePresent, methodPresent: after != null }),
816
846
  };
817
847
  },
848
+ // Ticket 01 (2026-11-20): the 500108 refusal must be LOCAL and actionable.
849
+ // F5 showed the bare platform error pushing an agent to unbind production
850
+ // rules by itself (rule.save minus the BIZ_ACTION node → change the
851
+ // scheduler time → delete again). This lint runs on BOTH the dry-run and
852
+ // the real path (write.ts shares it), reads the platform's authoritative
853
+ // count, and refuses with references + coverage + two non-automatic
854
+ // options. A missing method stays idempotent (execute's ok-absent branch),
855
+ // and a failed count read degrades to the platform 500108 gate.
856
+ writeLint: async (session, args) => {
857
+ const rows = wireRows((await wireCall(session, { path: ENDPOINTS.bizServiceMethodList, query: { serviceCode: args.serviceCode, filterFlag: "false" } })).data);
858
+ if (!rows.some((row) => row.code === args.methodCode))
859
+ return;
860
+ let count;
861
+ try {
862
+ count = await countMethodMapping(session, args.serviceCode, args.methodCode);
863
+ }
864
+ catch {
865
+ return;
866
+ }
867
+ if (count <= 0)
868
+ return;
869
+ const { sites, coverage } = await scanMethodReferenceSites(session, args.serviceCode, args.methodCode);
870
+ const readFirst = sites.length > 0
871
+ ? sites.map((site) => `omc call rule.get --args '{"schemaCode":"${site.schemaCode}","ruleCode":"${site.ruleCode}"}'`)
872
+ : [`omc call rule.references --args '{"kind":"service","code":"${args.serviceCode}"}'`];
873
+ throw new ToolRefusalError({
874
+ status: "refused",
875
+ blocker: "method-referenced",
876
+ serviceCode: args.serviceCode,
877
+ methodCode: args.methodCode,
878
+ referenceCount: count,
879
+ references: sites,
880
+ coverage,
881
+ ...(sites.length === 0
882
+ ? { scanNote: `本次扫描未命中引用点(count_mapping 计数 ${count} > 0)——零命中不代表无引用;可能来自未扫到的应用或非规则引用` }
883
+ : {}),
884
+ platformErrcode: 500108,
885
+ message: methodReferencedCoreMessage(args.serviceCode, args.methodCode, count) + methodReferenceIdentity(sites, args.serviceCode),
886
+ doNot: "不要自行解绑规则、不要改调度生效时间后再删方法;解绑属于高危写入,必须用户确认",
887
+ options: [
888
+ {
889
+ id: "read-only",
890
+ destructive: false,
891
+ summary: "保留方法,先不动规则;本次未删除、未改任何配置",
892
+ },
893
+ {
894
+ id: "unlink",
895
+ destructive: true,
896
+ requiresConfirmation: true,
897
+ summary: "先解绑引用规则里的 BIZ_ACTION 节点,再删方法(需用户明确确认)",
898
+ readFirst,
899
+ steps: [
900
+ "用 rule.get 读回完整 nodeGraph(保留其余节点、routes、schedulerSetting 等全部字段)",
901
+ `只在图里去掉 methodMapping 指向 ${args.serviceCode}/${args.methodCode} 的 BIZ_ACTION 节点`,
902
+ "omc call rule.save --args '<去掉该节点后的完整图>'(平台会铸新规则 id;未声明的节点逐字节保留)",
903
+ "重新调用 method.delete",
904
+ ],
905
+ note: "本工具不会自动解绑;解绑是独立的高危写入,必须由用户确认后另行执行",
906
+ },
907
+ ],
908
+ nextCommand: `omc call rule.references --args '{"kind":"service","code":"${args.serviceCode}"}'`,
909
+ });
910
+ },
818
911
  rollback: b2ServiceRollbackSpec("method.delete"),
819
912
  });
820
913
  tools.push(defineTool({
@@ -168,7 +168,7 @@ export const BUSINESSRULE_LANE_CONTRACT = Object.freeze({
168
168
  // 295,400B,HEAD 4c524b83 实测 295,331 仅余 69B——加对照句即红门)。对照
169
169
  // 教学住 read-shapes 的 notes[0](默认 describe 面即回,不进 tools/list);
170
170
  // MCP 面的同款对照由 omc_graph_explore 的 description 承担。
171
- description: "跨规则引用检索:一次调用替代 agent 逐 schema×ruleCode 全平台枚举 rule.get(删服务/模型/字段/规则前的影响面)。kind=service 查 BIZ_ACTION 的 methodMapping.serviceCode;kind=model 查 CREATE/UPDATE/DELETE 的 targetObjectCode 与 methodMapping.schemaCode(删模型前的影响面);kind=field 查 dataActions.targetDataItem、inputMappings/outputMappings 的 bizCode、规则条件叶子(filterCondition/BRANCH 出口等,只认主模型字段)与 datarule(propertyCodes + options 文本;字段 code 跨模型不唯一,建议配 schemaCodes 限范围);kind=rule 查流程事件绑定(flow 级 handler 与节点级 nodeEvent 的 bizActions,按模型枚举流程面)。实现为客户端聚合(应用树模型清单→逐模型 rule.list/rule.get 或 get_published),输出只回命中行;各 kind 的覆盖面与协议局限见回执 coverage。",
171
+ description: "跨规则引用检索:一次调用替代 agent 逐 schema×ruleCode 全平台枚举 rule.get(删服务/模型/字段/规则前的影响面)。kind=service 查 BIZ_ACTION 的 methodMapping.serviceCode;kind=model 查 CREATE/UPDATE/DELETE 的 targetObjectCode 与 methodMapping.schemaCode(删模型前的影响面);kind=field 查 dataActions.targetDataItem、inputMappings/outputMappings 的 bizCode、规则条件叶子(filterCondition/BRANCH 出口等,只认主模型字段)与 datarule(propertyCodes + options 文本;字段 code 跨模型不唯一,建议配 schemaCodes 限范围);kind=rule 查流程事件绑定(flow 级 handler 与节点级 nodeEvent 的 bizActions,按模型枚举流程面)。kind:\"trigger\" 按 schemaCode 列全触发点(流程三面/表单按钮/规则/预置事件/在线 JS)。实现为客户端聚合(应用树模型清单→逐模型 rule.list/rule.get 或 get_published),输出只回命中行;各 kind 的覆盖面与协议局限见回执 coverage。",
172
172
  }),
173
173
  "rule.save": Object.freeze({
174
174
  scope: "dead-state CRUD conditional node graphs",
@@ -10,7 +10,9 @@ import { defineTool, isRequiredAlternativePlaceholder, ToolInputError, ToolRefus
10
10
  import { resolveRuleRowId } from "../identity.js";
11
11
  import { extractDataRuleEdges, extractReferenceEdges } from "../graph.js";
12
12
  import { DEFAULT_SCAN_CONCURRENCY, mapWithConcurrency } from "../concurrency.js";
13
+ import { readFormButtons, readFormOrNull } from "../form-support.js";
13
14
  import { scanModelWorkflowBindings } from "./workflow.js";
15
+ import { readCustomScriptSource } from "./online-js.js";
14
16
  import { wireCall, wireCallWith404Fallback, wireRows } from "../wire.js";
15
17
  import { readModelRecord } from "../model-record.js";
16
18
  import { BUSINESSRULE_LANE_CONTRACT } from "./businessrule-contract.js";
@@ -753,6 +755,208 @@ async function readRuleListBody(session, schemaCode, options) {
753
755
  })),
754
756
  };
755
757
  }
758
+ /**
759
+ * T02(2026-11-20,retro 25):触发器视图——`kind:"trigger"` 把「一个模型有哪些
760
+ * 触发点」从 4–5 个读面拼成一张清单:workflow.get_published 的三面绑定、表单
761
+ * 按钮(form.get 紧凑面同一读法)、规则清单(预置 vs 自建)、表单在线 JS 直连
762
+ * 调用。零新工具、零新写面;只做一层清单(不做触发链路传递闭包)。
763
+ *
764
+ * wire 受控:应用树 1(出处 + 存在性)+ 流程面(isworkflow→getWorkflow→
765
+ * get_published,复用 scanModelWorkflowBindings)+ 规则清单 1(**不逐条
766
+ * rule.get**,因此本 kind 不回 bizRuleType/schedulerSetting)+ 表单 1
767
+ * (按钮与在线 JS 共用一次 bizsheet/get)。activityCode 过滤只读流程面,其余
768
+ * 面逐条记 notScanned。
769
+ */
770
+ const TRIGGER_PRESET_CODES = ["Create", "Update", "Delete"];
771
+ /**
772
+ * 在线 JS 触发点的**文本**匹配:每行至多一条(优先级 axios → fetch( → /api/)。
773
+ * 可能漏动态拼 URL、可能命中注释——这是协议局限,回执标 scanMode:"text"。
774
+ */
775
+ const ONLINEJS_TRIGGER_PATTERNS = [
776
+ { kind: "axios", test: /axios/ },
777
+ { kind: "fetch", test: /fetch\(/ },
778
+ { kind: "/api/", test: /\/api\// },
779
+ ];
780
+ function onlineJsTriggerHits(script) {
781
+ const hits = [];
782
+ script.split("\n").forEach((raw, index) => {
783
+ const line = raw.trim();
784
+ if (line === "")
785
+ return;
786
+ const matched = ONLINEJS_TRIGGER_PATTERNS.find((pattern) => pattern.test.test(line));
787
+ if (matched === undefined)
788
+ return;
789
+ // excerpt ≤120 字(含截断省略号本身)。
790
+ hits.push({ line: index + 1, excerpt: line.length > 120 ? `${line.slice(0, 119)}…` : line, kind: matched.kind });
791
+ });
792
+ return hits;
793
+ }
794
+ /**
795
+ * `action:"create"|"update"|"delete"` 的「绑定到该事件的自定义规则」反推:
796
+ * workflow 行的 activityCode/nodeEvent/handler、按钮的 buttonCode/targetCode
797
+ * 含该动作词即视为相关绑定(例:nodeEvent `onCreate`、activityCode
798
+ * `ACTIVITY_CREATE`、按钮 targetCode `Create`)。启发式——回执 note 写明判据,
799
+ * 拿不准时用省略 action 的全量清单。
800
+ */
801
+ function ruleCodesBoundToEvent(workflowRows, buttonRows, action) {
802
+ const codes = new Set();
803
+ const mentions = (...parts) => parts.filter((part) => typeof part === "string" && part !== "").join(" ").toLowerCase().includes(action);
804
+ for (const row of workflowRows) {
805
+ if (!mentions(row.activityCode, row.nodeEvent, row.handler))
806
+ continue;
807
+ for (const code of row.ruleCodes)
808
+ codes.add(code);
809
+ }
810
+ for (const row of buttonRows)
811
+ if (mentions(row.buttonCode, row.targetCode) && typeof row.targetCode === "string" && row.targetCode !== "")
812
+ codes.add(row.targetCode);
813
+ return codes;
814
+ }
815
+ async function scanSchemaTriggers(session, args) {
816
+ const schemaCode = args.code;
817
+ const sheetCode = args.sheetCode ?? schemaCode;
818
+ const mode = args.mode ?? "summary";
819
+ const action = args.action;
820
+ const activityCodeFilter = args.activityCode;
821
+ const notScanned = [];
822
+ // 1. 出处 + 模型存在性:沿用 kind=model 的 references-scan-empty 口径(空扫描
823
+ // 不能读成「没有触发」)。kind=trigger 只扫一个模型,不扫全平台。
824
+ const scope = await resolveApplicationScope(session, undefined);
825
+ const appScopeRefusal = (message, models) => new ToolRefusalError({
826
+ status: "refused",
827
+ blocker: "references-scan-empty",
828
+ message,
829
+ applicationResolution: { ...applicationResolutionOf(scope), mode: "trigger", models, schemaCode },
830
+ nextCommand: `omc call rule.references --env <env> --args '{"kind":"trigger","code":"<schemaCode>"}'`,
831
+ });
832
+ const treeModels = flattenTreeRows(wireRows((await wireCall(session, { path: ENDPOINTS.applicationTree, query: { appCode: scope.code } })).data))
833
+ .filter((row) => row.type === "BizModel" && typeof row.code === "string" && row.code !== "")
834
+ .map((row) => String(row.code));
835
+ if (!treeModels.includes(schemaCode))
836
+ throw appScopeRefusal(`模型 ${schemaCode} 不在应用 ${scope.code} 的模型树(${treeModels.length} 个模型)里——本次没有扫描任何东西,空 triggers 不代表「没有触发」;kind:"trigger" 的 code 是 schemaCode(不是规则码),先用 model.list 核对`, 0);
837
+ // 2. 流程三面(flow 级 handler / 节点级 nodeEvent / SYSTEM_ACTIVITY 顶层 bizActions)。
838
+ let workflows = 0;
839
+ let workflowFace = null;
840
+ try {
841
+ workflowFace = await scanModelWorkflowBindings(session, schemaCode);
842
+ if (workflowFace !== null)
843
+ workflows = 1;
844
+ }
845
+ catch (error) {
846
+ notScanned.push(`流程读取失败(${error instanceof Error ? error.message : String(error)}):workflow 三面未扫描`);
847
+ }
848
+ const workflowRows = [];
849
+ if (workflowFace !== null) {
850
+ for (const binding of workflowFace.ruleBindings)
851
+ workflowRows.push({ via: "workflow", workflowCode: workflowFace.workflowCode, published: workflowFace.published, activityCode: null, nodeEvent: null, handler: binding.handler, ruleCodes: binding.ruleCodes });
852
+ for (const binding of workflowFace.nodeRuleBindings)
853
+ workflowRows.push({ via: "workflow", workflowCode: workflowFace.workflowCode, published: workflowFace.published, activityCode: binding.activityCode, nodeEvent: binding.nodeEvent, handler: null, ruleCodes: binding.ruleCodes });
854
+ for (const binding of workflowFace.systemRuleBindings)
855
+ workflowRows.push({ via: "workflow", workflowCode: workflowFace.workflowCode, published: workflowFace.published, activityCode: binding.activityCode, nodeEvent: null, handler: null, ruleCodes: binding.ruleCodes, bizActionType: binding.bizActionType });
856
+ }
857
+ // 3. 表单按钮 + 在线 JS(同一次 bizsheet/get:form.get 紧凑面的同一读法)。
858
+ let scannedButtons = 0;
859
+ let onlinejsBytes = 0;
860
+ let script = null;
861
+ const buttonRows = [];
862
+ if (activityCodeFilter !== undefined) {
863
+ notScanned.push("activityCode 过滤:表单按钮/规则/预置事件/在线 JS 未扫描(只看该流程节点的绑定)");
864
+ }
865
+ else {
866
+ try {
867
+ const sheet = await readFormOrNull(session, schemaCode, sheetCode);
868
+ if (sheet === null) {
869
+ notScanned.push(`表单 ${sheetCode} 不存在:表单按钮与在线 JS 未扫描`);
870
+ }
871
+ else {
872
+ const buttons = readFormButtons(sheet.options) ?? [];
873
+ scannedButtons = buttons.length;
874
+ for (const button of buttons) {
875
+ // 只有 BUSINESS_RULE 绑定是触发点;其它按钮(SCRIPT/流程动作等)只计数。
876
+ if (button.bindAction !== "BUSINESS_RULE")
877
+ continue;
878
+ buttonRows.push({
879
+ via: "button",
880
+ sheetCode,
881
+ buttonCode: typeof button.code === "string" ? button.code : null,
882
+ buttonName: typeof button.name === "string" ? button.name : null,
883
+ bindAction: "BUSINESS_RULE",
884
+ targetCode: typeof button.targetCode === "string" ? button.targetCode : null,
885
+ });
886
+ }
887
+ script = readCustomScriptSource(typeof sheet.publishedHtmlJson === "string" ? sheet.publishedHtmlJson : null).script;
888
+ if (script === null)
889
+ notScanned.push(`在线 JS:表单 ${sheetCode} 的发布面无 customScript 脚本(未扫描)`);
890
+ }
891
+ }
892
+ catch (error) {
893
+ notScanned.push(`表单读取失败(${error instanceof Error ? error.message : String(error)}):表单按钮与在线 JS 未扫描`);
894
+ }
895
+ }
896
+ // 4. 规则清单:一次 list,自建行进 via:rule,预置 Create/Update/Delete 行进
897
+ // via:preset。默认 summary 不做 TIMING 识别(bizRuleType 只在 rule.get
898
+ // 的图里,逐条读会打爆 wire——定时摘要留给 rule.get {keys:["schedulerSetting"]})。
899
+ let scannedRules = 0;
900
+ const ruleRows = [];
901
+ const presetRows = [];
902
+ if (activityCodeFilter === undefined) {
903
+ const body = await readRuleListBody(session, schemaCode, { onlyCustom: false, full: false, withMappings: false });
904
+ if (body.modelPresent === false)
905
+ throw appScopeRefusal(`模型 ${schemaCode} 不存在(模型读面为空)——本次没有扫描任何东西,空 triggers 不代表「没有触发」`, 0);
906
+ const rows = Array.isArray(body.rules) ? body.rules : [];
907
+ scannedRules = rows.length;
908
+ for (const row of rows) {
909
+ const ruleCode = String(row.code ?? "");
910
+ if (row.defaultRule === true) {
911
+ const trigger = TRIGGER_PRESET_CODES.find((candidate) => candidate.toLowerCase() === ruleCode.toLowerCase());
912
+ if (trigger !== undefined)
913
+ presetRows.push({ via: "preset", trigger, ruleCode, enabled: row.enabled === true, note: "REST 写入面不派发数据事件——预置行只对平台内部写入生效" });
914
+ continue;
915
+ }
916
+ ruleRows.push({ via: "rule", ruleCode, name: row.name ?? null, defaultRule: false, enabled: row.enabled === true, status: row.status ?? null });
917
+ }
918
+ }
919
+ // 5. 在线 JS 文本匹配(零 wire;无脚本时第 3 步已记 notScanned)。
920
+ const hits = script === null ? [] : onlineJsTriggerHits(script);
921
+ onlinejsBytes = script === null ? 0 : Buffer.byteLength(script, "utf8");
922
+ const onlineRows = hits.length === 0
923
+ ? []
924
+ : [{ via: "onlinejs", sheetCode, scanMode: "text", hitCount: hits.length, ...(mode === "sites" ? { hits } : {}) }];
925
+ // 6. 并集 + action/activityCode 过滤(分组顺序:workflow → button → rule → preset → onlinejs)。
926
+ let triggers;
927
+ if (activityCodeFilter !== undefined) {
928
+ triggers = workflowRows.filter((row) => row.activityCode === activityCodeFilter);
929
+ }
930
+ else if (action === "flow") {
931
+ triggers = [...workflowRows, ...buttonRows];
932
+ }
933
+ else if (action !== undefined) {
934
+ const bound = ruleCodesBoundToEvent(workflowRows, buttonRows, action);
935
+ triggers = [
936
+ ...ruleRows.filter((row) => bound.has(row.ruleCode) || row.ruleCode.toLowerCase() === action),
937
+ ...presetRows.filter((row) => row.trigger.toLowerCase() === action),
938
+ ...onlineRows,
939
+ ];
940
+ }
941
+ else {
942
+ triggers = [...workflowRows, ...buttonRows, ...ruleRows, ...presetRows, ...onlineRows];
943
+ }
944
+ const filterNote = action !== undefined && action !== "flow"
945
+ ? `;action:"${action}" 的规则绑定判据=workflow 行的 activityCode/nodeEvent/handler 或按钮的 buttonCode/targetCode 含「${action}」,或规则 code 就是 ${action}(不区分大小写,启发式;完整清单去掉 action)`
946
+ : "";
947
+ return {
948
+ schemaCode,
949
+ action: action ?? null,
950
+ mode,
951
+ triggers,
952
+ scanned: { workflows, rules: scannedRules, buttons: scannedButtons, onlinejsBytes },
953
+ notScanned,
954
+ scanMode: "source",
955
+ note: "零命中=本次扫描未命中触发点,不代表没有触发;在线 JS 是文本匹配,可能漏动态拼 URL" + filterNote,
956
+ ...(activityCodeFilter !== undefined ? { activityCode: activityCodeFilter } : {}),
957
+ applicationResolution: { ...applicationResolutionOf(scope), mode: "trigger", models: 1 },
958
+ };
959
+ }
756
960
  export function registerBusinessRuleLane(tools) {
757
961
  tools.push(defineTool({
758
962
  name: "rule.list",
@@ -838,12 +1042,50 @@ export function registerBusinessRuleLane(tools) {
838
1042
  description: RULE_TOOLS["rule.references"].description,
839
1043
  inputSchema: {
840
1044
  environment: environmentArg,
841
- kind: z.enum(["service", "model", "field", "rule"]).describe("按什么找引用:service=BIZ_ACTION methodMapping.serviceCode(service 行带 serviceMethodCode);model=CREATE/UPDATE/DELETE targetObjectCode 与 methodMapping.schemaCode;field=dataActions.targetDataItem、映射 bizCode、规则条件叶子与 datarule;rule=流程事件绑定的规则码(flow 级 handler + 节点级 nodeEvent,扫应用内模型的流程面)"),
1045
+ kind: z.enum(["service", "model", "field", "rule", "trigger"]).describe("按什么找引用:service=BIZ_ACTION methodMapping.serviceCode(service 行带 serviceMethodCode);model=CREATE/UPDATE/DELETE targetObjectCode 与 methodMapping.schemaCode;field=dataActions.targetDataItem、映射 bizCode、规则条件叶子与 datarule;rule=流程事件绑定的规则码(flow 级 handler + 节点级 nodeEvent,扫应用内模型的流程面);trigger=一个模型的全部触发点(code 是 schemaCode,不是规则码)"),
842
1046
  code: z.string().min(1).describe("要查引用的编码(服务/模型/字段 code);kind=field 可用 schemaCode.field 消歧"),
843
1047
  schemaCodes: z.union([z.array(z.string().min(1)), z.string()]).optional().describe("只扫这些模型(省 wire 读);省略=全平台模型"),
1048
+ action: z.enum(["create", "update", "delete", "flow"]).optional().describe("仅 kind=trigger:动作过滤,省略=全量"),
1049
+ activityCode: z.string().min(1).optional().describe("仅 kind=trigger:只看该流程节点的绑定(与 action 互斥)"),
1050
+ sheetCode: z.string().min(1).optional().describe("仅 kind=trigger:多表单模型指定槽位;省略=默认槽位"),
1051
+ mode: z.enum(["summary", "sites"]).optional().describe("仅 kind=trigger:summary=默认,在线 JS 只回计数;sites=回命中行"),
844
1052
  capability: capabilityArg,
845
1053
  },
846
1054
  handler: async (ctx, args, self) => governedRead(ctx, self, args, async (session) => {
1055
+ // T02(2026-11-20,retro 25):触发器视图只扫一个模型(code=schemaCode),
1056
+ // 走独立分支。action/activityCode/sheetCode/mode 只在本 kind 有意义——其它
1057
+ // kind 传了拒绝(静默忽略会让调用方以为过滤生效了)。
1058
+ const triggerOnlyArgs = ["action", "activityCode", "sheetCode", "mode"].filter((key) => args[key] !== undefined);
1059
+ if (args.kind !== "trigger" && triggerOnlyArgs.length > 0)
1060
+ throw new ToolInputError({
1061
+ status: "error",
1062
+ blocker: "tool-input-invalid",
1063
+ tool: "rule.references",
1064
+ message: `${triggerOnlyArgs.join("/")} 只对 kind:"trigger" 有效;kind=${args.kind} 按 code 找引用,不收动作/槽位过滤`,
1065
+ });
1066
+ if (args.kind === "trigger") {
1067
+ if (args.action !== undefined && args.activityCode !== undefined)
1068
+ throw new ToolInputError({
1069
+ status: "error",
1070
+ blocker: "tool-input-invalid",
1071
+ tool: "rule.references",
1072
+ message: "action 与 activityCode 互斥——动作过滤(create/update/delete/flow)与单节点过滤(activityCode)是两种问题,二选一",
1073
+ });
1074
+ if (args.schemaCodes !== undefined)
1075
+ throw new ToolInputError({
1076
+ status: "error",
1077
+ blocker: "tool-input-invalid",
1078
+ tool: "rule.references",
1079
+ message: 'kind:"trigger" 只扫一个模型:code 就是 schemaCode,不接受 schemaCodes(全平台触发面清单不在本 kind)',
1080
+ });
1081
+ return scanSchemaTriggers(session, {
1082
+ code: args.code,
1083
+ ...(args.action !== undefined ? { action: args.action } : {}),
1084
+ ...(args.activityCode !== undefined ? { activityCode: args.activityCode } : {}),
1085
+ ...(args.sheetCode !== undefined ? { sheetCode: args.sheetCode } : {}),
1086
+ ...(args.mode !== undefined ? { mode: args.mode } : {}),
1087
+ });
1088
+ }
847
1089
  // r23(2026-10-27):agent 为查「谁引用了服务 X」枚举了 147 个
848
1090
  // schema×ruleCode 组合(171 次 rule.get / 229KB)。没有引用检索面时,
849
1091
  // 全库枚举是理性选择——所以给它一个。客户端聚合:模型清单 → 每模型
@@ -44,7 +44,7 @@ function parseLayoutElements(rawHtml) {
44
44
  * template area — omitting toolbar/template leaves the panel regions empty.
45
45
  */
46
46
  /** Extract the customScript element's innerHTML from a layout-JSON face; null when absent. */
47
- function readCustomScriptSource(rawHtml) {
47
+ export function readCustomScriptSource(rawHtml) {
48
48
  const elements = parseLayoutElements(rawHtml);
49
49
  // Match by id ONLY: beforeCustomScript/afterCustomScript are also
50
50
  // tagName:'script' elements with an empty innerHTML and would shadow the
@@ -8,7 +8,7 @@ export function dataListDescription() {
8
8
  return `按简化过滤 DSL 查询业务对象(runtime/query/list);DSL 在 CLI 内翻译为平台 queryCondition(${wire.dslShape}),并按发布字段元数据为每个条件注入 propertyType(未知过滤字段将被拒绝,可用 rawCondition 逃生);响应行在 items[],业务字段在 items[].fields.<code>(不是 rows[],也不是 item 顶层——--jq 常用 items[].fields.sku);空模型返回空列表;未配列的自定义字段投影为 null——这是显示面缺列配置、不是数据缺失(data.load 有值),显式选列在结果中全为 null 而发布字段元数据显示其存在时,readback 追加 projectionHint(先用 listview.configure 配置该模型的默认视图列,或用 data.load 读单条权威值)。`;
9
9
  }
10
10
  export function dataAggregateDescription() {
11
- return `临时计数与数值聚合(纯读)。count:runtime/query/list size:1 读 totalElements(服务端精确、不受 cap 影响;带 filter +1 field.list)。sum/avg/min/max:field 必填且已发布 propertyType=2(NUMERICAL);无 GET_LIST 改源时优先 /sum ALL_DATA(coverage.mode=server-aggregate,全量精确),否则/失败/键不符回退本地折叠(strategyFallback;size:200 翻页至 cap 1000,null 不进聚合、avg=sum/非 null 行数,nonNullCount=0→value:null)。complete 看 rowsScanned>=total,否则 missingCount+capNotice,绝不外推。groupBy 单列:count 值域可枚举(options/字典)→值域×count(V+3 wire),分桶并发窗口 4(限流退化 2,见 wire.concurrency),桶序稳定;按 count 降序取 topN(默认 10/上限 20),截断给 truncatedBuckets/bucketsTruncatedCount,null 单列 nullBucket;不可枚举或数值指标→本地扫描(coverage.mode=paged-local-scan/local-scan),数值桶 {key,count,nonNullCount,value} 按 value 降序、并列按 key,null 行进 nullBucket。filter.draftPolicy:count+groupBy 默认 includeDrafts:false 注入 sequenceStatus≠DRAFT;数值指标不默认排除;count 省略=平台默认(无条件含草稿、带条件排草稿);显式 false 强制排除。边界:临时问句用本工具;持久图表/看板用 report.chartdata,视图汇总列用 sumType,写时计算用 datarule type2。`;
11
+ return `临时计数与数值聚合(纯读)。count:runtime/query/list size:1 读 totalElements(服务端精确、不受 cap 影响;带 filter +1 field.list)。sum/avg/min/max:field 必填且已发布 propertyType=2(NUMERICAL);无 GET_LIST 改源时优先 /sum ALL_DATA(coverage.mode=server-aggregate,全量精确),否则/失败/键不符回退本地折叠(strategyFallback;size:200 翻页至 cap 1000,null 不进聚合、avg=sum/非 null 行数,nonNullCount=0→value:null)。complete 看 rowsScanned>=total,否则 missingCount+capNotice,绝不外推。groupBy 单列:count 值域可枚举(options/字典)→值域×count(V+3 wire),分桶并发窗口 4(限流退化 2,见 wire.concurrency),桶序稳定;按 count 降序取 topN(默认 10/上限 20),截断给 truncatedBuckets/bucketsTruncatedCount,null 单列 nullBucket;不可枚举或数值指标→本地扫描(coverage.mode=paged-local-scan/local-scan),数值桶 {key,count,nonNullCount,value} 按 value 降序、并列按 key,null 行进 nullBucket。filter.draftPolicy:count+groupBy 默认 includeDrafts:false 注入 sequenceStatus≠DRAFT;数值指标不默认排除;count 省略=平台默认(无条件含草稿、带条件排草稿);显式 false 强制排除。边界:临时问句用本工具;持久图表/看板用 report.chartdata,视图汇总列用 sumType,写时计算用 datarule type2。子表计数/求和用 child(主表 schemaCode + childSchemaCode/bizObjectId)。`;
12
12
  }
13
13
  export function dataUpdateDescription() {
14
14
  const wire = RUNTIME_DATA_WIRE;
@@ -1284,6 +1284,22 @@ function aggregateValue(metric, sum, nonNullCount, min, max) {
1284
1284
  return aggregateTidy(sum / nonNullCount);
1285
1285
  return metric === "min" ? min : max;
1286
1286
  }
1287
+ /**
1288
+ * `list_child` 的回执是 `PageVO<Map<String,Object>>`(FormRuntimeController
1289
+ * .list_child:1921 `new PageVO(data, queryData.getSize())`):总数在
1290
+ * `totalElements`(PageVO.java:40-53),`content` 是**扁平行 map**
1291
+ * (`toObjectMap()`),不是 query/list 的 `{bizObjectId,data}` 包装。
1292
+ */
1293
+ function childPageOf(payload) {
1294
+ const page = payload && typeof payload === "object" && !Array.isArray(payload) ? payload : {};
1295
+ const rawTotal = page.totalElements;
1296
+ const total = typeof rawTotal === "number" && Number.isFinite(rawTotal) ? rawTotal : null;
1297
+ const content = Array.isArray(page.content) ? page.content : [];
1298
+ return {
1299
+ total,
1300
+ rows: content.map((row) => (row && typeof row === "object" ? row : {})),
1301
+ };
1302
+ }
1287
1303
  /**
1288
1304
  * One property leaf as a level-1 AND group, so it can be appended to ANY base
1289
1305
  * condition (leaf / filters / filterGroup) without re-shaping the existing
@@ -1931,6 +1947,12 @@ export function registerRuntimeDataLane(tools) {
1931
1947
  filter: z.union([z.record(z.string(), z.unknown()), z.array(z.record(z.string(), z.unknown()))]).optional().describe('单子句 {op,field,value?}(或子句数组=AND);op 同 data.list(eq/neq/gt/lt/gte/lte/like/in/notin/isnull/isnotnull 等)'),
1932
1948
  filters: z.array(z.record(z.string(), z.unknown())).optional().describe("子句数组=AND"),
1933
1949
  filterGroup: z.record(z.string(), z.unknown()).optional().describe('嵌套组 {op:"and"|"or",clauses:[…]}'),
1950
+ child: z.object({
1951
+ childSchemaCode: z.string().min(1).describe("子表编码(模型里 CHILD_TABLE 字段的 code)"),
1952
+ bizObjectId: z.string().min(1).describe("主表记录 id(data.list 的 row.bizObjectId / data.submit 的 objectId)"),
1953
+ pageSize: z.number().int().min(1).max(500).default(500).optional().describe("数值指标翻页的每页行数(默认 500;list_child 必须显式传 size,空/0 平台会当 Integer.MAX_VALUE)"),
1954
+ maxPages: z.number().int().min(1).max(200).default(40).optional().describe("数值指标翻页上限(默认 40 页;打满仍未取空 → complete:false+truncated)"),
1955
+ }).describe("子表目标:count=服务端 totalElements 精确计数(零行内联);sum/avg/min/max=分页拉目标列后本地折叠").optional(),
1934
1956
  metric: z.enum(["count", "sum", "avg", "min", "max"]).describe("count=服务端 totalElements 精确计数(不读行,不需要 field);sum/avg/min/max=数值列本地折叠(需 field,翻页 cap 1000)。null 行不进聚合,avg 分母=已扫非 null 行数"),
1935
1957
  field: z.string().min(1).optional().describe("metric≠count 时必填:已发布且 propertyType=2(NUMERICAL)的字段 code。未发布→aggregate-field-unresolved(带 publishedFields/didYouMean);非数值→aggregate-field-not-numerical(计数请用 metric:count)"),
1936
1958
  groupBy: z.string().min(1).optional().describe("单列分组:count 值域可枚举走「值域×count」,不可枚举降级本地扫描;数值指标一律本地双列扫描(cap 1000,截断时 complete:false+capNotice)"),
@@ -1941,6 +1963,28 @@ export function registerRuntimeDataLane(tools) {
1941
1963
  handler: async (ctx, args, self) => {
1942
1964
  const metric = args.metric;
1943
1965
  const numeric = metric !== "count";
1966
+ const child = args.child;
1967
+ // 子表面 fail-closed(零 wire):分组与子表是两条独立能力(子表分组另案),
1968
+ // 而 list_child 的 filters 是扁平 List<FilterModel>,平台在没有 queryVersion
1969
+ // 时把它们全部 AND 起来(getFiltersByQueryParam:6584-6590)——filterGroup 的
1970
+ // OR 语义无处表达,宁可拒绝也不静默降级成 AND。
1971
+ if (child !== undefined && args.groupBy !== undefined)
1972
+ throw new ToolInputError({
1973
+ status: "error",
1974
+ blocker: "child-groupby-unsupported",
1975
+ tool: "data.aggregate",
1976
+ message: "child 与 groupBy 互斥:data.aggregate 的子表目标只做 count/sum/avg/min/max,不做分组(子表分组另案)。要去掉 child 做主子表分组,或去掉 groupBy 只算子表整体。",
1977
+ });
1978
+ if (child !== undefined && args.filterGroup !== undefined)
1979
+ throw new ToolInputError({
1980
+ status: "error",
1981
+ blocker: "child-filtergroup-unsupported",
1982
+ tool: "data.aggregate",
1983
+ message: "child 暂不支持 filterGroup:list_child 的 filters 是扁平 List<FilterModel>,平台只在没有 queryVersion 时把它们全部 AND(getFiltersByQueryParam:6584-6590),OR 组没有 wire 形状。只支持 AND:用 filter 或 filters(多子句=AND)。",
1984
+ });
1985
+ // 子表目标的元数据(field.list / 过滤字段 propertyType 注入)取子表 schema;
1986
+ // 回执的 schemaCode 仍是主表。
1987
+ const metaSchemaCode = child?.childSchemaCode ?? args.schemaCode;
1944
1988
  // 参数面 fail-closed(零 wire、零写入):metric 与 field 的组合只有两种合法形状。
1945
1989
  if (metric === "count" && args.field !== undefined)
1946
1990
  throw new ToolInputError({
@@ -1955,12 +1999,14 @@ export function registerRuntimeDataLane(tools) {
1955
1999
  blocker: "invalid-input",
1956
2000
  tool: "data.aggregate",
1957
2001
  message: `metric=${metric} 需要 field(已发布且 propertyType=2/NUMERICAL 的字段 code)——不给 field 无法知道聚合哪一列`,
1958
- nextCommand: `omc call field.list --env <env> --args '{"schemaCode":"${args.schemaCode}","published":true}'`,
2002
+ nextCommand: `omc call field.list --env <env> --args '{"schemaCode":"${metaSchemaCode}","published":true}'`,
1959
2003
  });
1960
2004
  // count+groupBy 要统一 base 与各桶的口径,省略时默认排除草稿;count 省略时保留
1961
2005
  // 平台默认(无条件含草稿),只有显式 false 才注入排除条件。数值指标(本地折叠)
1962
2006
  // 不做默认注入——结果如实反映平台返回行,要排除须显式 false。
1963
- const excludedByRequest = args.includeDrafts === false || (args.includeDrafts === undefined && args.groupBy !== undefined && !numeric);
2007
+ // 子表没有独立的流程状态(sequenceStatus 属主表),**绝不**给 list_child 注入
2008
+ // 草稿条件——否则会静默过滤掉本应计入的子行。
2009
+ const excludedByRequest = child === undefined && (args.includeDrafts === false || (args.includeDrafts === undefined && args.groupBy !== undefined && !numeric));
1964
2010
  const includeDrafts = args.includeDrafts === true;
1965
2011
  // 用户条件与草稿注入分开构造:filterGroup 会把 filters 覆盖掉(toQueryCondition
1966
2012
  // 的既有语义),所以草稿条件统一按「level1 AND 追加一组」合并,任何 DSL 形状都不丢。
@@ -1998,7 +2044,7 @@ export function registerRuntimeDataLane(tools) {
1998
2044
  return published;
1999
2045
  metaCalls += 1;
2000
2046
  try {
2001
- const rows = wireRows((await wireCall(session, { path: ENDPOINTS.fieldList, query: { schemaCode: args.schemaCode, isPublish: "true" } })).data);
2047
+ const rows = wireRows((await wireCall(session, { path: ENDPOINTS.fieldList, query: { schemaCode: metaSchemaCode, isPublish: "true" } })).data);
2002
2048
  const map = new Map();
2003
2049
  for (const row of rows) {
2004
2050
  const code = String(row.code ?? row.propertyCode ?? "");
@@ -2019,7 +2065,7 @@ export function registerRuntimeDataLane(tools) {
2019
2065
  }
2020
2066
  return published;
2021
2067
  };
2022
- const fieldListNext = `omc call field.list --env <env> --args '{"schemaCode":"${args.schemaCode}","published":true}'`;
2068
+ const fieldListNext = `omc call field.list --env <env> --args '{"schemaCode":"${metaSchemaCode}","published":true}'`;
2023
2069
  // 数值指标:field 必须已发布且 NUMERICAL(2)——fail closed,不做类型猜测。
2024
2070
  if (numeric) {
2025
2071
  const target = args.field;
@@ -2030,6 +2076,7 @@ export function registerRuntimeDataLane(tools) {
2030
2076
  blocker: "aggregate-field-unresolved",
2031
2077
  reason: "metadata-unavailable",
2032
2078
  schemaCode: args.schemaCode,
2079
+ ...(child !== undefined ? { childSchemaCode: child.childSchemaCode } : {}),
2033
2080
  field: target,
2034
2081
  message: `读不到已发布字段元数据(field.list),无法确认 ${target} 是 NUMERICAL(2)——数值聚合不做类型猜测`,
2035
2082
  nextCommand: fieldListNext,
@@ -2049,6 +2096,7 @@ export function registerRuntimeDataLane(tools) {
2049
2096
  status: "refused",
2050
2097
  blocker: "aggregate-field-unresolved",
2051
2098
  schemaCode: args.schemaCode,
2099
+ ...(child !== undefined ? { childSchemaCode: child.childSchemaCode } : {}),
2052
2100
  field: target,
2053
2101
  publishedFields: sample,
2054
2102
  publishedFieldsTotal: catalog.length,
@@ -2065,6 +2113,7 @@ export function registerRuntimeDataLane(tools) {
2065
2113
  status: "refused",
2066
2114
  blocker: "aggregate-field-not-numerical",
2067
2115
  schemaCode: args.schemaCode,
2116
+ ...(child !== undefined ? { childSchemaCode: child.childSchemaCode } : {}),
2068
2117
  field: target,
2069
2118
  propertyType: targetMeta.type,
2070
2119
  ...(numericFields.length > 0 ? { numericFields: numericFields.slice(0, AGGREGATE_FIELD_SAMPLE_LIMIT) } : {}),
@@ -2088,12 +2137,137 @@ export function registerRuntimeDataLane(tools) {
2088
2137
  status: "refused",
2089
2138
  blocker: "unknown-filter-field",
2090
2139
  schemaCode: args.schemaCode,
2140
+ ...(child !== undefined ? { childSchemaCode: child.childSchemaCode } : {}),
2091
2141
  missing: injected.missing,
2092
2142
  message: `filter 字段不在已发布元数据里:${injected.missing.join("、")}(聚合复用 data.list 的 propertyType 注入,不做猜测)`,
2093
2143
  nextCommand: fieldListNext,
2094
2144
  };
2095
2145
  condition = injected.condition;
2096
2146
  }
2147
+ // ---- 子表目标(child)------------------------------------------------
2148
+ // count:1 次 list_child(page:0,size:1),只取服务端 totalElements;
2149
+ // sum/avg/min/max:columns 列投影 + 分页,本地折叠。子表没有服务端 sum
2150
+ // (/runtime/query/sum 只认主 schema 的属性表,QueryRuntimeController.java:589-640)。
2151
+ if (child !== undefined) {
2152
+ const childDraftFilter = {
2153
+ draftPolicy: "not-applicable",
2154
+ hint: "子表没有独立的流程状态(sequenceStatus 属主表),未注入草稿条件;includeDrafts 对 child 无效",
2155
+ };
2156
+ // filters 是扁平 List<FilterModel>(FilterModel.java:45-55);filter/filters
2157
+ // 的 DSL 输出是单个 AND 组,展平即平台语义——queryVersion 不传时平台把
2158
+ // filters 全部 AND(BizObjectFacadeImpl.getFiltersByQueryParam:6584-6590)。
2159
+ const childFilters = condition === undefined
2160
+ ? undefined
2161
+ : condition.flat(2);
2162
+ const listChildBody = (page, size, columns) => ({
2163
+ schemaCode: args.schemaCode,
2164
+ childSchemaCode: child.childSchemaCode,
2165
+ bizObjectId: child.bizObjectId,
2166
+ page,
2167
+ // QueryDataVO.getSize() 在 size 空/0 时返回 Integer.MAX_VALUE
2168
+ // (QueryDataVO.java:186-191)——size 必须显式传,否则退化成全量。
2169
+ size,
2170
+ ...(childFilters !== undefined && childFilters.length > 0 ? { filters: childFilters } : {}),
2171
+ ...(columns !== undefined ? { columns: columns.map((propertyCode) => ({ propertyCode })) } : {}),
2172
+ });
2173
+ // 平台错误原样透出(message/errcode 不动),只在 hint 里补上
2174
+ // childSchemaCode/bizObjectId,便于把「主记录不存在/子表不存在」对回目标。
2175
+ const listChildCall = async (body) => {
2176
+ try {
2177
+ return await wireCall(session, { path: ENDPOINTS.runtimeFormListChild, method: "POST", body });
2178
+ }
2179
+ catch (error) {
2180
+ if (error instanceof WireError)
2181
+ throw new WireError(error.kind, error.message, error.errcode, error.diagnostic, `childSchemaCode=${child.childSchemaCode}; bizObjectId=${child.bizObjectId}${error.hint !== undefined ? `;${error.hint}` : ""}`);
2182
+ throw error;
2183
+ }
2184
+ };
2185
+ if (!numeric) {
2186
+ const page = childPageOf((await listChildCall(listChildBody(0, 1))).data);
2187
+ return {
2188
+ schemaCode: args.schemaCode,
2189
+ metric: "count",
2190
+ value: page.total,
2191
+ mode: "server-child",
2192
+ rows: 0,
2193
+ child: { childSchemaCode: child.childSchemaCode, bizObjectId: child.bizObjectId },
2194
+ ...(page.total === null ? { note: "list_child 未回 totalElements(PageVO 形状漂移)" } : {}),
2195
+ filter: childDraftFilter,
2196
+ wire: { calls: metaCalls + 1, plan: metaCalls > 0 ? "1 metadata + 1 list_child" : "1 list_child" },
2197
+ };
2198
+ }
2199
+ const target = args.field;
2200
+ const pageSize = child.pageSize ?? 500;
2201
+ const maxPages = child.maxPages ?? 40;
2202
+ const numericMetric = metric;
2203
+ let count = 0;
2204
+ let nonNullCount = 0;
2205
+ let sum = 0;
2206
+ let min = Number.POSITIVE_INFINITY;
2207
+ let max = Number.NEGATIVE_INFINITY;
2208
+ let pages = 0;
2209
+ let truncated = false;
2210
+ let readFailure;
2211
+ for (let pageIndex = 0; pageIndex < maxPages; pageIndex += 1) {
2212
+ let pageData;
2213
+ try {
2214
+ pageData = childPageOf((await listChildCall(listChildBody(pageIndex, pageSize, [target]))).data);
2215
+ }
2216
+ catch (error) {
2217
+ // 任何一页读取失败 → partial(complete:false),如实报已扫页数,
2218
+ // 不把部分和当全量、也不外推。
2219
+ readFailure = {
2220
+ page: pageIndex,
2221
+ ...(error instanceof WireError && error.errcode !== undefined ? { code: error.errcode } : {}),
2222
+ message: error instanceof Error ? error.message : String(error),
2223
+ };
2224
+ break;
2225
+ }
2226
+ pages += 1;
2227
+ for (const row of pageData.rows) {
2228
+ count += 1;
2229
+ const value = aggregateNumeric(row[target]);
2230
+ if (value === null)
2231
+ continue;
2232
+ nonNullCount += 1;
2233
+ sum += value;
2234
+ if (value < min)
2235
+ min = value;
2236
+ if (value > max)
2237
+ max = value;
2238
+ }
2239
+ // 不足一页 = 已取尽;正好一页且已到 maxPages = 无法证明取尽(可能还有)。
2240
+ if (pageData.rows.length < pageSize)
2241
+ break;
2242
+ if (pageIndex === maxPages - 1)
2243
+ truncated = true;
2244
+ }
2245
+ const complete = readFailure === undefined && !truncated;
2246
+ const value = aggregateValue(numericMetric, sum, nonNullCount, min, max);
2247
+ const capNotice = readFailure !== undefined
2248
+ ? `子表数值折叠:第 ${readFailure.page} 页(0 起)读取失败(${readFailure.code !== undefined ? `errcode ${readFailure.code} ` : ""}${readFailure.message}),只覆盖已扫 ${pages} 页 / ${count} 行(complete:false,非全集);已扫部分的值不是全量。`
2249
+ : `子表数值折叠:翻到 maxPages=${maxPages} 上限仍未取空(每页 ${pageSize} 行),只覆盖已扫 ${pages} 页 / ${count} 行(complete:false,非全集)。要全集:调大 maxPages/pageSize,或用 filter 按业务键分片重跑。`;
2250
+ return {
2251
+ schemaCode: args.schemaCode,
2252
+ metric,
2253
+ field: target,
2254
+ value,
2255
+ rows: count,
2256
+ nullCount: count - nonNullCount,
2257
+ pages,
2258
+ mode: "local-scan-child",
2259
+ coverage: { complete, pageSize, maxPages, truncated },
2260
+ child: { childSchemaCode: child.childSchemaCode, bizObjectId: child.bizObjectId },
2261
+ ...(value === null ? { note: "no numeric values in scanned child rows" } : {}),
2262
+ filter: childDraftFilter,
2263
+ ...(complete ? {} : { capNotice }),
2264
+ ...(readFailure !== undefined ? { partial: true, readFailure } : {}),
2265
+ wire: {
2266
+ calls: metaCalls + pages + (readFailure !== undefined ? 1 : 0),
2267
+ plan: `${metaCalls} metadata + ${pages} list_child pages${readFailure !== undefined ? " + 1 failed" : ""}`,
2268
+ },
2269
+ };
2270
+ }
2097
2271
  const queryBody = (size, page) => ({
2098
2272
  schemaCode: args.schemaCode,
2099
2273
  queryCode: args.schemaCode,
@@ -2416,7 +2590,7 @@ export function registerRuntimeDataLane(tools) {
2416
2590
  ...(scan.concurrency !== undefined ? { concurrency: scan.concurrency } : {}),
2417
2591
  },
2418
2592
  };
2419
- }, { target: `data.aggregate:${JSON.stringify({ schemaCode: args.schemaCode, metric: args.metric, field: args.field, filter: args.filter, filters: args.filters, filterGroup: args.filterGroup, groupBy: args.groupBy, topN: args.topN ?? 10, includeDrafts: args.includeDrafts ?? null })}` });
2593
+ }, { target: `data.aggregate:${JSON.stringify({ schemaCode: args.schemaCode, metric: args.metric, field: args.field, filter: args.filter, filters: args.filters, filterGroup: args.filterGroup, groupBy: args.groupBy, topN: args.topN ?? 10, includeDrafts: args.includeDrafts ?? null, child: args.child ?? null })}` });
2420
2594
  },
2421
2595
  }));
2422
2596
  tools.push(defineTool({
@@ -0,0 +1,134 @@
1
+ import { ENDPOINTS } from "./endpoints.js";
2
+ import { decodeJsonColumn, JSON_COLUMN_NULL_COALESCE } from "./json-column.js";
3
+ import { wireCall, wireRows } from "./wire.js";
4
+ export const METHOD_REFERENCE_LIMITS = { models: 25, rules: 50, sites: 8 };
5
+ /** Platform reference count: GET /app/bizmethod/count_mapping → Integer. Failures throw. */
6
+ export async function countMethodMapping(session, serviceCode, methodCode) {
7
+ const response = await wireCall(session, {
8
+ path: ENDPOINTS.bizMethodCountMapping,
9
+ query: { serviceCode, ...(methodCode !== undefined ? { serviceMethodCode: methodCode } : {}) },
10
+ });
11
+ const value = response.data;
12
+ if (typeof value === "number" && Number.isFinite(value))
13
+ return value;
14
+ const parsed = Number(value);
15
+ return Number.isFinite(parsed) ? parsed : 0;
16
+ }
17
+ /**
18
+ * Node codes in one rule graph whose `methodMapping` points at exactly this
19
+ * service+method. The `node` column may arrive as a JSON string or an array;
20
+ * anything else (corrupt column, object, null) yields no hits.
21
+ */
22
+ function mappedMethodNodeCodes(nodeColumn, serviceCode, methodCode) {
23
+ const decoded = decodeJsonColumn(nodeColumn, JSON_COLUMN_NULL_COALESCE);
24
+ if (!Array.isArray(decoded))
25
+ return [];
26
+ const nodeCodes = [];
27
+ for (const entry of decoded) {
28
+ if (!entry || typeof entry !== "object" || Array.isArray(entry))
29
+ continue;
30
+ const node = entry;
31
+ const mapping = node.methodMapping;
32
+ if (!mapping || typeof mapping !== "object" || Array.isArray(mapping))
33
+ continue;
34
+ const mapped = mapping;
35
+ if (String(mapped.serviceCode ?? "") !== serviceCode || String(mapped.serviceMethodCode ?? "") !== methodCode)
36
+ continue;
37
+ const nodeCode = String(node.nodeCode ?? "");
38
+ if (nodeCode !== "")
39
+ nodeCodes.push(nodeCode);
40
+ }
41
+ return nodeCodes;
42
+ }
43
+ /**
44
+ * Best-effort reference identity: viewReference → schemaCodes (≤25) → per-model
45
+ * rule list (≤50 rules) → per-rule graph read → methodMapping match
46
+ * (serviceCode + serviceMethodCode). A single failed read only lands in
47
+ * `coverage`; sites stop at 8 and the coverage says the scan was truncated.
48
+ */
49
+ export async function scanMethodReferenceSites(session, serviceCode, methodCode) {
50
+ const sites = [];
51
+ const coverage = {
52
+ source: "viewReference+rule.list+rule.get",
53
+ modelsDiscovered: 0,
54
+ modelsScanned: 0,
55
+ rulesScanned: 0,
56
+ modelsReadFailed: 0,
57
+ rulesReadFailed: 0,
58
+ truncated: false,
59
+ sitesReturned: 0,
60
+ };
61
+ let schemaCodes = [];
62
+ try {
63
+ const rows = wireRows((await wireCall(session, {
64
+ path: ENDPOINTS.bizServiceMethodViewReference,
65
+ query: { serviceCode, serviceMethodCode: methodCode },
66
+ })).data);
67
+ const discovered = [...new Set(rows.map((row) => String(row.schemaCode ?? "")).filter((code) => code !== ""))];
68
+ coverage.modelsDiscovered = discovered.length;
69
+ if (discovered.length > METHOD_REFERENCE_LIMITS.models)
70
+ coverage.truncated = true;
71
+ schemaCodes = discovered.slice(0, METHOD_REFERENCE_LIMITS.models);
72
+ }
73
+ catch {
74
+ // No model list: zero sites is all we can say. Callers must label it as a
75
+ // zero-HIT scan (never "no references").
76
+ return { sites, coverage };
77
+ }
78
+ for (const schemaCode of schemaCodes) {
79
+ coverage.modelsScanned += 1;
80
+ let rules = [];
81
+ try {
82
+ rules = wireRows((await wireCall(session, { path: ENDPOINTS.businessRuleListBySchemaCode, query: { schemaCode } })).data);
83
+ }
84
+ catch {
85
+ coverage.modelsReadFailed += 1;
86
+ continue;
87
+ }
88
+ if (rules.length > METHOD_REFERENCE_LIMITS.rules)
89
+ coverage.truncated = true;
90
+ for (const rule of rules.slice(0, METHOD_REFERENCE_LIMITS.rules)) {
91
+ const ruleCode = String(rule.code ?? "");
92
+ const id = rule.id;
93
+ if (ruleCode === "" || typeof id !== "string" || id === "")
94
+ continue;
95
+ let record = null;
96
+ try {
97
+ record = (await wireCall(session, { path: ENDPOINTS.businessRuleGet, query: { id } })).data;
98
+ }
99
+ catch {
100
+ coverage.rulesReadFailed += 1;
101
+ continue;
102
+ }
103
+ coverage.rulesScanned += 1;
104
+ if (!record)
105
+ continue;
106
+ for (const nodeCode of mappedMethodNodeCodes(record.node, serviceCode, methodCode)) {
107
+ sites.push({ schemaCode, ruleCode, nodeCode });
108
+ if (sites.length >= METHOD_REFERENCE_LIMITS.sites) {
109
+ coverage.truncated = true;
110
+ coverage.sitesReturned = sites.length;
111
+ return { sites, coverage };
112
+ }
113
+ }
114
+ }
115
+ }
116
+ coverage.sitesReturned = sites.length;
117
+ return { sites, coverage };
118
+ }
119
+ /**
120
+ * The single "this method is referenced" fact sentence: count + 500108 +
121
+ * platform source anchor + "rules and bindings stay untouched" + doNot. Both
122
+ * `method.delete` and the intent warning append `methodReferenceIdentity`.
123
+ */
124
+ export function methodReferencedCoreMessage(serviceCode, methodCode, count) {
125
+ return `业务方法 ${serviceCode}/${methodCode} 被 ${count} 条规则映射引用——平台删除会回 500108「业务方法已绑定默认方法,不可删除」(BizServiceMethodController.java:248-281),本次零写入:方法、规则与绑定保持原状。要删必须先解绑引用规则(rule.save 去掉对应 BIZ_ACTION 节点、保留其余节点/routes/schedulerSetting,重新发布)再删方法。不要自行解绑规则、不要改调度生效时间后再删方法——解绑属于高危写入,必须用户确认`;
126
+ }
127
+ /** Readable suffix for the reference scan: site identities, or a pointer when the scan hit nothing. */
128
+ export function methodReferenceIdentity(sites, serviceCode) {
129
+ if (sites.length === 0)
130
+ return `;定位:omc call rule.references --args '{"kind":"service","code":"${serviceCode}"}'`;
131
+ const shown = sites.slice(0, 3).map((site) => `${site.schemaCode}/${site.ruleCode}#${site.nodeCode}`).join("、");
132
+ return `;引用点:${shown}${sites.length > 3 ? ` 等 ${sites.length} 处` : ""}`;
133
+ }
134
+ //# sourceMappingURL=method-references.js.map
@@ -102,8 +102,8 @@ const READ_SHAPES = {
102
102
  },
103
103
  // r80:计数/分组统计的读回面。notes 只显首条——把陷阱并进第一句。
104
104
  "data.aggregate": {
105
- keys: ["schemaCode", "metric", "field?", "value?", "count", "nonNullCount?", "nullCount?", "groupBy?", "total", "buckets:array<{key,count,nonNullCount?,value?}>", "nullBucket:{count,nonNullCount?,value?}", "truncatedBuckets", "bucketsTruncatedCount", "unaccountedCount?", "shapeWarnings?", "strategyFallback?", "coverage:{mode:server-total|paged-local-scan|local-scan|server-aggregate,rowsScanned,cap:number|null,complete,missingCount?}", "filter:{draftPolicy,hint}", "wire:{calls,plan,concurrency?}", "capNotice?", "note?", "environmentFingerprint"],
106
- notes: ["计数用 total(totalElements);分组=值域×count,key 是存储值/code,null 单列 nullBucket;分桶 count 并发窗口 4,桶序稳定;数值指标(sum/avg/min/max+field)本地折叠(cap 1000,null 不进聚合、avg 分母排除 null);coverage.mode=server-total/paged-local-scan/local-scan/server-aggregate,/sum 不可用或形状不符回退本地(strategyFallback);complete:false 只覆盖已扫行,勿外推"],
105
+ keys: ["schemaCode", "metric", "field?", "value?", "count", "nonNullCount?", "nullCount?", "groupBy?", "total", "buckets:array<{key,count,nonNullCount?,value?}>", "nullBucket:{count,nonNullCount?,value?}", "truncatedBuckets", "bucketsTruncatedCount", "unaccountedCount?", "shapeWarnings?", "strategyFallback?", "coverage:{mode:server-total|paged-local-scan|local-scan|server-aggregate,rowsScanned,cap,complete,missingCount?}", "filter:{draftPolicy,hint}", "wire:{calls,plan,concurrency?}", "capNotice?", "note?", "environmentFingerprint"],
106
+ notes: ["计数用 total(totalElements);分组=值域×count,key 是存储值/code,null 单列 nullBucket;分桶 count 并发窗口 4;数值指标(sum/avg/min/max+field)本地折叠(cap 1000,null 不进聚合、avg 分母排除 null);coverage.mode=server-total/paged-local-scan/local-scan/server-aggregate,/sum 不可用或形状不符回退本地(strategyFallback);complete:false 只覆盖已扫行,勿外推"],
107
107
  },
108
108
  "app.list": {
109
109
  keys: ["applications:array<{code,name,groupId?,modelCount}>", "applicationsCount", "omitted"],
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@stalfh233/omc-cli",
3
- "version": "0.6.88",
3
+ "version": "0.6.89",
4
4
  "description": "CloudPivot 8.6 configuration capability CLI — governed, fail-closed, coverage-manifest bounded.",
5
5
  "type": "module",
6
6
  "bin": {
@@ -56,7 +56,7 @@
56
56
  },
57
57
  "dependencies": {
58
58
  "commander": "14.0.3",
59
- "omc-core": "0.6.88",
59
+ "omc-core": "0.6.89",
60
60
  "proper-lockfile": "4.1.2",
61
61
  "write-file-atomic": "6.0.0",
62
62
  "zod": "^3.23.8",
@@ -74,6 +74,6 @@
74
74
  "directory": "packages/omc-cli"
75
75
  },
76
76
  "optionalDependencies": {
77
- "@stalfh233/omc-fake-platform": "0.6.88"
77
+ "@stalfh233/omc-fake-platform": "0.6.89"
78
78
  }
79
79
  }