@yokla/report 0.5.0 → 0.6.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/src/html.ts CHANGED
@@ -31,7 +31,7 @@ type CheckResult = TurnResult['checks'][number];
31
31
  type ModelCall = NonNullable<TurnResult['proxy']>['calls'][number];
32
32
 
33
33
  /** Markup that is safe as it is. */
34
- interface Html {
34
+ export interface Html {
35
35
  readonly markup: string;
36
36
  }
37
37
  type Part = string | number | Html | readonly Html[] | undefined;
@@ -51,7 +51,7 @@ function markupOf(part: Part): string {
51
51
  }
52
52
 
53
53
  /** A template whose strings are markup and whose values are escaped text. */
54
- function h(strings: TemplateStringsArray, ...parts: readonly Part[]): Html {
54
+ export function h(strings: TemplateStringsArray, ...parts: readonly Part[]): Html {
55
55
  let markup = strings[0] ?? '';
56
56
  for (const [index, part] of parts.entries()) {
57
57
  markup += markupOf(part) + (strings[index + 1] ?? '');
@@ -59,7 +59,8 @@ function h(strings: TemplateStringsArray, ...parts: readonly Part[]): Html {
59
59
  return { markup };
60
60
  }
61
61
 
62
- const STYLE = `
62
+ // The helpers below are shared with the comparison page (ADR-0095).
63
+ export const STYLE = `
63
64
  :root { color-scheme: light dark; --bg: #ffffff; --fg: #1d2025; --muted: #5d6570;
64
65
  --line: #d8dce2; --panel: #f6f7f9; --code: #eef0f3;
65
66
  --good: #1a7f37; --bad: #c42b2b; --warn: #8f6200; }
@@ -107,7 +108,7 @@ a { color: inherit; }
107
108
  @media print { details.case { break-inside: avoid-page; } }
108
109
  `;
109
110
 
110
- const STATUS_TONE: Readonly<Record<CaseResult['status'], string>> = {
111
+ export const STATUS_TONE: Readonly<Record<CaseResult['status'], string>> = {
111
112
  pass: 'good',
112
113
  fail: 'bad',
113
114
  error: 'bad',
@@ -124,7 +125,7 @@ const VERDICT_TONE: Readonly<Record<string, string>> = {
124
125
  unmeasured: 'warn',
125
126
  };
126
127
 
127
- function badge(text: string, tone: string): Html {
128
+ export function badge(text: string, tone: string): Html {
128
129
  return h`<span class="status ${tone}">${text}</span>`;
129
130
  }
130
131
 
@@ -132,11 +133,11 @@ function seconds(durationMs: number): string {
132
133
  return `${(durationMs / 1000).toFixed(3)} s`;
133
134
  }
134
135
 
135
- function ms(value: number): string {
136
+ export function ms(value: number): string {
136
137
  return `${String(Math.round(value))} ms`;
137
138
  }
138
139
 
139
- function usd(value: number | null): string {
140
+ export function usd(value: number | null): string {
140
141
  return value === null ? 'no cost' : `$${round(value)}`;
141
142
  }
142
143
 
@@ -148,11 +149,15 @@ function item(term: string, value: Part): Html {
148
149
  return h`<dt>${term}</dt><dd>${value}</dd>`;
149
150
  }
150
151
 
151
- function list(lines: readonly string[], tone: string): Html {
152
+ export function list(lines: readonly string[], tone: string): Html {
152
153
  return h`<ul class="${tone}">${lines.map((line) => h`<li>${line}</li>`)}</ul>`;
153
154
  }
154
155
 
155
- function table(head: readonly string[], rows: readonly Html[], numeric: readonly number[] = []) {
156
+ export function table(
157
+ head: readonly string[],
158
+ rows: readonly Html[],
159
+ numeric: readonly number[] = [],
160
+ ): Html {
156
161
  const cells = head.map((name, index) =>
157
162
  numeric.includes(index) ? h`<th class="num">${name}</th>` : h`<th>${name}</th>`,
158
163
  );
@@ -506,7 +511,7 @@ function spansBlock(spans: NonNullable<TurnResult['spans']>): Html {
506
511
  )}</details>`;
507
512
  }
508
513
 
509
- function answerBlock(turn: TurnResult): Html {
514
+ export function answerBlock(turn: TurnResult): Html {
510
515
  const { response } = turn;
511
516
  if (response === undefined) return h`<p class="bad">No answer.</p>`;
512
517
  const facts = [
package/src/index.ts CHANGED
@@ -3,6 +3,8 @@
3
3
  export { CONTENT_SECURITY_POLICY, htmlReport } from './html.ts';
4
4
  export { junitXml, xmlAttribute, xmlText } from './junit.ts';
5
5
  export { comparisonText } from './compare.ts';
6
+ export { comparisonHtml } from './compare-html.ts';
6
7
  export { caseProblems, caseReason, type CaseProblems, type Problem } from './problems.ts';
8
+ export { markdownReport, MARKDOWN_ROWS } from './markdown.ts';
7
9
  export { terminalSummary, type TerminalSummary } from './terminal.ts';
8
10
  export { originText, withOrigin } from './format.ts';
@@ -0,0 +1,80 @@
1
+ // The Markdown summary of a run (ADR-0094), for a CI's job summary: what the
2
+ // terminal summary says, as Markdown, and, with the gate's outcome, the
3
+ // verdict first. It holds no answers, as the terminal summary holds none; the
4
+ // results file and the HTML report keep them. Its table shows the first
5
+ // MARKDOWN_ROWS cases, so it stays well under a CI's limit for a summary.
6
+
7
+ import type { GateOutcome, Results } from '@yokla/core';
8
+ import { caseRows, countLines, errorLines, noteLines } from './terminal.ts';
9
+
10
+ /** The most cases the table shows. */
11
+ export const MARKDOWN_ROWS = 100;
12
+
13
+ const HEADINGS: Readonly<Record<GateOutcome['verdict'], string>> = {
14
+ pass: 'the gate passed',
15
+ broken: 'the gate is broken',
16
+ unjudgeable: "the gate can't judge the run",
17
+ };
18
+
19
+ /** Text for a table cell: one line, with its pipes escaped. */
20
+ function cell(text: string): string {
21
+ return text
22
+ .replaceAll('\\', '\\\\')
23
+ .replaceAll('|', '\\|')
24
+ .replaceAll(/\s*\n\s*/gu, ' ');
25
+ }
26
+
27
+ /** Text for a list item: one line. */
28
+ function item(text: string): string {
29
+ return `- ${text.replaceAll(/\s*\n\s*/gu, ' ')}`;
30
+ }
31
+
32
+ /** A run's summary as Markdown; with the gate's outcome, its verdict first. */
33
+ export function markdownReport(results: Results, outcome?: GateOutcome): string {
34
+ const out: string[] = [
35
+ outcome === undefined ? '### yokla' : `### yokla: ${HEADINGS[outcome.verdict]}`,
36
+ '',
37
+ `Run \`${results.run.id}\` against \`${results.run.profile.target}\`.`,
38
+ '',
39
+ ...countLines(results).map(item),
40
+ ];
41
+
42
+ if (outcome !== undefined) {
43
+ const lines = [
44
+ ...outcome.breaches.map((breach) => breach.message),
45
+ ...outcome.problems.map((problem) => `can't judge: ${problem}`),
46
+ ...outcome.notices.map((notice) => `notice: ${notice}`),
47
+ ];
48
+ if (lines.length > 0) out.push('', '**The gate**', '', ...lines.map(item));
49
+ }
50
+
51
+ const rows = caseRows(results);
52
+ if (rows.length > 0) {
53
+ out.push('', '| Status | Case | Why |', '| --- | --- | --- |');
54
+ for (const [status, id, reason] of rows.slice(0, MARKDOWN_ROWS)) {
55
+ out.push(`| ${cell(status)} | \`${cell(id)}\` | ${cell(reason)} |`);
56
+ }
57
+ const more = rows.length - MARKDOWN_ROWS;
58
+ if (more > 0) {
59
+ out.push('', `And ${String(more)} more, which the HTML report lists.`);
60
+ }
61
+ }
62
+
63
+ const errors = errorLines(results);
64
+ if (errors.length > 0) out.push('', '**Errors**', '', ...errors.map(item));
65
+
66
+ const notes = noteLines(results);
67
+ if (notes.length > 0) {
68
+ out.push(
69
+ '',
70
+ '<details><summary>More about the run</summary>',
71
+ '',
72
+ '```text',
73
+ ...notes,
74
+ '```',
75
+ '',
76
+ '</details>',
77
+ );
78
+ }
79
+ return `${out.join('\n')}\n`;
80
+ }
package/src/terminal.ts CHANGED
@@ -76,16 +76,18 @@ function frameworkLines(results: Results): string[] {
76
76
  return lines;
77
77
  }
78
78
 
79
- export function terminalSummary(results: Results): TerminalSummary {
80
- const out: string[] = [];
81
- const err: string[] = [];
82
-
79
+ /**
80
+ * The lines that open a run's summary: the status counts and pass rate, then
81
+ * what --stop-early saved and how many cases are proposed.
82
+ */
83
+ export function countLines(results: Results): string[] {
84
+ const lines: string[] = [];
83
85
  const counts = CASE_STATUSES.flatMap((status) => {
84
86
  const count = results.summary.statuses[status];
85
87
  return count === undefined ? [] : [`${status} ${String(count)}`];
86
88
  });
87
89
  const passRate = results.summary.passRate;
88
- out.push(
90
+ lines.push(
89
91
  `${String(results.summary.cases)} cases: ${counts.join(', ')}` +
90
92
  (passRate === undefined ? '' : `; ${passRateText(passRate)}`),
91
93
  );
@@ -93,18 +95,24 @@ export function terminalSummary(results: Results): TerminalSummary {
93
95
  // How many samples --stop-early saved (ADR-0038).
94
96
  const ran = results.cases.reduce((n, c) => n + c.samples.length, 0);
95
97
  const planned = results.cases.reduce((n, c) => n + (c.samplesPlanned ?? c.samples.length), 0);
96
- out.push(` --stop-early: ${counted(ran, 'sample')} ran of ${String(planned)} planned`);
98
+ lines.push(`--stop-early: ${counted(ran, 'sample')} ran of ${String(planned)} planned`);
97
99
  }
98
100
  const proposed = results.cases.filter((c) => c.review === 'proposed').length;
99
101
  if (proposed > 0) {
100
- out.push(
101
- ` ${String(proposed)} proposed: they ran, and gate once a person sets their status to approved`,
102
+ lines.push(
103
+ `${String(proposed)} proposed: they ran, and gate once a person sets their status to approved`,
102
104
  );
103
105
  }
106
+ return lines;
107
+ }
104
108
 
105
- const rows: [string, string, string][] = [];
109
+ /** A case that didn't plainly pass, or its advisory findings: its status, its id, and why. */
110
+ export type CaseRow = readonly [status: string, id: string, reason: string];
111
+
112
+ /** The cases that didn't plainly pass, and advisory findings, heaviest first with weights (ADR-0076). */
113
+ export function caseRows(results: Results): CaseRow[] {
114
+ const rows: CaseRow[] = [];
106
115
  const weights = hasWeights(results);
107
- // Heaviest first when the cases carry weights: a heavy failure is worth fixing first (ADR-0076).
108
116
  for (const c of byWeight(results, results.cases)) {
109
117
  const problems = caseProblems(c);
110
118
  const reason = caseReason(c, problems);
@@ -121,18 +129,33 @@ export function terminalSummary(results: Results): TerminalSummary {
121
129
  }
122
130
  const advisory = dimensionSummary(c, problems.advisory, true);
123
131
  if (advisory !== '') rows.push(['advisory', c.id, advisory]);
132
+ }
133
+ return rows;
134
+ }
135
+
136
+ /** Each turn that ended in an error, and each problem of the run itself. */
137
+ export function errorLines(results: Results): string[] {
138
+ const lines: string[] = [];
139
+ for (const c of byWeight(results, results.cases)) {
124
140
  for (const sample of c.samples) {
125
141
  for (const turn of sample.turns) {
126
- if (turn.error !== undefined)
127
- err.push(` ${c.id} [sample ${String(sample.index)}]: ${turn.error}`);
142
+ if (turn.error !== undefined) {
143
+ lines.push(`${c.id} [sample ${String(sample.index)}]: ${turn.error}`);
144
+ }
128
145
  }
129
146
  }
130
147
  }
131
- const statusWidth = Math.max(0, ...rows.map(([status]) => status.length));
132
- const idWidth = Math.max(0, ...rows.map(([, id]) => id.length));
133
- for (const [status, id, reason] of rows) {
134
- out.push(` ${status.padEnd(statusWidth)} ${id.padEnd(idWidth)} ${reason}`);
135
- }
148
+ for (const issue of results.run.issues ?? []) lines.push(`run: ${issue}`);
149
+ return lines;
150
+ }
151
+
152
+ /**
153
+ * The rest of a run's summary: the cases by tag, what the target's logs, the
154
+ * model proxy and the spans observed, yokla's own models, the run's
155
+ * transforms, strategy, attacker and judge, and the frameworks.
156
+ */
157
+ export function noteLines(results: Results): string[] {
158
+ const out: string[] = [];
136
159
 
137
160
  // Per tag, the most failing first (ADR-0077).
138
161
  const tags = tagsByFailures(results);
@@ -202,6 +225,7 @@ export function terminalSummary(results: Results): TerminalSummary {
202
225
  out.push(
203
226
  `attacker: ${attacker.strategy}, ${attackerBound(attacker)}, ${counted(attacker.cases, 'case')}`,
204
227
  );
228
+ out.push(...unsentAttemptLines(results, attacker.strategy === 'escalation'));
205
229
  }
206
230
  // The judge: its model, its dimensions, and its calibration (ADR-0090).
207
231
  const { judge } = results.run;
@@ -215,8 +239,83 @@ export function terminalSummary(results: Results): TerminalSummary {
215
239
  out.push(
216
240
  `judge: ${judge.model ?? 'none'}, ${dimensions}; ${judge.unmeasured === undefined ? calibrated : `unmeasured: ${judge.unmeasured}`}`,
217
241
  );
242
+ // A run-wide reason already covers every verdict; else the turns' own gaps (ADR-0099).
243
+ if (judge.unmeasured === undefined) out.push(...unmeasuredVerdictLines(results));
218
244
  }
219
245
  out.push(...frameworkLines(results));
220
- for (const issue of results.run.issues ?? []) err.push(` run: ${issue}`);
221
- return { out, err };
246
+ return out;
247
+ }
248
+
249
+ /**
250
+ * The attacker's attempts not sent, counted by reason, with the values a
251
+ * reason quotes left out so that one reason counts once; and the escalations
252
+ * that never carried the attack (ADR-0101).
253
+ */
254
+ function unsentAttemptLines(results: Results, escalation: boolean): string[] {
255
+ const attacked = results.cases.flatMap((c) => c.samples).filter((s) => s.attacker !== undefined);
256
+ const noun = escalation ? 'conversation' : 'attempt';
257
+ const reasons = new Map<string, number>();
258
+ let neverCarried = 0;
259
+ for (const sample of attacked) {
260
+ const unsent = sample.attacker?.unsent;
261
+ if (unsent !== undefined) {
262
+ const reason = unsent.replaceAll(/"[^"]*"/gu, '"…"');
263
+ reasons.set(reason, (reasons.get(reason) ?? 0) + 1);
264
+ } else if (sample.turns.length > 0 && sample.turns.every((turn) => turn.approach === true)) {
265
+ neverCarried += 1;
266
+ }
267
+ }
268
+ const unsentCount = [...reasons.values()].reduce((sum, count) => sum + count, 0);
269
+ const lines: string[] = [];
270
+ if (unsentCount > 0) {
271
+ lines.push(
272
+ ` ${String(unsentCount)} of ${counted(attacked.length, noun)} ${escalation ? 'ended at a reply not sent' : 'not sent'}:`,
273
+ ...[...reasons].map(([reason, count]) => ` ${reason} (${counted(count, noun)})`),
274
+ );
275
+ }
276
+ if (neverCarried > 0) {
277
+ lines.push(` ${counted(neverCarried, 'conversation')} never carried the attack`);
278
+ }
279
+ return lines;
280
+ }
281
+
282
+ /** The judged turns' verdicts left unmeasured, counted by reason, if any (ADR-0099). */
283
+ function unmeasuredVerdictLines(results: Results): string[] {
284
+ let verdicts = 0;
285
+ const reasons = new Map<string, number>();
286
+ for (const turn of results.cases.flatMap((c) => c.samples).flatMap((s) => s.turns)) {
287
+ for (const check of turn.checks) {
288
+ if (check.check !== 'judge') continue;
289
+ verdicts += check.findings.length;
290
+ for (const gap of check.unmeasured ?? []) {
291
+ verdicts += 1;
292
+ reasons.set(gap.reason, (reasons.get(gap.reason) ?? 0) + 1);
293
+ }
294
+ }
295
+ }
296
+ const unmeasured = [...reasons.values()].reduce((sum, count) => sum + count, 0);
297
+ if (unmeasured === 0) return [];
298
+ return [
299
+ ` ${String(unmeasured)} of ${counted(verdicts, 'verdict')} unmeasured:`,
300
+ ...[...reasons].map(([reason, count]) => ` ${reason} (${counted(count, 'verdict')})`),
301
+ ];
302
+ }
303
+
304
+ export function terminalSummary(results: Results): TerminalSummary {
305
+ const [first = '', ...more] = countLines(results);
306
+ const rows = caseRows(results);
307
+ const statusWidth = Math.max(0, ...rows.map(([status]) => status.length));
308
+ const idWidth = Math.max(0, ...rows.map(([, id]) => id.length));
309
+ return {
310
+ out: [
311
+ first,
312
+ ...more.map((line) => ` ${line}`),
313
+ ...rows.map(
314
+ ([status, id, reason]) =>
315
+ ` ${status.padEnd(statusWidth)} ${id.padEnd(idWidth)} ${reason}`,
316
+ ),
317
+ ...noteLines(results),
318
+ ],
319
+ err: errorLines(results).map((line) => ` ${line}`),
320
+ };
222
321
  }