@yokla/report 0.0.0-stage → 0.3.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.
package/src/html.ts ADDED
@@ -0,0 +1,508 @@
1
+ // The static HTML report (ADR-0023): one offline file, rendered from
2
+ // results.v1 alone (ADR-0007), to read why a case didn't pass.
3
+ // - It has no script and loads nothing. Its styles are inline, and its
4
+ // Content-Security-Policy allows nothing else.
5
+ // - Every value is escaped, since the target's answers are untrusted text. The
6
+ // `h` template escapes what it interpolates unless it is markup already.
7
+ // It isn't named `html`, so that Prettier leaves its markup as written.
8
+ // - The same results give the same bytes: no render time, no locale formatting.
9
+ // - A model call's prompt is shown by role and size only (ADR-0015).
10
+
11
+ import { CASE_STATUSES, type Results } from '@yokla/core';
12
+ import { counted, observedTotals, round, withOrigin } from './format.ts';
13
+ import { xmlText } from './junit.ts';
14
+ import { caseProblems, caseReason, dimensionSummary, type CaseResult } from './problems.ts';
15
+
16
+ type TurnResult = CaseResult['samples'][number]['turns'][number];
17
+ type CheckResult = TurnResult['checks'][number];
18
+ type ModelCall = NonNullable<TurnResult['proxy']>['calls'][number];
19
+
20
+ /** Markup that is safe as it is. */
21
+ interface Html {
22
+ readonly markup: string;
23
+ }
24
+ type Part = string | number | Html | readonly Html[] | undefined;
25
+
26
+ export const CONTENT_SECURITY_POLICY = "default-src 'none'; style-src 'unsafe-inline'";
27
+
28
+ function escape(text: string): string {
29
+ return xmlText(text).replaceAll('"', '&quot;').replaceAll("'", '&#39;');
30
+ }
31
+
32
+ function markupOf(part: Part): string {
33
+ if (part === undefined) return '';
34
+ if (typeof part === 'string') return escape(part);
35
+ if (typeof part === 'number') return String(part);
36
+ if ('markup' in part) return part.markup;
37
+ return part.map((piece) => piece.markup).join('');
38
+ }
39
+
40
+ /** A template whose strings are markup and whose values are escaped text. */
41
+ function h(strings: TemplateStringsArray, ...parts: readonly Part[]): Html {
42
+ let markup = strings[0] ?? '';
43
+ for (const [index, part] of parts.entries()) {
44
+ markup += markupOf(part) + (strings[index + 1] ?? '');
45
+ }
46
+ return { markup };
47
+ }
48
+
49
+ const STYLE = `
50
+ :root { color-scheme: light dark; --bg: #ffffff; --fg: #1d2025; --muted: #5d6570;
51
+ --line: #d8dce2; --panel: #f6f7f9; --code: #eef0f3;
52
+ --good: #1a7f37; --bad: #c42b2b; --warn: #8f6200; }
53
+ @media (prefers-color-scheme: dark) {
54
+ :root { --bg: #16181b; --fg: #e5e7ea; --muted: #9ba3ad; --line: #30353c;
55
+ --panel: #1c1f23; --code: #23272c; --good: #4fc26f; --bad: #ff6f6f; --warn: #d6a832; }
56
+ }
57
+ * { box-sizing: border-box; }
58
+ body { margin: 0 auto; max-width: 76rem; padding: 1.5rem 1rem 3rem; background: var(--bg);
59
+ color: var(--fg); font: 14px/1.5 system-ui, -apple-system, "Segoe UI", sans-serif; }
60
+ h1 { font-size: 1.4rem; margin: 0 0 1rem; }
61
+ h2 { font-size: 1.1rem; margin: 2rem 0 .5rem; padding-bottom: .25rem; border-bottom: 1px solid var(--line); }
62
+ h3 { font-size: 1rem; margin: 1rem 0 .25rem; }
63
+ h4 { font-size: .95rem; margin: .75rem 0 .25rem; }
64
+ code, pre { font-family: ui-monospace, SFMono-Regular, Menlo, Consolas, monospace; }
65
+ pre { margin: .25rem 0 .5rem; padding: .5rem .75rem; border-radius: 4px; background: var(--code);
66
+ font-size: 12.5px; line-height: 1.45; white-space: pre-wrap; overflow-wrap: anywhere; }
67
+ pre.text { font-family: inherit; font-size: 14px; line-height: 1.5; }
68
+ .scroll { overflow-x: auto; }
69
+ table { width: 100%; margin: .25rem 0 .75rem; border-collapse: collapse; }
70
+ th, td { padding: .3rem .5rem; border-bottom: 1px solid var(--line); text-align: left; vertical-align: top; }
71
+ th { color: var(--muted); font-weight: 600; white-space: nowrap; }
72
+ td { overflow-wrap: break-word; }
73
+ td code { white-space: nowrap; }
74
+ .num { text-align: right; font-variant-numeric: tabular-nums; white-space: nowrap; }
75
+ dl { display: grid; grid-template-columns: max-content 1fr; gap: .2rem 1rem; margin: 0; }
76
+ dt { color: var(--muted); }
77
+ dd { margin: 0; overflow-wrap: anywhere; }
78
+ ul { margin: .25rem 0; padding-left: 1.25rem; }
79
+ .counts { display: flex; flex-wrap: wrap; gap: .5rem 1.25rem; padding: 0; list-style: none; }
80
+ .status { display: inline-block; padding: 0 .4rem; border: 1px solid currentColor; border-radius: 3px;
81
+ font-size: 12px; font-weight: 600; white-space: nowrap; }
82
+ .good { color: var(--good); }
83
+ .bad { color: var(--bad); }
84
+ .warn { color: var(--warn); }
85
+ .muted { color: var(--muted); }
86
+ .mark { margin-left: .4rem; color: var(--muted); font-size: 12px; }
87
+ .label { color: var(--muted); font-size: 12px; }
88
+ details.case { margin: .5rem 0; border: 1px solid var(--line); border-radius: 6px; background: var(--panel); }
89
+ details.case > summary { padding: .5rem .75rem; cursor: pointer; }
90
+ details.case > div { padding: 0 .75rem .75rem; }
91
+ .turn { margin-top: .75rem; padding-top: .5rem; border-top: 1px solid var(--line); }
92
+ details details > summary { color: var(--muted); cursor: pointer; }
93
+ a { color: inherit; }
94
+ @media print { details.case { break-inside: avoid-page; } }
95
+ `;
96
+
97
+ const STATUS_TONE: Readonly<Record<CaseResult['status'], string>> = {
98
+ pass: 'good',
99
+ fail: 'bad',
100
+ error: 'bad',
101
+ 'fixture-missing': 'bad',
102
+ unmeasured: 'warn',
103
+ 'known-gap': 'muted',
104
+ 'gap-closed': 'warn',
105
+ };
106
+
107
+ const VERDICT_TONE: Readonly<Record<string, string>> = {
108
+ pass: 'good',
109
+ fail: 'bad',
110
+ error: 'bad',
111
+ unmeasured: 'warn',
112
+ };
113
+
114
+ function badge(text: string, tone: string): Html {
115
+ return h`<span class="status ${tone}">${text}</span>`;
116
+ }
117
+
118
+ function seconds(durationMs: number): string {
119
+ return `${(durationMs / 1000).toFixed(3)} s`;
120
+ }
121
+
122
+ function ms(value: number): string {
123
+ return `${String(Math.round(value))} ms`;
124
+ }
125
+
126
+ function usd(value: number | null): string {
127
+ return value === null ? 'no cost' : `$${round(value)}`;
128
+ }
129
+
130
+ function json(value: unknown): Html {
131
+ return h`<pre>${JSON.stringify(value, null, 2)}</pre>`;
132
+ }
133
+
134
+ function item(term: string, value: Part): Html {
135
+ return h`<dt>${term}</dt><dd>${value}</dd>`;
136
+ }
137
+
138
+ function list(lines: readonly string[], tone: string): Html {
139
+ return h`<ul class="${tone}">${lines.map((line) => h`<li>${line}</li>`)}</ul>`;
140
+ }
141
+
142
+ function table(head: readonly string[], rows: readonly Html[], numeric: readonly number[] = []) {
143
+ const cells = head.map((name, index) =>
144
+ numeric.includes(index) ? h`<th class="num">${name}</th>` : h`<th>${name}</th>`,
145
+ );
146
+ return h`<div class="scroll"><table><thead><tr>${cells}</tr></thead><tbody>${rows}</tbody></table></div>`;
147
+ }
148
+
149
+ function runSection(results: Results): Html {
150
+ const { run } = results;
151
+ const items = [
152
+ item('Run', h`<code>${run.id}</code>`),
153
+ item('Target', run.profile.target),
154
+ item('Profile', h`<code>${run.profile.sha256}</code>`),
155
+ item('Started', `${run.startedAt} (UTC)`),
156
+ item('Finished', `${run.finishedAt} (UTC)`),
157
+ item('Duration', seconds(run.durationMs)),
158
+ item(
159
+ 'Completeness',
160
+ run.partial ? badge('partial: the run stopped early', 'warn') : 'every case ran',
161
+ ),
162
+ item('yokla', results.yokla.version),
163
+ item(
164
+ 'Environment',
165
+ `Node.js ${run.environment.node}, ${run.environment.platform} ${run.environment.arch}`,
166
+ ),
167
+ item('Correlation', run.correlation),
168
+ ];
169
+ const { proxy, observation } = run;
170
+ if (proxy !== undefined) {
171
+ const { calls: _calls, ...sums } = proxy.totals;
172
+ const totals = observedTotals(sums, proxy.missing, 'call');
173
+ items.push(
174
+ item(
175
+ 'Model proxy',
176
+ `${proxy.correlation}: ${counted(proxy.records, 'call')}, ${String(proxy.attributed)} attributed, ${String(proxy.unattributed)} unattributed${totals === '' ? '' : `; ${totals}`}`,
177
+ ),
178
+ );
179
+ if (proxy.prompts !== undefined) items.push(item('Prompts kept', proxy.prompts));
180
+ }
181
+ const { spans } = run;
182
+ if (spans !== undefined) {
183
+ const { calls: _calls, ...sums } = spans.totals;
184
+ const totals = observedTotals(sums, spans.missing, 'call');
185
+ items.push(
186
+ item(
187
+ 'Spans',
188
+ `traceparent: ${counted(spans.received, 'call')}, ${String(spans.attributed)} attributed, ${String(spans.unattributed)} unattributed${spans.settled ? '' : ', still coming when the wait ran out'}${totals === '' ? '' : `; ${totals}`}`,
189
+ ),
190
+ );
191
+ }
192
+ const own = run.own;
193
+ if (own !== undefined) {
194
+ items.push(
195
+ item(
196
+ "yokla's own model",
197
+ `${counted(own.calls, 'call')}, ${String(own.cached)} from the cache; ${own.costUsd === null ? 'cost unknown' : usd(own.costUsd)}`,
198
+ ),
199
+ );
200
+ }
201
+ if (observation !== undefined) {
202
+ const totals = observedTotals(observation.totals, observation.missing, 'turn');
203
+ const all = observation.matched + observation.unmatched;
204
+ items.push(
205
+ item(
206
+ "Target's logs",
207
+ `${String(observation.matched)} of ${String(all)} turns matched, by ${observation.correlation}${totals === '' ? '' : `; ${totals}`}`,
208
+ ),
209
+ );
210
+ }
211
+ const issues = run.issues ?? [];
212
+ return h`<section id="run"><h2>Run</h2><dl>${items}</dl>${
213
+ issues.length === 0 ? undefined : h`<h3>Run issues</h3>${list(issues, 'bad')}`
214
+ }</section>`;
215
+ }
216
+
217
+ function marks(c: CaseResult): Html[] {
218
+ return [
219
+ ...(c.review === 'proposed' ? [h`<span class="mark">[proposed]</span>`] : []),
220
+ ...(c.unstable ? [h`<span class="mark">[unstable]</span>`] : []),
221
+ // A case that stopped once its failure was settled (ADR-0038).
222
+ ...(c.samplesPlanned === undefined
223
+ ? []
224
+ : [
225
+ h`<span class="mark">[stopped after ${String(c.samples.length)} of ${String(c.samplesPlanned)} samples]</span>`,
226
+ ]),
227
+ ];
228
+ }
229
+
230
+ /** The one-line reason of the terminal summary, and the advisory findings. */
231
+ function reasonOf(c: CaseResult): string {
232
+ const problems = caseProblems(c);
233
+ const reason = caseReason(c, problems);
234
+ const advisory = dimensionSummary(c, problems.advisory, true);
235
+ return [reason, advisory === '' ? undefined : `advisory: ${advisory}`]
236
+ .filter((part) => part !== undefined)
237
+ .join('; ');
238
+ }
239
+
240
+ function casesSection(results: Results, ordered: readonly CaseResult[]): Html {
241
+ const counts = CASE_STATUSES.flatMap((status) => {
242
+ const count = results.summary.statuses[status];
243
+ return count === undefined ? [] : [h`<li>${badge(status, STATUS_TONE[status])} ${count}</li>`];
244
+ });
245
+ const proposed = results.cases.filter((c) => c.review === 'proposed').length;
246
+ const rows = ordered.map(
247
+ (c) =>
248
+ h`<tr><td>${badge(c.status, STATUS_TONE[c.status])}</td><td><a href="#case-${c.id}"><code>${c.id}</code></a>${marks(c)}</td><td>${c.suite}</td><td>${c.language}</td><td>${reasonOf(c)}</td></tr>`,
249
+ );
250
+ return h`<section id="cases"><h2>Cases</h2><p>${counted(results.summary.cases, 'case')}</p><ul class="counts">${counts}</ul>${
251
+ proposed === 0
252
+ ? undefined
253
+ : h`<p class="muted">${counted(proposed, 'proposed case')}: they ran, and gate once a person sets their status to approved.</p>`
254
+ }${table(['Status', 'Case', 'Suite', 'Language', 'Reason'], rows)}</section>`;
255
+ }
256
+
257
+ function checksSection(results: Results): Html | undefined {
258
+ if (results.checks.length === 0) return undefined;
259
+ const rows = results.checks.map(
260
+ (check) =>
261
+ h`<tr><td><code>${check.check}</code>${
262
+ check.applied === 0 ? h`<span class="mark">never applied</span>` : undefined
263
+ }</td><td class="num">${check.applied}</td><td class="num">${check.notApplicable}</td><td class="num">${check.passed}</td><td class="num">${check.failed}</td><td class="num">${check.errors}</td><td class="num">${check.unmeasured ?? 0}</td></tr>`,
264
+ );
265
+ return h`<section id="checks"><h2>Checks</h2><p class="muted">Turns per check.</p>${table(
266
+ ['Check', 'Applied', 'Not applicable', 'Passed', 'Failed', 'Errors', 'Unmeasured'],
267
+ rows,
268
+ [1, 2, 3, 4, 5, 6],
269
+ )}</section>`;
270
+ }
271
+
272
+ function dimensionsTable(c: CaseResult): Html | undefined {
273
+ if (c.dimensions.length === 0) return undefined;
274
+ const rows = c.dimensions.map(
275
+ (d) =>
276
+ h`<tr><td>${d.dimension}</td><td>${d.policy}</td><td>${badge(d.verdict, VERDICT_TONE[d.verdict] ?? 'muted')}</td><td class="num">${d.failed} of ${d.samples}</td><td class="num">${
277
+ d.interval === undefined
278
+ ? ''
279
+ : `${d.interval.lower.toFixed(3)} to ${d.interval.upper.toFixed(3)}`
280
+ }</td></tr>`,
281
+ );
282
+ return h`<h3>Dimensions</h3>${table(
283
+ ['Dimension', 'Policy', 'Verdict', 'Failed samples', 'Failure rate, 95 %'],
284
+ rows,
285
+ [3, 4],
286
+ )}`;
287
+ }
288
+
289
+ function checkRows(check: CheckResult): Html[] {
290
+ const name = h`<code>${check.check}</code>`;
291
+ const rows = check.findings.map(
292
+ (finding) =>
293
+ h`<tr><td>${name}</td><td>${badge(finding.verdict, VERDICT_TONE[finding.verdict] ?? 'muted')}</td><td>${finding.dimension}</td><td>${finding.severity}</td><td>${withOrigin(finding)}${
294
+ finding.evidence === undefined
295
+ ? undefined
296
+ : h`<details><summary>evidence</summary>${json(finding.evidence)}</details>`
297
+ }</td></tr>`,
298
+ );
299
+ for (const gap of check.unmeasured ?? []) {
300
+ rows.push(
301
+ h`<tr><td>${name}</td><td>${badge('unmeasured', 'warn')}</td><td>${gap.dimension}</td><td></td><td>${gap.reason}</td></tr>`,
302
+ );
303
+ }
304
+ if (rows.length === 0) {
305
+ rows.push(
306
+ h`<tr><td>${name}</td><td class="muted">no finding</td><td></td><td></td><td></td></tr>`,
307
+ );
308
+ }
309
+ return rows;
310
+ }
311
+
312
+ function tokens(value: number | null): string {
313
+ return value === null ? '–' : String(value);
314
+ }
315
+
316
+ /** The tools a call asked for, by name; the arguments stay in the results (ADR-0025). */
317
+ function toolsOf(call: ModelCall): string {
318
+ if (call.toolCalls === undefined) return '–';
319
+ if (call.toolCalls === null) return 'unreadable';
320
+ return call.toolCalls.length === 0
321
+ ? 'none'
322
+ : call.toolCalls.map((asked) => asked.name).join(', ');
323
+ }
324
+
325
+ function promptOf(call: ModelCall): string {
326
+ if (call.prompt === undefined) return '–';
327
+ if (call.prompt === null) return 'unreadable';
328
+ return call.prompt.map((message) => `${message.role} ${String(message.chars)}`).join(', ');
329
+ }
330
+
331
+ function callsBlock(proxy: NonNullable<TurnResult['proxy']>): Html {
332
+ const rows = proxy.calls.map(
333
+ (call) =>
334
+ h`<tr><td><code>${call.id}</code></td><td>${call.upstream}</td><td>${call.model ?? '–'}</td><td class="num">${call.status === null ? '–' : String(call.status)}</td><td class="num">${ms(call.durationMs)}</td><td class="num">${tokens(call.usage.input)}</td><td class="num">${tokens(call.usage.cachedInput)}</td><td class="num">${tokens(call.usage.cacheWrite)}</td><td class="num">${tokens(call.usage.output)}</td><td class="num">${tokens(call.usage.reasoning)}</td><td class="num">${usd(call.costUsd)}</td><td>${
335
+ call.fault === undefined
336
+ ? ''
337
+ : `${call.fault.kind}${call.fault.applied ? '' : ' (not applied)'}`
338
+ }</td><td>${toolsOf(call)}</td><td>${promptOf(call)}</td></tr>`,
339
+ );
340
+ return h`<details><summary>Model calls: ${counted(proxy.calls.length, 'call')}, ${usd(proxy.costUsd)}, ${proxy.correlation} correlation</summary>${table(
341
+ [
342
+ 'Call',
343
+ 'Upstream',
344
+ 'Model',
345
+ 'Status',
346
+ 'Duration',
347
+ 'Input',
348
+ 'Cached',
349
+ 'Cache write',
350
+ 'Output',
351
+ 'Reasoning',
352
+ 'Cost',
353
+ 'Fault',
354
+ 'Tool calls',
355
+ 'Prompt, characters per message',
356
+ ],
357
+ rows,
358
+ [3, 4, 5, 6, 7, 8, 9, 10],
359
+ )}</details>`;
360
+ }
361
+
362
+ /** The model calls a turn's OpenTelemetry spans showed (ADR-0029). */
363
+ function spansBlock(spans: NonNullable<TurnResult['spans']>): Html {
364
+ const rows = spans.calls.map(
365
+ (call) =>
366
+ h`<tr><td><code>${call.spanId}</code></td><td>${call.provider ?? '–'}</td><td>${call.model ?? '–'}</td><td class="num">${ms(call.durationMs)}</td><td class="num">${tokens(call.usage.input)}</td><td class="num">${tokens(call.usage.cachedInput)}</td><td class="num">${tokens(call.usage.cacheWrite)}</td><td class="num">${tokens(call.usage.output)}</td><td class="num">${tokens(call.usage.reasoning)}</td><td class="num">${usd(call.costUsd)}</td><td>${call.error ? 'failed' : ''}</td></tr>`,
367
+ );
368
+ return h`<details><summary>Model calls from spans: ${counted(spans.calls.length, 'call')}, ${usd(spans.costUsd)}, traceparent</summary>${table(
369
+ [
370
+ 'Span',
371
+ 'Provider',
372
+ 'Model',
373
+ 'Duration',
374
+ 'Input',
375
+ 'Cached',
376
+ 'Cache write',
377
+ 'Output',
378
+ 'Reasoning',
379
+ 'Cost',
380
+ 'Error',
381
+ ],
382
+ rows,
383
+ [3, 4, 5, 6, 7, 8, 9],
384
+ )}</details>`;
385
+ }
386
+
387
+ function answerBlock(turn: TurnResult): Html {
388
+ const { response } = turn;
389
+ if (response === undefined) return h`<p class="bad">No answer.</p>`;
390
+ const facts = [
391
+ `status ${String(response.status)}`,
392
+ ms(response.latencyMs),
393
+ ...(response.firstTextMs === undefined ? [] : [`first text ${ms(response.firstTextMs)}`]),
394
+ ...(response.route === undefined ? [] : [`route ${response.route}`]),
395
+ ...(response.id === undefined ? [] : [`id ${response.id}`]),
396
+ ];
397
+ const text =
398
+ response.text === undefined || response.text === ''
399
+ ? h`<p class="muted">The answer has no text.</p>`
400
+ : h`<pre class="text">${response.text}</pre>`;
401
+ const collections = Object.entries(response.evidence);
402
+ const evidence =
403
+ collections.length === 0
404
+ ? undefined
405
+ : h`<details><summary>Evidence: ${collections
406
+ .map(([name, items]) => `${name} ${String(items.length)}`)
407
+ .join(', ')}</summary>${json(response.evidence)}</details>`;
408
+ const seenCollections = Object.entries(turn.seen ?? {});
409
+ const seen =
410
+ seenCollections.length === 0
411
+ ? undefined
412
+ : h`<details><summary>Seen by the model in tool results: ${seenCollections
413
+ .map(([name, items]) => `${name} ${String(items.length)}`)
414
+ .join(', ')}</summary>${json(turn.seen)}</details>`;
415
+ return h`<div class="label">Answer · ${facts.join(' · ')}</div>${text}${
416
+ turn.clarifying === true
417
+ ? h`<p class="muted">The target asked a clarifying question.</p>`
418
+ : undefined
419
+ }${evidence}${seen}`;
420
+ }
421
+
422
+ function turnBlock(turn: TurnResult, sample: number, index: number): Html {
423
+ const applied = turn.checks.filter((check) => check.applicable);
424
+ const skipped = turn.checks.filter((check) => !check.applicable).map((check) => check.check);
425
+ return h`<div class="turn"><h4>Sample ${sample}, turn ${index}</h4><div class="label">User${
426
+ turn.requestId === undefined ? '' : ` · request id ${turn.requestId}`
427
+ }</div><pre class="text">${turn.user}</pre>${answerBlock(turn)}${
428
+ turn.error === undefined ? undefined : h`<p class="bad">Error: ${turn.error}</p>`
429
+ }${
430
+ turn.issues === undefined || turn.issues.length === 0
431
+ ? undefined
432
+ : h`<div class="label">Mapping issues</div>${list(turn.issues, 'warn')}`
433
+ }${
434
+ applied.length === 0
435
+ ? h`<p class="muted">No check applied.</p>`
436
+ : table(['Check', 'Verdict', 'Dimension', 'Severity', 'Message'], applied.flatMap(checkRows))
437
+ }${
438
+ skipped.length === 0 ? undefined : h`<p class="muted">Not applicable: ${skipped.join(', ')}</p>`
439
+ }${turn.proxy === undefined ? undefined : callsBlock(turn.proxy)}${
440
+ turn.spans === undefined ? undefined : spansBlock(turn.spans)
441
+ }${
442
+ turn.observed === undefined
443
+ ? undefined
444
+ : h`<details><summary>Observed in the target's logs, by ${turn.observed.correlation}</summary>${json(turn.observed.fields)}</details>`
445
+ }</div>`;
446
+ }
447
+
448
+ /** How a simulated customer's conversation went (ADR-0028). */
449
+ function customerLine(sample: CaseResult['samples'][number]): Html | undefined {
450
+ const { customer } = sample;
451
+ if (customer === undefined) return undefined;
452
+ const ended =
453
+ customer.ended === 'reached'
454
+ ? `reached the goal after answer ${String((customer.reachedAt ?? 0) + 1)}`
455
+ : customer.ended === 'maxTurns'
456
+ ? "didn't reach the goal within maxTurns"
457
+ : 'ended in an error';
458
+ const cached = customer.calls.filter((call) => call.cached).length;
459
+ return h`<p class="label">Simulated customer, seed ${customer.seed}: ${ended}; ${counted(customer.calls.length, 'call')}, ${String(cached)} from the cache, ${usd(customer.costUsd)}</p>`;
460
+ }
461
+
462
+ function caseBlock(c: CaseResult): Html {
463
+ const reason = reasonOf(c);
464
+ const samples = c.samples.map(
465
+ (sample) =>
466
+ h`<h3>Sample ${sample.index} · ${sample.cache}</h3>${customerLine(sample)}${sample.turns.map(
467
+ (turn, index) => turnBlock(turn, sample.index, index),
468
+ )}`,
469
+ );
470
+ return h`<details class="case" id="case-${c.id}"${c.status === 'pass' ? undefined : h` open`}><summary>${badge(c.status, STATUS_TONE[c.status])} <code>${c.id}</code>${marks(c)} <span class="muted">${c.suite} · ${c.language}</span>${
471
+ reason === '' ? undefined : h` · ${reason}`
472
+ }</summary><div>${
473
+ c.knownGap === undefined
474
+ ? undefined
475
+ : h`<p>Known gap: ${c.knownGap.reason}${c.knownGap.issue === undefined ? '' : ` (${c.knownGap.issue})`}</p>`
476
+ }${dimensionsTable(c)}${samples}</div></details>`;
477
+ }
478
+
479
+ /** The report as one HTML document. */
480
+ export function htmlReport(results: Results): string {
481
+ // Cases that didn't pass come first, in the order the results list them.
482
+ const ordered = [
483
+ ...results.cases.filter((c) => c.status !== 'pass'),
484
+ ...results.cases.filter((c) => c.status === 'pass'),
485
+ ];
486
+ const page = h`<!doctype html>
487
+ <html lang="en">
488
+ <head>
489
+ <meta charset="utf-8">
490
+ <meta http-equiv="Content-Security-Policy" content="${{ markup: CONTENT_SECURITY_POLICY }}">
491
+ <meta name="referrer" content="no-referrer">
492
+ <meta name="viewport" content="width=device-width, initial-scale=1">
493
+ <title>yokla run ${results.run.id}</title>
494
+ <style>${{ markup: STYLE }}</style>
495
+ </head>
496
+ <body>
497
+ <h1>yokla run</h1>
498
+ <p class="muted">This report holds the target's answers and evidence. Keep it as private as the results file.</p>
499
+ ${runSection(results)}
500
+ ${casesSection(results, ordered)}
501
+ ${checksSection(results)}
502
+ <section id="details"><h2>Case details</h2>
503
+ ${ordered.map((c) => h`${caseBlock(c)}\n`)}</section>
504
+ </body>
505
+ </html>
506
+ `;
507
+ return page.markup;
508
+ }
package/src/index.ts ADDED
@@ -0,0 +1,7 @@
1
+ // Public API of @yokla/report: reports rendered from results.v1 alone.
2
+
3
+ export { CONTENT_SECURITY_POLICY, htmlReport } from './html.ts';
4
+ export { junitXml, xmlAttribute, xmlText } from './junit.ts';
5
+ export { caseProblems, caseReason, type CaseProblems, type Problem } from './problems.ts';
6
+ export { terminalSummary, type TerminalSummary } from './terminal.ts';
7
+ export { originText, withOrigin } from './format.ts';
package/src/junit.ts ADDED
@@ -0,0 +1,129 @@
1
+ // JUnit XML (design §16), for CI systems that show test reports. One
2
+ // testsuite per yokla suite, one testcase per case:
3
+ // - fail becomes <failure>; error and fixture-missing become <error>;
4
+ // - unmeasured and known-gap become <skipped>, so neither reads as a pass;
5
+ // - gap-closed, unstable samples and advisory findings go to <system-out>.
6
+ // Only finding messages are written, never the target's answers.
7
+
8
+ import type { Results } from '@yokla/core';
9
+ import { caseProblems, caseReason, type CaseResult, type Problem } from './problems.ts';
10
+
11
+ /** Whether XML 1.0 can carry this code point; lone surrogates can't. */
12
+ function allowed(code: number): boolean {
13
+ return (
14
+ code === 0x09 ||
15
+ code === 0x0a ||
16
+ code === 0x0d ||
17
+ (code >= 0x20 && code <= 0xd7ff) ||
18
+ (code >= 0xe000 && code <= 0xfffd) ||
19
+ (code >= 0x10000 && code <= 0x10ffff)
20
+ );
21
+ }
22
+
23
+ export function xmlText(text: string): string {
24
+ let clean = '';
25
+ for (const char of text) clean += allowed(char.codePointAt(0) ?? 0) ? char : '\uFFFD';
26
+ return clean.replaceAll('&', '&amp;').replaceAll('<', '&lt;').replaceAll('>', '&gt;');
27
+ }
28
+
29
+ export function xmlAttribute(text: string): string {
30
+ return xmlText(text)
31
+ .replaceAll('"', '&quot;')
32
+ .replaceAll('\n', '&#10;')
33
+ .replaceAll('\r', '&#13;')
34
+ .replaceAll('\t', '&#9;');
35
+ }
36
+
37
+ function seconds(ms: number): string {
38
+ return (ms / 1000).toFixed(3);
39
+ }
40
+
41
+ function caseMs(c: CaseResult): number {
42
+ return c.samples
43
+ .flatMap((sample) => sample.turns)
44
+ .reduce((total, turn) => total + (turn.response?.latencyMs ?? 0), 0);
45
+ }
46
+
47
+ function problemLine(problem: Problem): string {
48
+ return `sample ${String(problem.sample)}, turn ${String(problem.turn)}: ${problem.check} (${problem.dimension}): ${problem.message}`;
49
+ }
50
+
51
+ interface Counts {
52
+ tests: number;
53
+ failures: number;
54
+ errors: number;
55
+ skipped: number;
56
+ }
57
+
58
+ function count(cases: readonly CaseResult[]): Counts {
59
+ // A proposed case doesn't gate (ADR-0004), so it is skipped whatever its status.
60
+ const approved = cases.filter((c) => c.review !== 'proposed');
61
+ const has = (...statuses: CaseResult['status'][]) =>
62
+ approved.filter((c) => statuses.includes(c.status)).length;
63
+ return {
64
+ tests: cases.length,
65
+ failures: has('fail'),
66
+ errors: has('error', 'fixture-missing'),
67
+ skipped: has('unmeasured', 'known-gap') + (cases.length - approved.length),
68
+ };
69
+ }
70
+
71
+ function countAttributes(counts: Counts): string {
72
+ return `tests="${String(counts.tests)}" failures="${String(counts.failures)}" errors="${String(counts.errors)}" skipped="${String(counts.skipped)}"`;
73
+ }
74
+
75
+ function testcase(c: CaseResult): string[] {
76
+ const problems = caseProblems(c);
77
+ const reason = caseReason(c, problems) ?? '';
78
+ const children: string[] = [];
79
+ if (c.review === 'proposed') {
80
+ const message = `proposed, not approved yet: ${c.status}${reason === '' ? '' : `: ${reason}`}`;
81
+ children.push(`<skipped message="${xmlAttribute(message)}"/>`);
82
+ } else if (c.status === 'fail') {
83
+ const body = problems.deciding.map(problemLine).join('\n');
84
+ children.push(
85
+ `<failure type="fail" message="${xmlAttribute(reason)}">${xmlText(body)}</failure>`,
86
+ );
87
+ } else if (c.status === 'error' || c.status === 'fixture-missing') {
88
+ const body = problems.errors.join('\n');
89
+ children.push(
90
+ `<error type="${c.status}" message="${xmlAttribute(reason)}">${xmlText(body)}</error>`,
91
+ );
92
+ } else if (c.status === 'unmeasured' || c.status === 'known-gap') {
93
+ const message = c.status === 'unmeasured' ? `unmeasured: ${reason}` : reason;
94
+ children.push(`<skipped message="${xmlAttribute(message)}"/>`);
95
+ }
96
+ const notes = [
97
+ ...(c.status === 'gap-closed' ? [`gap closed: ${reason}`] : []),
98
+ ...(c.unstable ? ['unstable: the samples disagree'] : []),
99
+ ...problems.advisory.map((problem) => `advisory: ${problemLine(problem)}`),
100
+ ];
101
+ if (notes.length > 0) children.push(`<system-out>${xmlText(notes.join('\n'))}</system-out>`);
102
+
103
+ const open = `<testcase name="${xmlAttribute(c.id)}" classname="${xmlAttribute(`yokla.${c.suite}`)}" time="${seconds(caseMs(c))}"`;
104
+ if (children.length === 0) return [` ${open}/>`];
105
+ return [` ${open}>`, ...children.map((child) => ` ${child}`), ' </testcase>'];
106
+ }
107
+
108
+ export function junitXml(results: Results): string {
109
+ const suites = new Map<string, CaseResult[]>();
110
+ for (const c of results.cases) {
111
+ const list = suites.get(c.suite) ?? [];
112
+ list.push(c);
113
+ suites.set(c.suite, list);
114
+ }
115
+ const lines = [
116
+ '<?xml version="1.0" encoding="UTF-8"?>',
117
+ `<testsuites name="yokla" ${countAttributes(count(results.cases))} time="${seconds(results.run.durationMs)}">`,
118
+ ];
119
+ for (const [suite, cases] of suites) {
120
+ const time = cases.reduce((total, c) => total + caseMs(c), 0);
121
+ lines.push(
122
+ ` <testsuite name="${xmlAttribute(suite)}" ${countAttributes(count(cases))} time="${seconds(time)}" timestamp="${xmlAttribute(results.run.startedAt)}">`,
123
+ ...cases.flatMap(testcase),
124
+ ' </testsuite>',
125
+ );
126
+ }
127
+ lines.push('</testsuites>', '');
128
+ return lines.join('\n');
129
+ }