niceeval 0.6.1 → 0.6.2

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 (296) hide show
  1. package/dist/agents/types.d.ts +67 -5
  2. package/dist/context/types.d.ts +32 -12
  3. package/dist/i18n/en.d.ts +54 -0
  4. package/dist/i18n/zh-CN.d.ts +55 -1
  5. package/dist/o11y/types.d.ts +16 -2
  6. package/dist/report/aggregate.d.ts +5 -3
  7. package/dist/report/aggregate.js +32 -5
  8. package/dist/report/built-ins/experiment-comparison.d.ts +39 -1
  9. package/dist/report/built-ins/experiment-comparison.js +116 -10
  10. package/dist/report/built-ins/index.d.ts +1 -0
  11. package/dist/report/built-ins/index.js +1 -1
  12. package/dist/report/components.d.ts +8 -2
  13. package/dist/report/components.js +3 -3
  14. package/dist/report/compute.d.ts +11 -18
  15. package/dist/report/compute.js +54 -34
  16. package/dist/report/flag.d.ts +16 -1
  17. package/dist/report/flag.js +19 -1
  18. package/dist/report/format.d.ts +16 -8
  19. package/dist/report/format.js +27 -12
  20. package/dist/report/index.d.ts +4 -3
  21. package/dist/report/index.js +5 -4
  22. package/dist/report/locale.d.ts +11 -2
  23. package/dist/report/locale.js +23 -5
  24. package/dist/report/metrics.d.ts +13 -1
  25. package/dist/report/metrics.js +65 -14
  26. package/dist/report/primitives.d.ts +6 -0
  27. package/dist/report/react/AttemptList.d.ts +2 -2
  28. package/dist/report/react/AttemptList.js +5 -6
  29. package/dist/report/react/EvalList.d.ts +1 -1
  30. package/dist/report/react/EvalList.js +0 -0
  31. package/dist/report/react/ExperimentComparison.d.ts +8 -0
  32. package/dist/report/react/ExperimentComparison.js +11 -0
  33. package/dist/report/react/ExperimentList.d.ts +2 -1
  34. package/dist/report/react/ExperimentList.js +8 -10
  35. package/dist/report/react/MetricScatter.js +5 -11
  36. package/dist/report/react/chart-math.d.ts +23 -6
  37. package/dist/report/react/chart-math.js +71 -19
  38. package/dist/report/react/fixtures.d.ts +3 -3
  39. package/dist/report/react/fixtures.js +21 -14
  40. package/dist/report/report.d.ts +5 -1
  41. package/dist/report/report.js +6 -2
  42. package/dist/report/text/faces.d.ts +1 -1
  43. package/dist/report/text/faces.js +42 -41
  44. package/dist/report/text/table.js +36 -5
  45. package/dist/report/types.d.ts +39 -21
  46. package/dist/results/types.d.ts +11 -0
  47. package/dist/runner/feedback/sink.d.ts +110 -0
  48. package/dist/runner/types.d.ts +513 -22
  49. package/dist/sandbox/docker.d.ts +23 -2
  50. package/dist/sandbox/e2b.d.ts +15 -1
  51. package/dist/sandbox/errors.d.ts +30 -3
  52. package/dist/sandbox/io-retry.d.ts +17 -0
  53. package/dist/sandbox/registry.d.ts +2 -0
  54. package/dist/sandbox/resolve.d.ts +18 -5
  55. package/dist/sandbox/retry.d.ts +11 -1
  56. package/dist/sandbox/types.d.ts +39 -5
  57. package/dist/sandbox/vercel.d.ts +7 -1
  58. package/dist/scoring/coverage.d.ts +30 -0
  59. package/dist/scoring/display.d.ts +21 -0
  60. package/dist/scoring/display.js +120 -0
  61. package/dist/scoring/types.d.ts +103 -20
  62. package/dist/shared/aggregate.d.ts +1 -0
  63. package/dist/shared/aggregate.js +3 -3
  64. package/dist/shared/types.d.ts +28 -0
  65. package/dist/tty-line.d.ts +0 -4
  66. package/dist/util.d.ts +23 -0
  67. package/docs-site/zh/concepts/adapter.mdx +22 -4
  68. package/docs-site/zh/concepts/experiment.mdx +1 -1
  69. package/docs-site/zh/concepts/overview.mdx +6 -6
  70. package/docs-site/zh/guides/agent-feedback-loop.mdx +28 -26
  71. package/docs-site/zh/guides/authoring.mdx +33 -0
  72. package/docs-site/zh/guides/ci-integration.mdx +23 -12
  73. package/docs-site/zh/guides/connect-your-agent.mdx +29 -3
  74. package/docs-site/zh/guides/custom-reports.mdx +29 -34
  75. package/docs-site/zh/guides/dataset-fanout.mdx +25 -3
  76. package/docs-site/zh/guides/debug-sandbox.mdx +57 -0
  77. package/docs-site/zh/guides/debugging.mdx +210 -0
  78. package/docs-site/zh/guides/experiments.mdx +10 -3
  79. package/docs-site/zh/guides/official-adapters.mdx +26 -2
  80. package/docs-site/zh/guides/publish-report.mdx +30 -16
  81. package/docs-site/zh/guides/report-components.mdx +42 -30
  82. package/docs-site/zh/guides/reporters.mdx +2 -2
  83. package/docs-site/zh/guides/results-data.mdx +17 -9
  84. package/docs-site/zh/guides/runner.mdx +17 -7
  85. package/docs-site/zh/guides/sandbox-agent.mdx +56 -7
  86. package/docs-site/zh/guides/sandbox-providers.mdx +257 -9
  87. package/docs-site/zh/guides/scoring-guide.mdx +4 -4
  88. package/docs-site/zh/guides/viewing-results.mdx +79 -36
  89. package/docs-site/zh/guides/write-experiment.mdx +5 -3
  90. package/docs-site/zh/guides/write-send.mdx +17 -1
  91. package/docs-site/zh/index.mdx +1 -1
  92. package/docs-site/zh/reference/builtin-agents.mdx +27 -0
  93. package/docs-site/zh/reference/capabilities.mdx +2 -2
  94. package/docs-site/zh/reference/cli.mdx +33 -7
  95. package/docs-site/zh/reference/define-agent.mdx +57 -4
  96. package/docs-site/zh/reference/define-config.mdx +1 -1
  97. package/docs-site/zh/reference/define-eval.mdx +42 -9
  98. package/docs-site/zh/reference/expect.mdx +26 -1
  99. package/package.json +5 -1
  100. package/src/agents/ai-sdk-otel.test.ts +1 -0
  101. package/src/agents/ai-sdk.test.ts +3 -0
  102. package/src/agents/ai-sdk.ts +3 -0
  103. package/src/agents/bub-install-spec.test.ts +34 -0
  104. package/src/agents/bub-install-spec.ts +32 -0
  105. package/src/agents/bub.ts +31 -32
  106. package/src/agents/claude-code.test.ts +130 -9
  107. package/src/agents/claude-code.ts +76 -4
  108. package/src/agents/codex.test.ts +189 -40
  109. package/src/agents/codex.ts +155 -14
  110. package/src/agents/coding-cli-versions.test.ts +15 -0
  111. package/src/agents/coding-cli-versions.ts +3 -0
  112. package/src/agents/index.ts +11 -0
  113. package/src/agents/langgraph.test.ts +204 -0
  114. package/src/agents/langgraph.ts +495 -0
  115. package/src/agents/marketplace.ts +85 -0
  116. package/src/agents/native-config.test.ts +179 -0
  117. package/src/agents/native-config.ts +267 -0
  118. package/src/agents/openai-compat.test.ts +1 -0
  119. package/src/agents/openclaw.test.ts +31 -0
  120. package/src/agents/openclaw.ts +171 -0
  121. package/src/agents/plugin-config.test.ts +1 -0
  122. package/src/agents/sdk-streams.test.ts +79 -0
  123. package/src/agents/sdk-streams.ts +55 -10
  124. package/src/agents/skills.test.ts +1 -0
  125. package/src/agents/streaming.test.ts +3 -9
  126. package/src/agents/types.ts +68 -5
  127. package/src/agents/ui-message-stream.test.ts +3 -0
  128. package/src/cli.ts +411 -108
  129. package/src/context/context.test.ts +51 -12
  130. package/src/context/context.ts +161 -29
  131. package/src/context/session.test.ts +1 -0
  132. package/src/context/session.ts +114 -6
  133. package/src/context/types.ts +30 -12
  134. package/src/define.test.ts +13 -8
  135. package/src/define.ts +25 -4
  136. package/src/expect/index.ts +53 -23
  137. package/src/i18n/en.ts +64 -2
  138. package/src/i18n/zh-CN.ts +65 -3
  139. package/src/o11y/cost.test.ts +1 -0
  140. package/src/o11y/execution-tree.test.ts +1 -20
  141. package/src/o11y/otlp/mappers/claude-code.test.ts +1 -0
  142. package/src/o11y/otlp/parse.test.ts +1 -0
  143. package/src/o11y/otlp/turn-otel.test.ts +1 -0
  144. package/src/o11y/parsers/bub.test.ts +1 -0
  145. package/src/o11y/parsers/claude-code.test.ts +1 -34
  146. package/src/o11y/parsers/openclaw.test.ts +154 -0
  147. package/src/o11y/parsers/openclaw.ts +310 -0
  148. package/src/o11y/prices.json +746 -311
  149. package/src/o11y/tool-names.test.ts +1 -0
  150. package/src/o11y/types.ts +16 -2
  151. package/src/report/aggregate.ts +34 -5
  152. package/src/report/built-in-user-parity.test.tsx +110 -153
  153. package/src/report/built-ins/experiment-comparison.tsx +173 -13
  154. package/src/report/built-ins/index.ts +6 -1
  155. package/src/report/components.tsx +9 -3
  156. package/src/report/compute.ts +70 -40
  157. package/src/report/dual-render.test.tsx +194 -67
  158. package/src/report/flag.ts +30 -2
  159. package/src/report/format.ts +35 -11
  160. package/src/report/index.ts +22 -4
  161. package/src/report/locale.ts +25 -5
  162. package/src/report/metrics.ts +67 -14
  163. package/src/report/primitives.tsx +6 -0
  164. package/src/report/react/AttemptList.tsx +6 -31
  165. package/src/report/react/EvalList.tsx +0 -0
  166. package/src/report/react/ExperimentComparison.tsx +68 -0
  167. package/src/report/react/ExperimentList.tsx +15 -9
  168. package/src/report/react/MetricScatter.tsx +12 -14
  169. package/src/report/react/chart-math.test.ts +85 -0
  170. package/src/report/react/chart-math.ts +101 -22
  171. package/src/report/react/enhance.js +33 -1
  172. package/src/report/react/fixtures.ts +24 -17
  173. package/src/report/react/render.test.tsx +9 -64
  174. package/src/report/react/styles.css +73 -2
  175. package/src/report/report.test.ts +306 -98
  176. package/src/report/report.ts +6 -2
  177. package/src/report/text/faces.ts +47 -43
  178. package/src/report/text/table.ts +42 -5
  179. package/src/report/types.ts +41 -21
  180. package/src/results/annotated-source.test.ts +62 -9
  181. package/src/results/annotated-source.ts +64 -6
  182. package/src/results/attempt-evidence.test.ts +9 -7
  183. package/src/results/attempt-evidence.ts +15 -8
  184. package/src/results/attempt-source.ts +6 -3
  185. package/src/results/copy.ts +145 -55
  186. package/src/results/host-equivalence.test.ts +8 -6
  187. package/src/results/index.ts +2 -0
  188. package/src/results/locator.test.ts +1 -22
  189. package/src/results/open.ts +7 -1
  190. package/src/results/publish.ts +149 -0
  191. package/src/results/results.test.ts +85 -51
  192. package/src/results/truncate.ts +90 -0
  193. package/src/results/types.ts +7 -0
  194. package/src/results/writer.ts +31 -13
  195. package/src/runner/attempt.test.ts +138 -7
  196. package/src/runner/attempt.ts +603 -104
  197. package/src/runner/discover.test.ts +47 -0
  198. package/src/runner/discover.ts +36 -2
  199. package/src/runner/eval-source.test.ts +1 -27
  200. package/src/runner/feedback/agent.test.ts +504 -0
  201. package/src/runner/feedback/agent.ts +409 -0
  202. package/src/runner/feedback/ci.test.ts +562 -0
  203. package/src/runner/feedback/ci.ts +401 -0
  204. package/src/runner/feedback/coordinator.test.ts +317 -0
  205. package/src/runner/feedback/coordinator.ts +397 -0
  206. package/src/runner/feedback/failure.ts +40 -0
  207. package/src/runner/feedback/human.test.ts +616 -0
  208. package/src/runner/feedback/human.ts +535 -0
  209. package/src/runner/feedback/index.ts +66 -0
  210. package/src/runner/feedback/io.ts +78 -0
  211. package/src/runner/feedback/profile.test.ts +50 -0
  212. package/src/runner/feedback/profile.ts +58 -0
  213. package/src/runner/feedback/reducer.test.ts +395 -0
  214. package/src/runner/feedback/reducer.ts +260 -0
  215. package/src/runner/feedback/renderer.ts +82 -0
  216. package/src/runner/feedback/sink.ts +203 -0
  217. package/src/runner/feedback/testing.ts +106 -0
  218. package/src/runner/ledger.test.ts +230 -0
  219. package/src/runner/ledger.ts +329 -0
  220. package/src/runner/report.test.ts +128 -3
  221. package/src/runner/report.ts +33 -9
  222. package/src/runner/reporters/artifacts.ts +8 -2
  223. package/src/runner/reporters/braintrust.test.ts +8 -7
  224. package/src/runner/reporters/braintrust.ts +9 -2
  225. package/src/runner/reporters/index.ts +2 -2
  226. package/src/runner/reporters/json.test.ts +162 -0
  227. package/src/runner/reporters/json.ts +35 -8
  228. package/src/runner/reporters/shared.ts +1 -5
  229. package/src/runner/run.test.ts +760 -3
  230. package/src/runner/run.ts +242 -36
  231. package/src/runner/sandbox-prep.ts +3 -42
  232. package/src/runner/timing.ts +158 -0
  233. package/src/runner/types.ts +518 -22
  234. package/src/sandbox/checkpoint.test.ts +55 -0
  235. package/src/sandbox/checkpoint.ts +29 -8
  236. package/src/sandbox/cli-commands.ts +407 -0
  237. package/src/sandbox/docker.ts +115 -16
  238. package/src/sandbox/e2b-agent-template.test.ts +56 -0
  239. package/src/sandbox/e2b-agent-template.ts +94 -0
  240. package/src/sandbox/e2b.ts +74 -9
  241. package/src/sandbox/errors.ts +111 -4
  242. package/src/sandbox/index.ts +2 -0
  243. package/src/sandbox/io-retry.test.ts +58 -0
  244. package/src/sandbox/io-retry.ts +45 -0
  245. package/src/sandbox/keep-registry.test.ts +86 -0
  246. package/src/sandbox/keep-registry.ts +142 -0
  247. package/src/sandbox/keep.ts +178 -0
  248. package/src/sandbox/paths.test.ts +1 -0
  249. package/src/sandbox/paths.ts +19 -8
  250. package/src/sandbox/registry.ts +20 -3
  251. package/src/sandbox/resolve.ts +76 -11
  252. package/src/sandbox/retry.test.ts +70 -0
  253. package/src/sandbox/retry.ts +46 -4
  254. package/src/sandbox/types.ts +44 -6
  255. package/src/sandbox/vercel.ts +43 -20
  256. package/src/scoring/collector.ts +60 -17
  257. package/src/scoring/coverage.ts +95 -0
  258. package/src/scoring/diff.ts +81 -0
  259. package/src/scoring/display.test.ts +121 -0
  260. package/src/scoring/display.ts +133 -0
  261. package/src/scoring/evidence.test.ts +189 -0
  262. package/src/scoring/judge.test.ts +142 -0
  263. package/src/scoring/judge.ts +15 -18
  264. package/src/scoring/scoped.ts +217 -50
  265. package/src/scoring/types.ts +117 -20
  266. package/src/scoring/verdict.ts +16 -4
  267. package/src/shared/aggregate.ts +3 -2
  268. package/src/shared/types.ts +31 -0
  269. package/src/show/compose.ts +2 -2
  270. package/src/show/index.ts +21 -1
  271. package/src/show/render.ts +619 -104
  272. package/src/show/show.test.ts +235 -19
  273. package/src/tty-line.ts +8 -26
  274. package/src/util.test.ts +1 -0
  275. package/src/util.ts +41 -0
  276. package/src/view/app/components/AttemptModal.tsx +153 -2
  277. package/src/view/app/components/CodeView.tsx +32 -11
  278. package/src/view/app/components/CopyControls.tsx +2 -2
  279. package/src/view/app/i18n.ts +6 -0
  280. package/src/view/app/lib/attempt-route.test.ts +1 -0
  281. package/src/view/app/lib/verdict.ts +7 -9
  282. package/src/view/artifact-serving.test.ts +2 -1
  283. package/src/view/client-dist/app.css +1 -1
  284. package/src/view/client-dist/app.js +17 -17
  285. package/src/view/data.test.ts +1 -0
  286. package/src/view/data.ts +11 -1
  287. package/src/view/index.ts +11 -0
  288. package/src/view/server.ts +2 -0
  289. package/src/view/styles.css +3 -0
  290. package/src/view/view-report.test.ts +6 -5
  291. package/src/runner/reporters/console.ts +0 -70
  292. package/src/runner/reporters/live.test.ts +0 -56
  293. package/src/runner/reporters/live.ts +0 -247
  294. package/src/runner/reporters/quiet.test.ts +0 -66
  295. package/src/runner/reporters/quiet.ts +0 -49
  296. package/src/runner/reporters/table.ts +0 -277
@@ -4,13 +4,14 @@
4
4
  // 全部纯函数(时间经 now 显式传入),证据数据由调用方 await 好了递进来。
5
5
 
6
6
  import { join, relative } from "node:path";
7
- import type { AssertionResult, DiffData, EvalResult, Verdict } from "../types.ts";
7
+ import type { AssertionResult, DiffData, EvalResult, TimingNode, TraceSpan, Verdict } from "../types.ts";
8
8
  import type { AttemptEvidence, AttemptHandle, Snapshot } from "../results/index.ts";
9
- import type { AnnotatedSourceLine } from "../results/index.ts";
9
+ import type { AnnotatedSourceLine, SendAnnotation } from "../results/index.ts";
10
10
  import { groupIncompatibleVersionSkips } from "../results/index.ts";
11
11
  import type { SkippedDir } from "../results/index.ts";
12
12
  import type { ExecutionNode } from "../o11y/execution-tree.ts";
13
13
  import { foldEvalVerdict } from "../shared/verdict.ts";
14
+ import { summaryText } from "../scoring/display.ts";
14
15
  import { attemptCostUSD } from "../report/metrics.ts";
15
16
  import { formatDurationMs, formatMetricValue, formatPlainNumber, formatUSD } from "../report/format.ts";
16
17
  import { indentBlock, padDisplay, renderAlignedRows, wrapDisplay } from "../report/text/layout.ts";
@@ -128,43 +129,97 @@ function scoreText(score: number): string {
128
129
  return formatPlainNumber(Math.round(score * 100) / 100);
129
130
  }
130
131
 
131
- /** 断言行:✓/✗ + severity + name;gate 失败带 detail,soft 恒带 score/1(失败再补 detail)。 */
132
+ /** 分组路径标题(嵌套用 " > " 拼接);无分组返回 undefined。 */
133
+ function groupTitle(a: AssertionResult): string | undefined {
134
+ return a.groupPath && a.groupPath.length > 0 ? a.groupPath.join(" > ") : undefined;
135
+ }
136
+
137
+ /** 断言行:✓/✗/◌ + severity + 标题;unavailable 带 reason,soft 恒带 score/1(失败再补 detail)。 */
132
138
  export function assertionLine(a: AssertionResult): string {
133
- const scope = a.group ? `${a.group} · ` : "";
134
- const head = `${a.passed ? "✓" : ""} ${a.severity} ${scope}${a.name}`;
139
+ const group = groupTitle(a);
140
+ const scope = group ? `${group} · ` : "";
141
+ const optional = a.optional ? "optional · " : "";
142
+ if (a.outcome === "unavailable") {
143
+ return `◌ ${a.severity} · ${optional}${scope}${a.name} — unavailable: ${a.reason}`;
144
+ }
145
+ const head = `${a.outcome === "passed" ? "✓" : "✗"} ${a.severity} ${optional}${scope}${a.name}`;
135
146
  if (a.severity === "soft") {
136
- const detail = !a.passed && a.detail ? `: ${a.detail}` : "";
137
- return `${head} ${scoreText(a.score)}/1${detail}`;
147
+ const detail = a.outcome === "failed" && a.detail ? `: ${a.detail}` : "";
148
+ const threshold = a.threshold !== undefined ? ` / ${scoreText(a.threshold)}` : "/1";
149
+ return `${head} — ${scoreText(a.score)}${threshold}${detail}`;
138
150
  }
139
- if (!a.passed) {
151
+ if (a.outcome === "failed") {
140
152
  const reason = a.detail ?? `score ${scoreText(a.score)}`;
141
- return a.evidence !== undefined ? `${head} — ${reason} · actual: ${a.evidence}` : `${head} — ${reason}`;
153
+ const received = a.received ?? a.evidence;
154
+ // 单行面只放摘要收口后的预览;多行值(如 output tail)的完整版在 attempt 首页展开。
155
+ return received !== undefined ? `${head} — ${reason} · received: ${summaryText(received)}` : `${head} — ${reason}`;
142
156
  }
143
157
  return head;
144
158
  }
145
159
 
146
- function equalsExpected(name: string): string | undefined {
147
- const match = /^equals\((.*)\)$/.exec(name);
148
- return match?.[1];
160
+ /** 字段行:首行 `<label>: <值首行>`,值的其余行( CommandResult output tail)缩进原样展开。 */
161
+ function fieldLines(label: string, value: string): string[] {
162
+ const [first, ...rest] = value.split("\n");
163
+ return [` ${label}: ${first ?? ""}`, ...rest.map((line) => ` ${line}`)];
149
164
  }
150
165
 
151
- /** 默认 Attempt 页的首要诊断:不要求用户再猜一次 evidence flag 才知道为何失败。 */
152
- export function failureDiagnostics(assertions: AssertionResult[], width: number): string | undefined {
153
- const failed = assertions.filter((a) => !a.passed);
154
- if (failed.length === 0) return undefined;
155
- const lines = ["failures:"];
156
- for (const a of failed) {
157
- const label = a.group ?? a.name;
158
- lines.push(` ${a.severity} · ${label}`);
159
- if (a.group) lines.push(` assertion: ${a.name}`);
160
- const expected = equalsExpected(a.name);
161
- if (expected !== undefined) lines.push(` expected: ${expected}`);
162
- if (a.evidence !== undefined) lines.push(` received: ${a.evidence}`);
163
- if (a.detail) lines.push(` reason: ${a.detail}`);
164
- if (a.loc) lines.push(` source: ${a.loc.file}:${a.loc.line}${a.loc.column ? `:${a.loc.column}` : ""}`);
165
- if (a.severity === "soft") lines.push(` score: ${scoreText(a.score)}/1`);
166
+ /** 每条的通用行组(见 docs/feature/scoring/library/display.md「通用渲染规则」):
167
+ * 首行 `severity · <标题>`(有分组时标题是分组路径,随后 assertion: 行给检查方式),
168
+ * 之后按有则显示的顺序列 expected / received / score / reason / source。 */
169
+ function assertionRecordLines(a: AssertionResult): string[] {
170
+ const group = groupTitle(a);
171
+ const optional = a.optional ? "optional · " : "";
172
+ const title = group ?? a.name;
173
+ const lines: string[] = [];
174
+ const scoreSuffix =
175
+ a.outcome !== "unavailable" && (a.severity === "soft" || a.threshold !== undefined)
176
+ ? ` ${scoreText(a.score)}${a.threshold !== undefined ? ` / ${scoreText(a.threshold)}` : ""}`
177
+ : "";
178
+ lines.push(` ${a.severity} · ${optional}${title}${scoreSuffix}`);
179
+ const detailLine = a.detail ?? (group ? a.name : undefined);
180
+ if (detailLine !== undefined && detailLine !== title) lines.push(` assertion: ${detailLine}`);
181
+ if (a.outcome === "unavailable") {
182
+ lines.push(` reason: ${a.reason}`);
183
+ } else {
184
+ if (a.expected !== undefined) lines.push(...fieldLines("expected", a.expected));
185
+ if (a.received !== undefined) lines.push(...fieldLines("received", a.received));
186
+ if (a.evidence !== undefined && a.evidence !== a.received) lines.push(...fieldLines("evidence", a.evidence));
166
187
  }
188
+ if (a.loc) lines.push(` source: ${a.loc.file}:${a.loc.line}${a.loc.column ? `:${a.loc.column}` : ""}`);
189
+ return lines;
190
+ }
191
+
192
+ /**
193
+ * 默认 Attempt 页的首要诊断:按结果分节,只逐条列出需要看的(见 display.md)——
194
+ * `failures:`(gate 失败,含 --strict 下改判的 soft)、`soft below threshold:`、
195
+ * `scores:`(无阈值 judge 的纯打分)、`unavailable:`(证据评不了的,带 reason)。
196
+ * 全部通过时这些节整体省略(返回 undefined),只留计数行。
197
+ */
198
+ export function failureDiagnostics(assertions: AssertionResult[], width: number, strict?: boolean): string | undefined {
199
+ const failures = assertions.filter(
200
+ (a) => a.outcome === "failed" && (a.severity === "gate" || strict),
201
+ );
202
+ const softBelow = assertions.filter(
203
+ (a) => a.outcome === "failed" && a.severity === "soft" && !strict,
204
+ );
205
+ const scores = assertions.filter(
206
+ (a) => a.outcome === "passed" && a.severity === "soft" && a.threshold === undefined && a.score < 1,
207
+ );
208
+ const unavailableOnes = assertions.filter((a) => a.outcome === "unavailable");
209
+ const lines: string[] = [];
210
+ const section = (title: string, items: AssertionResult[]) => {
211
+ if (items.length === 0) return;
212
+ if (lines.length > 0) lines.push("");
213
+ lines.push(title);
214
+ for (const a of items) lines.push(...assertionRecordLines(a));
215
+ };
216
+ section("failures:", failures);
217
+ section("soft below threshold:", softBelow);
218
+ section("scores:", scores);
219
+ section("unavailable:", unavailableOnes);
220
+ if (lines.length === 0) return undefined;
167
221
  return lines.flatMap((line) => {
222
+ if (line === "") return [line];
168
223
  const indent = line.length - line.trimStart().length;
169
224
  return wrapDisplay(line.trimStart(), Math.max(20, width - indent)).map((part) => `${" ".repeat(indent)}${part}`);
170
225
  }).join("\n");
@@ -205,10 +260,13 @@ export function attemptEvidenceHeader(evidence: AttemptEvidence): string {
205
260
  * 依赖它的内部实现细节。
206
261
  */
207
262
  export function verdictReasonLine(result: EvalResult): string | undefined {
208
- if (result.error !== undefined) return result.error;
263
+ if (result.error !== undefined) return result.error.message;
209
264
  if (result.skipReason !== undefined) return result.skipReason;
210
- const gates = result.assertions.filter((a) => !a.passed && a.severity === "gate");
211
- if (gates.length === 0) return undefined;
265
+ const gates = result.assertions.filter((a) => a.outcome === "failed" && a.severity === "gate");
266
+ if (gates.length === 0) {
267
+ const gap = result.assertions.find((a) => a.outcome === "unavailable" && !a.optional);
268
+ return gap && gap.outcome === "unavailable" ? `unavailable ${gap.name} (${gap.reason})` : undefined;
269
+ }
212
270
  return gates.map((a) => `gate ${a.name}`).join(", ");
213
271
  }
214
272
 
@@ -233,13 +291,15 @@ export function attemptIndexLine(opts: {
233
291
  * (未捕获源码),读 `result.assertions` 让这条摘要不因缺源码而跟着消失。
234
292
  */
235
293
  export function assertionSummaryLine(assertions: AssertionResult[]): string {
236
- const passed = assertions.filter((a) => a.passed).length;
237
- const gateFailed = assertions.filter((a) => !a.passed && a.severity === "gate").length;
238
- const softBelow = assertions.filter((a) => !a.passed && a.severity === "soft").length;
294
+ const passed = assertions.filter((a) => a.outcome === "passed").length;
295
+ const gateFailed = assertions.filter((a) => a.outcome === "failed" && a.severity === "gate").length;
296
+ const softBelow = assertions.filter((a) => a.outcome === "failed" && a.severity === "soft").length;
297
+ const unavailableCount = assertions.filter((a) => a.outcome === "unavailable").length;
239
298
  const parts: string[] = [];
240
299
  if (passed > 0) parts.push(`${passed} passed`);
241
300
  if (gateFailed > 0) parts.push(`${gateFailed} gate failed`);
242
301
  if (softBelow > 0) parts.push(`${softBelow} soft below target`);
302
+ if (unavailableCount > 0) parts.push(`${unavailableCount} unavailable`);
243
303
  return `assertions: ${parts.length > 0 ? parts.join(" · ") : "(none)"}`;
244
304
  }
245
305
 
@@ -301,7 +361,7 @@ export function evalDetailText(opts: EvalDetailOptions): string {
301
361
  lines.push(indentBlock(wrapDisplay(assertionLine(a), width - 2).join("\n"), " "));
302
362
  }
303
363
  if (detail.result.error !== undefined) {
304
- lines.push(indentBlock(wrapDisplay(`error: ${detail.result.error}`, width - 2).join("\n"), " "));
364
+ lines.push(indentBlock(wrapDisplay(`error: ${detail.result.error.message}`, width - 2).join("\n"), " "));
305
365
  }
306
366
  if (detail.result.skipReason !== undefined) {
307
367
  lines.push(indentBlock(wrapDisplay(`skipped: ${detail.result.skipReason}`, width - 2).join("\n"), " "));
@@ -403,28 +463,51 @@ function indentedText(text: string, width: number, indent = 4, maxLines = 18): s
403
463
 
404
464
  const MAX_SOURCE_LINES = 400;
405
465
 
406
- /** gate 失败 / soft 恒带分——与 assertionLine 的严重度口径一致,但不带断言 name(源码行本身就是名字)。 */
466
+ /** gate 失败 / soft 恒带分 / unavailable reason——与 assertionLine 的口径一致,但不带断言
467
+ * name(源码行本身就是名字)。 */
407
468
  function evalAssertionDetailLine(a: AssertionResult): string | undefined {
469
+ if (a.outcome === "unavailable") {
470
+ return `${a.severity} · unavailable · ${a.reason}`;
471
+ }
408
472
  if (a.severity === "soft") {
409
- const detail = !a.passed && a.detail ? ` · ${a.detail}` : "";
410
- return `soft · ${scoreText(a.score)}/1${detail}`;
473
+ const detail = a.outcome === "failed" && a.detail ? ` · ${a.detail}` : "";
474
+ const threshold = a.threshold !== undefined ? ` / ${scoreText(a.threshold)}` : "/1";
475
+ return `soft · ${scoreText(a.score)}${threshold}${detail}`;
411
476
  }
412
- if (!a.passed) {
477
+ if (a.outcome === "failed") {
478
+ // 标注行是源码页里的一行事实,不是证据面:expected / received 过摘要收口
479
+ // (折单行 + 上限),完整值在 attempt 首页与 events.json / diff.json。
413
480
  const parts = ["gate"];
414
- if (a.group) parts.push(a.group);
481
+ const group = groupTitle(a);
482
+ if (group) parts.push(group);
415
483
  parts.push(a.name);
416
- const expected = equalsExpected(a.name);
417
- if (expected !== undefined) parts.push(`expected ${expected}`);
418
- if (a.evidence !== undefined) parts.push(`received ${a.evidence}`);
419
- if (a.detail) parts.push(a.detail);
484
+ if (a.expected !== undefined) parts.push(`expected ${summaryText(a.expected)}`);
485
+ const received = a.received ?? a.evidence;
486
+ if (received !== undefined) parts.push(`received ${summaryText(received)}`);
487
+ if (a.detail) parts.push(summaryText(a.detail));
420
488
  return parts.join(" · ");
421
489
  }
422
490
  return undefined;
423
491
  }
424
492
 
493
+ /** send 行标注:轮身份 · status · 墙钟(有记录才出现),契约见 show.md「--eval」。 */
494
+ function sendAnnotationLine(send: SendAnnotation): string {
495
+ const parts = [send.label, send.status];
496
+ if (send.durationMs !== undefined) parts.push(formatDurationMs(send.durationMs));
497
+ return parts.join(" · ");
498
+ }
499
+
425
500
  function evalSourceLineText(line: AnnotatedSourceLine, gutterWidth: number, width: number): string[] {
426
- const anyFailed = line.assertions.some((a) => !a.passed);
427
- const glyph = line.assertions.length === 0 ? " " : anyFailed ? "✗" : "✓";
501
+ const anyFailed = line.assertions.some((a) => a.outcome === "failed") ||
502
+ line.sends.some((send) => send.status === "failed");
503
+ const anyUnavailable = line.assertions.some((a) => a.outcome === "unavailable");
504
+ const glyph = line.assertions.length === 0 && line.sends.length === 0
505
+ ? " "
506
+ : anyFailed
507
+ ? "✗"
508
+ : anyUnavailable
509
+ ? "◌"
510
+ : "✓";
428
511
  const marginWidth = gutterWidth + 2; // 行号列 + glyph + 分隔空格
429
512
  const prefix = `${padDisplay(String(line.line), gutterWidth)}${glyph} `;
430
513
  // 源码行的空白(尤其是缩进)是语义的一部分:wrapDisplay 按单词重排会把连续空格
@@ -433,6 +516,11 @@ function evalSourceLineText(line: AnnotatedSourceLine, gutterWidth: number, widt
433
516
  // 折行只对续行加统一 margin,救不回已经被吃掉的原始缩进,不如老实截断。
434
517
  const out = [prefix + clip(line.text, Math.max(20, width - marginWidth))];
435
518
  const margin = " ".repeat(marginWidth);
519
+ for (const send of line.sends) {
520
+ for (const wrapped2 of wrapDisplay(sendAnnotationLine(send), Math.max(20, width - marginWidth))) {
521
+ out.push(margin + wrapped2);
522
+ }
523
+ }
436
524
  for (const a of line.assertions) {
437
525
  const detail = evalAssertionDetailLine(a);
438
526
  if (detail === undefined) continue;
@@ -473,8 +561,14 @@ export function evalSourceText(
473
561
  );
474
562
  }
475
563
 
476
- blocks.push(assertionSummaryLine(evidence.result.assertions));
477
- if (artifact) blocks.push(`full eval source: ${artifact}`);
564
+ const tail = [assertionSummaryLine(evidence.result.assertions)];
565
+ // 标注行的值是收口预览;有未通过断言时给「更进一步」——attempt 首页展开完整 expected /
566
+ // received(含 output tail),再往下是 result.json / events.json。
567
+ if (evidence.result.assertions.some((a) => a.outcome !== "passed")) {
568
+ tail.push(`full failure detail: niceeval show ${evidence.locator}`);
569
+ }
570
+ if (artifact) tail.push(`full eval source: ${artifact}`);
571
+ blocks.push(tail.join("\n"));
478
572
  return blocks.join("\n\n");
479
573
  }
480
574
 
@@ -589,10 +683,30 @@ export function executionText(
589
683
  const agentNodes = tree.nodes.filter((node) => node.kind !== "telemetry");
590
684
  const telemetryCount = tree.nodes.length - agentNodes.length;
591
685
  const shown = agentNodes.slice(0, MAX_EVENTS);
592
- const lines = shown.flatMap((node, index) => [
593
- ...(index === 0 ? [] : [""]),
594
- ...executionNodeLines(node, originMs, timingAvailable, width),
595
- ]);
686
+
687
+ // 按轮分段( docs/feature/reports/show.md「--execution」):每轮以 TURN 头行开始——身份
688
+ // s<session>/t<turn>( --timing turn 节点、diff 的 windows 同一套标签,来自
689
+ // result.json.phases 的 turn 时间树)、该轮墙钟;边界按用户消息切(t.send 恒以用户消息开轮)。
690
+ const turnNodes = (evidence.result.phases ?? [])
691
+ .flatMap((p) => p.children ?? [])
692
+ .filter((n) => n.kind === "turn");
693
+ const lines: string[] = [];
694
+ let turnIndex = -1;
695
+ shown.forEach((node, index) => {
696
+ const isTurnStart = node.kind === "message" && node.role === "user";
697
+ if (isTurnStart) {
698
+ turnIndex += 1;
699
+ const turn = turnNodes[turnIndex];
700
+ const label = turn?.label ?? `t${turnIndex + 1}`;
701
+ const durationPart = turn ? ` · ${formatDurationMs(turn.durationMs)}` : "";
702
+ const failedPart = turn?.failed ? " · failed" : "";
703
+ if (index > 0) lines.push("");
704
+ lines.push(`TURN ${label}${failedPart || " · completed"}${durationPart}`);
705
+ } else if (index > 0) {
706
+ lines.push("");
707
+ }
708
+ lines.push(...executionNodeLines(node, originMs, timingAvailable, width).map((l) => (turnIndex >= 0 ? ` ${l}` : l)));
709
+ });
596
710
 
597
711
  const tail: string[] = [];
598
712
  if (timingAvailable) {
@@ -627,14 +741,38 @@ export function executionText(
627
741
 
628
742
  const MAX_OVERVIEW_DIFF_NAMES = 5;
629
743
 
744
+ /** net 效果的单字母标记(A/M/D;none = 动过但净无变化,标 ±)。 */
745
+ function netLetter(net: string): string {
746
+ switch (net) {
747
+ case "added":
748
+ return "A";
749
+ case "deleted":
750
+ return "D";
751
+ case "none":
752
+ return "±";
753
+ default:
754
+ return "M";
755
+ }
756
+ }
757
+
630
758
  function overviewDiffLine(diff: DiffData): string {
631
- const names = [
632
- ...Object.keys(diff.generatedFiles).sort().map((p) => `M ${p}`),
633
- ...[...diff.deletedFiles].sort().map((p) => `D ${p}`),
634
- ];
759
+ const names = Object.entries(diff.files)
760
+ .sort(([a], [b]) => a.localeCompare(b))
761
+ .map(([p, f]) => `${netLetter(f.net)} ${p}`);
635
762
  const shown = names.slice(0, MAX_OVERVIEW_DIFF_NAMES);
636
763
  const more = names.length > shown.length ? ` · +${names.length - shown.length} more` : "";
637
- return `changes: ${names.length} ${names.length === 1 ? "file" : "files"} changed · ${shown.join(", ")}${more}`;
764
+ return `changes: ${names.length} ${names.length === 1 ? "file" : "files"} changed by agent · ${shown.join(" · ")}${more}`;
765
+ }
766
+
767
+ /** 有界行 diff(公共前后缀修剪):对单区域编辑精确,复杂编辑给出上界近似。 */
768
+ function lineDelta(before: string | undefined, after: string | undefined): { adds: number; dels: number } {
769
+ const a = before === undefined ? [] : before.split("\n");
770
+ const b = after === undefined ? [] : after.split("\n");
771
+ let prefix = 0;
772
+ while (prefix < a.length && prefix < b.length && a[prefix] === b[prefix]) prefix++;
773
+ let suffix = 0;
774
+ while (suffix < a.length - prefix && suffix < b.length - prefix && a[a.length - 1 - suffix] === b[b.length - 1 - suffix]) suffix++;
775
+ return { adds: b.length - prefix - suffix, dels: a.length - prefix - suffix };
638
776
  }
639
777
 
640
778
  /**
@@ -642,6 +780,48 @@ function overviewDiffLine(diff: DiffData): string {
642
780
  * 执行事件计数、可选 OTel 时间指示、工作区 diff 摘要,不复现 `--eval` 的完整源码、
643
781
  * `--execution` 的完整事件流或 `--diff` 的完整文件列表(那些内容各自的证据 flag 才给)。
644
782
  */
783
+ /** lifecycle operation → 首页可读标签:点换空格,与 docs/feature/reports/show.md 的
784
+ * `phase: sandbox provision` 字面一致(不引入第二套本地化标签,show 首页用英文原样呈现)。 */
785
+ function operationWords(operation: string): string {
786
+ return operation.replace(/\./g, " ");
787
+ }
788
+
789
+ /**
790
+ * errored attempt 的结构化 `error:` 块(见 docs/feature/reports/show.md「errored attempt 的首页」)。
791
+ * 先展开 phase(= operation 的可读形态)/ code / message / cause,stack 放在块后、保持原始换行。
792
+ * 字段来自结构化 `AttemptError`;非 errored(`r.error === undefined`)返回 undefined。
793
+ */
794
+ function renderErrorBlock(r: EvalResult): string | undefined {
795
+ const err = r.error;
796
+ if (err === undefined) return undefined;
797
+ const lines = ["error:", ` phase: ${err.phase}`, ` code: ${err.code}`, ` message: ${err.message}`];
798
+ if (err.cause) {
799
+ const c = err.cause;
800
+ const causeText = c.name ? `${c.name} · ${c.message}` : c.message;
801
+ lines.push(` cause: ${causeText}`);
802
+ }
803
+ // stack 放在 error 块之后、保持原始换行(见 docs);没有 stack(如 timeout / turn-failed)就不加空块。
804
+ if (err.stack && err.stack.trim() !== "") return `${lines.join("\n")}\n\n${err.stack.replace(/\n+$/, "")}`;
805
+ return lines.join("\n");
806
+ }
807
+
808
+ /**
809
+ * attempt 级诊断块(见 docs/feature/reports/show.md「diagnostics」)。每条一行标头
810
+ * `<level> · <operation> · <code>`,message 缩进在下一行;`count > 1` 时补 `(N occurrences)`。
811
+ * 诊断的 level 与 verdict 无关 —— passed / failed / errored 都可能带一条 cleanup / teardown
812
+ * warning。没有诊断返回 undefined。
813
+ */
814
+ function renderAttemptDiagnostics(r: EvalResult): string | undefined {
815
+ if (!r.diagnostics || r.diagnostics.length === 0) return undefined;
816
+ const lines = ["diagnostics:"];
817
+ for (const d of r.diagnostics) {
818
+ lines.push(` ${d.level} · ${d.phase} · ${d.code}`);
819
+ const occ = d.count && d.count > 1 ? ` (${d.count} occurrences)` : "";
820
+ lines.push(` ${d.message}${occ}`);
821
+ }
822
+ return lines.join("\n");
823
+ }
824
+
645
825
  export function attemptOverviewText(
646
826
  evidence: AttemptEvidence,
647
827
  opts: { header: string; artifactPath?: string; width: number },
@@ -656,27 +836,43 @@ export function attemptOverviewText(
656
836
 
657
837
  const blocks: string[] = [[header, metaParts.join(" · ")].join("\n")];
658
838
 
659
- blocks.push(
660
- [
661
- assertionSummaryLine(r.assertions),
662
- evidence.evalSource
663
- ? `eval source: ${evidence.evalSource.sourcePath} · sha256:${evidence.evalSource.sourceSha256.slice(0, 8)}…`
664
- : "eval source: unavailable (not captured for this attempt)",
665
- ].join("\n"),
666
- );
839
+ // errored attempt 的首页不靠 trace 就要能解释基础设施错误(见 docs/feature/reports/show.md
840
+ // 「errored attempt 的首页」):先展开结构化 error(phase/operation/code/message/cause + stack),
841
+ // 断言块对没有断言的 errored attempt 省略(它在评分之前就挂了)
842
+ const errorBlock = renderErrorBlock(r);
843
+ if (errorBlock) blocks.push(errorBlock);
844
+
845
+ // errored 且没有任何断言时不打印空的 "assertions: 0 passed" —— 主因已经在 error 块里说清楚了。
846
+ if (r.assertions.length > 0 || r.error === undefined) {
847
+ blocks.push(
848
+ [
849
+ assertionSummaryLine(r.assertions),
850
+ evidence.evalSource
851
+ ? `eval source: ${evidence.evalSource.sourcePath} · sha256:${evidence.evalSource.sourceSha256.slice(0, 8)}…`
852
+ : "eval source: unavailable (not captured for this attempt)",
853
+ ].join("\n"),
854
+ );
855
+ }
667
856
 
668
857
  const diagnostics = failureDiagnostics(r.assertions, opts.width);
669
858
  if (diagnostics) blocks.push(diagnostics);
670
859
 
860
+ // attempt 级诊断(teardown/cleanup 等,与 verdict 独立;passed/failed/errored 都可能有)。
861
+ const attemptDiag = renderAttemptDiagnostics(r);
862
+ if (attemptDiag) blocks.push(attemptDiag);
863
+
671
864
  if (evidence.execution) {
672
865
  const nodes = evidence.execution.nodes.filter((node) => node.kind !== "telemetry");
673
866
  const skillLoads = nodes.filter((n) => n.kind === "skill.loaded").length;
674
867
  const toolCalls = nodes.filter((n) => n.kind === "action").length;
675
868
  const aiMessages = nodes.filter((n) => n.kind === "message" && n.role === "assistant").length;
676
- const execLines = [`execution: ${nodes.length} events · ${skillLoads} skill loads · ${toolCalls} tool calls · ${aiMessages} AI messages`];
677
- if (evidence.capabilities.timing) {
678
- execLines.push("timing: OTel spans recorded for this attempt — see --execution for per-step timing.");
679
- }
869
+ const counted = (count: number, singular: string, plural = `${singular}s`) =>
870
+ `${count} ${count === 1 ? singular : plural}`;
871
+ const execLines = [
872
+ `execution: ${counted(nodes.length, "event")} · ${counted(skillLoads, "skill load")} · ${counted(toolCalls, "tool call")} · ${counted(aiMessages, "AI message")}`,
873
+ ];
874
+ const timingLine = overviewTimingLine(r);
875
+ if (timingLine) execLines.push(timingLine);
680
876
  blocks.push(execLines.join("\n"));
681
877
  } else {
682
878
  blocks.push("execution: unavailable (no events recorded for this attempt)");
@@ -695,6 +891,7 @@ export function attemptOverviewText(
695
891
  const available = [
696
892
  evidence.capabilities.eval ? `niceeval show ${evidence.locator} --eval` : undefined,
697
893
  evidence.capabilities.execution ? `niceeval show ${evidence.locator} --execution` : undefined,
894
+ evidence.capabilities.timing ? `niceeval show ${evidence.locator} --timing` : undefined,
698
895
  evidence.capabilities.diff ? `niceeval show ${evidence.locator} --diff` : undefined,
699
896
  ].filter((command): command is string => command !== undefined);
700
897
  if (available.length > 0) tail.push(`available:\n${available.map((command) => ` ${command}`).join("\n")}`);
@@ -715,45 +912,363 @@ export function diffText(opts: {
715
912
  file?: string;
716
913
  }): string {
717
914
  const { header, diff, artifactPath, file } = opts;
718
- const source = artifactPath ? join( artifactPath, "diff.json") : undefined;
915
+ const source = artifactPath ? join(artifactPath, "diff.json") : undefined;
719
916
  if (!diff) {
720
- return `${header}\n\n(no diff recorded for this attempt${source ? ` · expected: ${source}` : ""})`;
917
+ return `${header}\n\ndiff unavailable (no diff recorded for this attempt: remote agent, or diff artifact not published${source ? `; expected: ${source}` : ""})`;
721
918
  }
722
919
 
723
920
  if (file !== undefined) {
724
- const content = diff.generatedFiles[file];
725
- if (content === undefined) {
726
- if (diff.deletedFiles.includes(file)) return `${header}\n\nD ${file} (deleted by the agent)`;
727
- const known = [...Object.keys(diff.generatedFiles), ...diff.deletedFiles];
728
- return `${header}\n\nFile "${file}" is not in this attempt's diff. Files: ${known.join(", ") || "(none)"}`;
921
+ const summary = diff.files[file];
922
+ if (summary === undefined) {
923
+ const known = Object.keys(diff.files).sort();
924
+ return `${header}\n\nFile "${file}" is not in this attempt's agent diff. Files: ${known.join(", ") || "(none)"}`;
729
925
  }
730
- const lines = content.split("\n");
731
- const shown = lines.slice(0, MAX_DIFF_LINES);
732
- const footer = [
733
- `${lines.length} ${lines.length === 1 ? "line" : "lines"}`,
734
- ...(lines.length > shown.length ? [`${lines.length - shown.length} more lines not shown`] : []),
735
- ...(source ? [`full diff: ${source}`] : []),
736
- ].join(" · ");
737
- return `${header}\n\n${file}\n${shown.join("\n")}\n\n(${footer})`;
738
- }
739
-
740
- const generated = Object.entries(diff.generatedFiles).sort(([a], [b]) => a.localeCompare(b));
741
- const deleted = [...diff.deletedFiles].sort();
742
- if (generated.length === 0 && deleted.length === 0) {
743
- return `${header}\n\n(no file changes recorded${source ? ` · full diff: ${source}` : ""})`;
744
- }
745
- // 落盘的 diff 只有改后全文(git name-status + readFile),没有基线:
746
- // 行数是文件现大小,不硬编 +/- 增删行;A/M 无从区分,统一 M(created or modified)
747
- const rows = [
748
- ...generated.map(([path, content]) => {
749
- const lines = content.split("\n").length;
750
- return ["M", path, `${lines} ${lines === 1 ? "line" : "lines"}`];
751
- }),
752
- ...deleted.map((path) => ["D", path, "(deleted)"]),
753
- ];
754
- const footer = [
755
- `${rows.length} ${rows.length === 1 ? "file" : "files"}`,
756
- ...(source ? [`full diff: ${source}`] : []),
757
- ].join(" · ");
758
- return `${header}\n\n${renderAlignedRows(rows)}\n\n(${footer})`;
926
+ // 单文件 patch 按窗口逐段渲染(diff.json 存的就是逐窗口 delta,不产出跨窗口合成 patch)
927
+ const head = `${netLetter(summary.net)} ${file} · touched in ${summary.windows.join(", ")}`;
928
+ if (summary.binary) {
929
+ const sections = diff.windows
930
+ .filter((w) => w.changes[file] !== undefined)
931
+ .map((w) => {
932
+ const c = w.changes[file]!;
933
+ const b = c.binary ?? {};
934
+ return `── window ${w.window}\nbinary · ${b.beforeBytes ?? 0} → ${b.afterBytes ?? 0} bytes`;
935
+ });
936
+ return `${header}\n\n${head}\n\n${sections.join("\n\n")}`;
937
+ }
938
+ const sections: string[] = [];
939
+ for (const w of diff.windows) {
940
+ const c = w.changes[file];
941
+ if (c === undefined) continue;
942
+ sections.push(`── window ${w.window}\n${windowHunk(c)}`);
943
+ }
944
+ return `${header}\n\n${head}\n\n${sections.join("\n\n")}${source ? `\n\n(full diff: ${source})` : ""}`;
945
+ }
946
+
947
+ const entries = Object.entries(diff.files).sort(([a], [b]) => a.localeCompare(b));
948
+ if (entries.length === 0) {
949
+ return `${header}\n\n(no file changes by the agent in any send window${source ? ` · full diff: ${source}` : ""})`;
950
+ }
951
+ const rows = entries.map(([path, summary]) => {
952
+ if (summary.binary) {
953
+ return [netLetter(summary.net), path, "binary", summary.windows.join(", ")];
954
+ }
955
+ let adds = 0;
956
+ let dels = 0;
957
+ for (const w of diff.windows) {
958
+ const c = w.changes[path];
959
+ if (!c) continue;
960
+ const d = lineDelta(c.before, c.after);
961
+ adds += Math.max(0, d.adds);
962
+ dels += Math.max(0, d.dels);
963
+ }
964
+ const delta = [adds > 0 ? `+${adds}` : "", dels > 0 ? `-${dels}` : ""].filter(Boolean).join(" ") || "±0";
965
+ return [netLetter(summary.net), path, delta, summary.windows.join(", ")];
966
+ });
967
+ const headLine = `${entries.length} ${entries.length === 1 ? "file" : "files"} changed by agent`;
968
+ const single = entries[0] ? `\n\nsingle file: niceeval show @… --diff=${entries[0][0]}` : "";
969
+ return `${header}\n\n${headLine}\n${renderAlignedRows(rows).split("\n").map((l) => ` ${l}`).join("\n")}${single}`;
970
+ }
971
+
972
+ /** 一个窗口内单文件的最小 unified hunk:公共前后缀修剪出的编辑区,一段 @@ 展示。 */
973
+ function windowHunk(c: { status: string; before?: string; after?: string }): string {
974
+ const a = c.before === undefined ? [] : c.before.replace(/\n$/, "").split("\n");
975
+ const b = c.after === undefined ? [] : c.after.replace(/\n$/, "").split("\n");
976
+ let prefix = 0;
977
+ while (prefix < a.length && prefix < b.length && a[prefix] === b[prefix]) prefix++;
978
+ let suffix = 0;
979
+ while (suffix < a.length - prefix && suffix < b.length - prefix && a[a.length - 1 - suffix] === b[b.length - 1 - suffix]) suffix++;
980
+ const removed = a.slice(prefix, a.length - suffix);
981
+ const added = b.slice(prefix, b.length - suffix);
982
+ const ctxBefore = a.slice(Math.max(0, prefix - 2), prefix);
983
+ const lines: string[] = [];
984
+ lines.push(`@@ -${Math.max(1, prefix - ctxBefore.length + 1)},${removed.length + ctxBefore.length} +${Math.max(1, prefix - ctxBefore.length + 1)},${added.length + ctxBefore.length} @@`);
985
+ for (const l of ctxBefore) lines.push(` ${l}`);
986
+ const MAX_HUNK_LINES = 200;
987
+ const shownRemoved = removed.slice(0, MAX_HUNK_LINES);
988
+ const shownAdded = added.slice(0, MAX_HUNK_LINES);
989
+ for (const l of shownRemoved) lines.push(`-${l}`);
990
+ if (removed.length > shownRemoved.length) lines.push(`… (${removed.length - shownRemoved.length} more removed lines)`);
991
+ for (const l of shownAdded) lines.push(`+${l}`);
992
+ if (added.length > shownAdded.length) lines.push(`… (${added.length - shownAdded.length} more added lines)`);
993
+ return lines.join("\n");
994
+ }
995
+
996
+ // ───────────────────────── 证据切面:--timing(统一时间树) ─────────────────────────
997
+
998
+ const CLOSING_PHASE_NAMES = new Set(["eval.teardown", "agent.teardown", "sandbox.teardown", "sandbox.suspend", "sandbox.stop"]);
999
+
1000
+ // 首页只保留能回答「大头在哪」的阶段。分类账锚点与 telemetry bookkeeping 在很短时
1001
+ // 留给 --timing 完整树;一旦自身变成慢点或失败,仍必须抬到首页,不能被静默藏掉。
1002
+ const OVERVIEW_DETAIL_PHASE_NAMES = new Set(["workspace.baseline", "telemetry.configure", "telemetry.collect"]);
1003
+ const OVERVIEW_DETAIL_THRESHOLD_MS = 1_000;
1004
+
1005
+ /** phases 主链摘要行(首页 `timing:`):各主链阶段耗时点隔,收尾段合计以 `teardown +N` 单列。 */
1006
+ export function overviewTimingLine(r: EvalResult): string | undefined {
1007
+ if (!r.phases || r.phases.length === 0) return undefined;
1008
+ const main = r.phases.filter(
1009
+ (p) =>
1010
+ !CLOSING_PHASE_NAMES.has(p.name) &&
1011
+ (p.failed === true || !OVERVIEW_DETAIL_PHASE_NAMES.has(p.name) || p.durationMs >= OVERVIEW_DETAIL_THRESHOLD_MS),
1012
+ );
1013
+ const closing = r.phases.filter((p) => CLOSING_PHASE_NAMES.has(p.name));
1014
+ const parts = main.map((p) => `${p.name} ${formatDurationMs(p.durationMs)}${p.failed ? " ✗" : ""}`);
1015
+ const closingMs = closing.reduce((sum, p) => sum + p.durationMs, 0);
1016
+ if (closingMs > 0) parts.push(`teardown +${formatDurationMs(closingMs)}`);
1017
+ return `timing: ${parts.join(" · ")}`;
1018
+ }
1019
+
1020
+ const TIMING_DETAIL_NODE_BUDGET = 80;
1021
+
1022
+ interface DiagnosticTimingNode {
1023
+ id: string;
1024
+ label: string;
1025
+ startOffsetMs: number;
1026
+ durationMs: number;
1027
+ failed: boolean;
1028
+ otel: boolean;
1029
+ children: DiagnosticTimingNode[];
1030
+ }
1031
+
1032
+ function timingNodeLabel(node: TimingNode): string {
1033
+ if (node.kind === "command" && node.command) return `shell · ${node.command.display}`;
1034
+ if (node.kind === "turn") return `turn ${node.label}`;
1035
+ if (node.kind === "operation" || node.kind === "provider") return `${node.kind} · ${node.label}`;
1036
+ return node.label;
1037
+ }
1038
+
1039
+ function traceReferenceCounts(nodes: readonly TimingNode[], counts = new Map<string, number>()): Map<string, number> {
1040
+ for (const node of nodes) {
1041
+ if (node.kind === "turn" && node.traceId) counts.set(node.traceId, (counts.get(node.traceId) ?? 0) + 1);
1042
+ traceReferenceCounts(node.children ?? [], counts);
1043
+ }
1044
+ return counts;
1045
+ }
1046
+
1047
+ /** OTel 只按唯一 traceId 归属和 span parent 关系挂接;不按绝对墙钟猜跨进程顺序。 */
1048
+ function otelForest(traceId: string, spans: readonly TraceSpan[], turnStartOffsetMs: number): DiagnosticTimingNode[] {
1049
+ const unique = new Map<string, TraceSpan>();
1050
+ for (const span of spans) if (span.traceId === traceId && !unique.has(span.spanId)) unique.set(span.spanId, span);
1051
+ const selected = [...unique.values()];
1052
+ if (selected.length === 0) return [];
1053
+ const traceOrigin = Math.min(...selected.map((span) => span.startMs));
1054
+ const nodes = new Map<string, DiagnosticTimingNode>();
1055
+ for (const span of selected) {
1056
+ nodes.set(span.spanId, {
1057
+ id: `otel:${span.traceId}:${span.spanId}`,
1058
+ label: `${span.kind ?? "span"} · ${span.name}`,
1059
+ startOffsetMs: turnStartOffsetMs + Math.max(0, span.startMs - traceOrigin),
1060
+ durationMs: Math.max(0, span.endMs - span.startMs),
1061
+ failed: span.status === "error",
1062
+ otel: true,
1063
+ children: [],
1064
+ });
1065
+ }
1066
+ const roots: DiagnosticTimingNode[] = [];
1067
+ for (const span of selected) {
1068
+ const node = nodes.get(span.spanId)!;
1069
+ const parent = span.parentSpanId && span.parentSpanId !== span.spanId ? nodes.get(span.parentSpanId) : undefined;
1070
+ if (parent) parent.children.push(node);
1071
+ else roots.push(node);
1072
+ }
1073
+ const sort = (items: DiagnosticTimingNode[]) => {
1074
+ items.sort((a, b) => a.startOffsetMs - b.startOffsetMs || a.id.localeCompare(b.id));
1075
+ for (const item of items) sort(item.children);
1076
+ };
1077
+ sort(roots);
1078
+ return roots;
1079
+ }
1080
+
1081
+ function diagnosticTimingNode(
1082
+ node: TimingNode,
1083
+ spans: readonly TraceSpan[],
1084
+ uniqueTraceIds: ReadonlySet<string>,
1085
+ ): DiagnosticTimingNode {
1086
+ const children = (node.children ?? []).map((child) => diagnosticTimingNode(child, spans, uniqueTraceIds));
1087
+ if (node.kind === "turn" && node.traceId && uniqueTraceIds.has(node.traceId)) {
1088
+ children.push(...otelForest(node.traceId, spans, node.startOffsetMs));
1089
+ }
1090
+ return {
1091
+ id: `runner:${node.id}`,
1092
+ label: timingNodeLabel(node),
1093
+ startOffsetMs: node.startOffsetMs,
1094
+ durationMs: node.durationMs,
1095
+ failed: node.failed === true,
1096
+ otel: false,
1097
+ children,
1098
+ };
1099
+ }
1100
+
1101
+ interface FlatTimingNode {
1102
+ node: DiagnosticTimingNode;
1103
+ path: readonly DiagnosticTimingNode[];
1104
+ }
1105
+
1106
+ function flattenTimingForest(roots: readonly DiagnosticTimingNode[]): FlatTimingNode[] {
1107
+ const flat: FlatTimingNode[] = [];
1108
+ const visit = (node: DiagnosticTimingNode, ancestors: readonly DiagnosticTimingNode[]) => {
1109
+ const path = [...ancestors, node];
1110
+ flat.push({ node, path });
1111
+ for (const child of node.children) visit(child, path);
1112
+ };
1113
+ for (const root of roots) visit(root, []);
1114
+ return flat;
1115
+ }
1116
+
1117
+ /**
1118
+ * 默认 80-node 投影。四个稳定池先各用自己的配额,再把空余额按失败→最慢→首尾重分配。
1119
+ * 选中深层节点必须连同祖先整条加入;四池合并后按 id 去重。
1120
+ */
1121
+ function selectTimingNodes(roots: readonly DiagnosticTimingNode[]): ReadonlySet<string> {
1122
+ const flat = flattenTimingForest(roots);
1123
+ if (flat.length <= TIMING_DETAIL_NODE_BUDGET) return new Set(flat.map(({ node }) => node.id));
1124
+
1125
+ const selected = new Set<string>();
1126
+ const byStart = [...flat].sort(
1127
+ (a, b) => a.node.startOffsetMs - b.node.startOffsetMs || a.node.id.localeCompare(b.node.id),
1128
+ );
1129
+ const failed = byStart.filter(({ node }) => node.failed);
1130
+ const slow = [...flat].sort(
1131
+ (a, b) => b.node.durationMs - a.node.durationMs || a.node.startOffsetMs - b.node.startOffsetMs || a.node.id.localeCompare(b.node.id),
1132
+ );
1133
+ const latest = [...flat].sort(
1134
+ (a, b) => b.node.startOffsetMs - a.node.startOffsetMs || a.node.id.localeCompare(b.node.id),
1135
+ );
1136
+
1137
+ const add = (candidate: FlatTimingNode, allowance: number): number => {
1138
+ const missing = candidate.path.filter((node) => !selected.has(node.id));
1139
+ if (missing.length === 0 || missing.length > allowance || selected.size + missing.length > TIMING_DETAIL_NODE_BUDGET) {
1140
+ return 0;
1141
+ }
1142
+ for (const node of missing) selected.add(node.id);
1143
+ return missing.length;
1144
+ };
1145
+ const pool = (candidates: readonly FlatTimingNode[], cap: number) => {
1146
+ let remaining = cap;
1147
+ for (const candidate of candidates) {
1148
+ if (remaining === 0) break;
1149
+ remaining -= add(candidate, remaining);
1150
+ }
1151
+ };
1152
+
1153
+ pool(failed, 40);
1154
+ pool(slow, 20);
1155
+ pool(byStart, 10);
1156
+ pool(latest, 10);
1157
+
1158
+ // 固定池未用满时,剩余额度按契约优先级继续分配;候选稳定、无法容纳的整条路径跳过。
1159
+ for (const candidate of [...failed, ...slow, ...byStart, ...latest]) {
1160
+ const remaining = TIMING_DETAIL_NODE_BUDGET - selected.size;
1161
+ if (remaining === 0) break;
1162
+ add(candidate, remaining);
1163
+ }
1164
+ return selected;
1165
+ }
1166
+
1167
+ function subtreeStats(node: DiagnosticTimingNode): { nodes: number; failed: number } {
1168
+ let nodes = 1;
1169
+ let failed = node.failed ? 1 : 0;
1170
+ for (const child of node.children) {
1171
+ const stats = subtreeStats(child);
1172
+ nodes += stats.nodes;
1173
+ failed += stats.failed;
1174
+ }
1175
+ return { nodes, failed };
1176
+ }
1177
+
1178
+ type VisibleTimingEntry =
1179
+ | { kind: "node"; node: DiagnosticTimingNode }
1180
+ | { kind: "omitted"; nodes: number; failed: number };
1181
+
1182
+ function visibleTimingEntries(
1183
+ nodes: readonly DiagnosticTimingNode[],
1184
+ selected: ReadonlySet<string> | undefined,
1185
+ ): VisibleTimingEntry[] {
1186
+ if (!selected) return nodes.map((node) => ({ kind: "node", node }));
1187
+ const entries: VisibleTimingEntry[] = [];
1188
+ for (let i = 0; i < nodes.length;) {
1189
+ const node = nodes[i]!;
1190
+ if (selected.has(node.id)) {
1191
+ entries.push({ kind: "node", node });
1192
+ i += 1;
1193
+ continue;
1194
+ }
1195
+ let omittedNodes = 0;
1196
+ let omittedFailed = 0;
1197
+ while (i < nodes.length && !selected.has(nodes[i]!.id)) {
1198
+ const stats = subtreeStats(nodes[i]!);
1199
+ omittedNodes += stats.nodes;
1200
+ omittedFailed += stats.failed;
1201
+ i += 1;
1202
+ }
1203
+ entries.push({ kind: "omitted", nodes: omittedNodes, failed: omittedFailed });
1204
+ }
1205
+ return entries;
1206
+ }
1207
+
1208
+ function diagnosticTimingLines(
1209
+ nodes: readonly DiagnosticTimingNode[],
1210
+ prefix: string,
1211
+ selected: ReadonlySet<string> | undefined,
1212
+ locator: string,
1213
+ ): string[] {
1214
+ const entries = visibleTimingEntries(nodes, selected);
1215
+ const lines: string[] = [];
1216
+ entries.forEach((entry, index) => {
1217
+ const last = index === entries.length - 1;
1218
+ const branch = `${prefix}${last ? "└─ " : "├─ "}`;
1219
+ const childPrefix = `${prefix}${last ? " " : "│ "}`;
1220
+ if (entry.kind === "omitted") {
1221
+ const failed = entry.failed > 0 ? ` · ${entry.failed} failed` : "";
1222
+ lines.push(`${branch}… ${entry.nodes} nodes omitted${failed} · full: niceeval show ${locator} --timing=full`);
1223
+ return;
1224
+ }
1225
+ const node = entry.node;
1226
+ lines.push(
1227
+ `${branch}${node.label} ${formatDurationMs(node.durationMs)}${node.failed ? " ✗" : ""}${node.otel ? " OTel" : ""}`,
1228
+ );
1229
+ lines.push(...diagnosticTimingLines(node.children, childPrefix, selected, locator));
1230
+ });
1231
+ return lines;
1232
+ }
1233
+
1234
+ /**
1235
+ * `--timing`:整个 attempt 的统一时间树(见 docs/feature/reports/show.md)。先按
1236
+ * `result.json.phases` 输出 runner 生命周期,再展开 hook / 命令 / turn;turn 带 traceId 时
1237
+ * 从 trace.json 挂接 agent/model/tool spans。缩进表达包含关系,子项不能求和后与父项比较。
1238
+ */
1239
+ export function timingText(
1240
+ evidence: AttemptEvidence,
1241
+ opts: { header: string; artifactPath?: string; width: number; mode?: "summary" | "full" },
1242
+ ): string {
1243
+ const r = evidence.result;
1244
+ if (!r.phases || r.phases.length === 0) {
1245
+ return `${opts.header}\n\nphase timing unavailable (this result was not produced by a runner with phase timing)`;
1246
+ }
1247
+ const spans = evidence.trace;
1248
+ const main = r.phases.filter((p) => !CLOSING_PHASE_NAMES.has(p.name));
1249
+ const closing = r.phases.filter((p) => CLOSING_PHASE_NAMES.has(p.name));
1250
+ const traceCounts = new Map<string, number>();
1251
+ for (const phase of r.phases) traceReferenceCounts(phase.children ?? [], traceCounts);
1252
+ const uniqueTraceIds = new Set([...traceCounts].filter(([, count]) => count === 1).map(([traceId]) => traceId));
1253
+ const phaseForests = new Map(
1254
+ r.phases.map((phase) => [
1255
+ phase,
1256
+ (phase.children ?? []).map((node) => diagnosticTimingNode(node, spans ?? [], uniqueTraceIds)),
1257
+ ]),
1258
+ );
1259
+ const allRoots = [...phaseForests.values()].flat();
1260
+ const selected = opts.mode === "full" ? undefined : selectTimingNodes(allRoots);
1261
+
1262
+ const lines: string[] = [`total ${formatDurationMs(r.durationMs)}`, ""];
1263
+ const renderPhase = (p: NonNullable<EvalResult["phases"]>[number]) => {
1264
+ const failedNote = p.failed ? ` ✗ failed here${r.error ? ` (${r.error.code})` : ""}` : "";
1265
+ lines.push(`${p.name.padEnd(22)}${formatDurationMs(p.durationMs)}${failedNote}`);
1266
+ lines.push(...diagnosticTimingLines(phaseForests.get(p) ?? [], " ", selected, evidence.locator));
1267
+ };
1268
+ for (const p of main) renderPhase(p);
1269
+ if (closing.length > 0) {
1270
+ lines.push("", "teardown (not counted in total):");
1271
+ for (const p of closing) renderPhase(p);
1272
+ }
1273
+ return `${opts.header}\n\n${lines.join("\n")}`;
759
1274
  }