niceeval 0.6.2 → 0.7.1

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.
Files changed (218) hide show
  1. package/INDEX.md +23 -23
  2. package/README.zh.md +6 -6
  3. package/dist/agents/types.d.ts +2 -2
  4. package/dist/i18n/zh-CN.d.ts +3 -3
  5. package/dist/report/aggregate.d.ts +32 -26
  6. package/dist/report/aggregate.js +157 -76
  7. package/dist/report/built-in/index.d.ts +2 -0
  8. package/dist/report/built-in/index.js +8 -0
  9. package/dist/report/components.d.ts +91 -164
  10. package/dist/report/components.js +377 -114
  11. package/dist/report/compute.d.ts +86 -73
  12. package/dist/report/compute.js +592 -432
  13. package/dist/report/flag.d.ts +28 -17
  14. package/dist/report/flag.js +86 -16
  15. package/dist/report/format.d.ts +11 -11
  16. package/dist/report/format.js +17 -15
  17. package/dist/report/index.d.ts +16 -17
  18. package/dist/report/index.js +20 -22
  19. package/dist/report/load.js +3 -2
  20. package/dist/report/locale.d.ts +49 -34
  21. package/dist/report/locale.js +106 -58
  22. package/dist/report/metrics.d.ts +10 -3
  23. package/dist/report/metrics.js +46 -12
  24. package/dist/report/primitives.d.ts +42 -15
  25. package/dist/report/primitives.js +135 -26
  26. package/dist/report/react/AttemptList.d.ts +10 -8
  27. package/dist/report/react/AttemptList.js +18 -10
  28. package/dist/report/react/DeltaTable.js +19 -18
  29. package/dist/report/react/EvalList.d.ts +3 -3
  30. package/dist/report/react/EvalList.js +0 -0
  31. package/dist/report/react/ExperimentComparison.d.ts +4 -2
  32. package/dist/report/react/ExperimentComparison.js +5 -4
  33. package/dist/report/react/ExperimentList.d.ts +3 -3
  34. package/dist/report/react/ExperimentList.js +16 -15
  35. package/dist/report/react/MetricBars.js +5 -4
  36. package/dist/report/react/MetricLine.js +12 -5
  37. package/dist/report/react/MetricMatrix.js +1 -1
  38. package/dist/report/react/MetricScatter.js +54 -17
  39. package/dist/report/react/MetricTable.js +2 -12
  40. package/dist/report/react/ScopeSummary.d.ts +10 -0
  41. package/dist/report/react/ScopeSummary.js +17 -0
  42. package/dist/report/react/Scoreboard.js +6 -6
  43. package/dist/report/react/cell.js +2 -2
  44. package/dist/report/react/fixtures.d.ts +5 -9
  45. package/dist/report/react/fixtures.js +105 -149
  46. package/dist/report/react/index.d.ts +15 -5
  47. package/dist/report/react/index.js +18 -7
  48. package/dist/report/report.d.ts +137 -20
  49. package/dist/report/report.js +261 -34
  50. package/dist/report/text/faces.d.ts +17 -19
  51. package/dist/report/text/faces.js +225 -157
  52. package/dist/report/text/plot.js +1 -1
  53. package/dist/report/text/table.js +2 -2
  54. package/dist/report/tree.d.ts +90 -40
  55. package/dist/report/tree.js +252 -94
  56. package/dist/report/types.d.ts +245 -300
  57. package/dist/report/types.js +4 -3
  58. package/dist/report/web.d.ts +21 -5
  59. package/dist/report/web.js +42 -16
  60. package/dist/results/select.d.ts +38 -16
  61. package/dist/results/select.js +73 -25
  62. package/dist/results/types.d.ts +38 -14
  63. package/dist/shared/aggregate.d.ts +3 -2
  64. package/dist/shared/aggregate.js +5 -4
  65. package/docs-site/zh/README.md +44 -0
  66. package/docs-site/zh/examples/ai-agent-application.mdx +63 -0
  67. package/docs-site/zh/examples/coding-agent-extensions.mdx +57 -0
  68. package/docs-site/zh/examples/index.mdx +50 -0
  69. package/docs-site/zh/{concepts → explanation}/adapter.mdx +11 -11
  70. package/docs-site/zh/{concepts → explanation}/assert.mdx +7 -7
  71. package/docs-site/zh/{concepts → explanation}/drive.mdx +8 -8
  72. package/docs-site/zh/{concepts → explanation}/evals.mdx +4 -4
  73. package/docs-site/zh/{concepts → explanation}/experiment.mdx +8 -8
  74. package/docs-site/zh/{concepts → explanation}/hitl.mdx +8 -8
  75. package/docs-site/zh/{concepts → explanation}/judge.mdx +5 -5
  76. package/docs-site/zh/{concepts → explanation}/overview.mdx +5 -5
  77. package/docs-site/zh/{guides → explanation}/runner.mdx +1 -1
  78. package/docs-site/zh/{concepts → explanation}/tier.mdx +6 -6
  79. package/docs-site/zh/{guides → how-to}/agent-feedback-loop.mdx +7 -7
  80. package/docs-site/zh/{guides → how-to}/authoring.mdx +2 -2
  81. package/docs-site/zh/{guides → how-to}/connect-otel.mdx +6 -6
  82. package/docs-site/zh/{guides → how-to}/connect-your-agent.mdx +18 -18
  83. package/docs-site/zh/{guides → how-to}/custom-reports.mdx +6 -6
  84. package/docs-site/zh/{guides → how-to}/experiments.mdx +3 -3
  85. package/docs-site/zh/{guides → how-to}/publish-report.mdx +2 -2
  86. package/docs-site/zh/{guides → how-to}/sandbox-agent.mdx +2 -2
  87. package/docs-site/zh/{guides → how-to}/sandbox-providers.mdx +1 -1
  88. package/docs-site/zh/{guides → how-to}/viewing-results.mdx +6 -6
  89. package/docs-site/zh/{guides → how-to}/write-experiment.mdx +3 -3
  90. package/docs-site/zh/{guides → how-to}/write-send.mdx +13 -13
  91. package/docs-site/zh/index.mdx +23 -25
  92. package/docs-site/zh/introduction.mdx +8 -8
  93. package/docs-site/zh/reference/builtin-agents.mdx +5 -5
  94. package/docs-site/zh/reference/capabilities.mdx +6 -6
  95. package/docs-site/zh/reference/cli.mdx +9 -7
  96. package/docs-site/zh/reference/define-agent.mdx +1 -1
  97. package/docs-site/zh/reference/events.mdx +3 -3
  98. package/docs-site/zh/{guides → reference}/official-adapters.mdx +7 -7
  99. package/docs-site/zh/{guides → reference}/report-components.mdx +5 -5
  100. package/docs-site/zh/{guides → reference}/results-data.mdx +5 -5
  101. package/docs-site/zh/{guides → troubleshooting}/debug-sandbox.mdx +2 -2
  102. package/docs-site/zh/{guides → troubleshooting}/debugging.mdx +4 -2
  103. package/docs-site/zh/{quickstart.mdx → tutorials/quickstart.mdx} +5 -17
  104. package/package.json +6 -2
  105. package/src/agents/index.ts +2 -2
  106. package/src/agents/openai-compat.ts +1 -1
  107. package/src/agents/streaming.ts +2 -2
  108. package/src/agents/types.ts +3 -3
  109. package/src/cli.ts +42 -23
  110. package/src/context/context.ts +1 -1
  111. package/src/context/session.test.ts +1 -1
  112. package/src/context/session.ts +1 -1
  113. package/src/i18n/en.ts +18 -16
  114. package/src/i18n/zh-CN.ts +16 -15
  115. package/src/report/aggregate.ts +175 -87
  116. package/src/report/built-in/index.tsx +9 -0
  117. package/src/report/components.tsx +625 -285
  118. package/src/report/compute.ts +717 -515
  119. package/src/report/dual-render.test.tsx +738 -1148
  120. package/src/report/flag.ts +97 -33
  121. package/src/report/format.ts +18 -22
  122. package/src/report/index.ts +113 -58
  123. package/src/report/load.ts +3 -2
  124. package/src/report/locale.ts +120 -69
  125. package/src/report/metrics.ts +42 -12
  126. package/src/report/primitives.tsx +190 -45
  127. package/src/report/react/AttemptList.tsx +32 -20
  128. package/src/report/react/DeltaTable.tsx +63 -45
  129. package/src/report/react/EvalList.tsx +0 -0
  130. package/src/report/react/ExperimentComparison.tsx +12 -7
  131. package/src/report/react/ExperimentList.tsx +38 -26
  132. package/src/report/react/MetricBars.tsx +5 -4
  133. package/src/report/react/MetricLine.tsx +13 -8
  134. package/src/report/react/MetricMatrix.tsx +2 -2
  135. package/src/report/react/MetricScatter.tsx +74 -20
  136. package/src/report/react/MetricTable.tsx +4 -76
  137. package/src/report/react/ScopeSummary.tsx +86 -0
  138. package/src/report/react/Scoreboard.tsx +28 -10
  139. package/src/report/react/cell.tsx +2 -2
  140. package/src/report/react/enhance.js +57 -5
  141. package/src/report/react/fixtures.ts +109 -156
  142. package/src/report/react/index.tsx +24 -39
  143. package/src/report/react/render.test.tsx +139 -104
  144. package/src/report/react/styles.css +181 -91
  145. package/src/report/report.test.ts +761 -1031
  146. package/src/report/report.ts +425 -47
  147. package/src/report/text/faces.ts +257 -164
  148. package/src/report/text/plot.ts +1 -1
  149. package/src/report/text/table.ts +2 -2
  150. package/src/report/tree.ts +362 -104
  151. package/src/report/types.ts +257 -287
  152. package/src/report/web.ts +63 -20
  153. package/src/results/attempt-evidence.test.ts +4 -4
  154. package/src/results/attempt-evidence.ts +5 -5
  155. package/src/results/copy.ts +6 -6
  156. package/src/results/host-equivalence.test.ts +26 -14
  157. package/src/results/index.ts +10 -4
  158. package/src/results/open.ts +8 -4
  159. package/src/results/results.test.ts +4 -3
  160. package/src/results/select.ts +104 -34
  161. package/src/results/types.ts +36 -14
  162. package/src/runner/feedback/human.test.ts +1 -1
  163. package/src/runner/run.ts +1 -1
  164. package/src/sandbox/cli-commands.ts +2 -2
  165. package/src/scoring/judge.test.ts +1 -1
  166. package/src/shared/aggregate.ts +5 -4
  167. package/src/show/compose.ts +50 -67
  168. package/src/show/index.ts +107 -56
  169. package/src/show/render.ts +43 -27
  170. package/src/show/report-host.test.ts +188 -0
  171. package/src/show/report-host.ts +375 -0
  172. package/src/show/show.test.ts +86 -36
  173. package/src/view/app/App.test.tsx +69 -0
  174. package/src/view/app/App.tsx +144 -48
  175. package/src/view/app/components/AttemptModal.tsx +324 -63
  176. package/src/view/app/components/CodeView.tsx +10 -4
  177. package/src/view/app/i18n.ts +31 -17
  178. package/src/view/app/lib/artifact-url.ts +14 -3
  179. package/src/view/app/main.tsx +13 -8
  180. package/src/view/app/pages/{RunsPage.tsx → AttemptsPage.tsx} +6 -6
  181. package/src/view/app/types.ts +4 -1
  182. package/src/view/artifact-serving.test.ts +21 -1
  183. package/src/view/client-dist/app.css +1 -1
  184. package/src/view/client-dist/app.js +6 -6
  185. package/src/view/data.test.ts +9 -3
  186. package/src/view/data.ts +145 -49
  187. package/src/view/index.ts +48 -44
  188. package/src/view/server.ts +35 -15
  189. package/src/view/shared/types.ts +34 -5
  190. package/src/view/styles.css +224 -0
  191. package/src/view/view-report.test.ts +161 -57
  192. package/dist/report/built-ins/experiment-comparison.d.ts +0 -39
  193. package/dist/report/built-ins/experiment-comparison.js +0 -119
  194. package/dist/report/built-ins/index.d.ts +0 -2
  195. package/dist/report/built-ins/index.js +0 -2
  196. package/dist/report/react/GroupSummary.d.ts +0 -8
  197. package/dist/report/react/GroupSummary.js +0 -8
  198. package/dist/report/react/RunOverview.d.ts +0 -8
  199. package/dist/report/react/RunOverview.js +0 -12
  200. package/docs-site/zh/example/ai-agent-application.mdx +0 -152
  201. package/docs-site/zh/example/claude-code-codex-plugin.mdx +0 -167
  202. package/docs-site/zh/example/claude-code-codex-skill.mdx +0 -152
  203. package/docs-site/zh/example/showcase.mdx +0 -39
  204. package/src/report/built-in-user-parity.test.tsx +0 -597
  205. package/src/report/built-ins/experiment-comparison.tsx +0 -179
  206. package/src/report/built-ins/index.ts +0 -7
  207. package/src/report/react/GroupSummary.tsx +0 -66
  208. package/src/report/react/RunOverview.tsx +0 -109
  209. /package/docs-site/zh/{example/tier1-ai-sdk-v7.mdx → examples/integrations/ai-sdk-v7.mdx} +0 -0
  210. /package/docs-site/zh/{example/tier1-claude-sdk.mdx → examples/integrations/claude-sdk.mdx} +0 -0
  211. /package/docs-site/zh/{example/tier1-codex-sdk.mdx → examples/integrations/codex-sdk.mdx} +0 -0
  212. /package/docs-site/zh/{example/tier1-langgraph.mdx → examples/integrations/langgraph.mdx} +0 -0
  213. /package/docs-site/zh/{example/tier1-pi-sdk.mdx → examples/integrations/pi-sdk.mdx} +0 -0
  214. /package/docs-site/zh/{guides → how-to}/ci-integration.mdx +0 -0
  215. /package/docs-site/zh/{guides → how-to}/dataset-fanout.mdx +0 -0
  216. /package/docs-site/zh/{guides → how-to}/fixtures.mdx +0 -0
  217. /package/docs-site/zh/{guides → how-to}/reporters.mdx +0 -0
  218. /package/docs-site/zh/{guides → how-to}/scoring-guide.mdx +0 -0
@@ -1,42 +1,49 @@
1
- // 计算函数:Selection → 一份组件数据。跑在 Node 侧,产物是算好的、可序列化的普通 JSON
2
- // (终值 + 渲染提示,不含公式);渲染面(web/text)只做展示。
3
- //
4
- // 这些函数不做顶层导出,而是挂在对应组件上(MetricTable.data / Scoreboard.data …,
5
- // 见 components.tsx):配对打点即发现,泛化名不占顶层导出。
1
+ // 计算函数(*Data):ReportInput → 一份组件数据。跑在 Node 侧,产物是算好的、可序列化的
2
+ // 普通 JSON(终值 + 渲染提示,不含公式);渲染面(web/text)只做展示。
3
+ // 它们是双面组件解析面的具名形式(MetricTable / metricTableData),与组件成对导出,
4
+ // 只住在 niceeval/report(docs/feature/reports/library.md「数据计算与缓存边界」)。
6
5
  //
7
6
  // 共同约定(docs/feature/reports/architecture.md「指标聚合不变量」):
8
- // - 第一参收 Selection | Snapshot[];收 Selection 时 warnings 随行进 OverviewData;
7
+ // - 第一参收 ReportInput = Scope | readonly Snapshot[];warnings 不进组件数据(宿主统一显示);
9
8
  // - 聚合前按身份键去重(dedupeAttempts;missing-startedAt 不去重、如实保留、不透出警告);
10
9
  // - null ≠ 0:缺数据不编数,覆盖率经 samples/total 如实暴露;
10
+ // - 显式传入的列表(questions / pairs / metrics)保留声明顺序,从数据发现的维度 domain
11
+ // 按稳定 key 字典序;
11
12
  // - core 中立:只认 Metric / Dimension 接口,不出现具体 agent 名的分支。
12
13
 
13
14
  import type {
14
15
  AttemptListItem,
15
16
  AttemptLocator,
16
- AxisInput,
17
17
  DeltaData,
18
+ DeltaPair,
18
19
  DimensionInput,
20
+ EntityListDataOptions,
19
21
  EvalListItem,
22
+ ExperimentComparisonData,
23
+ ExperimentComparisonGroupData,
20
24
  ExperimentListEvalRow,
21
25
  ExperimentListItem,
22
- GroupSummaryData,
26
+ FlagPairs,
23
27
  LineData,
24
28
  MatrixData,
25
29
  Metric,
26
30
  MetricCell,
27
- OverviewData,
31
+ NumericAxis,
32
+ ReportInput,
28
33
  ScatterData,
34
+ ScopeSummaryData,
29
35
  ScoreboardData,
30
36
  TableData,
31
- TableRowMeta,
37
+ VerdictTally,
32
38
  } from "./types.ts";
33
- import type { AssertionResult, AttemptError, DiagnosticRecord, EvalResult } from "../types.ts";
34
- import type { AttemptHandle } from "../results/types.ts";
39
+ import type { EvalResult, JsonValue } from "../types.ts";
40
+ import type { Snapshot } from "../results/types.ts";
41
+ import { comparabilityConfigOf, deepEqualJson } from "../results/select.ts";
35
42
  import { evalLevelStats, foldEvalVerdict } from "../shared/verdict.ts";
43
+ import { experimentGroupOf } from "../shared/aggregate.ts";
36
44
  import {
37
- applyAggregator,
38
45
  assertUniqueMetricNames,
39
- axisValue,
46
+ axisValueOf,
40
47
  collectItems,
41
48
  computeCell,
42
49
  dimensionKey,
@@ -44,291 +51,190 @@ import {
44
51
  displayValue,
45
52
  evalGroupOf,
46
53
  evalIdOf,
47
- evalPrefixPredicate,
48
54
  evaluateMetric,
49
55
  experimentIdOf,
50
56
  filterItems,
57
+ fullEvalKey,
51
58
  groupItems,
52
59
  locatorOf,
60
+ refDisplayKey,
53
61
  resolveInput,
54
62
  snapshotKeyOf,
55
63
  toColumn,
56
64
  type Item,
57
- type SnapshotsInput,
58
65
  } from "./aggregate.ts";
59
66
  import { attemptCostUSD, costUSD, durationMs, endToEndPassRate, examScore, tokens } from "./metrics.ts";
60
- import { formatMetricValue, formatPlainNumber } from "./format.ts";
61
- import { compactAssertionSummary, primaryAssertionSummary } from "../scoring/display.ts";
67
+ import { formatMetricValue, formatPlainNumber, localizedDisplay } from "./format.ts";
68
+ import { compactAssertionSummary, primaryAssertionSummary, summaryText } from "../scoring/display.ts";
69
+ import { defineMetric } from "./metrics.ts";
70
+ import type { LocalizedText } from "./locale.ts";
62
71
 
63
- // ───────────────────────── MetricTable.data ─────────────────────────
72
+ // ───────────────────────── metricTableData ─────────────────────────
64
73
 
65
- export interface TableDataOptions<M extends readonly Metric[]> {
66
- /** 行维度(内置 / 自定义 / flag())。 */
74
+ export interface MetricTableOptions {
75
+ /** 行维度(内置 / 自定义 / flag() / runConfig())。 */
67
76
  rows: DimensionInput;
68
- /** 每列一个指标;列键 = metric.name 的字面量,拼错编译不过。 */
69
- columns: M;
70
- /** 构建时排序,方向随 better(higher 降序,「好」的一头在上);缺数据行沉底。两面同口径,预排即终排。 */
77
+ /** 每列一个指标;非空元组,元素是静态 import Metric 实例。 */
78
+ columns: readonly [Metric, ...Metric[]];
79
+ /**
80
+ * 初始行序:必须是 columns 中同一个 Metric 实例且声明了 better,方向随 better
81
+ * (「好」的一头在上),缺数据行沉底;省略时按行 key 字典序。
82
+ */
71
83
  sort?: Metric;
72
- /** eval id 前缀过滤,同 CLI 位置参数语义。 */
73
- evals?: string | string[];
84
+ /** eval id 前缀过滤,同 CLI 位置参数语义;在聚合之前收窄题集。 */
85
+ evals?: string | readonly string[];
74
86
  }
75
87
 
76
- // 一组 Item eval 全身份键:experimentId + eval id。单 experiment 场景(如 experimentRowMeta,
77
- // 一组本就只有一个 experimentId)下退化为只按 eval id 折叠,与旧行为一致;多 experiment 场景
78
- // (GroupSummary 的组可能跨多个 experiment)下避免两个 experiment 里同名 eval 被误合并成一道题。
79
- // 分隔符是 NUL(同 aggregate.ts 的 KEY_SEP 手法):不会出现在 eval id / experimentId 里,拼接键不串味。
80
- const GROUP_KEY_SEP = "\u0000";
81
- function fullEvalKey(item: Item): string {
82
- return `${experimentIdOf(item)}${GROUP_KEY_SEP}${evalIdOf(item)}`;
83
- }
84
-
85
- /**
86
- * 一批 Item 的组级统计:eval 级折叠计票(evalLevelStats,与 view 榜单 / `TableRowMeta.verdicts`
87
- * 同一套 foldEvalVerdict 口径,按完整身份键折叠)、experiment/eval/attempt 数量、总成本
88
- * (null-safe 求和)、最后运行时间(组内快照 startedAt 的最大值)。`experimentRowMeta`
89
- * `groupSummaryData` 共用这一份实现,不各自拼装 evalLevelStats。
90
- *
91
- * 内部纯函数,不导出、不进 index.ts:对外只经 `experimentRowMeta`(挑 verdicts)与
92
- * `groupSummaryData`(挑全部字段,包成 `GroupSummaryData`)暴露,调用方拿不到 `Item[]`
93
- * 本身,所以这里也不用担心被越权复用。
94
- */
95
- function summarizeItems(items: Item[]): {
96
- experiments: number;
97
- evals: number;
98
- attempts: number;
99
- verdicts: { passed: number; failed: number; errored: number; skipped: number };
100
- /** 折叠后代表每个「已跑」(非 skipped)eval 的一条 attempt 引用,与 ran 同序同数。 */
101
- refs: AttemptLocator[];
102
- /** 计入通过率分母的 eval 数(passed + failed + errored,不含 skipped)。 */
103
- ran: number;
104
- totalCostUSD: number | null;
105
- lastRunAt: string | undefined;
106
- } {
107
- const experimentIds = new Set<string>();
108
- for (const item of items) experimentIds.add(experimentIdOf(item));
109
-
110
- const byEval = new Map<string, Item[]>();
111
- for (const item of items) {
112
- const key = fullEvalKey(item);
113
- const list = byEval.get(key);
114
- if (list) list.push(item);
115
- else byEval.set(key, [item]);
116
- }
117
- const stats = evalLevelStats(
118
- items.map((item) => ({ verdict: item.attempt.result.verdict, key: fullEvalKey(item) })),
119
- (r) => r.key,
120
- );
121
- // 折叠代表 attempt:每个已跑的 eval 挑一条与折叠判定一致的 attempt 做证据引用,
122
- // skipped 的 eval 不进分母、不出证据。
123
- const refs: AttemptLocator[] = [];
124
- for (const group of byEval.values()) {
125
- const verdict = foldEvalVerdict(group.map((item) => item.attempt.result));
126
- if (verdict === "skipped") continue;
127
- const rep = group.find((item) => item.attempt.result.verdict === verdict) ?? group[0]!;
128
- refs.push(locatorOf(rep));
129
- }
130
-
131
- let totalCostUSD: number | null = null;
132
- for (const item of items) {
133
- const cost = attemptCostUSD(item.attempt.result);
134
- if (cost !== null) totalCostUSD = (totalCostUSD ?? 0) + cost;
135
- }
136
-
137
- let lastRunAt: string | undefined;
138
- for (const item of items) {
139
- const startedAt = item.snapshot.startedAt;
140
- if (lastRunAt === undefined || startedAt > lastRunAt) lastRunAt = startedAt;
88
+ export async function metricTableData(input: ReportInput, options: MetricTableOptions): Promise<TableData> {
89
+ assertUniqueMetricNames(options.columns, "metricTableData columns");
90
+ if (options.sort !== undefined) {
91
+ if (!options.columns.includes(options.sort)) {
92
+ throw new Error(
93
+ `metricTableData sort must be one of the Metric instances passed in columns (got "${options.sort.name}"). ` +
94
+ "Pass the same imported instance in both places so the sorted column is visible in the table.",
95
+ );
96
+ }
97
+ if (options.sort.better === undefined) {
98
+ throw new Error(
99
+ `metricTableData cannot sort by "${options.sort.name}": the metric declares no "better" direction, so there is no defined order. ` +
100
+ 'Declare better: "higher" | "lower" on the metric, or drop sort to keep the lexicographic row order.',
101
+ );
102
+ }
141
103
  }
142
-
143
- return {
144
- experiments: experimentIds.size,
145
- evals: stats.evals,
146
- attempts: items.length,
147
- verdicts: { passed: stats.passed, failed: stats.failed, errored: stats.errored, skipped: stats.skipped },
148
- refs,
149
- ran: stats.passed + stats.failed + stats.errored,
150
- totalCostUSD,
151
- lastRunAt,
152
- };
153
- }
154
-
155
- /**
156
- * experiment 行的元信息:agent/model 身份(组内去重后拼接)+ eval 级折叠计票 + eval/attempt
157
- * 数量与最后运行时间(summarizeItems,即 view 榜单 / ExperimentList 的同一套 foldEvalVerdict
158
- * 口径)。其它行维度(agent/eval/自定义…)没有唯一身份,不携带。
159
- */
160
- function experimentRowMeta(group: Item[]): TableRowMeta {
161
- const agents = new Set<string>();
162
- const models = new Set<string>();
163
- for (const item of group) {
164
- agents.add(item.attempt.result.agent);
165
- const model = item.attempt.result.model ?? item.snapshot.model;
166
- if (model !== undefined) models.add(model);
167
- }
168
- const stats = summarizeItems(group);
169
- return {
170
- ...(agents.size > 0 ? { agent: [...agents].join(", ") } : {}),
171
- ...(models.size > 0 ? { model: [...models].join(", ") } : {}),
172
- verdicts: stats.verdicts,
173
- evals: stats.evals,
174
- attempts: stats.attempts,
175
- ...(stats.lastRunAt !== undefined ? { lastRunAt: stats.lastRunAt } : {}),
176
- };
177
- }
178
-
179
- /** 一次 attempt 的有界结果摘要:error → skipReason → 一条主失败断言 + 其余失败计数。 */
180
- export function reasonFor(result: EvalResult): string | undefined {
181
- if (result.error !== undefined) return result.error.message;
182
- if (result.skipReason !== undefined) return result.skipReason;
183
- const summary = primaryAssertionSummary(result.assertions, result.verdict);
184
- return summary === undefined ? undefined : compactAssertionSummary(summary);
185
- }
186
-
187
- export async function tableData<const M extends readonly Metric[]>(
188
- input: SnapshotsInput,
189
- opts: TableDataOptions<M>,
190
- ): Promise<TableData<M[number]["name"]>> {
191
- assertUniqueMetricNames(opts.columns, "MetricTable.data columns");
192
104
  const { snapshots } = resolveInput(input);
193
- const items = filterItems(collectItems(snapshots), opts.evals);
194
- const groups = groupItems(items, opts.rows);
105
+ const items = filterItems(collectItems(snapshots), options.evals);
106
+ const groups = groupItems(items, options.rows);
195
107
  const rows: TableData["rows"] = [];
196
- const sortCells = new Map<string, MetricCell>();
197
108
  for (const [key, group] of groups) {
198
109
  const cells: Record<string, MetricCell> = {};
199
- for (const metric of opts.columns) cells[metric.name] = await computeCell(metric, group);
200
- if (opts.sort) {
201
- // sort 指标不在 columns 里时单独算一遍,只用于排序、不进输出
202
- sortCells.set(key, cells[opts.sort.name] ?? (await computeCell(opts.sort, group)));
203
- }
204
- const meta: TableRowMeta = opts.rows === "experiment" ? experimentRowMeta(group) : {};
205
- rows.push({
206
- key,
207
- cells,
208
- ...(Object.keys(meta).length > 0 ? { meta } : {}),
209
- });
110
+ for (const metric of options.columns) cells[metric.name] = await computeCell(metric, group);
111
+ rows.push({ key, cells });
210
112
  }
211
- if (opts.sort) {
212
- const better = opts.sort.better ?? "higher";
113
+ if (options.sort) {
114
+ const better = options.sort.better ?? "higher";
115
+ const name = options.sort.name;
213
116
  rows.sort((a, b) => {
214
- const va = sortCells.get(a.key)?.value ?? null;
215
- const vb = sortCells.get(b.key)?.value ?? null;
216
- if (va === null && vb === null) return 0;
117
+ const va = a.cells[name]?.value ?? null;
118
+ const vb = b.cells[name]?.value ?? null;
119
+ if (va === null && vb === null) return a.key < b.key ? -1 : a.key > b.key ? 1 : 0;
217
120
  if (va === null) return 1; // 缺数据沉底
218
121
  if (vb === null) return -1;
219
- return better === "lower" ? va - vb : vb - va;
122
+ const diff = better === "lower" ? va - vb : vb - va;
123
+ if (diff !== 0) return diff;
124
+ return a.key < b.key ? -1 : a.key > b.key ? 1 : 0; // 稳定排序,同值以 key 收口
220
125
  });
221
126
  }
222
127
  return {
223
- dimension: dimensionName(opts.rows),
224
- columns: opts.columns.map(toColumn),
128
+ rowDimension: dimensionName(options.rows),
129
+ columns: options.columns.map(toColumn),
225
130
  rows,
226
- } as TableData<M[number]["name"]>;
131
+ };
227
132
  }
228
133
 
229
- // ───────────────────────── ExperimentList.data / EvalList.data / AttemptList.data ─────────────────────────
230
- //
231
- // 三个实体列表逐级下钻(experiment experimentId × eval → attempt),固定展示实体事实,
232
- // 没有列配置;过滤是报告作者对返回数组调用 .filter()/.slice() 的事,不进这里
233
- // (docs/feature/reports/library.md「实体列表」)。AttemptListItem 是三者共用的叶子形状——
234
- // ExperimentList / EvalList 的下钻数组直接复用它,不各自精简一份。
235
-
236
- /** 自由文本(断言 detail / evidence)的展示层遮蔽钩子;身份字段(name/severity/loc)不经它。 */
237
- function redactAssertions(assertions: AssertionResult[], redact: (text: string) => string): AssertionResult[] {
238
- if (assertions.length === 0) return assertions;
239
- return assertions.map((a) => ({
240
- ...a,
241
- ...(a.detail !== undefined ? { detail: redact(a.detail) } : {}),
242
- ...(a.outcome !== "unavailable" && a.evidence !== undefined ? { evidence: redact(a.evidence) } : {}),
243
- ...(a.outcome !== "unavailable" && a.expected !== undefined ? { expected: redact(a.expected) } : {}),
244
- ...(a.outcome !== "unavailable" && a.received !== undefined ? { received: redact(a.received) } : {}),
245
- }));
134
+ // ───────────────────────── metricMatrixData(= MetricBars 的数据)─────────────────────────
135
+
136
+ export interface MetricMatrixOptions {
137
+ rows: DimensionInput;
138
+ columns: DimensionInput;
139
+ cell: Metric;
140
+ /** eval id 前缀过滤,同 CLI 位置参数语义。 */
141
+ evals?: string | readonly string[];
246
142
  }
247
143
 
248
- /**
249
- * 结构化 error 的遮蔽:message / stack / cause.message 是自由文本,经钩子;
250
- * code / operation / cause.name / cause.code 是分类与身份字段,原样保留
251
- * (与 copySnapshots({ redact }) 的改写范围约定一致)。
252
- */
253
- function redactError(error: AttemptError, redact: (text: string) => string): AttemptError {
144
+ export async function metricMatrixData(input: ReportInput, options: MetricMatrixOptions): Promise<MatrixData> {
145
+ const { snapshots } = resolveInput(input);
146
+ const items = filterItems(collectItems(snapshots), options.evals);
147
+ // 稀疏分组:只有真有 attempt (row, column) 组合成格;没有样本的格子不出现
148
+ const groups = new Map<string, { row: string; column: string; items: Item[] }>();
149
+ for (const item of items) {
150
+ const row = dimensionKey(options.rows, item);
151
+ const column = dimensionKey(options.columns, item);
152
+ const key = JSON.stringify([row, column]);
153
+ const group = groups.get(key);
154
+ if (group) group.items.push(item);
155
+ else groups.set(key, { row, column, items: [item] });
156
+ }
157
+ const ordered = [...groups.values()].sort(
158
+ (a, b) => (a.row < b.row ? -1 : a.row > b.row ? 1 : a.column < b.column ? -1 : a.column > b.column ? 1 : 0),
159
+ );
160
+ const cells: MatrixData["cells"] = [];
161
+ for (const group of ordered) {
162
+ cells.push({ row: group.row, column: group.column, cell: await computeCell(options.cell, group.items) });
163
+ }
254
164
  return {
255
- ...error,
256
- message: redact(error.message),
257
- ...(error.stack !== undefined ? { stack: redact(error.stack) } : {}),
258
- ...(error.cause !== undefined ? { cause: { ...error.cause, message: redact(error.cause.message) } } : {}),
165
+ rowDimension: dimensionName(options.rows),
166
+ columnDimension: dimensionName(options.columns),
167
+ metric: toColumn(options.cell),
168
+ cells,
259
169
  };
260
170
  }
261
171
 
262
- /** JsonValue 树里逐个字符串值经钩子;结构与非字符串标量原样。 */
263
- function redactJsonValue<T>(value: T, redact: (text: string) => string): T {
264
- if (typeof value === "string") return redact(value) as unknown as T;
265
- if (Array.isArray(value)) return value.map((v) => redactJsonValue(v, redact)) as unknown as T;
266
- if (typeof value === "object" && value !== null) {
267
- return Object.fromEntries(
268
- Object.entries(value).map(([k, v]) => [k, redactJsonValue(v, redact)]),
269
- ) as unknown as T;
172
+ // ───────────────────────── 实体列表(experimentListData / evalListData / attemptListData)─────────────────────────
173
+
174
+ /**
175
+ * 一次 attempt 的单行结果摘要(Scoring display 契约):failed 取主失败断言摘要(不含
176
+ * "+N more",N 单独进 moreFailures),errored 取结构化 error 的一层摘要
177
+ * (phase · code · message),passed / skipped 为 null。
178
+ */
179
+ function failureSummaryOf(result: EvalResult): { summary: string | null; more: number } {
180
+ if (result.verdict === "errored" && result.error !== undefined) {
181
+ const parts = [result.error.phase, result.error.code, result.error.message].filter(
182
+ (part): part is string => typeof part === "string" && part.length > 0,
183
+ );
184
+ return { summary: summaryText(parts.join(" · ")), more: 0 };
270
185
  }
271
- return value;
186
+ if (result.verdict === "failed" || result.verdict === "errored") {
187
+ const primary = primaryAssertionSummary(result.assertions, result.verdict);
188
+ if (primary !== undefined) {
189
+ return {
190
+ summary: compactAssertionSummary({ ...primary, additionalFailures: 0 }),
191
+ more: primary.additionalFailures,
192
+ };
193
+ }
194
+ if (result.verdict === "errored" && result.skipReason !== undefined) {
195
+ return { summary: summaryText(result.skipReason), more: 0 };
196
+ }
197
+ return { summary: null, more: 0 };
198
+ }
199
+ return { summary: null, more: 0 };
272
200
  }
273
201
 
274
- /** diagnostics 的遮蔽:message data(自由内容)经钩子;code / operation / level / count 原样。 */
275
- function redactDiagnostics(
276
- diagnostics: readonly DiagnosticRecord[],
277
- redact: (text: string) => string,
278
- ): DiagnosticRecord[] {
279
- return diagnostics.map((d) => ({
280
- ...d,
281
- message: redact(d.message),
282
- ...(d.data !== undefined ? { data: redactJsonValue(d.data, redact) } : {}),
283
- }));
284
- }
202
+ const identityRedact = (text: string): string => text;
285
203
 
286
204
  /** AttemptList / ExperimentList / EvalList 共用的叶子构造:一个 Item → 一个 AttemptListItem。 */
287
- function attemptListItemOf(item: Item, redact: (text: string) => string): AttemptListItem {
205
+ async function attemptListItemOf(item: Item, redact: (text: string) => string): Promise<AttemptListItem> {
288
206
  const result = item.attempt.result;
289
- const cost = attemptCostUSD(result);
207
+ const { summary, more } = failureSummaryOf(result);
290
208
  return {
291
- evalId: evalIdOf(item),
292
209
  experimentId: experimentIdOf(item),
210
+ evalId: evalIdOf(item),
293
211
  attempt: result.attempt,
294
212
  agent: result.agent,
295
213
  verdict: result.verdict,
296
- ...(result.error !== undefined ? { error: redactError(result.error, redact) } : {}),
297
- ...(result.diagnostics !== undefined && result.diagnostics.length > 0
298
- ? { diagnostics: redactDiagnostics(result.diagnostics, redact) }
299
- : {}),
300
- assertions: redactAssertions(result.assertions, redact),
214
+ failureSummary: summary === null ? null : redact(summary),
215
+ moreFailures: more,
216
+ examScore: await computeCell(examScore, [item]),
301
217
  durationMs: result.durationMs,
302
- ...(cost !== null ? { costUSD: cost } : {}),
218
+ costUSD: attemptCostUSD(result),
303
219
  locator: locatorOf(item),
304
220
  };
305
221
  }
306
222
 
307
- const identityRedact = (text: string): string => text;
308
-
309
- export interface AttemptListDataOptions {
310
- /**
311
- * 展示层遮蔽:error 的 message/cause/stack、diagnostic 的 message/data、断言 detail 与
312
- * evidence 经这个钩子;experimentId、evalId、locator、error/diagnostic code 与 lifecycle
313
- * operation 等身份和分类字段不经它。只作用于这次计算产出的组件数据,不改盘上 artifact。
314
- */
315
- redact?: (text: string) => string;
316
- }
317
-
318
- /** `AttemptList.data(selection)`:每个 Attempt 一项,顺序取自 Selection 展平顺序(不重排)。 */
223
+ /** `attemptListData(input)`:每个 Attempt 一项,顺序取自 Scope 展平顺序(不重排) */
319
224
  export async function attemptListData(
320
- input: SnapshotsInput,
321
- opts?: AttemptListDataOptions,
225
+ input: ReportInput,
226
+ options?: EntityListDataOptions,
322
227
  ): Promise<AttemptListItem[]> {
323
228
  const { snapshots } = resolveInput(input);
324
- const redact = opts?.redact ?? identityRedact;
229
+ const redact = options?.redact ?? identityRedact;
325
230
  const items = collectItems(snapshots);
326
- return items.map((item) => attemptListItemOf(item, redact));
231
+ return Promise.all(items.map((item) => attemptListItemOf(item, redact)));
327
232
  }
328
233
 
329
- /** `EvalList.data(selection)`:每个 `experimentId + evalId` 一项,按 evalId 再按 experimentId 升序。 */
330
- export async function evalListData(input: SnapshotsInput): Promise<EvalListItem[]> {
234
+ /** `evalListData(input)`:每个 `experimentId + evalId` 一项,按 evalId 再按 experimentId 升序。 */
235
+ export async function evalListData(input: ReportInput, options?: EntityListDataOptions): Promise<EvalListItem[]> {
331
236
  const { snapshots } = resolveInput(input);
237
+ const redact = options?.redact ?? identityRedact;
332
238
  const items = collectItems(snapshots);
333
239
  const groups = new Map<string, Item[]>();
334
240
  for (const item of items) {
@@ -341,14 +247,14 @@ export async function evalListData(input: SnapshotsInput): Promise<EvalListItem[
341
247
  for (const group of groups.values()) {
342
248
  const sorted = [...group].sort((a, b) => a.attempt.result.attempt - b.attempt.result.attempt);
343
249
  const verdict = foldEvalVerdict(sorted.map((item) => item.attempt.result));
344
- const attempts = sorted.map((item) => attemptListItemOf(item, identityRedact));
250
+ const attempts = await Promise.all(sorted.map((item) => attemptListItemOf(item, redact)));
345
251
  out.push({
346
- evalId: evalIdOf(sorted[0]!),
347
252
  experimentId: experimentIdOf(sorted[0]!),
253
+ evalId: evalIdOf(sorted[0]!),
348
254
  verdict,
349
- score: await computeCell(examScore, sorted),
350
- duration: await computeCell(durationMs, sorted),
351
- cost: await computeCell(costUSD, sorted),
255
+ examScore: await computeCell(examScore, sorted),
256
+ durationMs: await computeCell(durationMs, sorted),
257
+ costUSD: await computeCell(costUSD, sorted),
352
258
  attempts,
353
259
  });
354
260
  }
@@ -356,9 +262,37 @@ export async function evalListData(input: SnapshotsInput): Promise<EvalListItem[
356
262
  return out;
357
263
  }
358
264
 
359
- /** `ExperimentList.data(selection)`:每个 experiment 一项,按 experimentId 升序;展开到每道 Eval。 */
360
- export async function experimentListData(input: SnapshotsInput): Promise<ExperimentListItem[]> {
265
+ /**
266
+ * `experimentListData(input)`:每个 experiment 一项,展开到每道 Eval;初始按端到端成功率
267
+ * 从高到低(缺数据沉底,同分按 id)。一行只有一套 agent / model / flags 是输入约束:
268
+ * 宿主注入的 current() Scope 保证每个 experiment 只由可比性配置一致的快照拼成;作者自选
269
+ * Snapshot[] 时若同一 experiment 混入不一致的可比性配置,按完整用户反馈失败并指引——
270
+ * 看跨配置演化用 snapshot 维度或 MetricLine,不把两套配置拼成一行冒充单一配置。
271
+ */
272
+ export async function experimentListData(
273
+ input: ReportInput,
274
+ options?: EntityListDataOptions,
275
+ ): Promise<ExperimentListItem[]> {
361
276
  const { snapshots } = resolveInput(input);
277
+ const redact = options?.redact ?? identityRedact;
278
+
279
+ // 可比性配置单义检查:同一 experiment 的输入快照必须共享一套可比性配置。
280
+ const configByExperiment = new Map<string, { snapshot: Snapshot; config: unknown }>();
281
+ for (const snapshot of snapshots) {
282
+ const config = comparabilityConfigOf(snapshot);
283
+ const existing = configByExperiment.get(snapshot.experimentId);
284
+ if (existing === undefined) {
285
+ configByExperiment.set(snapshot.experimentId, { snapshot, config });
286
+ } else if (!deepEqualJson(existing.config, config)) {
287
+ throw new Error(
288
+ `experimentListData got inconsistent comparability configs for experiment "${snapshot.experimentId}" ` +
289
+ `(snapshots ${existing.snapshot.startedAt} and ${snapshot.startedAt} differ in agent/model/reasoningEffort/flags/budget/timeoutMs/sandbox). ` +
290
+ "One row shows one configuration — it cannot honestly merge two. To chart evolution across configs, " +
291
+ 'use the "snapshot" dimension or MetricLine; to show the current level, pass results.current() which selects a single config per experiment.',
292
+ );
293
+ }
294
+ }
295
+
362
296
  const items = collectItems(snapshots);
363
297
  const groups = groupItems(items, "experiment");
364
298
  const out: ExperimentListItem[] = [];
@@ -370,28 +304,26 @@ export async function experimentListData(input: SnapshotsInput): Promise<Experim
370
304
  for (const [evalId, evalItems] of evalGroups) {
371
305
  const sorted = [...evalItems].sort((a, b) => a.attempt.result.attempt - b.attempt.result.attempt);
372
306
  const verdict = foldEvalVerdict(sorted.map((item) => item.attempt.result));
373
- const attempts = sorted.map((item) => attemptListItemOf(item, identityRedact));
307
+ const attempts = await Promise.all(sorted.map((item) => attemptListItemOf(item, redact)));
374
308
  evalRows.push({
375
309
  evalId,
376
310
  verdict,
377
- duration: await computeCell(durationMs, sorted),
378
- cost: await computeCell(costUSD, sorted),
311
+ durationMs: await computeCell(durationMs, sorted),
312
+ costUSD: await computeCell(costUSD, sorted),
379
313
  attempts,
380
314
  });
381
315
  }
382
- evalRows.sort((a, b) => a.evalId.localeCompare(b.evalId));
383
316
  const experiment = newest.snapshot.experiment ?? newest.attempt.result.experiment;
317
+ const model = newest.attempt.result.model ?? newest.snapshot.model;
384
318
  out.push({
385
319
  experimentId,
386
- agent: newest.snapshot.agent,
387
- ...((newest.attempt.result.model ?? newest.snapshot.model) !== undefined
388
- ? { model: newest.attempt.result.model ?? newest.snapshot.model }
389
- : {}),
320
+ agent: newest.snapshot.agent || newest.attempt.result.agent,
321
+ ...(model !== undefined ? { model } : {}),
390
322
  ...(experiment?.flags ? { flags: experiment.flags } : {}),
391
- verdicts: stats.verdicts,
392
- passRate: await computeCell(endToEndPassRate, group),
393
- cost: await computeCell(costUSD, group),
394
- duration: await computeCell(durationMs, group),
323
+ evalVerdicts: stats.verdicts,
324
+ endToEndPassRate: await computeCell(endToEndPassRate, group),
325
+ costUSD: await computeCell(costUSD, group),
326
+ durationMs: await computeCell(durationMs, group),
395
327
  tokens: await computeCell(tokens, group),
396
328
  evals: stats.evals,
397
329
  attempts: stats.attempts,
@@ -399,383 +331,653 @@ export async function experimentListData(input: SnapshotsInput): Promise<Experim
399
331
  evalRows,
400
332
  });
401
333
  }
402
- // ExperimentList 是默认实验比较表:初始态按端到端成功率(endToEndPassRate)从高到低,缺数据沉底;
403
- // 同分时按 experiment id 稳定排序。web 增强可临时重排,text 面沿用同一基准顺序。
334
+ // 初始态按端到端成功率(endToEndPassRate)从高到低,缺数据沉底;同分按 experiment id 稳定排序。
404
335
  out.sort((a, b) => {
405
- if (a.passRate.value === null && b.passRate.value === null) return a.experimentId.localeCompare(b.experimentId);
406
- if (a.passRate.value === null) return 1;
407
- if (b.passRate.value === null) return -1;
408
- return b.passRate.value - a.passRate.value || a.experimentId.localeCompare(b.experimentId);
336
+ const va = a.endToEndPassRate.value;
337
+ const vb = b.endToEndPassRate.value;
338
+ if (va === null && vb === null) return a.experimentId.localeCompare(b.experimentId);
339
+ if (va === null) return 1;
340
+ if (vb === null) return -1;
341
+ return vb - va || a.experimentId.localeCompare(b.experimentId);
409
342
  });
410
343
  return out;
411
344
  }
412
345
 
413
- // ───────────────────────── MetricMatrix.data(= MetricBars.data)─────────────────────────
346
+ // ───────────────────────── scopeSummaryData ─────────────────────────
414
347
 
415
- export interface MatrixDataOptions {
416
- rows: DimensionInput;
417
- columns: DimensionInput;
418
- cell: Metric;
419
- /** eval id 前缀过滤,同 CLI 位置参数语义。 */
420
- evals?: string | string[];
348
+ /** costUSD 的求和投影:两级都 sum(题内多轮求和 + 跨题求和 = 全量求和),display 走 $。 */
349
+ const totalCostMetric = defineMetric({
350
+ name: "total-cost",
351
+ label: costUSD.label,
352
+ unit: "$",
353
+ value: costUSD.value,
354
+ aggregate: { perEval: "sum", acrossEvals: "sum" },
355
+ });
356
+
357
+ function tallyOf(): VerdictTally {
358
+ return { passed: 0, failed: 0, errored: 0, skipped: 0 };
421
359
  }
422
360
 
423
- export async function matrixData(input: SnapshotsInput, opts: MatrixDataOptions): Promise<MatrixData> {
424
- const { snapshots } = resolveInput(input);
425
- const items = filterItems(collectItems(snapshots), opts.evals);
426
- // 稀疏分组:只有真有 attempt 的 (row, column) 组合成格;没有样本的格子不出现
427
- const groups = new Map<string, { row: string; column: string; items: Item[] }>();
361
+ /** 一批 Item 的组级统计(experimentListData / scopeSummaryData 共用) */
362
+ function summarizeItems(items: Item[]): {
363
+ experiments: number;
364
+ evals: number;
365
+ attempts: number;
366
+ verdicts: VerdictTally;
367
+ lastRunAt: string | undefined;
368
+ } {
369
+ const experimentIds = new Set<string>();
370
+ for (const item of items) experimentIds.add(experimentIdOf(item));
371
+ const stats = evalLevelStats(
372
+ items.map((item) => ({ verdict: item.attempt.result.verdict, key: fullEvalKey(item) })),
373
+ (r) => r.key,
374
+ );
375
+ let lastRunAt: string | undefined;
428
376
  for (const item of items) {
429
- const row = dimensionKey(opts.rows, item);
430
- const column = dimensionKey(opts.columns, item);
431
- const key = JSON.stringify([row, column]);
432
- const group = groups.get(key);
433
- if (group) group.items.push(item);
434
- else groups.set(key, { row, column, items: [item] });
377
+ const startedAt = item.snapshot.startedAt;
378
+ if (lastRunAt === undefined || startedAt > lastRunAt) lastRunAt = startedAt;
435
379
  }
436
- const cells: MatrixData["cells"] = [];
437
- for (const group of groups.values()) {
438
- cells.push({ row: group.row, column: group.column, cell: await computeCell(opts.cell, group.items) });
380
+ return {
381
+ experiments: experimentIds.size,
382
+ evals: stats.evals,
383
+ attempts: items.length,
384
+ verdicts: { passed: stats.passed, failed: stats.failed, errored: stats.errored, skipped: stats.skipped },
385
+ lastRunAt,
386
+ };
387
+ }
388
+
389
+ /**
390
+ * `scopeSummaryData(input)`:范围摘要——快照时间窗、experiment / eval / attempt 数、
391
+ * 两级判定计票、端到端成功率与总成本(docs/feature/reports/library/summaries.md)。
392
+ * data 恒携带两级计票;成功率来自官方两级指标引擎,不从任一计票重算。
393
+ */
394
+ export async function scopeSummaryData(input: ReportInput): Promise<ScopeSummaryData> {
395
+ const { snapshots } = resolveInput(input);
396
+ const items = collectItems(snapshots);
397
+
398
+ let earliest: string | null = null;
399
+ let latest: string | null = null;
400
+ for (const snapshot of snapshots) {
401
+ if (earliest === null || snapshot.startedAt < earliest) earliest = snapshot.startedAt;
402
+ if (latest === null || snapshot.startedAt > latest) latest = snapshot.startedAt;
439
403
  }
404
+
405
+ const stats = summarizeItems(items);
406
+ const attemptVerdicts = tallyOf();
407
+ for (const item of items) attemptVerdicts[item.attempt.result.verdict] += 1;
408
+
440
409
  return {
441
- rows: dimensionName(opts.rows),
442
- columns: dimensionName(opts.columns),
443
- metric: toColumn(opts.cell),
444
- cells,
410
+ range: { earliestStartedAt: earliest, latestStartedAt: latest },
411
+ experiments: stats.experiments,
412
+ evals: stats.evals,
413
+ attempts: stats.attempts,
414
+ evalVerdicts: stats.verdicts,
415
+ attemptVerdicts,
416
+ endToEndPassRate: await computeCell(endToEndPassRate, items),
417
+ totalCostUSD: await computeCell(totalCostMetric, items),
445
418
  };
446
419
  }
447
420
 
448
- // ───────────────────────── Scoreboard.data ─────────────────────────
421
+ // ───────────────────────── experimentComparisonData ─────────────────────────
422
+
423
+ /** 完整父路径是组键;没有父路径的 experiment 不能互相比,自己形成单例组。 */
424
+ export function experimentComparisonGroupKey(experimentId: string): string {
425
+ return experimentGroupOf(experimentId) ?? experimentId;
426
+ }
427
+
428
+ /** 每组散点的唯一口径:默认 definition 与公开计算共用,不各写一份。 */
429
+ const COMPARISON_SCATTER_OPTIONS: MetricScatterOptions = {
430
+ points: "experiment",
431
+ series: "agent",
432
+ x: costUSD,
433
+ y: endToEndPassRate,
434
+ };
435
+
436
+ /**
437
+ * `experimentComparisonData(input)`:先把 input 按可比组分区(experiment id 的完整父路径),
438
+ * 再为每组分别计算 ScopeSummary、成本 × 端到端成功率散点和 ExperimentList——分区发生在任何
439
+ * 指标计算之前,组外 attempt 不可能污染该组的坐标尺度、series、成功率、成本、排序或缺数据计数。
440
+ */
441
+ export async function experimentComparisonData(input: ReportInput): Promise<ExperimentComparisonData> {
442
+ const { snapshots } = resolveInput(input);
443
+ const snapshotsByGroup = new Map<string, Snapshot[]>();
444
+ for (const snapshot of snapshots) {
445
+ const key = experimentComparisonGroupKey(snapshot.experimentId);
446
+ const group = snapshotsByGroup.get(key);
447
+ if (group) group.push(snapshot);
448
+ else snapshotsByGroup.set(key, [snapshot]);
449
+ }
450
+ const groups = await Promise.all(
451
+ [...snapshotsByGroup.entries()]
452
+ .sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0))
453
+ .map(async ([key, groupSnapshots]): Promise<ExperimentComparisonGroupData> => {
454
+ const [summary, scatter, experiments] = await Promise.all([
455
+ scopeSummaryData(groupSnapshots),
456
+ metricScatterData(groupSnapshots, COMPARISON_SCATTER_OPTIONS),
457
+ experimentListData(groupSnapshots),
458
+ ]);
459
+ return { key, summary, scatter, experiments };
460
+ }),
461
+ );
462
+ return { groups };
463
+ }
464
+
465
+ // ───────────────────────── scoreboardData ─────────────────────────
449
466
 
450
- export interface ScoreboardDataOptions {
451
- /** 给谁打分(被打分的维度);维度槽与 MetricTable.data 统一叫 rows。 */
467
+ export interface ScoreboardOptions {
452
468
  rows: DimensionInput;
453
- /** 按什么分科;默认 "evalGroup"(考试里的「科目」)。 */
454
- subjects?: DimensionInput;
455
- /** eval id 前缀 每题分值;未列默认 1;前缀重叠时最长的生效。 */
456
- weights?: Record<string, number>;
457
- /** 折算满分;默认 100。 */
469
+ /** 固定题集;eval id 必须唯一。元素引用运行时数据,类型放宽为普通数组,空数组在计算时报错。 */
470
+ questions: readonly string[];
471
+ /** 分科函数;默认与 evalGroup 维度同一条规则:取 eval id 的完整父路径,无 `/` 取完整 id。 */
472
+ subject?: (evalId: string) => string;
473
+ /** 权重按 eval id 前缀匹配,多个命中时最长前缀生效;默认 1。 */
474
+ weights?: Readonly<Record<string, number>>;
458
475
  fullMarks?: number;
459
- /** 每题得分指标;缺省即 examScore,可换自定义(如「答对但超预算扣分」)。 */
460
476
  score?: Metric;
461
- /** 选中范围:eval id 前缀过滤;题集(分母)只遍历这个范围。 */
462
- evals?: string | string[];
463
477
  }
464
478
 
465
479
  /**
466
- * 逐题分值制,分母对所有被打分者恒定:
467
- * 题分值 = 命中的权重(默认 1) 题得分 = score 指标的题级值(perEval 折叠后)
468
- * 总分 = fullMarks × Σ(题得分 × 题分值) / Σ(题分值) Σ 遍历选中范围内全部题
469
- * 没跑到的题挣 0 分但留在分母里,missing 如实报 —— 这是显式的考试契约,不是「null ≠ 0」的例外。
480
+ * 固定题集分母:未跑题按 0 分计入 `notRun`,跑了但指标为 null 的题按 0 分计入 `unscorable`,
481
+ * 两个计数不合并——成绩单能回答「这 0 分是没去考还是考了判不了」。组件不从已观测 attempt
482
+ * 的并集猜分母;Scope 中题集之外的 eval 被忽略并计入 `ignoredEvals`。
470
483
  */
471
- export async function scoreboardData(
472
- input: SnapshotsInput,
473
- opts: ScoreboardDataOptions,
474
- ): Promise<ScoreboardData> {
475
- const { snapshots } = resolveInput(input);
476
- const fullMarks = opts.fullMarks ?? 100;
477
- const scoreMetric = opts.score ?? examScore;
478
- const subjectsDim: DimensionInput = opts.subjects ?? "evalGroup";
479
- const match = evalPrefixPredicate(opts.evals);
480
- const items = filterItems(collectItems(snapshots), opts.evals);
481
-
482
- // 题集(固定分母):选中范围内、任一快照声明覆盖或实际出现过的全部题
483
- const universe = new Set<string>();
484
- for (const snapshot of snapshots) {
485
- for (const e of snapshot.evals) if (match(e.id)) universe.add(e.id);
486
- for (const id of snapshot.knownEvalIds ?? []) if (match(id)) universe.add(id);
484
+ export async function scoreboardData(input: ReportInput, options: ScoreboardOptions): Promise<ScoreboardData> {
485
+ const questions = options.questions;
486
+ if (!Array.isArray(questions) || questions.length === 0) {
487
+ throw new Error(
488
+ "scoreboardData questions must be a non-empty list of eval ids: the fixed question set is the denominator, and an empty denominator makes no scoreboard. " +
489
+ "Pass the eval ids to grade, or filter your source list before passing it.",
490
+ );
491
+ }
492
+ const seen = new Set<string>();
493
+ for (const q of questions) {
494
+ if (seen.has(q)) {
495
+ throw new Error(
496
+ `scoreboardData questions contains "${q}" twice — each question is one denominator slot; remove the duplicate.`,
497
+ );
498
+ }
499
+ seen.add(q);
500
+ }
501
+ const fullMarks = options.fullMarks ?? 100;
502
+ if (!Number.isFinite(fullMarks) || fullMarks <= 0) {
503
+ throw new Error(`scoreboardData fullMarks must be a positive finite number (got ${String(fullMarks)}).`);
504
+ }
505
+ const weightEntries = Object.entries(options.weights ?? {});
506
+ for (const [prefix, weight] of weightEntries) {
507
+ if (prefix.length === 0) {
508
+ throw new Error('scoreboardData weights contains an empty prefix ""; weight prefixes must be non-empty eval id prefixes.');
509
+ }
510
+ if (!Number.isFinite(weight) || weight <= 0) {
511
+ throw new Error(
512
+ `scoreboardData weight for prefix "${prefix}" must be a positive finite number (got ${String(weight)}).`,
513
+ );
514
+ }
487
515
  }
488
- for (const item of items) universe.add(evalIdOf(item));
489
- const sortedUniverse = [...universe].sort();
516
+ const scoreMetric = options.score ?? examScore;
517
+ const subjectOf = options.subject ?? evalGroupOf;
490
518
 
491
- // 每题的科目:先从任一 attempt 解析(自定义 subjects 维度也能算);
492
- // 全程无 attempt 的题按内置规则兜底,自定义维度无从计算时如实标 "(unknown)"
493
- const subjectByEval = new Map<string, string>();
494
- for (const item of items) {
519
+ const { snapshots } = resolveInput(input);
520
+ const allItems = collectItems(snapshots);
521
+ const questionSet = new Set(questions);
522
+ const items = allItems.filter((item) => questionSet.has(evalIdOf(item)));
523
+ const ignored = new Set<string>();
524
+ for (const item of allItems) {
495
525
  const id = evalIdOf(item);
496
- if (!subjectByEval.has(id)) subjectByEval.set(id, dimensionKey(subjectsDim, item));
497
- }
498
- const subjectOf = (id: string): string => {
499
- const known = subjectByEval.get(id);
500
- if (known !== undefined) return known;
501
- if (subjectsDim === "eval") return id;
502
- if (subjectsDim === "evalGroup") return evalGroupOf(id);
503
- return "(unknown)";
504
- };
526
+ if (!questionSet.has(id)) ignored.add(id);
527
+ }
505
528
 
506
529
  // 权重:最长前缀生效(排序后线性找第一个命中即最长)
507
- const weights = Object.entries(opts.weights ?? {})
530
+ const weights = weightEntries
508
531
  .map(([prefix, weight]) => ({ prefix, weight }))
509
532
  .sort((a, b) => b.prefix.length - a.prefix.length);
510
533
  const weightOf = (id: string): number => weights.find((w) => id.startsWith(w.prefix))?.weight ?? 1;
511
534
 
512
- const groups = groupItems(items, opts.rows);
535
+ const subjectByQuestion = new Map<string, string>();
536
+ for (const id of questions) {
537
+ const subject = subjectOf(id);
538
+ if (typeof subject !== "string" || subject.length === 0) {
539
+ throw new Error(
540
+ `scoreboardData subject("${id}") returned an empty value; every question must map to a non-empty subject name.`,
541
+ );
542
+ }
543
+ subjectByQuestion.set(id, subject);
544
+ }
545
+
546
+ const groups = groupItems(items, options.rows);
513
547
  const rows: ScoreboardData["rows"] = [];
514
548
  for (const [key, group] of groups) {
515
- // 题得分:perEval 折叠(同 eval × 快照 内);同题出现在多个快照时取快照级值的均值
516
- const perSnapshot = new Map<string, Map<string, number[]>>(); // evalId → 快照键 → 原始值
549
+ const byQuestion = new Map<string, Item[]>();
517
550
  for (const item of group) {
518
- const value = await evaluateMetric(scoreMetric, item.attempt);
519
- if (value === null) continue; // 测不了的 attempt 不进题得分;整题无样本 → missing
520
551
  const id = evalIdOf(item);
521
- const snapKey = snapshotKeyOf(item.snapshot);
522
- let bySnap = perSnapshot.get(id);
523
- if (!bySnap) perSnapshot.set(id, (bySnap = new Map()));
524
- const bucket = bySnap.get(snapKey);
525
- if (bucket) bucket.push(value);
526
- else bySnap.set(snapKey, [value]);
527
- }
528
- const perEvalAgg = scoreMetric.aggregate?.perEval ?? "mean";
529
- const scoreByEval = new Map<string, number>();
530
- for (const [id, bySnap] of perSnapshot) {
531
- const snapValues = [...bySnap.values()].map((values) => applyAggregator(perEvalAgg, values));
532
- scoreByEval.set(id, snapValues.reduce((a, b) => a + b, 0) / snapValues.length);
552
+ const list = byQuestion.get(id);
553
+ if (list) list.push(item);
554
+ else byQuestion.set(id, [item]);
533
555
  }
534
556
 
535
- // 科目累计:固定分母 —— 没跑的题 0 分挣、留在分母、计入 missing
536
557
  const subjects = new Map<
537
558
  string,
538
- { key: string; earned: number; possible: number; evals: number; missing: number }
559
+ {
560
+ key: string;
561
+ earned: number;
562
+ possible: number;
563
+ questions: number;
564
+ notRun: number;
565
+ unscorable: number;
566
+ refs: Set<AttemptLocator>;
567
+ }
539
568
  >();
540
- for (const id of sortedUniverse) {
541
- const subjectKey = subjectOf(id);
569
+ const totalRefs = new Set<AttemptLocator>();
570
+ for (const id of questions) {
571
+ const subjectKey = subjectByQuestion.get(id)!;
542
572
  let subject = subjects.get(subjectKey);
543
573
  if (!subject) {
544
- subjects.set(subjectKey, (subject = { key: subjectKey, earned: 0, possible: 0, evals: 0, missing: 0 }));
574
+ subjects.set(
575
+ subjectKey,
576
+ (subject = { key: subjectKey, earned: 0, possible: 0, questions: 0, notRun: 0, unscorable: 0, refs: new Set() }),
577
+ );
545
578
  }
546
579
  const weight = weightOf(id);
547
- const got = scoreByEval.get(id);
548
- subject.earned += (got ?? 0) * weight;
549
580
  subject.possible += weight;
550
- subject.evals += 1;
551
- if (got === undefined) subject.missing += 1;
581
+ subject.questions += 1;
582
+ const questionItems = byQuestion.get(id);
583
+ if (questionItems === undefined) {
584
+ subject.notRun += 1;
585
+ continue;
586
+ }
587
+ for (const item of questionItems) {
588
+ const locator = locatorOf(item);
589
+ subject.refs.add(locator);
590
+ totalRefs.add(locator);
591
+ }
592
+ const cell = await computeCell(scoreMetric, questionItems);
593
+ if (cell.value === null) {
594
+ subject.unscorable += 1;
595
+ continue;
596
+ }
597
+ if (cell.value < 0 || cell.value > 1) {
598
+ throw new Error(
599
+ `scoreboardData score metric "${scoreMetric.name}" produced ${cell.value} for eval "${id}" — scores must stay in [0, 1] so weighted totals stay auditable. Normalize the metric, or use a different score metric.`,
600
+ );
601
+ }
602
+ subject.earned += cell.value * weight;
552
603
  }
604
+
553
605
  let earned = 0;
554
606
  let possible = 0;
607
+ let notRun = 0;
608
+ let unscorable = 0;
555
609
  for (const subject of subjects.values()) {
556
610
  earned += subject.earned;
557
611
  possible += subject.possible;
612
+ notRun += subject.notRun;
613
+ unscorable += subject.unscorable;
558
614
  }
559
615
  const value = possible === 0 ? 0 : (fullMarks * earned) / possible;
560
- rows.push({ key, total: { value, display: formatPlainNumber(value) }, subjects: [...subjects.values()] });
616
+ rows.push({
617
+ key,
618
+ total: {
619
+ value,
620
+ display: formatPlainNumber(value),
621
+ notRun,
622
+ unscorable,
623
+ refs: [...totalRefs].sort(),
624
+ },
625
+ subjects: [...subjects.values()].map((subject) => ({
626
+ key: subject.key,
627
+ earned: subject.earned,
628
+ possible: subject.possible,
629
+ questions: subject.questions,
630
+ notRun: subject.notRun,
631
+ unscorable: subject.unscorable,
632
+ display: subjectDisplay(subject.earned, subject.possible),
633
+ refs: [...subject.refs].sort(),
634
+ })),
635
+ });
561
636
  }
562
637
 
563
- return { dimension: dimensionName(opts.rows), fullMarks, weights, rows };
638
+ return {
639
+ rowDimension: dimensionName(options.rows),
640
+ questions: [...questions],
641
+ fullMarks,
642
+ weights,
643
+ ignoredEvals: ignored.size,
644
+ rows,
645
+ };
646
+ }
647
+
648
+ /** 分科显示:earned / possible 与同尺度百分比。 */
649
+ function subjectDisplay(earned: number, possible: number): LocalizedText {
650
+ const ratio = possible === 0 ? 0 : earned / possible;
651
+ return `${formatPlainNumber(earned)}/${formatPlainNumber(possible)} (${formatMetricValue(ratio, "%")})`;
564
652
  }
565
653
 
566
- // ───────────────────────── MetricScatter.data ─────────────────────────
654
+ // ───────────────────────── metricScatterData ─────────────────────────
567
655
 
568
- export interface ScatterDataOptions {
656
+ export interface MetricScatterOptions {
569
657
  /** 点维度:每个点 = 该组 attempt 的聚合。 */
570
658
  points: DimensionInput;
571
- /** 可选:同系列的点连成线;省略 = 纯散点。 */
659
+ /** 可选:只决定颜色和分组,默认不连线。 */
572
660
  series?: DimensionInput;
573
661
  x: Metric;
574
662
  y: Metric;
663
+ /** eval id 前缀过滤,同 CLI 位置参数语义。 */
664
+ evals?: string | readonly string[];
575
665
  }
576
666
 
577
- export async function scatterData(input: SnapshotsInput, opts: ScatterDataOptions): Promise<ScatterData> {
667
+ export async function metricScatterData(input: ReportInput, options: MetricScatterOptions): Promise<ScatterData> {
578
668
  const { snapshots } = resolveInput(input);
579
- const items = collectItems(snapshots);
580
- const groups = groupItems(items, opts.points);
669
+ const items = filterItems(collectItems(snapshots), options.evals);
670
+ const groups = groupItems(items, options.points);
581
671
  const rows: ScatterData["rows"] = [];
582
672
  for (const [key, group] of groups) {
583
673
  rows.push({
584
674
  key,
585
675
  // 组内取第一条解析系列:点维度细于系列维度时(experiment ⊂ agent)天然一致
586
- series: opts.series ? dimensionKey(opts.series, group[0]) : undefined,
587
- x: await computeCell(opts.x, group),
588
- y: await computeCell(opts.y, group), // 任一轴 null 的点留在 rows 里:组件不画,但注脚要报的数就从这里数
676
+ ...(options.series ? { series: dimensionKey(options.series, group[0]!) } : {}),
677
+ x: await computeCell(options.x, group),
678
+ y: await computeCell(options.y, group), // 任一轴 null 的点留在 rows 里:组件不画,但注脚要报的数就从这里数
589
679
  });
590
680
  }
591
681
  return {
592
- points: dimensionName(opts.points),
593
- series: opts.series ? dimensionName(opts.series) : undefined,
594
- x: toColumn(opts.x),
595
- y: toColumn(opts.y),
682
+ pointDimension: dimensionName(options.points),
683
+ ...(options.series ? { seriesDimension: dimensionName(options.series) } : {}),
684
+ x: toColumn(options.x),
685
+ y: toColumn(options.y),
596
686
  rows,
597
687
  };
598
688
  }
599
689
 
600
- // ───────────────────────── MetricLine.data ─────────────────────────
690
+ // ───────────────────────── metricLineData ─────────────────────────
601
691
 
602
- export interface LineDataOptions {
603
- /** x 轴:experiment 声明的 flag 或顶层运行配置 config()(要求数值),不解析 experiment 命名。 */
604
- x: AxisInput;
605
- y: Metric;
606
- /** 可选:每个系列一条线(flag / config 或普通维度);省略 = 单系列。 */
692
+ export interface MetricLineOptions {
693
+ /** x 轴:NumericAxis(numericFlag() / numericRunConfig() 或自定义 of),不解析 experiment 命名。 */
694
+ x: NumericAxis;
607
695
  series?: DimensionInput;
696
+ y: Metric;
697
+ /** eval id 前缀过滤,同 CLI 位置参数语义。 */
698
+ evals?: string | readonly string[];
608
699
  }
609
700
 
610
- /** 每个点 = 一个 experiment 的聚合;同系列的点按 x 排序连线(排序在组件面,数据保持分组序)。 */
611
- export async function lineData(input: SnapshotsInput, opts: LineDataOptions): Promise<LineData> {
701
+ /**
702
+ * 点身份 = (series, x):落进同一桶的全部 attempt 先在各自 experiment × eval 内 perEval 聚合,
703
+ * 再 acrossEvals 跨题折成该点唯一的 y——聚合顺序是 (series, x, experiment, eval),同一桶里有
704
+ * 多个 experiment 时它们合成一个点,不画垂直来回线。前提是 x 在同一 experiment × eval 内恒定:
705
+ * 自定义 NumericAxis.of() 对同一 experiment × eval 的不同 attempt 返回不同值时按完整用户反馈失败。
706
+ * x 为 null 的 attempt 不伪造 x 值,归入该 series 的未绘制行,组件报告未绘制数量。
707
+ */
708
+ export async function metricLineData(input: ReportInput, options: MetricLineOptions): Promise<LineData> {
612
709
  const { snapshots } = resolveInput(input);
613
- const items = collectItems(snapshots);
614
- const groups = groupItems(items, "experiment");
710
+ const items = filterItems(collectItems(snapshots), options.evals);
711
+
712
+ // x 恒定性检查:同一 experiment × eval 内的全部 attempt 必须得到同一个 x。
713
+ const xByEvalKey = new Map<string, { x: number | null; item: Item }>();
714
+ const buckets = new Map<string, { series: string | undefined; x: number | null; items: Item[] }>();
715
+ for (const item of items) {
716
+ const x = axisValueOf(options.x, item.attempt);
717
+ const evalKey = fullEvalKey(item);
718
+ const existing = xByEvalKey.get(evalKey);
719
+ if (existing === undefined) {
720
+ xByEvalKey.set(evalKey, { x, item });
721
+ } else if (!Object.is(existing.x, x)) {
722
+ throw new Error(
723
+ `Numeric axis "${options.x.name}" is not constant within experiment "${experimentIdOf(item)}" × eval "${evalIdOf(item)}" ` +
724
+ `(got ${String(existing.x)} and ${String(x)} for different attempts). A parameter axis must describe the configuration, ` +
725
+ "not vary per attempt — a per-attempt quantity is material for the y metric, not an x axis. " +
726
+ "Fix of() to read experiment-level configuration (numericFlag()/numericRunConfig() do this by construction).",
727
+ );
728
+ }
729
+ const series = options.series ? dimensionKey(options.series, item) : undefined;
730
+ const bucketKey = `${series ?? ""}${x === null ? "null" : String(x)}`;
731
+ const bucket = buckets.get(bucketKey);
732
+ if (bucket) bucket.items.push(item);
733
+ else buckets.set(bucketKey, { series, x, items: [item] });
734
+ }
735
+
736
+ const ordered = [...buckets.values()].sort((a, b) => {
737
+ const sa = a.series ?? "";
738
+ const sb = b.series ?? "";
739
+ if (sa !== sb) return sa < sb ? -1 : 1;
740
+ if (a.x === null) return b.x === null ? 0 : 1;
741
+ if (b.x === null) return -1;
742
+ return a.x - b.x;
743
+ });
744
+
615
745
  const rows: LineData["rows"] = [];
616
- for (const [key, group] of groups) {
617
- const x = axisValue(opts.x, group[0]); // flag / config 都是 experiment 级声明,组内一致
746
+ for (const bucket of ordered) {
618
747
  rows.push({
619
- key,
620
- series: opts.series ? dimensionKey(opts.series, group[0]) : undefined,
621
- x,
622
- xDisplay: x === null ? "" : formatMetricValue(x, opts.x.unit),
623
- y: await computeCell(opts.y, group),
748
+ key: bucket.x === null ? "null" : String(bucket.x),
749
+ ...(bucket.series !== undefined ? { series: bucket.series } : {}),
750
+ x: bucket.x,
751
+ xDisplay: bucket.x === null ? "" : formatMetricValue(bucket.x, options.x.unit),
752
+ y: await computeCell(options.y, bucket.items),
624
753
  });
625
754
  }
755
+
626
756
  return {
627
757
  x: {
628
- key: opts.x.name,
629
- label: typeof opts.x.label === "string" ? opts.x.label : opts.x.name,
630
- unit: opts.x.unit,
758
+ key: options.x.name,
759
+ label: options.x.label ?? options.x.name,
760
+ ...(options.x.unit !== undefined ? { unit: options.x.unit } : {}),
631
761
  },
632
- series: opts.series ? dimensionName(opts.series) : undefined,
633
- y: toColumn(opts.y),
762
+ ...(options.series ? { seriesDimension: dimensionName(options.series) } : {}),
763
+ y: toColumn(options.y),
634
764
  rows,
635
765
  };
636
766
  }
637
767
 
638
- // ───────────────────────── RunOverview.data ─────────────────────────
768
+ // ───────────────────────── deltaTableData 与 pairsByFlag ─────────────────────────
639
769
 
640
- /** Selection 的 warnings 随行进 OverviewData,RunOverview 直接渲染 —— 诚实不靠使用者记得接线。 */
641
- export async function overviewData(input: SnapshotsInput): Promise<OverviewData> {
642
- const { snapshots, warnings } = resolveInput(input);
643
- const items = collectItems(snapshots);
644
- const evalIds = new Set<string>();
645
- let passed = 0;
646
- let failed = 0;
647
- let errored = 0;
648
- let skipped = 0;
649
- let durationMs = 0;
650
- let costUSD: number | null = null; // 任一 attempt 报了成本才有;全缺 = null,不编 0
651
- for (const item of items) {
652
- const result = item.attempt.result;
653
- evalIds.add(evalIdOf(item));
654
- switch (result.verdict) {
655
- case "passed":
656
- passed += 1;
657
- break;
658
- case "failed":
659
- failed += 1;
660
- break;
661
- case "errored":
662
- errored += 1;
663
- break;
664
- case "skipped":
665
- skipped += 1;
666
- break;
667
- }
668
- durationMs += result.durationMs;
669
- const cost = attemptCostUSD(result);
670
- if (cost !== null) costUSD = (costUSD ?? 0) + cost;
671
- }
672
- // 默认成功率的唯一官方口径:endToEndPassRate 的两级聚合(computeCell),不是从上面四个
673
- // verdict 计票现场重算——一道题内 attempt 部分通过要算部分 credit,不是二元投票;
674
- // failed / errored 都记 0,只有 skipped 不进聚合。
675
- const passRateCell = await computeCell(endToEndPassRate, items);
770
+ /**
771
+ * flag 派生 A/B 对(docs/feature/reports/library/metric-views.md「DeltaTable」):
772
+ * 配对域 = 同可比组 + 删除该 flag 后可比性配置深相等;a 取 baseline(缺省 = 未声明该 flag),
773
+ * b 侧该 flag 的每个其它取值各成一对;label 自动 `<a 末段> · <flag>=<显示键>`。
774
+ */
775
+ export function pairsByFlag(name: string, options?: { baseline?: JsonValue }): FlagPairs {
776
+ if (typeof name !== "string" || name.length === 0) {
777
+ throw new Error("pairsByFlag: name must be a non-empty string (the key declared in the experiment's flags).");
778
+ }
676
779
  return {
677
- snapshots: snapshots.map((s) => ({
678
- experimentId: s.experimentId,
679
- agent: s.agent,
680
- model: s.model,
681
- startedAt: s.startedAt,
682
- })),
683
- totals: {
684
- evals: evalIds.size,
685
- attempts: items.length,
686
- passed,
687
- failed,
688
- errored,
689
- skipped,
690
- passRate: passRateCell,
691
- costUSD,
692
- durationMs,
693
- },
694
- warnings: [...warnings],
780
+ kind: "flagPairs",
781
+ flag: name,
782
+ ...(options?.baseline !== undefined ? { baseline: options.baseline } : {}),
695
783
  };
696
784
  }
697
785
 
698
- // ───────────────────────── GroupSummary.data ─────────────────────────
786
+ export interface DeltaTableOptions {
787
+ /** 显式维度,必填——"baseline" 不会被猜成 experiment、agent、flag 或 snapshot 中的某一种。 */
788
+ by: DimensionInput;
789
+ /** 字面 pair 数组(自定义 label),或 pairsByFlag() 的派生声明;空数组在计算时报错。 */
790
+ pairs: readonly DeltaPair[] | FlagPairs;
791
+ metrics: readonly [Metric, ...Metric[]];
792
+ /** eval id 前缀过滤,同 CLI 位置参数语义。 */
793
+ evals?: string | readonly string[];
794
+ }
699
795
 
700
- /**
701
- * 一组 experiment 的摘要:experiment/eval/attempt 数量、eval 级折叠计票、通过率(
702
- * `GroupSelector` 卡片口径,见 summarizeItems)、总成本(null-safe 求和)、最后运行时间
703
- * (组内快照 startedAt 最大值)。`input` 就是调用方已经收窄好的组 Selection(如自定义报告
704
- * 按 experiment 组前缀 filter 出来的那份)——本函数不再自己分组。
705
- */
706
- export async function groupSummaryData(input: SnapshotsInput): Promise<GroupSummaryData> {
707
- const { snapshots } = resolveInput(input);
708
- const items = collectItems(snapshots);
709
- const summary = summarizeItems(items);
710
- const ratio = summary.ran > 0 ? summary.verdicts.passed / summary.ran : null; // 分母为 0 → 缺数据,不编 0%
711
- const passRateCell: MetricCell = {
712
- value: ratio,
713
- display: ratio === null ? "—" : formatMetricValue(ratio, "%"),
714
- samples: summary.ran,
715
- total: summary.evals,
716
- refs: summary.refs,
717
- };
718
- return {
719
- experiments: summary.experiments,
720
- evals: summary.evals,
721
- attempts: summary.attempts,
722
- verdicts: summary.verdicts,
723
- passRate: passRateCell,
724
- totalCostUSD: summary.totalCostUSD,
725
- ...(summary.lastRunAt !== undefined ? { lastRunAt: summary.lastRunAt } : {}),
726
- };
796
+ function isFlagPairs(pairs: DeltaTableOptions["pairs"]): pairs is FlagPairs {
797
+ return typeof pairs === "object" && pairs !== null && !Array.isArray(pairs) && (pairs as FlagPairs).kind === "flagPairs";
798
+ }
799
+
800
+ /** experiment id 相对可比组的末段。 */
801
+ function experimentTail(experimentId: string): string {
802
+ const slash = experimentId.lastIndexOf("/");
803
+ return slash === -1 ? experimentId : experimentId.slice(slash + 1);
727
804
  }
728
805
 
729
- // ───────────────────────── DeltaTable.data ─────────────────────────
806
+ /** 派生配对:同可比组 + 删除该 flag 后可比性配置深相等。返回 pair 列表与配对域实验数。 */
807
+ function derivePairsByFlag(
808
+ snapshots: readonly Snapshot[],
809
+ spec: FlagPairs,
810
+ ): { pairs: DeltaPair[]; experiments: number } {
811
+ // 每个 experiment 取最新快照的配置(current() Scope 天然一实验一快照)。
812
+ const byExperiment = new Map<string, Snapshot>();
813
+ for (const snapshot of snapshots) {
814
+ const existing = byExperiment.get(snapshot.experimentId);
815
+ if (existing === undefined || snapshot.startedAt > existing.startedAt) {
816
+ byExperiment.set(snapshot.experimentId, snapshot);
817
+ }
818
+ }
819
+ interface Entry {
820
+ id: string;
821
+ flagValue: JsonValue | undefined;
822
+ bucket: string;
823
+ }
824
+ const entries: Entry[] = [];
825
+ for (const [id, snapshot] of byExperiment) {
826
+ const config = comparabilityConfigOf(snapshot) as { flags?: Record<string, JsonValue> };
827
+ const flagValue = config.flags?.[spec.flag];
828
+ const reduced = { ...config, flags: { ...config.flags } };
829
+ delete reduced.flags[spec.flag];
830
+ const group = experimentGroupOf(id) ?? id;
831
+ entries.push({ id, flagValue, bucket: `${group}${JSON.stringify(sortedJson(reduced))}` });
832
+ }
730
833
 
731
- export interface DeltaPair {
732
- /** 基线侧:experiment id,或快照键 "<experimentId> @ <startedAt>"(时间轴对比用手挑的快照数组)。 */
733
- a: string;
734
- /** 对比侧,同上。 */
735
- b: string;
736
- label?: string;
834
+ const baseline = spec.baseline; // undefined = 未声明该 flag 的实验作 a
835
+ const buckets = new Map<string, Entry[]>();
836
+ for (const entry of entries) {
837
+ const list = buckets.get(entry.bucket);
838
+ if (list) list.push(entry);
839
+ else buckets.set(entry.bucket, [entry]);
840
+ }
841
+
842
+ const pairs: DeltaPair[] = [];
843
+ for (const bucket of buckets.values()) {
844
+ const aSide = bucket.filter((e) => deepEqualJson(e.flagValue, baseline));
845
+ const bSide = bucket.filter((e) => !deepEqualJson(e.flagValue, baseline));
846
+ for (const a of aSide) {
847
+ for (const b of bSide) {
848
+ pairs.push({
849
+ a: a.id,
850
+ b: b.id,
851
+ label: `${experimentTail(a.id)} · ${spec.flag}=${refDisplayKey(b.flagValue)[0]}`,
852
+ });
853
+ }
854
+ }
855
+ }
856
+ pairs.sort((p, q) => {
857
+ const ta = experimentTail(p.a);
858
+ const tb = experimentTail(q.a);
859
+ if (ta !== tb) return ta < tb ? -1 : 1;
860
+ const la = p.label as string;
861
+ const lb = q.label as string;
862
+ return la < lb ? -1 : la > lb ? 1 : 0;
863
+ });
864
+ return { pairs, experiments: byExperiment.size };
737
865
  }
738
866
 
739
- export interface DeltaDataOptions<M extends readonly Metric[]> {
740
- /** 每行一对:B 相对 A。 */
741
- pairs: DeltaPair[];
742
- metrics: M;
867
+ /** 对象键递归排序(派生配对的 bucket 键用;undefined 字段剔除)。 */
868
+ function sortedJson(value: unknown): unknown {
869
+ if (Array.isArray(value)) return value.map(sortedJson);
870
+ if (typeof value === "object" && value !== null) {
871
+ const out: Record<string, unknown> = {};
872
+ for (const key of Object.keys(value as Record<string, unknown>).sort()) {
873
+ const v = (value as Record<string, unknown>)[key];
874
+ if (v !== undefined) out[key] = sortedJson(v);
875
+ }
876
+ return out;
877
+ }
878
+ return value;
743
879
  }
744
880
 
745
- export async function deltaData<const M extends readonly Metric[]>(
746
- input: SnapshotsInput,
747
- opts: DeltaDataOptions<M>,
748
- ): Promise<DeltaData<M[number]["name"]>> {
749
- assertUniqueMetricNames(opts.metrics, "DeltaTable.data metrics");
881
+ export async function deltaTableData(input: ReportInput, options: DeltaTableOptions): Promise<DeltaData> {
882
+ assertUniqueMetricNames(options.metrics, "deltaTableData metrics");
883
+ if (!Array.isArray(options.metrics) || options.metrics.length === 0) {
884
+ throw new Error("deltaTableData metrics must be a non-empty tuple of Metric instances.");
885
+ }
750
886
  const { snapshots } = resolveInput(input);
751
- const items = collectItems(snapshots);
752
- // 一侧的键既匹配 experiment id 也匹配快照键 —— 与 "snapshot" 维度同一格式,不另造对比语义
753
- const sideItems = (key: string) =>
754
- items.filter((item) => experimentIdOf(item) === key || snapshotKeyOf(item.snapshot) === key);
887
+
888
+ let pairs: readonly DeltaPair[];
889
+ let experiments: number | undefined;
890
+ if (isFlagPairs(options.pairs)) {
891
+ if (options.by !== "experiment") {
892
+ throw new Error(
893
+ `deltaTableData pairs came from pairsByFlag("${options.pairs.flag}"), which derives experiment A/B pairs — it only works with by: "experiment" (got by: ${JSON.stringify(
894
+ dimensionName(options.by),
895
+ )}). Set by: "experiment", or write literal pairs for other dimensions.`,
896
+ );
897
+ }
898
+ const derived = derivePairsByFlag(snapshots, options.pairs);
899
+ pairs = derived.pairs;
900
+ experiments = derived.experiments;
901
+ } else {
902
+ if (!Array.isArray(options.pairs)) {
903
+ throw new Error("deltaTableData pairs must be an array of { label, a, b } or a pairsByFlag(...) declaration.");
904
+ }
905
+ if (options.pairs.length === 0) {
906
+ throw new Error(
907
+ "deltaTableData pairs is empty — a delta table with no pairs has nothing to compare. " +
908
+ "Declare at least one { label, a, b } pair, or use pairsByFlag(name) to derive pairs from experiment flags.",
909
+ );
910
+ }
911
+ const seenLabels = new Set<string>();
912
+ for (const pair of options.pairs) {
913
+ const labelKey = JSON.stringify(sortedJson(pair.label));
914
+ if (pair.label === undefined || pair.label === "" || labelKey === "{}") {
915
+ throw new Error(`deltaTableData pair (${pair.a} vs ${pair.b}) has an empty label; every pair needs a display label.`);
916
+ }
917
+ if (seenLabels.has(labelKey)) {
918
+ throw new Error(`deltaTableData pair label ${labelKey} is used twice — labels must be unique within one table.`);
919
+ }
920
+ seenLabels.add(labelKey);
921
+ if (pair.a === pair.b) {
922
+ throw new Error(`deltaTableData pair "${labelKey}" compares "${pair.a}" with itself; a and b must differ.`);
923
+ }
924
+ }
925
+ pairs = options.pairs;
926
+ }
927
+
928
+ const items = filterItems(collectItems(snapshots), options.evals);
929
+ const groups = groupItems(items, options.by);
755
930
  const rows: DeltaData["rows"] = [];
756
- for (const pair of opts.pairs) {
757
- const aItems = sideItems(pair.a);
758
- const bItems = sideItems(pair.b);
759
- const cells: Record<string, DeltaData["rows"][number]["cells"][string]> = {};
760
- for (const metric of opts.metrics) {
931
+ for (const pair of pairs) {
932
+ // 精确匹配分组后的维度 key,不做前缀或模糊匹配;未命中保留 pair,对应侧格子为缺失。
933
+ const aItems = groups.get(pair.a) ?? [];
934
+ const bItems = groups.get(pair.b) ?? [];
935
+ const cells: DeltaData["rows"][number]["cells"] = {};
936
+ for (const metric of options.metrics) {
761
937
  const a = await computeCell(metric, aItems);
762
938
  const b = await computeCell(metric, bItems);
763
- const d = a.value === null || b.value === null ? null : b.value - a.value;
764
- cells[metric.name] = { a, b, delta: d, display: deltaDisplay(metric, d) };
939
+ const delta = a.value === null || b.value === null ? null : b.value - a.value;
940
+ cells[metric.name] = {
941
+ a,
942
+ b,
943
+ delta,
944
+ display: deltaDisplay(metric, delta),
945
+ outcome: deltaOutcome(metric, delta),
946
+ };
765
947
  }
766
948
  rows.push({
767
- key: pair.label ?? `${pair.a} vs ${pair.b}`,
768
- a: { experimentId: pair.a },
769
- b: { experimentId: pair.b },
949
+ key: `${pair.a} ${pair.b}`,
950
+ label: pair.label,
951
+ a: { key: pair.a },
952
+ b: { key: pair.b },
770
953
  cells,
771
954
  });
772
955
  }
773
- return { columns: opts.metrics.map(toColumn), rows } as DeltaData<M[number]["name"]>;
956
+ return {
957
+ byDimension: dimensionName(options.by),
958
+ columns: options.metrics.map(toColumn),
959
+ ...(experiments !== undefined ? { experiments } : {}),
960
+ rows,
961
+ };
774
962
  }
775
963
 
776
- function deltaDisplay(metric: Metric, delta: number | null): string {
964
+ function deltaDisplay(metric: Metric, delta: number | null): LocalizedText {
777
965
  if (delta === null) return "—"; // 任一侧缺数据:Δ 显示为缺,不硬算
778
966
  if (delta === 0) return "±0";
779
- const text = displayValue(metric, delta); // 负号由格式化自带
780
- return delta > 0 ? `+${text}` : text;
967
+ if (metric.display) {
968
+ const display = metric.display;
969
+ return localizedDisplay((locale) => {
970
+ const text = display(Math.abs(delta), locale);
971
+ return delta > 0 ? `+${text}` : `-${text}`;
972
+ });
973
+ }
974
+ const text = formatMetricValue(Math.abs(delta), metric.unit);
975
+ return delta > 0 ? `+${text}` : `-${text}`;
976
+ }
977
+
978
+ function deltaOutcome(metric: Metric, delta: number | null): "improved" | "regressed" | "unchanged" | "unavailable" {
979
+ if (delta === null) return "unavailable";
980
+ if (delta === 0) return "unchanged";
981
+ const better = metric.better ?? "higher";
982
+ return (delta > 0) === (better === "higher") ? "improved" : "regressed";
781
983
  }