niceeval 0.6.2 → 0.7.0

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