@stalfh233/omc-cli 0.6.81 → 0.6.83

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -74,6 +74,8 @@ export const RUNTIME_DATA_LANE_CONTRACT = Object.freeze({
74
74
  queryConditionShape: RUNTIME_DATA_WIRE.queryConditionShape,
75
75
  dslShape: RUNTIME_DATA_WIRE.dslShape,
76
76
  queryBodyCanon: RUNTIME_DATA_WIRE.queryBodyCanon,
77
+ subtableFilterFace: RUNTIME_DATA_WIRE.subtableFilterFace,
78
+ queryOrdersFace: RUNTIME_DATA_WIRE.queryOrdersFace,
77
79
  typeCastErrcode: RUNTIME_DATA_WIRE.typeCastErrcode,
78
80
  emptyModelErrcode: RUNTIME_DATA_WIRE.emptyModelErrcode,
79
81
  absenceErrcode: RUNTIME_DATA_WIRE.absenceErrcode,
@@ -95,6 +97,8 @@ export const RUNTIME_DATA_LANE_CONTRACT = Object.freeze({
95
97
  queryConditionShape: Object.freeze([emitterBinding("data-list-filter.toQueryCondition", assertRuntimeDataContract)]),
96
98
  dslShape: Object.freeze([emitterBinding("data-list-filter.SIMPLE_OP_MAP", assertRuntimeDataContract)]),
97
99
  queryBodyCanon: Object.freeze([behaviorBinding("test/data-list.test.ts#data.list translates simplified filters", assertRuntimeDataContract)]),
100
+ subtableFilterFace: Object.freeze([behaviorBinding("test/r86-data-list-subtable.test.ts#data.list refuses a DSL filter on a subtable schema before the wire and maps the rawCondition 50000", assertRuntimeDataContract)]),
101
+ queryOrdersFace: Object.freeze([behaviorBinding("test/r86-data-list-order.test.ts#data.list orderBy maps to wire orders and validates the orderable face", assertRuntimeDataContract)]),
98
102
  typeCastErrcode: Object.freeze([emitterBinding("data-list-filter.injectPropertyTypes", assertRuntimeDataContract)]),
99
103
  emptyModelErrcode: Object.freeze([emitterBinding("omc-core/wire-facts.RUNTIME_DATA_WIRE", assertRuntimeDataContract)]),
100
104
  absenceErrcode: Object.freeze([emitterBinding("omc-core/wire-facts.RUNTIME_DATA_WIRE", assertRuntimeDataContract)]),
@@ -163,6 +167,10 @@ export function assertRuntimeDataContract() {
163
167
  throw new Error("runtime-data contract pins the create-only workflow start duplicate errcode to 40000");
164
168
  if (!RUNTIME_DATA_WIRE.queryConditionShape.includes("level 3 AND across leaves"))
165
169
  throw new Error("runtime-data contract must pin the three-layer queryCondition shape");
170
+ if (!RUNTIME_DATA_WIRE.subtableFilterFace.includes("unsupported-filter-on-subtable"))
171
+ throw new Error("runtime-data contract must pin the r86 subtable filter refusal face");
172
+ if (!RUNTIME_DATA_WIRE.queryOrdersFace.includes("orders") || !RUNTIME_DATA_WIRE.queryOrdersFace.includes("createdTime"))
173
+ throw new Error("runtime-data contract must pin the r86 server-side orders face");
166
174
  if (!RUNTIME_DATA_WIRE.dslShape.includes("or>and"))
167
175
  throw new Error("runtime-data contract must pin the or>and>leaf DSL shape");
168
176
  if (!RUNTIME_DATA_WIRE.queryBodyCanon.includes("queryVersion:1") || !RUNTIME_DATA_WIRE.queryBodyCanon.includes("queryCode=schemaCode"))
@@ -1162,7 +1162,10 @@ export function registerRuntimeDataLane(tools) {
1162
1162
  fields: z.array(z.string().min(1)).optional().describe("列投影别名(=displayFields;与 data.load/data.save/data.update 的 fields 同语义)"),
1163
1163
  // r73 #4(GitLab #40 P1):只读查询的排序 fallback 首选曾是写操作(listview.configure
1164
1164
  // 会改线上视图、影响所有用户)。顺序反转——本地排序第一,视图级写操作殿后并注明代价。
1165
- orders: z.array(z.object({ field: z.string().min(1), dir: z.enum(["ASC", "DESC"]) })).optional().describe("query/list 不支持服务端排序。首选本地排(items[].fields.<字段>;--jq 只投影);listview.configure 的 sorts 是写操作(改线上视图、影响所有用户),仅确需时用"),
1165
+ // r86(retro issue 16):wire 侧其实有服务端排序(QueryDataVO.orders,真机 1.1.25
1166
+ // 实证生效)——orderBy 映射为 orders:[{propertyCode,dir:ASC|DESC}];教学进
1167
+ // contract/notes(tools/list 只留这句)。
1168
+ orderBy: z.array(z.object({ field: z.string().min(1), direction: z.enum(["asc", "desc"]) })).optional().describe("服务端排序 [{field,direction:asc|desc}](wire=orders,dir 发送时转大写);多键按数组序优先;可排面=已发布字段+系统列(createdTime/modifiedTime 等);子表 schema 面被平台忽略"),
1166
1169
  mobile: z.boolean().optional(),
1167
1170
  // r63(b-F12):draftPolicy 此前只能从结果反推——探针无法控制也无法预知
1168
1171
  // 草稿口径。显式开关:false 注入 sequenceStatus≠DRAFT(真机验证可过滤,
@@ -1189,17 +1192,14 @@ export function registerRuntimeDataLane(tools) {
1189
1192
  tool: "data.list",
1190
1193
  message: '没有 `query` 参数——过滤用 `filter: {"op":"eq","field":"<字段>","value":"<值>"}`(或 `filters` 数组=AND、`filterGroup` 嵌套)。r31 真机:`query:{...}` 被静默忽略、total 不变,极易误判为"无数据/已过滤"。',
1191
1194
  });
1192
- if (args.orders !== undefined)
1193
- throw new ToolInputError({
1194
- status: "error",
1195
- blocker: "invalid-input",
1196
- tool: "data.list",
1197
- // r73 #4(GitLab #40 P1):旧文案把写操作(listview.configure 改线上视图)放在
1198
- // 首位、nextCommand 直接指向它——只读查询的 fallback 不该默认引向写。本地排序
1199
- // 第一(并说清怎么排),视图级写操作放末尾并注明影响所有用户。
1200
- message: "运行面 query/list 不支持服务端排序。排序请先在本地做:用本工具取回数据(全量 all:true 或逐页翻页),再按 items[].fields.<字段> 在本地排序(--jq 只能投影不能排序,需用客户端脚本/管道排)。只有确实要改**视图级**默认排序时才用 listview.configure 的 sorts(写操作:会改线上视图排序、影响所有用户,谨慎)。",
1201
- nextCommand: `omc call data.list --env <env> --args '${JSON.stringify({ schemaCode: args.schemaCode, all: true })}'(取回全量后本地排序)`,
1202
- });
1195
+ // r86(retro issue 16):orderBy 参数面 → wire orders(QueryDataVO.orders,
1196
+ // 真机 1.1.25 实证:dir 枚举 ASC|DESC 大小写敏感、未知列 40000、多键数组序
1197
+ // 优先、orders 优先于视图 sorts、无则平台默认 createdTime DESC)。
1198
+ const orderBy = args.orderBy;
1199
+ // r86(retro issue 15):子表拒绝只看**调用方显式给的**过滤面。includeDrafts:false
1200
+ // 注入的 sequenceStatus≠DRAFT 是默认属性(平台子表分支自建同款 parent-scope
1201
+ // notDraftFilter),按父模型解析也成立,不该被新门误伤。
1202
+ const userFilterRequested = args.rawCondition !== undefined || args.filter !== undefined || (args.filters?.length ?? 0) > 0 || args.filterGroup !== undefined;
1203
1203
  let condition;
1204
1204
  let fromDsl = false;
1205
1205
  try {
@@ -1266,6 +1266,22 @@ export function registerRuntimeDataLane(tools) {
1266
1266
  publishedTypes = new Map((await publishedFields()).map((row) => [row.code, row.type]));
1267
1267
  return publishedTypes;
1268
1268
  };
1269
+ /**
1270
+ * r86(retro issue 15):子表 schema 判别——bizmodels/get_all 的 parentCode
1271
+ * (BizSchemaModel.parentCode,QueryRuntimeController.list 同源判别)。
1272
+ * 非子表/读不到(8.0/8.1 不挂载该路径、模型不存在)都返回 undefined,
1273
+ * 调用方按「不能预判」处理(发 wire,50000 时再映射)。
1274
+ */
1275
+ const subtableParentCodeOf = async (session, schemaCode) => {
1276
+ try {
1277
+ const record = (await wireCall(session, { path: ENDPOINTS.modelGet, query: { schemaCode } })).data;
1278
+ const parent = record?.parentCode;
1279
+ return typeof parent === "string" && parent.trim().length > 0 ? parent : undefined;
1280
+ }
1281
+ catch {
1282
+ return undefined;
1283
+ }
1284
+ };
1269
1285
  if (fromDsl) {
1270
1286
  const typeByCode = await publishedTypeByCode();
1271
1287
  const injected = injectPropertyTypes(condition, (code) => {
@@ -1353,6 +1369,58 @@ export function registerRuntimeDataLane(tools) {
1353
1369
  message: `这些字段是子表(propertyType=${CHILD_TABLE_PROPERTY_TYPE},值是行数组):运行面 query/list 只支持标量过滤,按子表字段过滤会回 errcode 50000 且无明细。改法:用 data.load 读主表记录(子表行随主记录返回),或在本地按子表字段筛选。`,
1354
1370
  nextCommand: `omc call data.load --env <env> --args '{"schemaCode":"${args.schemaCode}","bizObjectId":"<主表 bizObjectId>"}'`,
1355
1371
  };
1372
+ // r86(retro issue 15,真机 1.1.25 实证):schemaCode 本身是子表 schema
1373
+ // (get_all parentCode 非空)时,queryCondition 的裸叶子被平台按**父模型**
1374
+ // 元数据解析(ChildBizObjectAssembler.buildFilter(父code) + 无点号→
1375
+ // schema=parentCode)——子表自身字段(含 parentId)→ 50000 服务异常。
1376
+ // DSL 叶子按子表自身 field.list 注入 propertyType 后必然是裸子表字段,
1377
+ // 全部是错误形状,写前整批拒绝(+1 wire 读 get_all 换拒绝面)。
1378
+ const parentCode = await subtableParentCodeOf(session, args.schemaCode);
1379
+ if (parentCode !== undefined && userFilterRequested)
1380
+ return {
1381
+ status: "refused",
1382
+ blocker: "unsupported-filter-on-subtable",
1383
+ schemaCode: args.schemaCode,
1384
+ parentSchema: parentCode,
1385
+ fields: collectConditionLeafFields(condition),
1386
+ message: `${args.schemaCode} 是子表模型(父模型 ${parentCode}):运行面 query/list 的过滤叶子按**父模型**解析——裸子表字段(含 parentId)会回 errcode 50000「服务异常」(真机实证),不是平台故障。` +
1387
+ `读子表行的正路:data.load 父模型记录(子表行随主记录返回),或本工具不带 filter 全量拉子表后本地筛。要点号「<子表code>.<字段>」形状请走 rawCondition。`,
1388
+ nextCommand: `omc call data.load --env <env> --args '{"schemaCode":"${parentCode}","bizObjectId":"<主表 bizObjectId>"}' --jq 'data.${args.schemaCode}'`,
1389
+ };
1390
+ }
1391
+ // r86(retro issue 16):orderBy 参数面 → wire orders。可排面 = 已发布字段 +
1392
+ // 系统列(平台默认排序本身用 createdTime,8.6.26 resolveSorts;真机 1.1.25
1393
+ // 实证 createdTime/modifiedTime/业务列均可排)。不在可排面的列写前拒——
1394
+ // 平台会回 40000「调用数据库发生异常」(真机),与真故障难分。
1395
+ let wireOrders;
1396
+ if (orderBy !== undefined && orderBy.length > 0) {
1397
+ // r86(retro issue 16):可排面 = 已发布业务字段 + **全部**默认属性列
1398
+ // (DefaultPropertyType.codes:id/name/creater/createdDeptId/owner/
1399
+ // ownerDeptId/createdTime/modifier/modifiedTime/workflowInstanceId/
1400
+ // sequenceNo/sequenceStatus/ownerDeptQueryCode/version)——真机 1.1.25
1401
+ // 逐列实证 createdTime/name/id/sequenceNo 均可排;它们都是物理列,不是
1402
+ // 元数据特例。只放 createdTime/modifiedTime 会把合法排序误拒。
1403
+ const ORDERABLE_SYSTEM_FIELDS = new Set([
1404
+ "id", "name", "creater", "createdDeptId", "owner", "ownerDeptId", "createdTime",
1405
+ "modifier", "modifiedTime", "workflowInstanceId", "sequenceNo", "sequenceStatus",
1406
+ "ownerDeptQueryCode", "version",
1407
+ ]);
1408
+ const catalog = await publishedFields();
1409
+ const codes = catalog.map((row) => row.code);
1410
+ const missing = [...new Set(orderBy.map((entry) => entry.field))].filter((field) => !ORDERABLE_SYSTEM_FIELDS.has(field) && !codes.includes(field));
1411
+ if (missing.length > 0)
1412
+ return {
1413
+ status: "refused",
1414
+ blocker: "unsupported-order-field",
1415
+ schemaCode: args.schemaCode,
1416
+ fields: missing,
1417
+ ...(catalog.length > 0 && catalog.length <= FILTER_FIELD_SAMPLE_LIMIT ? { acceptedValues: { "orderBy.field": [...ORDERABLE_SYSTEM_FIELDS, ...codes] } } : {}),
1418
+ message: `排序字段不在可排面:${missing.join("、")}(可排 = 已发布字段 + 系统列,如 createdTime/modifiedTime/name/id/sequenceNo)。` +
1419
+ `平台对未知排序列回 40000「调用数据库发生异常」(真机实证:no_such_col DESC → 40000),与数据库真故障同码——写前拒绝免歧义。` +
1420
+ `排序形状:orderBy:[{"field":"modifiedTime","direction":"desc"}],多键按数组序优先。`,
1421
+ ...(catalog.length > 0 ? { nextCommand: `omc call field.list --env <env> --args '{"schemaCode":"${args.schemaCode}","published":true}'` } : {}),
1422
+ };
1423
+ wireOrders = orderBy.map((entry) => ({ propertyCode: entry.field, dir: entry.direction === "desc" ? "DESC" : "ASC" }));
1356
1424
  }
1357
1425
  // r29b F9: fields 是 displayFields/columns 的同义别名(与 data.load 对齐)。
1358
1426
  const requestedFields = args.displayFields ?? args.columns ?? args.fields;
@@ -1367,6 +1435,7 @@ export function registerRuntimeDataLane(tools) {
1367
1435
  queryVersion: 1,
1368
1436
  showTotal: args.showTotal !== false,
1369
1437
  ...(condition !== undefined ? { queryCondition: condition } : {}),
1438
+ ...(wireOrders !== undefined ? { orders: wireOrders } : {}),
1370
1439
  };
1371
1440
  // An empty model answers with a business error (301005) on this face;
1372
1441
  // that is "no data yet", not a query failure.
@@ -1524,7 +1593,25 @@ export function registerRuntimeDataLane(tools) {
1524
1593
  // 不改判定的排查提示——子表/子表 schema 的过滤与系统字段过滤是这个面
1525
1594
  // 最常见的"服务异常"来源(live: 子表 schema 加 parentId 过滤 → 50000,
1526
1595
  // 去掉 filter 就正常)。只加 hint,不猜 blocker。
1596
+ // r86(retro issue 15):rawCondition 路径无法写前预判(点号形状合法),
1597
+ // 50000 后补读一次 get_all parentCode——确认是子表 schema 就把该形状
1598
+ // 重写为结构化 blocker(平台原文进 detail,不吞),否则维持原样抛出。
1527
1599
  if (error instanceof WireError && error.kind === "business" && error.errcode === 50000) {
1600
+ if (condition !== undefined) {
1601
+ const parentCodeOn50000 = await subtableParentCodeOf(session, args.schemaCode);
1602
+ if (parentCodeOn50000 !== undefined)
1603
+ return {
1604
+ status: "refused",
1605
+ blocker: "unsupported-filter-on-subtable",
1606
+ schemaCode: args.schemaCode,
1607
+ parentSchema: parentCodeOn50000,
1608
+ rawCondition: true,
1609
+ detail: `平台原文:errcode 50000 ${error.message}`,
1610
+ message: `${args.schemaCode} 是子表模型(父模型 ${parentCodeOn50000}),本次查询带了 rawCondition——运行面 query/list 的过滤叶子按**父模型**解析,裸子表字段(含 parentId)会回 50000「服务异常」。` +
1611
+ `合法 wire 形状只有点号「<子表code>.<字段>」(真机实证 errcode 0);或改 data.load 读父模型记录后看子表数组。若 rawCondition 里已经全是点号字段仍 50000,按真服务异常排查(平台原文见 detail)。`,
1612
+ nextCommand: `omc call data.load --env <env> --args '{"schemaCode":"${parentCodeOn50000}","bizObjectId":"<主表 bizObjectId>"}' --jq 'data.${args.schemaCode}'`,
1613
+ };
1614
+ }
1528
1615
  throw new WireError(error.kind, error.message, error.errcode, error.diagnostic, `若 filter/filters 里含子表字段或子表自身 schema 的 parentId 等系统字段:运行面 query/list 的标量过滤不适用于子表,去掉 filter 后按主表 id 用 data.load 读子表行。其余情况按真服务异常处理(同一 schemaCode 去掉 filter 可读即说明是过滤形状问题)。`);
1529
1616
  }
1530
1617
  throw error;
@@ -0,0 +1,376 @@
1
+ import { randomUUID } from "node:crypto";
2
+ import { z } from "zod";
3
+ import { ENDPOINTS } from "../endpoints.js";
4
+ import { capabilityArg, environmentArg } from "../args.js";
5
+ import { governedRead } from "../read.js";
6
+ import { writeArtifact } from "../support.js";
7
+ import { defineTool, ToolRefusalError } from "../tool-types.js";
8
+ import { wireCallWith404Fallback } from "../wire.js";
9
+ import { B2_LANE_CONTRACT } from "./b2-registration-contract.js";
10
+ /**
11
+ * Business-service invocation logs (`h_log_biz_service`) — the only place that
12
+ * records what a rule actually sent to an integration endpoint (params), what
13
+ * came back (result) and whether it failed (bizServiceStatus). Wire facts live
14
+ * in B2_LANE_CONTRACT.wire.logFace; the short version:
15
+ *
16
+ * GET /api/log/list_bizservicelog?code&methodName&dataTitle&startTime&endTime&page&size&status
17
+ *
18
+ * `page` is REQUIRED and 0-based (LogManagerController.java:239). The server
19
+ * filters code/methodName as LIKE-contains (comma → IN), dataTitle likewise,
20
+ * `startTime >= startTime` AND `endTime <= endTime`, and always orders
21
+ * startTime DESC. schemaCode/bizObjectId are NOT query parameters on this face
22
+ * (BizServiceLogModel carries them on the row; the controller ignores them), so
23
+ * those two selectors are matched client-side over a bounded number of wire
24
+ * pages and the scan accounting is reported instead of pretending a full scan.
25
+ *
26
+ * A log table grows without bound; an unfiltered query is exactly the 60s
27
+ * socket-timeout trap the manual JDBC route hit. So the tool is fail-closed:
28
+ * no selector → refusal, and the time window defaults to the last 60 minutes.
29
+ */
30
+ const DEFAULT_WINDOW_MINUTES = 60;
31
+ const DEFAULT_LIMIT = 20;
32
+ const MAX_LIMIT = 100;
33
+ /** Client-side matching (schemaCode/bizObjectId) reads at most this many wire pages. */
34
+ const CLIENT_FILTER_SCAN_PAGES = 5;
35
+ /** One-line params/result summary length. */
36
+ const SUMMARY_CHARS = 240;
37
+ /** Full params/result payloads above this size go to an artifact file. */
38
+ const FULL_PAYLOAD_ARTIFACT_BYTES = 4096;
39
+ const TIME_PATTERN = /^\d{4}-\d{2}-\d{2}(?:[ T]\d{2}:\d{2}(?::\d{2})?)?$/;
40
+ const B2_LANE = B2_LANE_CONTRACT.lane;
41
+ const B2_TOOLS = B2_LANE_CONTRACT.tools;
42
+ const pad = (value) => String(value).padStart(2, "0");
43
+ /** Platform-local wall clock (the log columns are wall-clock strings, no TZ). */
44
+ function formatLocal(date) {
45
+ return `${date.getFullYear()}-${pad(date.getMonth() + 1)}-${pad(date.getDate())} ${pad(date.getHours())}:${pad(date.getMinutes())}:${pad(date.getSeconds())}`;
46
+ }
47
+ /** Best-effort parse of the same shapes the wire accepts (date or 19-char datetime). */
48
+ function parseLocal(value) {
49
+ const match = value.match(/^(\d{4})-(\d{2})-(\d{2})(?:[ T](\d{2}):(\d{2})(?::(\d{2}))?)?$/);
50
+ if (!match)
51
+ return undefined;
52
+ const [, year, month, day, hour, minute, second] = match;
53
+ return new Date(Number(year), Number(month) - 1, Number(day), Number(hour ?? 0), Number(minute ?? 0), Number(second ?? 0));
54
+ }
55
+ /** `T` is accepted on input; the platform's DateUtility expects a space. */
56
+ const wireTime = (value) => value.replace("T", " ");
57
+ /** Single-line summary of a free-form log column, with the original byte size. */
58
+ function summarize(value) {
59
+ if (value === null || value === undefined)
60
+ return { text: null, bytes: 0, truncated: false };
61
+ const full = typeof value === "string" ? value : JSON.stringify(value);
62
+ const bytes = Buffer.byteLength(full, "utf8");
63
+ const oneLine = full.replace(/\s+/g, " ").trim();
64
+ if (oneLine.length <= SUMMARY_CHARS)
65
+ return { text: oneLine, bytes, truncated: false };
66
+ return { text: `${oneLine.slice(0, SUMMARY_CHARS)}…`, bytes, truncated: true };
67
+ }
68
+ const RULE_KEYS = ["ruleCode", "ruleName", "nodeCode", "nodeName"];
69
+ /** extensionLog is the caller-supplied trace context (rule/node) in the usual case. */
70
+ function ruleOf(raw) {
71
+ if (raw === null || raw === undefined)
72
+ return undefined;
73
+ const text = typeof raw === "string" ? raw : JSON.stringify(raw);
74
+ if (!text)
75
+ return undefined;
76
+ try {
77
+ const parsed = JSON.parse(text);
78
+ if (parsed && typeof parsed === "object" && !Array.isArray(parsed)) {
79
+ const picked = {};
80
+ for (const key of RULE_KEYS) {
81
+ const value = parsed[key];
82
+ if (typeof value === "string" && value.length > 0)
83
+ picked[key] = value;
84
+ }
85
+ if (Object.keys(picked).length > 0)
86
+ return picked;
87
+ }
88
+ }
89
+ catch {
90
+ // Fall through: an unparseable extensionLog is still evidence — surface it
91
+ // as a truncated raw string rather than dropping it.
92
+ }
93
+ return { raw: summarize(text).text ?? text };
94
+ }
95
+ const statusOf = (value) => {
96
+ if (value === 1 || value === "1" || value === "FAILURE")
97
+ return { status: "failure", statusName: "失败" };
98
+ if (value === 2 || value === "2" || value === "SUCCESS")
99
+ return { status: "success", statusName: "成功" };
100
+ return { status: null };
101
+ };
102
+ export function registerServiceLogLane(tools) {
103
+ tools.push(defineTool({
104
+ name: "servicelog.search",
105
+ layer: "low",
106
+ kind: "read",
107
+ lane: B2_LANE,
108
+ search: {
109
+ intents: [
110
+ "业务服务日志", "业务服务调用日志", "服务调用日志", "接口调用日志", "调用记录",
111
+ "接口调用记录", "调接口记录", "业务集成日志", "规则传了什么参数", "规则到底传了什么参数",
112
+ "接口传了什么参数", "接口返回了什么",
113
+ ],
114
+ },
115
+ scope: B2_TOOLS["servicelog.search"].scope,
116
+ description: B2_TOOLS["servicelog.search"].description,
117
+ inputSchema: {
118
+ environment: environmentArg,
119
+ code: z.string().min(1).optional().describe("业务服务编码(服务侧叫 serviceCode);平台按 LIKE 包含匹配,逗号分隔=精确 IN"),
120
+ methodName: z.string().min(1).optional().describe("业务方法名(LIKE 包含;逗号分隔=精确 IN)"),
121
+ dataTitle: z.string().min(1).optional().describe("数据标题(LIKE 包含)"),
122
+ schemaCode: z.string().min(1).optional().describe("模型编码:平台列表端点没有这个过滤参数,本工具在扫描页内客户端精确匹配"),
123
+ bizObjectId: z.string().min(1).optional().describe("业务对象 id:同上,客户端精确匹配(规则排查最常用)"),
124
+ status: z.union([z.literal(0), z.literal(1), z.literal(2)]).optional().describe("1=失败 2=成功 0=全部(平台只有成功/失败两态)"),
125
+ startTime: z.string().regex(TIME_PATTERN).optional().describe("开始时间:yyyy-MM-dd 或 yyyy-MM-dd HH:mm:ss(平台按 startTime>= 过滤)"),
126
+ endTime: z.string().regex(TIME_PATTERN).optional().describe("结束时间:同上(平台按 endTime<= 过滤)"),
127
+ minutes: z.number().int().min(1).max(1440).optional().describe(`未给时间时向前取多少分钟(默认 ${DEFAULT_WINDOW_MINUTES})`),
128
+ limit: z.number().int().min(1).max(MAX_LIMIT).optional().describe(`每页条数(默认 ${DEFAULT_LIMIT},上限 ${MAX_LIMIT})`),
129
+ page: z.number().int().min(0).optional().describe("wire 页码,从 0 开始(时间倒序的第几页)"),
130
+ capability: capabilityArg,
131
+ },
132
+ handler: async (ctx, args, self) => governedRead(ctx, self, args, async (session) => {
133
+ const hasSelector = args.code !== undefined || args.methodName !== undefined || args.dataTitle !== undefined
134
+ || args.schemaCode !== undefined || args.bizObjectId !== undefined;
135
+ if (!hasSelector) {
136
+ throw new ToolRefusalError({
137
+ status: "refused",
138
+ blocker: "servicelog-filter-required",
139
+ message: "没有任何过滤条件——业务服务日志表会无限增长,无过滤查询正是全表扫描超时的来源;本工具 fail-closed,不提供「查全部」。至少给 code / methodName / dataTitle / schemaCode / bizObjectId 之一(时间窗默认最近 60 分钟,也可传 startTime/endTime 或 minutes)。",
140
+ nextCommand: `omc call servicelog.search --args '{"bizObjectId":"<单据id>","minutes":60}'`,
141
+ examples: [
142
+ { why: "规则给这个单据调过哪些接口、传了什么参数", args: { bizObjectId: "<bizObjectId>" } },
143
+ { why: "某个集成服务最近一小时的失败调用", args: { code: "<服务编码>", status: 1, minutes: 60 } },
144
+ { why: "按模型 + 方法名缩小", args: { schemaCode: "<模型code>", methodName: "<方法名>", startTime: "2026-01-01 00:00:00", endTime: "2026-01-01 23:59:59" } },
145
+ ],
146
+ });
147
+ }
148
+ const limit = args.limit ?? DEFAULT_LIMIT;
149
+ const startPage = args.page ?? 0;
150
+ const minutes = args.minutes ?? DEFAULT_WINDOW_MINUTES;
151
+ const now = new Date();
152
+ let startTime = args.startTime;
153
+ let endTime = args.endTime;
154
+ let windowSource;
155
+ if (startTime === undefined && endTime === undefined) {
156
+ startTime = formatLocal(new Date(now.getTime() - minutes * 60_000));
157
+ endTime = formatLocal(now);
158
+ windowSource = "default";
159
+ }
160
+ else if (startTime !== undefined && endTime === undefined) {
161
+ endTime = formatLocal(now);
162
+ windowSource = "explicit-start";
163
+ }
164
+ else if (startTime === undefined && endTime !== undefined) {
165
+ const end = parseLocal(endTime);
166
+ startTime = formatLocal(new Date((end ?? now).getTime() - minutes * 60_000));
167
+ windowSource = "explicit-end";
168
+ }
169
+ else {
170
+ windowSource = "explicit";
171
+ }
172
+ const clientFilter = args.schemaCode !== undefined || args.bizObjectId !== undefined;
173
+ const fetchPage = async (page) => {
174
+ const query = {
175
+ page: String(page),
176
+ size: String(limit),
177
+ startTime: wireTime(startTime),
178
+ endTime: wireTime(endTime),
179
+ };
180
+ if (args.code !== undefined)
181
+ query.code = args.code;
182
+ if (args.methodName !== undefined)
183
+ query.methodName = args.methodName;
184
+ if (args.dataTitle !== undefined)
185
+ query.dataTitle = args.dataTitle;
186
+ // status=0 is the平台「全部」值; omitting it keeps the query identical.
187
+ if (args.status !== undefined && args.status !== 0)
188
+ query.status = String(args.status);
189
+ let endpointFamily;
190
+ const result = await wireCallWith404Fallback(session, [
191
+ { path: ENDPOINTS.bizServiceLogList, query },
192
+ { path: ENDPOINTS.bizServiceLogListSinglePrefix, query },
193
+ ], (failed, next) => { endpointFamily = { used: next.path, reason: `${failed.path} HTTP 404(该部署只在单前缀挂载日志控制器,已下探)` }; });
194
+ const envelope = result.data;
195
+ const content = envelope && Array.isArray(envelope.content)
196
+ ? envelope.content.filter((row) => Boolean(row) && typeof row === "object")
197
+ : [];
198
+ return {
199
+ content,
200
+ totalElements: typeof envelope?.totalElements === "number" ? envelope.totalElements : null,
201
+ totalPages: typeof envelope?.totalPages === "number" ? envelope.totalPages : null,
202
+ endpointFamily,
203
+ path: result.path,
204
+ };
205
+ };
206
+ const matches = (row) => (args.schemaCode === undefined || row.schemaCode === args.schemaCode)
207
+ && (args.bizObjectId === undefined || row.bizObjectId === args.bizObjectId);
208
+ let rows = [];
209
+ let totalElements = null;
210
+ let totalPages = null;
211
+ let wireCalls = 0;
212
+ let rowsFetched = 0;
213
+ let endpointFamily;
214
+ let usedPath = ENDPOINTS.bizServiceLogList;
215
+ let rowFilter;
216
+ if (!clientFilter) {
217
+ const page = await fetchPage(startPage);
218
+ wireCalls = 1;
219
+ rowsFetched = page.content.length;
220
+ rows = page.content;
221
+ totalElements = page.totalElements;
222
+ totalPages = page.totalPages;
223
+ endpointFamily = page.endpointFamily;
224
+ usedPath = page.path;
225
+ }
226
+ else {
227
+ // Wire paging is startTime DESC; scan a bounded page window from `page`
228
+ // and match the two row-only selectors locally. `exhausted:false` says
229
+ // the scan stopped before the end — never read it as "no such call".
230
+ const matched = [];
231
+ let scannedPages = 0;
232
+ let scannedElements = 0;
233
+ let exhausted = false;
234
+ let moreLikely = false;
235
+ for (let offset = 0; offset < CLIENT_FILTER_SCAN_PAGES; offset += 1) {
236
+ const page = await fetchPage(startPage + offset);
237
+ wireCalls += 1;
238
+ scannedPages += 1;
239
+ totalElements = page.totalElements;
240
+ totalPages = page.totalPages;
241
+ endpointFamily = page.endpointFamily ?? endpointFamily;
242
+ usedPath = page.path;
243
+ scannedElements += page.content.length;
244
+ rowsFetched += page.content.length;
245
+ for (const row of page.content)
246
+ if (matches(row))
247
+ matched.push(row);
248
+ if (matched.length >= limit) {
249
+ moreLikely = true;
250
+ break;
251
+ }
252
+ const noNextPage = page.totalPages !== null && startPage + offset + 1 >= page.totalPages;
253
+ if (page.content.length < limit || noNextPage) {
254
+ exhausted = true;
255
+ break;
256
+ }
257
+ }
258
+ rows = matched.slice(0, limit);
259
+ rowFilter = {
260
+ ...(args.schemaCode !== undefined ? { schemaCode: args.schemaCode } : {}),
261
+ ...(args.bizObjectId !== undefined ? { bizObjectId: args.bizObjectId } : {}),
262
+ matched: matched.length,
263
+ returned: rows.length,
264
+ scannedPages,
265
+ scannedElements,
266
+ exhausted,
267
+ ...(moreLikely ? { moreLikely: true } : {}),
268
+ ...(matched.length > rows.length ? { truncatedMatches: matched.length - rows.length } : {}),
269
+ };
270
+ }
271
+ const full = [];
272
+ let fullPayloadBytes = 0;
273
+ const logs = rows.map((row) => {
274
+ const params = summarize(row.params);
275
+ const result = summarize(row.result);
276
+ const detail = typeof row.detail === "string" && row.detail.length > 0 ? summarize(row.detail) : undefined;
277
+ fullPayloadBytes += params.bytes + result.bytes;
278
+ full.push({ id: row.id ?? null, startTime: row.startTime ?? null, code: row.code ?? null, methodName: row.methodName ?? null, params: row.params ?? null, result: row.result ?? null });
279
+ const status = statusOf(row.bizServiceStatus);
280
+ const rule = ruleOf(row.extensionLog);
281
+ return {
282
+ startTime: row.startTime ?? null,
283
+ ...(typeof row.endTime === "string" && row.endTime !== row.startTime ? { endTime: row.endTime } : {}),
284
+ usedTime: row.usedTime ?? null,
285
+ code: row.code ?? null,
286
+ methodName: row.methodName ?? null,
287
+ status: status.status,
288
+ ...(typeof row.bizServiceStatusName === "string" ? { statusName: row.bizServiceStatusName } : {}),
289
+ dataTitle: row.dataTitle ?? null,
290
+ schemaCode: row.schemaCode ?? null,
291
+ bizObjectId: row.bizObjectId ?? null,
292
+ ...(rule ? { rule } : {}),
293
+ params: params.text,
294
+ paramsBytes: params.bytes,
295
+ ...(params.truncated ? { paramsTruncated: true } : {}),
296
+ result: result.text,
297
+ resultBytes: result.bytes,
298
+ ...(result.truncated ? { resultTruncated: true } : {}),
299
+ ...(detail ? { detail: detail.text, ...(detail.truncated ? { detailTruncated: true } : {}) } : {}),
300
+ };
301
+ });
302
+ // Full params/result over the threshold leave the envelope; the summary
303
+ // above already answers "what did the rule send" for normal payloads.
304
+ let payload;
305
+ if (fullPayloadBytes > FULL_PAYLOAD_ARTIFACT_BYTES) {
306
+ const artifact = writeArtifact(ctx, `servicelog-${randomUUID().slice(0, 8)}.json`, {
307
+ window: { startTime, endTime },
308
+ rows: full,
309
+ });
310
+ payload = {
311
+ payloadFile: artifact.detailFile,
312
+ payloadSha256: artifact.detailSha256,
313
+ payloadBytes: fullPayloadBytes,
314
+ payloadHint: `完整 params/result 共 ${fullPayloadBytes}B 已外置(单行摘要见 logs);用 jq 定向取回(例如 jq '.rows[0].params' <payloadFile>),勿整份读入。params 侧平台入库上限 2000 字符。`,
315
+ };
316
+ }
317
+ const returned = logs.length;
318
+ const hasMore = clientFilter
319
+ ? (rowFilter?.exhausted === false || rowFilter?.moreLikely === true)
320
+ : (totalPages !== null ? startPage + wireCalls < totalPages : null);
321
+ const nextPage = clientFilter
322
+ ? (rowFilter?.exhausted === false && rowFilter.moreLikely !== true ? startPage + wireCalls : undefined)
323
+ : (hasMore === true ? startPage + 1 : undefined);
324
+ const notes = [
325
+ "服务端过滤 code/methodName(LIKE 包含,逗号=精确 IN)、dataTitle、时间(startTime>= 且 endTime<= 两列)、status;schemaCode/bizObjectId 不在平台列表参数里,本工具在扫描页内客户端匹配。",
326
+ "日志异步落库(刚触发的调用可能晚数秒才可见);历史按平台保留天数清理。params 入库上限 2000 字符(更长的部分平台已截断),result 无此上限但可能很大。",
327
+ windowSource === "default"
328
+ ? `未给时间,默认窗口最近 ${minutes} 分钟(本机时钟,与平台同时区才可直接用;跨时区请显式 startTime/endTime)。`
329
+ : "时间窗为显式传入(按字符串原样上送;平台按 startTime>=、endTime<= 两列过滤)。",
330
+ ...(clientFilter ? [`schemaCode/bizObjectId 是客户端匹配:最多扫 ${CLIENT_FILTER_SCAN_PAGES} 个 wire 页(约 ${limit * CLIENT_FILTER_SCAN_PAGES} 行),exhausted:false 表示扫描被上限截断——未命中不代表没有更早的调用。`] : []),
331
+ ...(typeof rowFilter?.truncatedMatches === "number" ? [`扫描到的命中数(${String(rowFilter.matched)})超过 limit,只回前 ${returned} 条——提高 limit 重查;page 是 wire 页码(时间倒序),不是命中偏移。`] : []),
332
+ ...(endpointFamily ? [`端点下探:${endpointFamily.reason}`] : []),
333
+ ...(payload ? [payload.payloadHint] : []),
334
+ ];
335
+ const emptyHint = returned === 0
336
+ ? "0 条先核对:① code 是 LIKE 包含匹配(crm_expiry 能命中 crm_expiry_service);② 日志异步落库,稍后重试;③ 时间窗/时区是否覆盖到;④ schemaCode/bizObjectId 是客户端匹配、且扫描有页数上限。"
337
+ : undefined;
338
+ return {
339
+ window: { startTime, endTime, minutes, source: windowSource },
340
+ filters: {
341
+ ...(args.code !== undefined ? { code: args.code } : {}),
342
+ ...(args.methodName !== undefined ? { methodName: args.methodName } : {}),
343
+ ...(args.dataTitle !== undefined ? { dataTitle: args.dataTitle } : {}),
344
+ ...(args.status !== undefined ? { status: args.status } : {}),
345
+ ...(args.schemaCode !== undefined ? { schemaCode: args.schemaCode } : {}),
346
+ ...(args.bizObjectId !== undefined ? { bizObjectId: args.bizObjectId } : {}),
347
+ },
348
+ paging: {
349
+ page: startPage,
350
+ size: limit,
351
+ totalElements,
352
+ totalPages,
353
+ returned,
354
+ hasMore,
355
+ ...(nextPage !== undefined ? { nextPage } : {}),
356
+ ...(nextPage !== undefined ? { nextCommand: `omc call servicelog.search --args '${JSON.stringify({ ...plannableFilters(args), page: nextPage })}'` } : {}),
357
+ },
358
+ ...(rowFilter ? { rowFilter } : {}),
359
+ logs,
360
+ ...(emptyHint ? { emptyHint } : {}),
361
+ notes,
362
+ wire: { path: usedPath, calls: wireCalls, rowsFetched },
363
+ ...(payload ?? {}),
364
+ };
365
+ }, { target: `servicelog.search:${JSON.stringify(args)}` }),
366
+ }));
367
+ }
368
+ /** Echo the human filters into the copyable next command (never the paging/window defaults). */
369
+ function plannableFilters(args) {
370
+ const picked = {};
371
+ for (const key of ["code", "methodName", "dataTitle", "status", "schemaCode", "bizObjectId", "startTime", "endTime", "limit"])
372
+ if (args[key] !== undefined)
373
+ picked[key] = args[key];
374
+ return picked;
375
+ }
376
+ //# sourceMappingURL=servicelog.js.map