@stalfh233/omc-cli 0.6.78 → 0.6.79

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.
@@ -190,7 +190,7 @@ const SURFACES = [
190
190
  id: "data",
191
191
  title: "运行数据",
192
192
  lane: LANES.runtimeData,
193
- description: "运行数据条目的列出、加载、保存、更新、删除、提交,以及计数/分组统计。",
193
+ description: "运行数据条目的列出、加载、保存、更新、删除、提交,以及计数/分组/求和平均等统计。",
194
194
  operations: ["list", "aggregate", "load", "save", "update", "delete", "submit"],
195
195
  requires: ["field"],
196
196
  intent: { level: "none", note: "未覆盖;用 omc call data.*。" },
@@ -824,7 +824,13 @@ function goalRouteInner(registry, goal) {
824
824
  const dataRoute = routeById.get("data");
825
825
  if (dataRoute !== undefined) {
826
826
  const readTools = readToolsInLane(registry, dataRoute.lane);
827
- const action = readTools.includes("data.list") ? "omc call data.list --args '{\"schemaCode\":\"<模型code>\",\"size\":1,\"filter\":{\"op\":\"eq\",\"field\":\"<字段>\",\"value\":\"<值>\"}}' --jq '.result.total'" : "omc commands --capability data";
827
+ // r82:data.aggregate 已覆盖 count(服务端 totalElements)与 sum/avg/min/max
828
+ // (本地折叠),聚合问句直指本工具;手工 size:1+filter 只作降级路径保留。
829
+ const action = readTools.includes("data.aggregate")
830
+ ? "omc call data.aggregate --args '{\"schemaCode\":\"<模型code>\",\"metric\":\"count\"}' --jq '.result.total'"
831
+ : readTools.includes("data.list")
832
+ ? "omc call data.list --args '{\"schemaCode\":\"<模型code>\",\"size\":1,\"filter\":{\"op\":\"eq\",\"field\":\"<字段>\",\"value\":\"<值>\"}}' --jq '.result.total'"
833
+ : "omc commands --capability data";
828
834
  return {
829
835
  status: "ok",
830
836
  goal,
@@ -835,7 +841,7 @@ function goalRouteInner(registry, goal) {
835
841
  route: {
836
842
  capability: "data",
837
843
  lane: dataRoute.lane,
838
- note: "平台没有 group-by:**计数/分组计数用 data.list size:1 + filter 只读 total**(服务端精确计数,~1.3KB,不拉行);分组=值域×count,值域从 field.list options/字典元数据取;sum/avg 才拉列(all:true cap 1000,超出分片并如实标 complete:false);跨模型/持久看板归 report,写时计算归 datarule type2。本路由只读。",
844
+ note: "**计数/分组/数值聚合用 data.aggregate**:metric:count=服务端 totalElements(~0.4KB,不拉行);groupBy 单列分组(count 可枚举=值域×count,值域从 field.list options/字典元数据取;数值指标一律本地扫描);sum/avg/min/max 需 field 且已发布 NUMERICAL(2)——本地折叠 cap 1000,null 行不进聚合、avg 分母排除 null,截断如实标 complete:false;跨模型/持久看板归 report,写时计算归 datarule type2。本路由只读。",
839
845
  readTools,
840
846
  readiness: DISCOVERY_AUTHORITY.readiness,
841
847
  firstCommands: [action],
@@ -846,7 +852,7 @@ function goalRouteInner(registry, goal) {
846
852
  state: "needs-input",
847
853
  question: "要统计哪个模型(schemaCode 或业务名)?按哪个字段分组/什么条件?",
848
854
  action,
849
- why: "计数用 size:1+filter→total(服务端精确计数、无需拉行);分组计数=值域×count(值域从 field.list/字典元数据取);sum/avg 才需要拉列(all:true cap 1000)",
855
+ why: "计数用 data.aggregate metric:count→total(服务端精确、无需拉行);分组用 groupBy(值域从 field.list/字典元数据取);数值聚合用 metric:sum/avg/min/max + field(本地折叠 cap 1000,截断标 complete:false)",
850
856
  },
851
857
  };
852
858
  }
@@ -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 `临时计数/分组统计(纯读,metric=count)。count:runtime/query/list size:1 读 totalElements(服务端精确,不受 cap 1000 影响;带 filter 2 wire=1 field.list 注入 propertyType+1 list)。groupBy 单列且值域可枚举(field.list options/字典)→ 值域×count(V+3 wire:1 metadata+1 base+V 桶+1 isnull),桶按 count 降序取 topN(默认 10/上限 20),截断给 truncatedBuckets/bucketsTruncatedCount,null 单列 nullBucket。不可枚举(自由文本/高基数)→ 1 列投影 all:true(cap 1000)本地计数,coverage.mode=local-scan+missingCount+capNotice,**永不外推行数**。filter.draftPolicy:groupBy 默认 includeDrafts:false 注入 sequenceStatus≠DRAFT(excluded)统一双口径;count 省略=平台默认(无条件下含草稿 included、带条件排草稿 excluded);显式 false 可强制排除。边界:临时问句用本工具;持久图表/看板用 report.chartdata,视图汇总列用 sumType,写时计算用 datarule type2。`;
11
+ return `临时计数与数值聚合(纯读,metric=count|sum|avg|min|max)。count:runtime/query/list size:1 读 totalElements(服务端精确,不受 cap 1000 影响;带 filter 2 wire=1 field.list 注入 propertyType+1 list)。sum/avg/min/max:field 必填且须已发布 propertyType=2(NUMERICAL),本地折叠——列投影+size:200 翻页至 cap 1000,null 行不进聚合、avg=sum/非 null 行数,nonNullCount=0 时 value:null;rowsScanned>=total 才 complete:true,否则 complete:false+missingCount+capNotice,**绝不外推**。groupBy 单列:count 时值域可枚举(field.list options/字典)→ 值域×count(V+3 wire:1 metadata+1 base+V 桶+1 isnull),桶按 count 降序取 topN(默认 10/上限 20),截断给 truncatedBuckets/bucketsTruncatedCount,null 单列 nullBucket;不可枚举或数值指标 → 本地扫描(coverage.mode=local-scan),数值桶 {key,count,nonNullCount,value} 按 value 降序、并列按 key,null 行进 nullBucket。filter.draftPolicy:count+groupBy 默认 includeDrafts:false 注入 sequenceStatus≠DRAFT(excluded)统一双口径;数值指标不默认排除(如实反映平台返回行);count 省略=平台默认(无条件下含草稿 included、带条件排草稿 excluded);显式 false 可强制排除。边界:临时问句用本工具;持久图表/看板用 report.chartdata,视图汇总列用 sumType,写时计算用 datarule type2。`;
12
12
  }
13
13
  export function dataUpdateDescription() {
14
14
  const wire = RUNTIME_DATA_WIRE;
@@ -146,7 +146,7 @@ function desc(lead) {
146
146
  export function assertRuntimeDataContract() {
147
147
  assertLaneContract(RUNTIME_DATA_LANE_CONTRACT);
148
148
  assertDescriptionCarries(RUNTIME_DATA_LANE_CONTRACT, "data.list", ["queryCondition", "propertyType", "rawCondition", "projectionHint", "listview.configure", "data.load", "items[].fields"]);
149
- assertDescriptionCarries(RUNTIME_DATA_LANE_CONTRACT, "data.aggregate", ["totalElements", "groupBy", "local-scan", "cap 1000", "draftPolicy", "report.chartdata"]);
149
+ assertDescriptionCarries(RUNTIME_DATA_LANE_CONTRACT, "data.aggregate", ["totalElements", "groupBy", "local-scan", "cap 1000", "draftPolicy", "report.chartdata", "sum", "avg", "NUMERICAL", "nonNullCount"]);
150
150
  assertDescriptionCarries(RUNTIME_DATA_LANE_CONTRACT, "data.save", ["bizObjectId", "sheetCode", "bizsheet/get", "workflowCode", "sequenceStatus", "workItem", "propertyType 9", "50000", "mappings", "rowStatus", "DRAFT", "submit:true", "CHILD_TABLE"]);
151
151
  assertDescriptionCarries(RUNTIME_DATA_LANE_CONTRACT, "data.update", ["runtime/form/save", "bizObjectId", "COMPLETED", "304001", "form/load", "rowStatus", "child-rows-upsert"]);
152
152
  assertDescriptionCarries(RUNTIME_DATA_LANE_CONTRACT, "data.delete", ["absence", "sheetCode"]);
@@ -13,7 +13,7 @@ import { closestMatch } from "../closest-match.js";
13
13
  import { getInstanceBaseInfo, 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";
16
+ import { SYSTEM_FIELD_CODES, familyName } from "../field-families.js";
17
17
  import { applicationResolutionOf, resolveApplicationScope } from "../support.js";
18
18
  /** r29b F8: keep ids/itemsPreview through governedRead's compact diet. */
19
19
  const DATA_LIST_PREVIEW_LIMIT = 20;
@@ -1064,6 +1064,38 @@ async function diagnoseDbException(session, schemaCode, error) {
1064
1064
  /** `data.aggregate` caps: server-total counts are exact; the local-scan fallback shares data.list's row cap. */
1065
1065
  const AGGREGATE_CAP = 1000;
1066
1066
  const AGGREGATE_PAGE_SIZE = 200;
1067
+ /** 数值聚合的字段拒绝面:publishedFields 只列前 N 个(与 data.list 的过滤目录同口径)。 */
1068
+ const AGGREGATE_FIELD_SAMPLE_LIMIT = 20;
1069
+ /**
1070
+ * 数值列的 wire 值 → number。null/undefined/非数值字符串 → null(null 行**不进**
1071
+ * sum/avg/min/max,也不进 min/max 初值比较)。平台数值列通常回 number,兼容回
1072
+ * 数字字符串的形状(历史读回见过)。
1073
+ */
1074
+ function aggregateNumeric(value) {
1075
+ if (typeof value === "number")
1076
+ return Number.isFinite(value) ? value : null;
1077
+ if (typeof value === "string" && value.trim() !== "") {
1078
+ const parsed = Number(value);
1079
+ return Number.isFinite(parsed) ? parsed : null;
1080
+ }
1081
+ return null;
1082
+ }
1083
+ /**
1084
+ * sum/avg 是**派生值**:12 位有效数字去掉二进制求和噪声(0.1+0.2),不做外推精度、
1085
+ * 不改存储值。min/max 是存储值本身,原样返回(tidy 会改掉长整数尾部)。
1086
+ */
1087
+ function aggregateTidy(value) {
1088
+ return Number.isFinite(value) ? Number(value.toPrecision(12)) : value;
1089
+ }
1090
+ function aggregateValue(metric, sum, nonNullCount, min, max) {
1091
+ if (nonNullCount === 0)
1092
+ return null;
1093
+ if (metric === "sum")
1094
+ return aggregateTidy(sum);
1095
+ if (metric === "avg")
1096
+ return aggregateTidy(sum / nonNullCount);
1097
+ return metric === "min" ? min : max;
1098
+ }
1067
1099
  /**
1068
1100
  * One property leaf as a level-1 AND group, so it can be appended to ANY base
1069
1101
  * condition (leaf / filters / filterGroup) without re-shaping the existing
@@ -1079,13 +1111,19 @@ function withAggregateLeaf(condition, leafGroup) {
1079
1111
  /**
1080
1112
  * Draft口径(继承 data.list r26/r28b 的键名,调用方同一套分支)。
1081
1113
  *
1082
- * - `includeDrafts:false`(含 groupBy 的默认)→ 注入 sequenceStatus≠DRAFT(excluded);
1114
+ * - `includeDrafts:false`(含 count+groupBy 的默认)→ 注入 sequenceStatus≠DRAFT(excluded);
1083
1115
  * - count 省略 → 平台默认:无条件时含草稿(included),带条件时平台自己排草稿(excluded);
1084
1116
  * - `includeDrafts:true` → 不注入;无条件时含草稿(included),带条件时平台仍排草稿。
1117
+ * - 数值指标(numeric)**不做默认排除**:本地折叠只反映平台返回行,要排除须显式 false。
1085
1118
  */
1086
- function aggregateDraftFilter(excludedByRequest, includeDrafts, hasUserCondition) {
1119
+ function aggregateDraftFilter(excludedByRequest, includeDrafts, hasUserCondition, numeric = false) {
1087
1120
  if (excludedByRequest)
1088
- return { draftPolicy: "excluded", hint: "includeDrafts:false(groupBy 默认)——已注入 sequenceStatus≠DRAFT;total/桶只计非草稿" };
1121
+ return { draftPolicy: "excluded", hint: numeric ? "includeDrafts:false——已注入 sequenceStatus≠DRAFT;扫描行与桶只计非草稿" : "includeDrafts:false(groupBy 默认)——已注入 sequenceStatus≠DRAFT;total/桶只计非草稿" };
1122
+ if (numeric)
1123
+ return {
1124
+ draftPolicy: "included",
1125
+ hint: `数值指标本地折叠不做默认排除:结果反映平台返回行${hasUserCondition ? "(带条件时平台自身排草稿,r26/r28b)" : ""};要排除草稿显式传 includeDrafts:false`,
1126
+ };
1089
1127
  if (includeDrafts && hasUserCondition)
1090
1128
  return { draftPolicy: "excluded", hint: "带条件计数时平台排除草稿(r26/r28b);includeDrafts:true 无法强制包含" };
1091
1129
  if (hasUserCondition)
@@ -1607,7 +1645,7 @@ export function registerRuntimeDataLane(tools) {
1607
1645
  }));
1608
1646
  tools.push(defineTool({
1609
1647
  name: "data.aggregate",
1610
- search: { intents: ["分组计数", "聚合计数", "计数汇总", "按状态分组", "值域分布", "分组分布", "每类几个", "分桶计数"] },
1648
+ search: { intents: ["分组计数", "聚合计数", "计数汇总", "按状态分组", "值域分布", "分组分布", "每类几个", "分桶计数", "求和", "合计", "总额", "平均值", "最大值", "最小值"] },
1611
1649
  layer: "low",
1612
1650
  kind: "read",
1613
1651
  lane: RUNTIME_LANE,
@@ -1620,16 +1658,36 @@ export function registerRuntimeDataLane(tools) {
1620
1658
  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 等)'),
1621
1659
  filters: z.array(z.record(z.string(), z.unknown())).optional().describe("子句数组=AND"),
1622
1660
  filterGroup: z.record(z.string(), z.unknown()).optional().describe('嵌套组 {op:"and"|"or",clauses:[…]}'),
1623
- metric: z.enum(["count"]).describe("首片仅 count(服务端 totalElements 精确);sum/avg/min/max 第二批"),
1624
- groupBy: z.string().min(1).optional().describe("单列分组:值域可枚举走「值域×count」;不可枚举(自由文本/高基数)退化为本地扫描(cap 1000,截断时 complete:false+capNotice)"),
1625
- topN: z.number().int().min(1).max(20).default(10).describe("分组桶上限,默认 10、上限 20(按 count 降序)"),
1626
- includeDrafts: z.boolean().optional().describe("groupBy 默认 false(注入 sequenceStatus≠DRAFT 统一双口径);count 省略=平台默认(无条件含草稿、带条件排草稿);显式 false 可强制排除——口径看 filter.draftPolicy"),
1661
+ metric: z.enum(["count", "sum", "avg", "min", "max"]).describe("count=服务端 totalElements 精确计数(不读行,不需要 field);sum/avg/min/max=数值列本地折叠(需 field,翻页 cap 1000)。null 行不进聚合,avg 分母=已扫非 null 行数"),
1662
+ field: z.string().min(1).optional().describe("metric≠count 时必填:已发布且 propertyType=2(NUMERICAL)的字段 code。未发布→aggregate-field-unresolved(带 publishedFields/didYouMean);非数值→aggregate-field-not-numerical(计数请用 metric:count)"),
1663
+ groupBy: z.string().min(1).optional().describe("单列分组:count 值域可枚举走「值域×count」,不可枚举降级本地扫描;数值指标一律本地双列扫描(cap 1000,截断时 complete:false+capNotice)"),
1664
+ topN: z.number().int().min(1).max(20).default(10).describe("分组桶上限,默认 10、上限 20(count 按 count 降序;数值指标按 value 降序、并列按 key)"),
1665
+ includeDrafts: z.boolean().optional().describe("count+groupBy 默认 false(注入 sequenceStatus≠DRAFT 统一双口径);数值指标不默认排除(反映平台返回行);count 省略=平台默认(无条件含草稿、带条件排草稿);显式 false 可强制排除——口径看 filter.draftPolicy"),
1627
1666
  capability: capabilityArg,
1628
1667
  },
1629
1668
  handler: async (ctx, args, self) => {
1630
- // groupBy 要统一 base 与各桶的口径,省略时默认排除草稿;count 省略时保留
1631
- // 平台默认(无条件含草稿),只有显式 false 才注入排除条件。
1632
- const excludedByRequest = args.includeDrafts === false || (args.includeDrafts === undefined && args.groupBy !== undefined);
1669
+ const metric = args.metric;
1670
+ const numeric = metric !== "count";
1671
+ // 参数面 fail-closed(零 wire、零写入):metric 与 field 的组合只有两种合法形状。
1672
+ if (metric === "count" && args.field !== undefined)
1673
+ throw new ToolInputError({
1674
+ status: "error",
1675
+ blocker: "invalid-input",
1676
+ tool: "data.aggregate",
1677
+ message: "metric=count 只回 total(服务端 totalElements 精确计数),不接受 field——count 的草稿口径已在 filter.draftPolicy 标注。要按数值列聚合请用 metric:sum/avg/min/max + field",
1678
+ });
1679
+ if (numeric && (args.field === undefined || args.field.trim() === ""))
1680
+ throw new ToolInputError({
1681
+ status: "error",
1682
+ blocker: "invalid-input",
1683
+ tool: "data.aggregate",
1684
+ message: `metric=${metric} 需要 field(已发布且 propertyType=2/NUMERICAL 的字段 code)——不给 field 无法知道聚合哪一列`,
1685
+ nextCommand: `omc call field.list --env <env> --args '{"schemaCode":"${args.schemaCode}","published":true}'`,
1686
+ });
1687
+ // count+groupBy 要统一 base 与各桶的口径,省略时默认排除草稿;count 省略时保留
1688
+ // 平台默认(无条件含草稿),只有显式 false 才注入排除条件。数值指标(本地折叠)
1689
+ // 不做默认注入——结果如实反映平台返回行,要排除须显式 false。
1690
+ const excludedByRequest = args.includeDrafts === false || (args.includeDrafts === undefined && args.groupBy !== undefined && !numeric);
1633
1691
  const includeDrafts = args.includeDrafts === true;
1634
1692
  // 用户条件与草稿注入分开构造:filterGroup 会把 filters 覆盖掉(toQueryCondition
1635
1693
  // 的既有语义),所以草稿条件统一按「level1 AND 追加一组」合并,任何 DSL 形状都不丢。
@@ -1657,10 +1715,11 @@ export function registerRuntimeDataLane(tools) {
1657
1715
  const hasUserCondition = userCondition !== undefined;
1658
1716
  let condition = excludedByRequest ? withAggregateLeaf(userCondition, aggregateLeafGroup("sequenceStatus", 0, "NotEq", "DRAFT")) : userCondition;
1659
1717
  return governedRead(ctx, self, args, async (session) => {
1660
- const draftFilter = aggregateDraftFilter(excludedByRequest, includeDrafts, hasUserCondition);
1718
+ const draftFilter = aggregateDraftFilter(excludedByRequest, includeDrafts, hasUserCondition, numeric);
1661
1719
  let metaCalls = 0;
1662
1720
  let published;
1663
- // field.list 至多一跳:同时服务 filter 的 propertyType 注入与 groupBy 值域解析。
1721
+ // field.list 至多一跳:同时服务 filter 的 propertyType 注入、groupBy 值域解析
1722
+ // 与数值字段的类型校验(数值指标至少 1 次;有 filter 时同一跳兼注入)。
1664
1723
  const fieldMeta = async () => {
1665
1724
  if (published !== undefined)
1666
1725
  return published;
@@ -1672,9 +1731,12 @@ export function registerRuntimeDataLane(tools) {
1672
1731
  const code = String(row.code ?? row.propertyCode ?? "");
1673
1732
  if (!code)
1674
1733
  continue;
1734
+ const rawName = row.name ?? row.propertyName;
1735
+ const name = typeof rawName === "string" && rawName.length > 0 && rawName !== code ? rawName : undefined;
1675
1736
  map.set(code, {
1676
1737
  type: Number(row.propertyType ?? row.type),
1677
1738
  choiceCodes: choiceCodesFromFieldOptions(row, parseOptions(row.options)),
1739
+ ...(name !== undefined ? { name } : {}),
1678
1740
  });
1679
1741
  }
1680
1742
  published = map;
@@ -1684,6 +1746,62 @@ export function registerRuntimeDataLane(tools) {
1684
1746
  }
1685
1747
  return published;
1686
1748
  };
1749
+ const fieldListNext = `omc call field.list --env <env> --args '{"schemaCode":"${args.schemaCode}","published":true}'`;
1750
+ // 数值指标:field 必须已发布且 NUMERICAL(2)——fail closed,不做类型猜测。
1751
+ if (numeric) {
1752
+ const target = args.field;
1753
+ const meta = await fieldMeta();
1754
+ if (meta === null)
1755
+ return {
1756
+ status: "refused",
1757
+ blocker: "aggregate-field-unresolved",
1758
+ reason: "metadata-unavailable",
1759
+ schemaCode: args.schemaCode,
1760
+ field: target,
1761
+ message: `读不到已发布字段元数据(field.list),无法确认 ${target} 是 NUMERICAL(2)——数值聚合不做类型猜测`,
1762
+ nextCommand: fieldListNext,
1763
+ };
1764
+ const targetMeta = meta.get(target);
1765
+ if (targetMeta === undefined) {
1766
+ const catalog = [...meta].map(([code, info]) => ({ code, ...(info.name !== undefined ? { name: info.name } : {}), type: info.type }));
1767
+ const sample = catalog.slice(0, AGGREGATE_FIELD_SAMPLE_LIMIT);
1768
+ const numericCodes = catalog.filter((row) => row.type === 2).map((row) => row.code);
1769
+ // 名字最像但类型不对时改推 NUMERICAL 字段(同 data.list 的数值算子判例)。
1770
+ const suggestion = closestMatch(target, catalog.map((row) => row.code));
1771
+ const numericSuggestion = suggestion !== undefined && meta.get(suggestion)?.type !== 2
1772
+ ? numericCodes.find((code) => closestMatch(target, [code]) === code)
1773
+ : undefined;
1774
+ const didYouMean = numericSuggestion ?? suggestion;
1775
+ return {
1776
+ status: "refused",
1777
+ blocker: "aggregate-field-unresolved",
1778
+ schemaCode: args.schemaCode,
1779
+ field: target,
1780
+ publishedFields: sample,
1781
+ publishedFieldsTotal: catalog.length,
1782
+ ...(didYouMean !== undefined ? { didYouMean: { [target]: didYouMean } } : {}),
1783
+ message: `field 不在已发布元数据里:${target}(数值聚合要用已发布且 propertyType=2 的字段 code,不做猜测)` +
1784
+ (didYouMean !== undefined ? `;是否想写 ${didYouMean}` : "") +
1785
+ (catalog.length === 0 ? ";该模型当前没有已发布字段" : `;已发布字段共 ${catalog.length} 个,code/名称见 publishedFields(仅列前 ${sample.length} 个,其余用 field.list 查)`),
1786
+ nextCommand: fieldListNext,
1787
+ };
1788
+ }
1789
+ if (targetMeta.type !== 2) {
1790
+ const numericFields = [...meta].filter(([, info]) => info.type === 2).map(([code]) => code);
1791
+ return {
1792
+ status: "refused",
1793
+ blocker: "aggregate-field-not-numerical",
1794
+ schemaCode: args.schemaCode,
1795
+ field: target,
1796
+ propertyType: targetMeta.type,
1797
+ ...(numericFields.length > 0 ? { numericFields: numericFields.slice(0, AGGREGATE_FIELD_SAMPLE_LIMIT) } : {}),
1798
+ message: `字段 ${target} 是 ${familyName(targetMeta.type)}(propertyType=${targetMeta.type}),不是 NUMERICAL(2)——sum/avg/min/max 只对数值列有意义;该字段是文本/选项,要条数用 metric:count(只回 total,不需要 field)`,
1799
+ ...(numericFields.length > 0
1800
+ ? { nextCommand: `omc call data.aggregate --env <env> --args '${JSON.stringify({ schemaCode: args.schemaCode, metric, field: numericFields[0] })}'(同模型第一个 NUMERICAL 字段)` }
1801
+ : {}),
1802
+ };
1803
+ }
1804
+ }
1687
1805
  // Only a USER DSL filter needs published metadata; the injected draft
1688
1806
  // leaf (sequenceStatus) has a platform-fixed propertyType.
1689
1807
  if (hasUserCondition) {
@@ -1699,7 +1817,7 @@ export function registerRuntimeDataLane(tools) {
1699
1817
  schemaCode: args.schemaCode,
1700
1818
  missing: injected.missing,
1701
1819
  message: `filter 字段不在已发布元数据里:${injected.missing.join("、")}(聚合复用 data.list 的 propertyType 注入,不做猜测)`,
1702
- nextCommand: `omc call field.list --env <env> --args '{"schemaCode":"${args.schemaCode}","published":true}'`,
1820
+ nextCommand: fieldListNext,
1703
1821
  };
1704
1822
  condition = injected.condition;
1705
1823
  }
@@ -1722,6 +1840,116 @@ export function registerRuntimeDataLane(tools) {
1722
1840
  return extractBizObjectPage(response.data).total;
1723
1841
  };
1724
1842
  const topN = args.topN ?? 10;
1843
+ // 数值指标(sum/avg/min/max):平台无服务端聚合面 → 列投影 + size:200 翻页
1844
+ // 本地折叠至 cap 1000。null 行不进聚合;扫不完就给 complete:false + capNotice,
1845
+ // 绝不按扫描比例外推(与 count 的自由文本路径同一诚实口径)。
1846
+ if (numeric) {
1847
+ const target = args.field;
1848
+ const groupBy = args.groupBy;
1849
+ const emptyAcc = () => ({ count: 0, nonNullCount: 0, sum: 0, min: Number.POSITIVE_INFINITY, max: Number.NEGATIVE_INFINITY });
1850
+ const overall = emptyAcc();
1851
+ const nullBucket = emptyAcc();
1852
+ const buckets = new Map();
1853
+ let rowsScanned = 0;
1854
+ let total = 0;
1855
+ let pages = 0;
1856
+ for (let pageIndex = 0; rowsScanned < AGGREGATE_CAP; pageIndex += 1) {
1857
+ const response = await wireCall(session, { path: ENDPOINTS.runtimeQueryList, method: "POST", body: queryBody(AGGREGATE_PAGE_SIZE, pageIndex) });
1858
+ pages += 1;
1859
+ const pageData = extractBizObjectPage(response.data);
1860
+ if (pages === 1)
1861
+ total = pageData.total;
1862
+ if (pageData.content.length === 0)
1863
+ break;
1864
+ for (const row of pageData.content) {
1865
+ // 平台 query/list 无服务端列投影面:投影在本地做(只读这两列,其余不落内存)。
1866
+ const data = row.data && typeof row.data === "object" ? row.data : row;
1867
+ const value = aggregateNumeric(data[target]);
1868
+ let bucket;
1869
+ if (groupBy !== undefined) {
1870
+ const raw = data[groupBy];
1871
+ if (raw === null || raw === undefined)
1872
+ bucket = nullBucket;
1873
+ else {
1874
+ const key = String(raw);
1875
+ bucket = buckets.get(key);
1876
+ if (bucket === undefined) {
1877
+ bucket = emptyAcc();
1878
+ buckets.set(key, bucket);
1879
+ }
1880
+ }
1881
+ }
1882
+ for (const acc of bucket === undefined ? [overall] : [overall, bucket]) {
1883
+ acc.count += 1;
1884
+ if (value === null)
1885
+ continue;
1886
+ acc.nonNullCount += 1;
1887
+ acc.sum += value;
1888
+ if (value < acc.min)
1889
+ acc.min = value;
1890
+ if (value > acc.max)
1891
+ acc.max = value;
1892
+ }
1893
+ }
1894
+ rowsScanned += pageData.content.length;
1895
+ if (rowsScanned >= total)
1896
+ break;
1897
+ }
1898
+ const complete = rowsScanned >= total;
1899
+ const numericMetric = metric;
1900
+ const scanValue = (acc) => aggregateValue(numericMetric, acc.sum, acc.nonNullCount, acc.min, acc.max);
1901
+ const coverage = {
1902
+ mode: "local-scan",
1903
+ rowsScanned,
1904
+ cap: AGGREGATE_CAP,
1905
+ complete,
1906
+ ...(complete ? {} : { missingCount: Math.max(0, total - rowsScanned) }),
1907
+ };
1908
+ const capNotice = `数值列本地折叠:已扫前 ${rowsScanned}/${total} 行,${metric} 只覆盖已扫部分(complete:false,非全集)。要全集:filters 按日期/业务键 gte/lt 分片重跑,或 page/size 手动翻页。`;
1909
+ const wire = { calls: metaCalls + pages, plan: `1 metadata + ${pages} pages` };
1910
+ if (groupBy === undefined) {
1911
+ const value = scanValue(overall);
1912
+ return {
1913
+ schemaCode: args.schemaCode,
1914
+ metric,
1915
+ field: target,
1916
+ value,
1917
+ count: overall.count,
1918
+ nonNullCount: overall.nonNullCount,
1919
+ nullCount: overall.count - overall.nonNullCount,
1920
+ ...(value === null ? { note: "no numeric values in scanned rows" } : {}),
1921
+ coverage,
1922
+ filter: draftFilter,
1923
+ ...(complete ? {} : { capNotice }),
1924
+ wire,
1925
+ };
1926
+ }
1927
+ // 降序按 value(并列按 key);value:null(整桶无数值)排在最后,不参与排名。
1928
+ const ranked = [...buckets].map(([key, acc]) => ({ key, count: acc.count, nonNullCount: acc.nonNullCount, value: scanValue(acc) })).sort((left, right) => {
1929
+ if (left.value === null || right.value === null) {
1930
+ if (left.value === null && right.value === null)
1931
+ return left.key.localeCompare(right.key);
1932
+ return left.value === null ? 1 : -1;
1933
+ }
1934
+ return right.value - left.value || left.key.localeCompare(right.key);
1935
+ });
1936
+ const shown = ranked.slice(0, topN);
1937
+ return {
1938
+ schemaCode: args.schemaCode,
1939
+ metric,
1940
+ field: target,
1941
+ groupBy,
1942
+ total,
1943
+ buckets: shown,
1944
+ nullBucket: { count: nullBucket.count, nonNullCount: nullBucket.nonNullCount, value: scanValue(nullBucket) },
1945
+ truncatedBuckets: ranked.length > shown.length,
1946
+ bucketsTruncatedCount: ranked.length - shown.length,
1947
+ coverage,
1948
+ filter: draftFilter,
1949
+ ...(complete ? {} : { capNotice }),
1950
+ wire,
1951
+ };
1952
+ }
1725
1953
  // 1) 无 groupBy:service-total 精确计数(1 wire;带用户 filter 时 +1 元数据)。
1726
1954
  if (args.groupBy === undefined) {
1727
1955
  const total = await countAt();
@@ -1812,7 +2040,7 @@ export function registerRuntimeDataLane(tools) {
1812
2040
  }),
1813
2041
  wire: { calls: metaCalls + pages, plan: `${metaCalls > 0 ? "1 metadata + " : ""}${pages} pages` },
1814
2042
  };
1815
- }, { target: `data.aggregate:${JSON.stringify({ schemaCode: args.schemaCode, metric: args.metric, filter: args.filter, filters: args.filters, filterGroup: args.filterGroup, groupBy: args.groupBy, topN: args.topN ?? 10, includeDrafts: args.includeDrafts ?? null })}` });
2043
+ }, { 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 })}` });
1816
2044
  },
1817
2045
  }));
1818
2046
  tools.push(defineTool({
@@ -72,8 +72,8 @@ const READ_SHAPES = {
72
72
  },
73
73
  // r80:计数/分组统计的读回面。notes 只显首条——把陷阱并进第一句。
74
74
  "data.aggregate": {
75
- keys: ["schemaCode", "metric", "groupBy?", "total", "buckets:array<{key,count}>", "nullBucket:{count}", "truncatedBuckets", "bucketsTruncatedCount", "unaccountedCount?", "coverage:{mode,rowsScanned,cap,complete,missingCount?}", "filter:{draftPolicy,hint}", "wire:{calls,plan}", "capNotice?", "environmentFingerprint"],
76
- notes: ["计数用 total(服务端 totalElements,精确);分组是「值域×count」——buckets[].key 是字段存储值/code,null 单列 nullBucket;coverage.complete:false 时只覆盖已扫行,勿外推"],
75
+ keys: ["schemaCode", "metric", "field?", "value?", "count", "nonNullCount?", "nullCount?", "groupBy?", "total", "buckets:array<{key,count,nonNullCount?,value?}>", "nullBucket:{count,nonNullCount?,value?}", "truncatedBuckets", "bucketsTruncatedCount", "unaccountedCount?", "coverage:{mode,rowsScanned,cap,complete,missingCount?}", "filter:{draftPolicy,hint}", "wire:{calls,plan}", "capNotice?", "note?", "environmentFingerprint"],
76
+ notes: ["计数用 total(服务端 totalElements,精确);分组是「值域×count」——buckets[].key 是字段存储值/code,null 单列 nullBucket;数值指标(metric=sum/avg/min/max+field)是本地折叠(cap 1000,null 行不进聚合、avg 分母排除 null),coverage.complete:false 时只覆盖已扫行,勿外推"],
77
77
  },
78
78
  "app.list": {
79
79
  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.78",
3
+ "version": "0.6.79",
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.78",
59
+ "omc-core": "0.6.79",
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.78"
77
+ "@stalfh233/omc-fake-platform": "0.6.79"
78
78
  }
79
79
  }