@edjbarron/ux-guard 0.0.0-stage → 0.6.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.
@@ -0,0 +1,1769 @@
1
+ import {
2
+ unavailableJourneyComparison,
3
+ validateJourneyComparison,
4
+ } from './baselines.mjs';
5
+ import { validateJourneyPolicy } from './journey-policy.mjs';
6
+ import { validateJourneyReport } from './journeys.mjs';
7
+ import { canonicalize, policyDigest, validateRunEnvelope } from './run-contract.mjs';
8
+ import {
9
+ unavailableTargetAttainment,
10
+ validateTargetAttainment,
11
+ } from './targets.mjs';
12
+ import {
13
+ unavailableVisualComparison,
14
+ validateVisualComparison,
15
+ } from './visuals.mjs';
16
+
17
+ export const VERDICT_REPORT_KIND = 'ux-guard-verdict-report';
18
+ export const VERDICT_REPORT_VERSION = 6;
19
+
20
+ const QUALITY_VERDICTS = new Set([
21
+ 'incomplete',
22
+ 'needs-improvement',
23
+ 'acceptable',
24
+ ]);
25
+ const DIMENSIONS = [
26
+ 'efficiency',
27
+ 'clarity',
28
+ 'feedback-and-recovery',
29
+ 'accessibility',
30
+ 'consistency',
31
+ ];
32
+ const STATUS_ORDER = new Map([
33
+ ['infrastructure-error', 0],
34
+ ['failed', 1],
35
+ ['skipped', 2],
36
+ ['unexecutable', 3],
37
+ ['unmeasured', 4],
38
+ ['successful', 5],
39
+ ]);
40
+
41
+ export class VerdictReportError extends Error {
42
+ constructor(message) {
43
+ super(message);
44
+ this.name = 'VerdictReportError';
45
+ }
46
+ }
47
+
48
+ export function createVerdictReport({
49
+ catalog,
50
+ policy,
51
+ measurements,
52
+ patterns,
53
+ comparison = unavailableJourneyComparison('reviewed journey baseline is not configured'),
54
+ targets = unavailableTargetAttainment(
55
+ 'not-configured',
56
+ 'owner targets are not configured',
57
+ ),
58
+ readinessEvidence = null,
59
+ visuals = defaultVisualSummary(),
60
+ } = {}) {
61
+ validateJourneyPolicy(policy);
62
+ validateJourneyReport(measurements);
63
+ validateJourneyComparison(comparison);
64
+ validateTargetAttainment(targets);
65
+ if (measurements.run.policy.digest !== policyDigest(policy)) {
66
+ throw new VerdictReportError('measurement report policy digest does not match reviewed policy');
67
+ }
68
+ const catalogEntries = catalogUseCases(catalog);
69
+ const catalogById = new Map(catalogEntries.map((useCase) => [useCase.id, useCase]));
70
+ const definitions = new Map(
71
+ policy.journeys.map((journey) => [`${journey.useCaseId}\0${journey.journeyId}`, journey]),
72
+ );
73
+ const measured = new Map(
74
+ measurements.journeys.map((journey) => [
75
+ `${journey.useCaseId}\0${journey.journeyId}`,
76
+ journey,
77
+ ]),
78
+ );
79
+ for (const finding of measurements.findings) {
80
+ bindFinding(finding, catalogById, definitions, measurements.journeys);
81
+ }
82
+
83
+ const journeys = [];
84
+ const useCases = [];
85
+ const recommendations = [];
86
+ for (const coverage of policy.coverage) {
87
+ const catalogEntry = catalogById.get(coverage.useCaseId);
88
+ if (!catalogEntry) {
89
+ throw new VerdictReportError(
90
+ `coverage policy names uncatalogued use case ${coverage.useCaseId}`,
91
+ );
92
+ }
93
+ const useCaseJourneys = coverage.requiredVariants.map((variant) => {
94
+ const definition = definitions.get(`${coverage.useCaseId}\0${variant.journeyId}`);
95
+ if (!definition) {
96
+ throw new VerdictReportError(
97
+ `required variant has no definition: ${coverage.useCaseId}/${variant.journeyId}`,
98
+ );
99
+ }
100
+ const measurement = measured.get(`${coverage.useCaseId}\0${variant.journeyId}`);
101
+ const status = measurement?.status ?? 'unmeasured';
102
+ const findingRefs = measurement?.findingRefs ?? [];
103
+ const verdict =
104
+ status !== 'successful'
105
+ ? 'incomplete'
106
+ : findingRefs.length
107
+ ? 'needs-improvement'
108
+ : 'acceptable';
109
+ const record = {
110
+ id: `journey.${coverage.useCaseId}.${variant.journeyId}`,
111
+ useCaseId: coverage.useCaseId,
112
+ variantId: variant.variantId,
113
+ label: variant.label,
114
+ journeyId: variant.journeyId,
115
+ executionStatus: status,
116
+ verdict,
117
+ metrics: measurement?.metrics ?? null,
118
+ findingRefs: [...findingRefs].sort(),
119
+ };
120
+ journeys.push(record);
121
+ return record;
122
+ });
123
+ const successful = useCaseJourneys.filter(
124
+ (journey) => journey.executionStatus === 'successful',
125
+ ).length;
126
+ const findingRefs = [
127
+ ...new Set(useCaseJourneys.flatMap((journey) => journey.findingRefs)),
128
+ ].sort();
129
+ const complete = successful === useCaseJourneys.length;
130
+ const verdict = complete
131
+ ? findingRefs.length
132
+ ? 'needs-improvement'
133
+ : 'acceptable'
134
+ : 'incomplete';
135
+ const useCase = {
136
+ useCaseId: coverage.useCaseId,
137
+ title: catalogEntry.title,
138
+ verdict,
139
+ reason: useCaseReason(useCaseJourneys, findingRefs.length),
140
+ coverage: {
141
+ status: complete ? 'complete' : 'incomplete',
142
+ requiredVariants: useCaseJourneys.length,
143
+ measuredVariants: useCaseJourneys.filter(
144
+ (journey) => journey.executionStatus !== 'unmeasured',
145
+ ).length,
146
+ successfulVariants: successful,
147
+ statuses: Object.fromEntries(
148
+ [...STATUS_ORDER.keys()].map((status) => [
149
+ status,
150
+ useCaseJourneys
151
+ .filter((journey) => journey.executionStatus === status)
152
+ .map((journey) => journey.variantId),
153
+ ]),
154
+ ),
155
+ },
156
+ journeyRefs: useCaseJourneys.map((journey) => journey.id),
157
+ findingRefs,
158
+ recommendationRefs: [],
159
+ comparison: crossVariantComparison(useCaseJourneys),
160
+ };
161
+ for (const findingRef of findingRefs) {
162
+ const finding = measurements.findings.find((candidate) => candidate.id === findingRef);
163
+ const id = `recommendation.${finding.ruleId}`;
164
+ recommendations.push({
165
+ id,
166
+ findingRef,
167
+ targetRef: null,
168
+ useCaseId: coverage.useCaseId,
169
+ severity: finding.severity,
170
+ type: finding.type,
171
+ affectedJourneyRefs: [...finding.journeyRefs],
172
+ text: finding.recommendation,
173
+ });
174
+ useCase.recommendationRefs.push(id);
175
+ }
176
+ for (const journey of useCaseJourneys.filter(
177
+ (candidate) => candidate.executionStatus === 'unmeasured',
178
+ )) {
179
+ const id = `recommendation.coverage.${coverage.useCaseId}.${journey.variantId}`;
180
+ recommendations.push({
181
+ id,
182
+ findingRef: null,
183
+ targetRef: null,
184
+ useCaseId: coverage.useCaseId,
185
+ severity: 'high',
186
+ type: 'coverage',
187
+ affectedJourneyRefs: [journey.id],
188
+ text: `Bind and measure the ${journey.label} required variant.`,
189
+ });
190
+ useCase.recommendationRefs.push(id);
191
+ }
192
+ useCases.push(useCase);
193
+ }
194
+
195
+ const staticPatterns = createStaticPatternReport(patterns);
196
+ const requiredVariants = useCases.reduce(
197
+ (total, useCase) => total + useCase.coverage.requiredVariants,
198
+ 0,
199
+ );
200
+ const measuredVariants = useCases.reduce(
201
+ (total, useCase) => total + useCase.coverage.measuredVariants,
202
+ 0,
203
+ );
204
+ const successfulVariants = useCases.reduce(
205
+ (total, useCase) => total + useCase.coverage.successfulVariants,
206
+ 0,
207
+ );
208
+ const complete =
209
+ useCases.length === catalogEntries.length &&
210
+ useCases.length > 0 &&
211
+ useCases.every((useCase) => useCase.coverage.status === 'complete');
212
+ const qualityVerdict = !complete
213
+ ? 'incomplete'
214
+ : useCases.some((useCase) => useCase.verdict === 'needs-improvement')
215
+ ? 'needs-improvement'
216
+ : 'acceptable';
217
+ recommendations.push(
218
+ ...targetRecommendations(targets),
219
+ );
220
+ const readiness = scoringReadiness({
221
+ comparison,
222
+ measurements,
223
+ readinessEvidence,
224
+ });
225
+ const report = {
226
+ kind: VERDICT_REPORT_KIND,
227
+ version: VERDICT_REPORT_VERSION,
228
+ run: structuredClone(measurements.run),
229
+ rollout: 'advisory',
230
+ coverage: {
231
+ status: complete ? 'complete' : 'incomplete',
232
+ cataloguedUseCases: catalogEntries.length,
233
+ reportedUseCases: useCases.length,
234
+ requiredVariants,
235
+ measuredVariants,
236
+ successfulVariants,
237
+ },
238
+ quality: {
239
+ verdict: qualityVerdict,
240
+ reason: qualityReason(qualityVerdict, useCases),
241
+ dimensions: qualityDimensions(measurements.findings),
242
+ },
243
+ targetAttainment: structuredClone(targets),
244
+ regression: regressionReport(comparison, staticPatterns),
245
+ readiness,
246
+ scoring: numericalScore(policy, targets),
247
+ visuals: normalizeVisualSummary(visuals),
248
+ staticPatterns,
249
+ useCases,
250
+ journeys: journeys.sort((left, right) => left.id.localeCompare(right.id)),
251
+ findings: structuredClone(measurements.findings),
252
+ recommendations: {
253
+ status: recommendations.length ? 'available' : 'none',
254
+ items: recommendations.sort(compareRecommendation),
255
+ },
256
+ details: structuredClone(measurements.details),
257
+ };
258
+ return validateVerdictReport(report);
259
+ }
260
+
261
+ export function validateVerdictReport(report) {
262
+ assertMap(report, 'report');
263
+ assertExactKeys(
264
+ report,
265
+ [
266
+ 'kind',
267
+ 'version',
268
+ 'run',
269
+ 'rollout',
270
+ 'coverage',
271
+ 'quality',
272
+ 'targetAttainment',
273
+ 'regression',
274
+ 'readiness',
275
+ 'scoring',
276
+ 'visuals',
277
+ 'staticPatterns',
278
+ 'useCases',
279
+ 'journeys',
280
+ 'findings',
281
+ 'recommendations',
282
+ 'details',
283
+ ],
284
+ 'report',
285
+ );
286
+ if (report.kind !== VERDICT_REPORT_KIND) {
287
+ throw new VerdictReportError(`report.kind must be ${VERDICT_REPORT_KIND}`);
288
+ }
289
+ if (report.version !== VERDICT_REPORT_VERSION) {
290
+ throw new VerdictReportError(
291
+ `unsupported verdict report version ${String(report.version)}; migrate to version ${VERDICT_REPORT_VERSION}`,
292
+ );
293
+ }
294
+ validateRunEnvelope(report.run);
295
+ if (report.rollout !== 'advisory') {
296
+ throw new VerdictReportError('report.rollout must be advisory');
297
+ }
298
+ validateQuality(report.quality);
299
+ validateTargetAttainment(report.targetAttainment);
300
+ validateRegression(report.regression);
301
+ validateReadiness(report.readiness);
302
+ validateVisualSummary(report.visuals);
303
+ validateCoverage(report.coverage);
304
+ validateNumericalScore(report.scoring);
305
+ validateStaticPatterns(report.staticPatterns);
306
+ for (const field of ['useCases', 'journeys', 'findings']) {
307
+ if (!Array.isArray(report[field])) {
308
+ throw new VerdictReportError(`report.${field} must be an array`);
309
+ }
310
+ }
311
+ assertMap(report.details, 'report.details');
312
+ assertExactKeys(report.details, ['steps', 'observations'], 'report.details');
313
+ if (!Array.isArray(report.details.steps) || !Array.isArray(report.details.observations)) {
314
+ throw new VerdictReportError('report.details is invalid');
315
+ }
316
+ const journeyIds = uniqueIds(report.journeys, 'report.journeys');
317
+ const findingIds = uniqueIds(report.findings, 'report.findings');
318
+ assertMap(report.recommendations, 'report.recommendations');
319
+ assertExactKeys(
320
+ report.recommendations,
321
+ ['status', 'items'],
322
+ 'report.recommendations',
323
+ );
324
+ if (
325
+ !['available', 'none'].includes(report.recommendations.status) ||
326
+ !Array.isArray(report.recommendations.items) ||
327
+ (report.recommendations.items.length > 0) !==
328
+ (report.recommendations.status === 'available')
329
+ ) {
330
+ throw new VerdictReportError('report.recommendations is invalid');
331
+ }
332
+ const recommendationIds = uniqueIds(
333
+ report.recommendations.items,
334
+ 'report.recommendations.items',
335
+ );
336
+ const useCaseIds = new Set();
337
+ for (const [index, journey] of report.journeys.entries()) {
338
+ validateJourney(journey, `report.journeys[${index}]`, findingIds);
339
+ }
340
+ for (const [index, useCase] of report.useCases.entries()) {
341
+ validateUseCase(
342
+ useCase,
343
+ `report.useCases[${index}]`,
344
+ journeyIds,
345
+ findingIds,
346
+ recommendationIds,
347
+ );
348
+ if (useCaseIds.has(useCase.useCaseId)) {
349
+ throw new VerdictReportError(`report.useCases repeats ${useCase.useCaseId}`);
350
+ }
351
+ useCaseIds.add(useCase.useCaseId);
352
+ }
353
+ for (const [index, recommendation] of report.recommendations.items.entries()) {
354
+ const path = `report.recommendations.items[${index}]`;
355
+ assertMap(recommendation, path);
356
+ assertExactKeys(
357
+ recommendation,
358
+ [
359
+ 'id',
360
+ 'findingRef',
361
+ 'targetRef',
362
+ 'useCaseId',
363
+ 'severity',
364
+ 'type',
365
+ 'affectedJourneyRefs',
366
+ 'text',
367
+ ],
368
+ path,
369
+ );
370
+ if (recommendation.findingRef !== null && !findingIds.has(recommendation.findingRef)) {
371
+ throw new VerdictReportError(`${path}.findingRef is invalid`);
372
+ }
373
+ if (recommendation.targetRef !== null) {
374
+ assertText(recommendation.targetRef, `${path}.targetRef`);
375
+ }
376
+ if (
377
+ recommendation.findingRef !== null &&
378
+ recommendation.targetRef !== null
379
+ ) {
380
+ throw new VerdictReportError(
381
+ `${path} cannot reference a finding and target together`,
382
+ );
383
+ }
384
+ if (recommendation.useCaseId !== null) {
385
+ assertText(recommendation.useCaseId, `${path}.useCaseId`);
386
+ }
387
+ if (
388
+ !Array.isArray(recommendation.affectedJourneyRefs) ||
389
+ recommendation.affectedJourneyRefs.some((id) => !journeyIds.has(id))
390
+ ) {
391
+ throw new VerdictReportError(`${path}.affectedJourneyRefs is invalid`);
392
+ }
393
+ assertText(recommendation.text, `${path}.text`);
394
+ }
395
+ return report;
396
+ }
397
+
398
+ export function serializeVerdictReport(report) {
399
+ validateVerdictReport(report);
400
+ return `${JSON.stringify(canonicalize(report), null, 2)}\n`;
401
+ }
402
+
403
+ export function parseVerdictReport(text) {
404
+ let report;
405
+ try {
406
+ report = JSON.parse(text);
407
+ } catch {
408
+ throw new VerdictReportError('verdict report is not valid JSON');
409
+ }
410
+ if (report?.kind === VERDICT_REPORT_KIND && report.version !== VERDICT_REPORT_VERSION) {
411
+ throw new VerdictReportError(
412
+ `unsupported verdict report version ${String(report.version)}; migrate to version ${VERDICT_REPORT_VERSION}`,
413
+ );
414
+ }
415
+ return validateVerdictReport(report);
416
+ }
417
+
418
+ export function renderVerdictMarkdown(report) {
419
+ validateVerdictReport(report);
420
+ const lines = [
421
+ '# ux-guard advisory verdict report',
422
+ '',
423
+ '> Advisory evidence only. Journey and visual results do not change the command exit status.',
424
+ '',
425
+ '## Run and evidence status',
426
+ '',
427
+ `- **Run result:** ${capitalize(report.run.completion.result)} (${report.run.completion.received}/${report.run.completion.expected} required variants aggregated)`,
428
+ `- **Candidate commit:** ${report.run.provenance.candidate.commit ?? 'Unavailable locally'}`,
429
+ `- **Trusted/base commit:** ${report.run.provenance.base.commit ?? 'Not supplied'}`,
430
+ `- **Policy digest:** \`${report.run.policy.digest}\``,
431
+ `- **Browser/profile:** ${report.run.browser.name} / ${report.run.browser.profile}`,
432
+ `- **Quality verdict:** ${verdictLabel(report.quality.verdict)} — ${report.quality.reason}`,
433
+ `- **Target attainment:** ${targetAttainmentLabel(report.targetAttainment)}`,
434
+ `- **Regression/backslide:** ${comparisonLabel(report.regression.journeyComparison)}`,
435
+ `- **Visual evidence:** ${visualLabel(report.visuals)}`,
436
+ `- **Scoring readiness:** ${capitalize(report.readiness.state)} — ${report.readiness.reasons.join('; ')}`,
437
+ '- **Execution trust:** Candidate ux-guard code produced this diagnostic; only pinned-base authoritative regeneration may create the authoritative advisory artifact.',
438
+ `- **Numerical scoring:** ${scoreLabel(report.scoring)}`,
439
+ `- **Accessibility:** ${report.quality.dimensions.find(({ dimension }) => dimension === 'accessibility').reason}`,
440
+ `- **Pattern debt:** ${report.staticPatterns.meaning}`,
441
+ ];
442
+ if (report.run.errors.length) {
443
+ lines.push('- **Run errors:**');
444
+ for (const error of report.run.errors) {
445
+ lines.push(` - \`${error.journeyRef}\` (${error.category}): ${error.message}`);
446
+ }
447
+ } else {
448
+ lines.push('- **Run errors:** None.');
449
+ }
450
+ if (report.staticPatterns.findings.length) {
451
+ lines.push('- **Observed pattern-debt growth:**');
452
+ for (const finding of report.staticPatterns.findings) {
453
+ lines.push(` - **${finding.ruleId}:** ${finding.summary}`);
454
+ }
455
+ } else {
456
+ lines.push('- **Observed pattern-debt growth:** None detected.');
457
+ }
458
+ lines.push(
459
+ '',
460
+ '## Target attainment',
461
+ '',
462
+ `**${targetAttainmentLabel(report.targetAttainment)}**`,
463
+ '',
464
+ );
465
+ if (report.targetAttainment.hardFloors.length === 0) {
466
+ lines.push('No reviewed target values were evaluated.', '');
467
+ } else {
468
+ for (const floor of report.targetAttainment.hardFloors) {
469
+ lines.push(
470
+ `- \`${floor.id}\`: **${floor.status}** (actual ${floor.actual}; ${operatorLabel(floor.operator)} ${floor.target})`,
471
+ );
472
+ }
473
+ for (const journey of report.targetAttainment.journeys) {
474
+ for (const metric of journey.metrics) {
475
+ lines.push(
476
+ `- \`${journey.journeyRef}/${metric.metric}\`: **${metric.status}** (actual ${metric.actual ?? 'unavailable'}; ${operatorLabel(metric.operator)} ${metric.target})`,
477
+ );
478
+ }
479
+ }
480
+ lines.push('');
481
+ }
482
+
483
+ lines.push(
484
+ '## Regression and backslide',
485
+ '',
486
+ `- **Journey comparison:** ${comparisonLabel(report.regression.journeyComparison)}`,
487
+ `- **Metric comparison completeness:** ${report.regression.journeyComparison.completeness.status} (${report.regression.journeyComparison.completeness.metrics.notEvaluated} not evaluated)`,
488
+ `- **Pattern comparison:** ${report.regression.patternDebt.reason}`,
489
+ '- **Interpretation:** Equality with a reviewed baseline means no observed backslide; it does not mean the UX is good or that known defects are acceptable.',
490
+ '',
491
+ '## Numerical scores',
492
+ '',
493
+ `${scoreLabel(report.scoring)} Scores are based only on reviewed owner metric targets; baselines never produce scores.`,
494
+ '',
495
+ );
496
+ const scoredUseCases = report.scoring.useCases.filter(
497
+ ({ score }) => score !== null,
498
+ );
499
+ if (scoredUseCases.length === 0) {
500
+ lines.push('No use case has a target-backed numerical score.', '');
501
+ } else {
502
+ for (const useCase of scoredUseCases) {
503
+ lines.push(
504
+ `- \`${useCase.useCaseId}\`: **${useCase.score}** (${useCase.status}; minimum of ${useCase.scoredJourneys} scored required journey${useCase.scoredJourneys === 1 ? '' : 's'})`,
505
+ );
506
+ }
507
+ lines.push('');
508
+ }
509
+
510
+ lines.push('## Recommendations', '');
511
+ if (report.recommendations.items.length === 0) {
512
+ lines.push('No policy-bound recommendation was generated.', '');
513
+ } else {
514
+ for (const recommendation of report.recommendations.items) {
515
+ lines.push(
516
+ `- **${capitalize(recommendation.severity)} — ${recommendation.id}:** ${recommendation.text}`,
517
+ );
518
+ }
519
+ lines.push('');
520
+ }
521
+
522
+ const groups = [
523
+ ['Incomplete and missing product paths', ['incomplete']],
524
+ ['Needs-improvement findings', ['needs-improvement']],
525
+ ['Acceptable cases', ['acceptable']],
526
+ ];
527
+ for (const [heading, verdicts] of groups) {
528
+ lines.push(`## ${heading}`, '');
529
+ const selected = report.useCases.filter((useCase) => verdicts.includes(useCase.verdict));
530
+ if (selected.length === 0) {
531
+ lines.push('None.', '');
532
+ continue;
533
+ }
534
+ for (const useCase of selected) renderUseCase(lines, report, useCase);
535
+ }
536
+
537
+ lines.push('## Evidence details', '');
538
+ if (report.findings.length === 0) {
539
+ lines.push('No policy findings generated evidence records.', '');
540
+ } else {
541
+ for (const finding of report.findings) {
542
+ lines.push(`### ${finding.ruleId}`, '');
543
+ for (const evidence of finding.evidence) {
544
+ lines.push(
545
+ `- \`${evidence.id}\` — ${variantLabel(report, evidence.journeyRef)} / step \`${evidence.stepId}\`: ${renderFacts(evidence.facts)}`,
546
+ );
547
+ }
548
+ lines.push('');
549
+ }
550
+ }
551
+ return `${lines.join('\n')}\n`;
552
+ }
553
+
554
+ function renderUseCase(lines, report, useCase) {
555
+ lines.push(
556
+ `### ${useCase.title} (\`${useCase.useCaseId}\`)`,
557
+ '',
558
+ `- **Verdict:** ${verdictLabel(useCase.verdict)}`,
559
+ `- **Coverage:** ${useCase.coverage.successfulVariants}/${useCase.coverage.requiredVariants} successful; ${useCase.coverage.measuredVariants}/${useCase.coverage.requiredVariants} measured`,
560
+ `- **Reason:** ${useCase.reason}`,
561
+ );
562
+ const affected = report.journeys
563
+ .filter((journey) => useCase.journeyRefs.includes(journey.id))
564
+ .sort(
565
+ (left, right) =>
566
+ STATUS_ORDER.get(left.executionStatus) - STATUS_ORDER.get(right.executionStatus) ||
567
+ left.label.localeCompare(right.label),
568
+ );
569
+ for (const journey of affected) {
570
+ lines.push(
571
+ ` - **${journey.label}:** ${statusLabel(journey.executionStatus)}${
572
+ journey.metrics ? `; ${renderMetrics(journey.metrics)}` : ''
573
+ }`,
574
+ );
575
+ }
576
+ if (useCase.findingRefs.length) {
577
+ lines.push('- **Findings:**');
578
+ for (const findingRef of useCase.findingRefs) {
579
+ const finding = report.findings.find((candidate) => candidate.id === findingRef);
580
+ const labels = finding.journeyRefs.map((journeyRef) => variantLabel(report, journeyRef));
581
+ lines.push(
582
+ ` - **${finding.ruleId}** — ${capitalize(finding.severity)} ${finding.type}; ${finding.dimension}; affects ${labels.join(', ')}`,
583
+ ` - ${finding.summary}`,
584
+ ` - Recommendation: ${finding.recommendation}`,
585
+ ` - Evidence: ${finding.evidence.map((evidence) => `\`${evidence.id}\``).join(', ')}`,
586
+ );
587
+ }
588
+ }
589
+ lines.push('');
590
+ }
591
+
592
+ function bindFinding(finding, catalogById, definitions, journeys) {
593
+ const affected = finding.journeyRefs.map((journeyRef) =>
594
+ journeys.find((journey) => journey.id === journeyRef),
595
+ );
596
+ if (affected.some((journey) => !journey)) {
597
+ throw new VerdictReportError(`${finding.ruleId} names an unknown journey`);
598
+ }
599
+ const useCases = new Set(affected.map((journey) => journey.useCaseId));
600
+ if (useCases.size !== 1) {
601
+ throw new VerdictReportError(`${finding.ruleId} spans multiple use cases`);
602
+ }
603
+ const useCaseId = [...useCases][0];
604
+ const useCase = catalogById.get(useCaseId);
605
+ for (const reference of finding.policy) {
606
+ if (reference.source === 'use-case-requirement') {
607
+ if (!useCase.requirements.includes(reference.statement)) {
608
+ throw new VerdictReportError(
609
+ `${finding.ruleId} does not match an owner requirement for ${useCaseId}`,
610
+ );
611
+ }
612
+ continue;
613
+ }
614
+ if (
615
+ !affected.some((journey) => {
616
+ const definition = definitions.get(`${journey.useCaseId}\0${journey.journeyId}`);
617
+ if (definition.approval.status !== 'owner-approved') return false;
618
+ const values =
619
+ reference.field === 'intent.steps'
620
+ ? definition.intent.steps
621
+ : reference.field === 'intent.summary'
622
+ ? [definition.intent.summary]
623
+ : [definition.intent.success];
624
+ return values.includes(reference.statement);
625
+ })
626
+ ) {
627
+ throw new VerdictReportError(
628
+ `${finding.ruleId} does not match approved journey ${reference.field}`,
629
+ );
630
+ }
631
+ }
632
+ }
633
+
634
+ function crossVariantComparison(journeys) {
635
+ const occurrence = new Map();
636
+ for (const journey of journeys.filter((candidate) => candidate.executionStatus !== 'unmeasured')) {
637
+ for (const findingRef of journey.findingRefs) {
638
+ const refs = occurrence.get(findingRef) ?? [];
639
+ refs.push(journey.id);
640
+ occurrence.set(findingRef, refs);
641
+ }
642
+ }
643
+ return {
644
+ status: journeys.every((journey) => journey.executionStatus !== 'unmeasured')
645
+ ? 'complete'
646
+ : 'partial',
647
+ sharedFindingRefs: [...occurrence.entries()]
648
+ .filter(([, refs]) => refs.length === journeys.length)
649
+ .map(([findingRef]) => findingRef)
650
+ .sort(),
651
+ differingFindingRefs: [...occurrence.entries()]
652
+ .filter(([, refs]) => refs.length < journeys.length)
653
+ .map(([findingRef, journeyRefs]) => ({
654
+ findingRef,
655
+ journeyRefs: [...journeyRefs].sort(),
656
+ }))
657
+ .sort((left, right) => left.findingRef.localeCompare(right.findingRef)),
658
+ };
659
+ }
660
+
661
+ function createStaticPatternReport(patterns) {
662
+ const raw = patterns?.findings ?? [];
663
+ if (!Array.isArray(raw)) throw new VerdictReportError('patterns.findings must be an array');
664
+ const findings = [...raw]
665
+ .sort((left, right) => JSON.stringify(left).localeCompare(JSON.stringify(right)))
666
+ .map((finding) => ({
667
+ id: `finding.pattern.${finding.rule}.${finding.key ?? finding.file ?? 'global'}`,
668
+ ruleId: `pattern.${finding.rule}`,
669
+ severity: 'medium',
670
+ dimension: 'consistency',
671
+ type: 'regression',
672
+ summary:
673
+ finding.rule === 'new-control-value'
674
+ ? `${finding.key} introduces value ${finding.value} beyond the reviewed pattern baseline.`
675
+ : `${finding.rule} grew beyond the reviewed pattern baseline${finding.file ? ` in ${finding.file}` : ''}.`,
676
+ evidence: structuredClone(finding),
677
+ recommendation:
678
+ finding.rule === 'new-control-value'
679
+ ? 'Use a reviewed existing control value, or obtain explicit pattern-policy review.'
680
+ : 'Remove the new pattern debt, or obtain explicit review before changing the baseline.',
681
+ }));
682
+ return {
683
+ status: findings.length ? 'growth' : 'no-growth',
684
+ baseline: {
685
+ status: 'reviewed',
686
+ regressionStatus: findings.length ? 'regression' : 'unchanged',
687
+ },
688
+ meaning: findings.length
689
+ ? 'Observed pattern debt grew beyond the reviewed non-growth baseline; preferred-pattern alignment was not evaluated.'
690
+ : 'No observed pattern-debt growth; preferred-pattern alignment was not evaluated.',
691
+ findings,
692
+ };
693
+ }
694
+
695
+ function catalogUseCases(catalog) {
696
+ const entries = Array.isArray(catalog?.useCases)
697
+ ? catalog.useCases
698
+ : Array.isArray(catalog?.use_cases)
699
+ ? catalog.use_cases
700
+ : null;
701
+ if (!entries) throw new VerdictReportError('catalog must contain use cases');
702
+ return entries.map((entry) => {
703
+ if (
704
+ typeof entry?.id !== 'string' ||
705
+ typeof entry?.title !== 'string' ||
706
+ !Array.isArray(entry.requirements ?? [])
707
+ ) {
708
+ throw new VerdictReportError('catalog contains an invalid use case');
709
+ }
710
+ return { ...entry, requirements: entry.requirements ?? [] };
711
+ });
712
+ }
713
+
714
+ function useCaseReason(journeys, findingCount) {
715
+ const incomplete = journeys.filter((journey) => journey.executionStatus !== 'successful');
716
+ if (incomplete.length) {
717
+ return `Coverage is incomplete: ${incomplete
718
+ .map((journey) => `${journey.label} is ${journey.executionStatus}`)
719
+ .join('; ')}.`;
720
+ }
721
+ if (findingCount) {
722
+ return `Coverage is complete, and ${findingCount} policy-evaluated finding${findingCount === 1 ? '' : 's'} remain.`;
723
+ }
724
+ return 'Coverage is complete and no policy-evaluated finding was generated.';
725
+ }
726
+
727
+ function validateCoverage(coverage) {
728
+ assertMap(coverage, 'report.coverage');
729
+ assertExactKeys(
730
+ coverage,
731
+ [
732
+ 'status',
733
+ 'cataloguedUseCases',
734
+ 'reportedUseCases',
735
+ 'requiredVariants',
736
+ 'measuredVariants',
737
+ 'successfulVariants',
738
+ ],
739
+ 'report.coverage',
740
+ );
741
+ if (!['complete', 'incomplete'].includes(coverage.status)) {
742
+ throw new VerdictReportError('report.coverage.status is invalid');
743
+ }
744
+ for (const field of [
745
+ 'cataloguedUseCases',
746
+ 'reportedUseCases',
747
+ 'requiredVariants',
748
+ 'measuredVariants',
749
+ 'successfulVariants',
750
+ ]) {
751
+ if (!Number.isSafeInteger(coverage[field]) || coverage[field] < 0) {
752
+ throw new VerdictReportError(`report.coverage.${field} is invalid`);
753
+ }
754
+ }
755
+ }
756
+
757
+ function validateUseCase(useCase, path, journeyIds, findingIds, recommendationIds) {
758
+ assertMap(useCase, path);
759
+ assertExactKeys(
760
+ useCase,
761
+ [
762
+ 'useCaseId',
763
+ 'title',
764
+ 'verdict',
765
+ 'reason',
766
+ 'coverage',
767
+ 'journeyRefs',
768
+ 'findingRefs',
769
+ 'recommendationRefs',
770
+ 'comparison',
771
+ ],
772
+ path,
773
+ );
774
+ assertText(useCase.useCaseId, `${path}.useCaseId`);
775
+ assertText(useCase.title, `${path}.title`);
776
+ assertText(useCase.reason, `${path}.reason`);
777
+ assertVerdict(useCase.verdict, `${path}.verdict`);
778
+ validateRefs(useCase.journeyRefs, journeyIds, `${path}.journeyRefs`);
779
+ validateRefs(useCase.findingRefs, findingIds, `${path}.findingRefs`);
780
+ validateRefs(useCase.recommendationRefs, recommendationIds, `${path}.recommendationRefs`);
781
+ assertMap(useCase.coverage, `${path}.coverage`);
782
+ assertMap(useCase.comparison, `${path}.comparison`);
783
+ }
784
+
785
+ function validateJourney(journey, path, findingIds) {
786
+ assertMap(journey, path);
787
+ assertExactKeys(
788
+ journey,
789
+ [
790
+ 'id',
791
+ 'useCaseId',
792
+ 'variantId',
793
+ 'label',
794
+ 'journeyId',
795
+ 'executionStatus',
796
+ 'verdict',
797
+ 'metrics',
798
+ 'findingRefs',
799
+ ],
800
+ path,
801
+ );
802
+ for (const field of ['id', 'useCaseId', 'variantId', 'label', 'journeyId']) {
803
+ assertText(journey[field], `${path}.${field}`);
804
+ }
805
+ if (!STATUS_ORDER.has(journey.executionStatus)) {
806
+ throw new VerdictReportError(`${path}.executionStatus is invalid`);
807
+ }
808
+ assertVerdict(journey.verdict, `${path}.verdict`);
809
+ validateRefs(journey.findingRefs, findingIds, `${path}.findingRefs`);
810
+ }
811
+
812
+ function validateStaticPatterns(patterns) {
813
+ assertMap(patterns, 'report.staticPatterns');
814
+ assertExactKeys(
815
+ patterns,
816
+ ['status', 'baseline', 'meaning', 'findings'],
817
+ 'report.staticPatterns',
818
+ );
819
+ if (!['growth', 'no-growth'].includes(patterns.status)) {
820
+ throw new VerdictReportError('report.staticPatterns.status is invalid');
821
+ }
822
+ assertText(patterns.meaning, 'report.staticPatterns.meaning');
823
+ validateBaseline(patterns.baseline, 'report.staticPatterns.baseline');
824
+ if (
825
+ patterns.baseline.status !== 'reviewed' ||
826
+ patterns.baseline.regressionStatus !==
827
+ (patterns.status === 'growth' ? 'regression' : 'unchanged')
828
+ ) {
829
+ throw new VerdictReportError('report.staticPatterns.baseline is invalid');
830
+ }
831
+ if (!Array.isArray(patterns.findings)) {
832
+ throw new VerdictReportError('report.staticPatterns.findings must be an array');
833
+ }
834
+ }
835
+
836
+ function reportBaseline(comparison) {
837
+ const reviewed = comparison.baselineHash !== null;
838
+ return {
839
+ status: reviewed ? 'reviewed' : 'not-reviewed',
840
+ regressionStatus:
841
+ comparison.status === 'unavailable' && !reviewed
842
+ ? 'not-evaluated'
843
+ : comparison.status,
844
+ };
845
+ }
846
+
847
+ function validateBaseline(baseline, path) {
848
+ assertMap(baseline, path);
849
+ assertExactKeys(baseline, ['status', 'regressionStatus'], path);
850
+ if (!['not-reviewed', 'reviewed'].includes(baseline.status)) {
851
+ throw new VerdictReportError(`${path}.status is invalid`);
852
+ }
853
+ if (
854
+ ![
855
+ 'not-evaluated',
856
+ 'regression',
857
+ 'improvement',
858
+ 'unchanged',
859
+ 'incompatible',
860
+ 'unavailable',
861
+ ].includes(baseline.regressionStatus)
862
+ ) {
863
+ throw new VerdictReportError(`${path}.regressionStatus is invalid`);
864
+ }
865
+ if (baseline.status === 'not-reviewed' && baseline.regressionStatus !== 'not-evaluated') {
866
+ throw new VerdictReportError(`${path} cannot evaluate an unreviewed baseline`);
867
+ }
868
+ }
869
+
870
+ function qualityReason(verdict, useCases) {
871
+ if (verdict === 'incomplete') {
872
+ const incomplete = useCases.filter(
873
+ (useCase) => useCase.verdict === 'incomplete',
874
+ ).length;
875
+ return `${incomplete} use case${incomplete === 1 ? ' is' : 's are'} incomplete; baseline equality cannot make missing product paths acceptable.`;
876
+ }
877
+ if (verdict === 'needs-improvement') {
878
+ return 'Required journeys completed, but policy-evaluated findings remain.';
879
+ }
880
+ return 'Required journeys completed and no configured policy finding was generated; this is not a claim of universally good UX.';
881
+ }
882
+
883
+ function qualityDimensions(findings) {
884
+ return DIMENSIONS.map((dimension) => {
885
+ const findingRefs = findings
886
+ .filter((finding) => finding.dimension === dimension)
887
+ .map(({ id }) => id)
888
+ .sort();
889
+ if (findingRefs.length) {
890
+ return {
891
+ dimension,
892
+ status: 'findings',
893
+ findingRefs,
894
+ reason: `${findingRefs.length} policy-evaluated finding${findingRefs.length === 1 ? '' : 's'} remain.`,
895
+ };
896
+ }
897
+ if (dimension === 'accessibility') {
898
+ return {
899
+ dimension,
900
+ status: 'not-measured',
901
+ findingRefs: [],
902
+ reason:
903
+ 'Not comprehensively measured; zero accessibility findings is not evidence of good accessibility.',
904
+ };
905
+ }
906
+ return {
907
+ dimension,
908
+ status: 'no-policy-findings',
909
+ findingRefs: [],
910
+ reason:
911
+ 'No configured policy finding was generated; this is not a measured-good claim.',
912
+ };
913
+ });
914
+ }
915
+
916
+ function validateQuality(quality) {
917
+ assertMap(quality, 'report.quality');
918
+ assertExactKeys(
919
+ quality,
920
+ ['verdict', 'reason', 'dimensions'],
921
+ 'report.quality',
922
+ );
923
+ assertVerdict(quality.verdict, 'report.quality.verdict');
924
+ assertText(quality.reason, 'report.quality.reason');
925
+ if (
926
+ !Array.isArray(quality.dimensions) ||
927
+ quality.dimensions.length !== DIMENSIONS.length
928
+ ) {
929
+ throw new VerdictReportError('report.quality.dimensions is invalid');
930
+ }
931
+ const dimensions = new Set();
932
+ for (const [index, dimension] of quality.dimensions.entries()) {
933
+ const path = `report.quality.dimensions[${index}]`;
934
+ assertMap(dimension, path);
935
+ assertExactKeys(
936
+ dimension,
937
+ ['dimension', 'status', 'findingRefs', 'reason'],
938
+ path,
939
+ );
940
+ if (!DIMENSIONS.includes(dimension.dimension) || dimensions.has(dimension.dimension)) {
941
+ throw new VerdictReportError(`${path}.dimension is invalid`);
942
+ }
943
+ dimensions.add(dimension.dimension);
944
+ if (
945
+ !['findings', 'no-policy-findings', 'not-measured'].includes(
946
+ dimension.status,
947
+ ) ||
948
+ !Array.isArray(dimension.findingRefs) ||
949
+ new Set(dimension.findingRefs).size !== dimension.findingRefs.length
950
+ ) {
951
+ throw new VerdictReportError(`${path} is invalid`);
952
+ }
953
+ assertText(dimension.reason, `${path}.reason`);
954
+ if (
955
+ dimension.dimension === 'accessibility' &&
956
+ dimension.findingRefs.length === 0 &&
957
+ dimension.status !== 'not-measured'
958
+ ) {
959
+ throw new VerdictReportError(
960
+ `${path} cannot claim measured-good accessibility from zero findings`,
961
+ );
962
+ }
963
+ }
964
+ }
965
+
966
+ function regressionReport(comparison, staticPatterns) {
967
+ const patternRegression = staticPatterns.status === 'growth';
968
+ return {
969
+ status: patternRegression ? 'regression' : comparison.status,
970
+ reason: patternRegression
971
+ ? 'Observed pattern debt grew beyond the reviewed non-growth baseline.'
972
+ : comparison.reason,
973
+ baseline: reportBaseline(comparison),
974
+ journeyComparison: structuredClone(comparison),
975
+ patternDebt: {
976
+ status: patternRegression ? 'regression' : 'no-growth',
977
+ reason: staticPatterns.meaning,
978
+ },
979
+ };
980
+ }
981
+
982
+ function validateRegression(regression) {
983
+ assertMap(regression, 'report.regression');
984
+ assertExactKeys(
985
+ regression,
986
+ ['status', 'reason', 'baseline', 'journeyComparison', 'patternDebt'],
987
+ 'report.regression',
988
+ );
989
+ if (
990
+ ![
991
+ 'regression',
992
+ 'improvement',
993
+ 'unchanged',
994
+ 'incompatible',
995
+ 'unavailable',
996
+ ].includes(regression.status)
997
+ ) {
998
+ throw new VerdictReportError('report.regression.status is invalid');
999
+ }
1000
+ assertText(regression.reason, 'report.regression.reason');
1001
+ validateBaseline(regression.baseline, 'report.regression.baseline');
1002
+ validateJourneyComparison(regression.journeyComparison);
1003
+ assertMap(regression.patternDebt, 'report.regression.patternDebt');
1004
+ assertExactKeys(
1005
+ regression.patternDebt,
1006
+ ['status', 'reason'],
1007
+ 'report.regression.patternDebt',
1008
+ );
1009
+ if (!['regression', 'no-growth'].includes(regression.patternDebt.status)) {
1010
+ throw new VerdictReportError('report.regression.patternDebt.status is invalid');
1011
+ }
1012
+ assertText(regression.patternDebt.reason, 'report.regression.patternDebt.reason');
1013
+ const expected =
1014
+ regression.patternDebt.status === 'regression'
1015
+ ? 'regression'
1016
+ : regression.journeyComparison.status;
1017
+ if (regression.status !== expected) {
1018
+ throw new VerdictReportError(
1019
+ 'report.regression.status does not match its independent comparisons',
1020
+ );
1021
+ }
1022
+ const expectedBaseline = reportBaseline(regression.journeyComparison);
1023
+ if (
1024
+ regression.baseline.status !== expectedBaseline.status ||
1025
+ regression.baseline.regressionStatus !== expectedBaseline.regressionStatus
1026
+ ) {
1027
+ throw new VerdictReportError(
1028
+ 'report.regression.baseline does not match its journey comparison',
1029
+ );
1030
+ }
1031
+ }
1032
+
1033
+ function numericalScore(policy, attainment) {
1034
+ const targetBacked = ['met', 'breached', 'partial'].includes(
1035
+ attainment.status,
1036
+ );
1037
+ const targetJourneys = new Map(
1038
+ attainment.journeys.map((journey) => [journey.journeyRef, journey]),
1039
+ );
1040
+ const journeys = policy.coverage.flatMap((coverage) =>
1041
+ coverage.requiredVariants.map((variant) => {
1042
+ const journeyRef = `journey.${coverage.useCaseId}.${variant.journeyId}`;
1043
+ const target = targetJourneys.get(journeyRef);
1044
+ if (!target) {
1045
+ return {
1046
+ journeyRef,
1047
+ useCaseId: coverage.useCaseId,
1048
+ status: 'not-targeted',
1049
+ score: null,
1050
+ configuredMetrics: 0,
1051
+ scoredMetrics: 0,
1052
+ reason: 'No reviewed metric target is configured for this journey.',
1053
+ metrics: [],
1054
+ };
1055
+ }
1056
+ const metrics = target.metrics.map((metric) => {
1057
+ if (metric.operator !== 'at-most') {
1058
+ return {
1059
+ metric: metric.metric,
1060
+ status: 'not-scored',
1061
+ target: metric.target,
1062
+ actual: metric.actual,
1063
+ score: null,
1064
+ reason: `${metric.operator} targets do not have an approved numerical scoring formula.`,
1065
+ };
1066
+ }
1067
+ if (metric.actual === null || target.executionStatus !== 'successful') {
1068
+ return {
1069
+ metric: metric.metric,
1070
+ status: 'not-scored',
1071
+ target: metric.target,
1072
+ actual: metric.actual,
1073
+ score: null,
1074
+ reason: `${target.executionStatus} journey evidence is not scoreable.`,
1075
+ };
1076
+ }
1077
+ return {
1078
+ metric: metric.metric,
1079
+ status: 'scored',
1080
+ target: metric.target,
1081
+ actual: metric.actual,
1082
+ score: atMostScore(metric.actual, metric.target),
1083
+ reason:
1084
+ metric.actual <= metric.target
1085
+ ? 'The measured value attained the reviewed at-most target.'
1086
+ : 'The measured value exceeded the reviewed at-most target.',
1087
+ };
1088
+ });
1089
+ const metricScores = metrics
1090
+ .map(({ score }) => score)
1091
+ .filter((score) => score !== null);
1092
+ const score = metricScores.length ? Math.min(...metricScores) : null;
1093
+ const status =
1094
+ metricScores.length === 0
1095
+ ? 'not-scored'
1096
+ : metricScores.length === metrics.length
1097
+ ? 'scored'
1098
+ : 'partially-scored';
1099
+ return {
1100
+ journeyRef,
1101
+ useCaseId: coverage.useCaseId,
1102
+ status,
1103
+ score,
1104
+ configuredMetrics: metrics.length,
1105
+ scoredMetrics: metricScores.length,
1106
+ reason:
1107
+ status === 'scored'
1108
+ ? 'Score is the minimum configured metric score; stronger metrics cannot compensate for the weakest metric.'
1109
+ : status === 'partially-scored'
1110
+ ? 'Score uses the available configured metric scores; at least one configured metric was not scoreable.'
1111
+ : 'Configured target metrics were unavailable or had no approved scoring formula.',
1112
+ metrics,
1113
+ };
1114
+ }),
1115
+ );
1116
+ const byJourney = new Map(
1117
+ journeys.map((journey) => [journey.journeyRef, journey]),
1118
+ );
1119
+ const useCases = policy.coverage.map((coverage) => {
1120
+ const journeyRefs = coverage.requiredVariants.map(
1121
+ (variant) => `journey.${coverage.useCaseId}.${variant.journeyId}`,
1122
+ );
1123
+ const required = journeyRefs.map((journeyRef) => byJourney.get(journeyRef));
1124
+ const configuredJourneys = required.filter(
1125
+ ({ status }) => status !== 'not-targeted',
1126
+ ).length;
1127
+ const scores = required
1128
+ .map(({ score }) => score)
1129
+ .filter((score) => score !== null);
1130
+ const status =
1131
+ scores.length === 0
1132
+ ? 'not-scored'
1133
+ : scores.length === required.length &&
1134
+ required.every(({ status: journeyStatus }) => journeyStatus === 'scored')
1135
+ ? 'scored'
1136
+ : 'partially-scored';
1137
+ return {
1138
+ useCaseId: coverage.useCaseId,
1139
+ status,
1140
+ score: scores.length ? Math.min(...scores) : null,
1141
+ requiredJourneys: required.length,
1142
+ configuredJourneys,
1143
+ scoredJourneys: scores.length,
1144
+ journeyRefs,
1145
+ reason:
1146
+ scores.length === 0
1147
+ ? 'No required journey has a target-backed numerical score.'
1148
+ : 'Score is the minimum required scored journey; stronger journeys cannot compensate for the weakest scored journey.',
1149
+ };
1150
+ });
1151
+ const scoredUseCases = useCases.filter(({ score }) => score !== null).length;
1152
+ const status =
1153
+ scoredUseCases === 0
1154
+ ? 'not-scored'
1155
+ : useCases.every(({ status: useCaseStatus }) => useCaseStatus === 'scored')
1156
+ ? 'scored'
1157
+ : 'partially-scored';
1158
+ return {
1159
+ kind: 'ux-guard-numerical-score',
1160
+ version: 1,
1161
+ status,
1162
+ reason:
1163
+ status === 'not-scored'
1164
+ ? 'No reviewed at-most metric target produced a score.'
1165
+ : status === 'scored'
1166
+ ? 'Every required journey has a target-backed score.'
1167
+ : 'Only part of the required journey set has target-backed scores.',
1168
+ aggregation: 'minimum',
1169
+ basis: {
1170
+ type: targetBacked ? 'reviewed-owner-targets' : 'none',
1171
+ targetHash: targetBacked ? attainment.canonicalHash : null,
1172
+ },
1173
+ useCases,
1174
+ journeys,
1175
+ };
1176
+ }
1177
+
1178
+ function atMostScore(actual, target) {
1179
+ if (actual <= target) return 100;
1180
+ if (target === 0) return 0;
1181
+ return Math.round((100 * target) / actual);
1182
+ }
1183
+
1184
+ function validateNumericalScore(scoring) {
1185
+ assertMap(scoring, 'report.scoring');
1186
+ assertExactKeys(
1187
+ scoring,
1188
+ [
1189
+ 'kind',
1190
+ 'version',
1191
+ 'status',
1192
+ 'reason',
1193
+ 'aggregation',
1194
+ 'basis',
1195
+ 'useCases',
1196
+ 'journeys',
1197
+ ],
1198
+ 'report.scoring',
1199
+ );
1200
+ if (
1201
+ scoring.kind !== 'ux-guard-numerical-score' ||
1202
+ scoring.version !== 1 ||
1203
+ !['scored', 'partially-scored', 'not-scored'].includes(scoring.status) ||
1204
+ scoring.aggregation !== 'minimum'
1205
+ ) {
1206
+ throw new VerdictReportError('report.scoring has an unsupported contract');
1207
+ }
1208
+ assertText(scoring.reason, 'report.scoring.reason');
1209
+ assertMap(scoring.basis, 'report.scoring.basis');
1210
+ assertExactKeys(
1211
+ scoring.basis,
1212
+ ['type', 'targetHash'],
1213
+ 'report.scoring.basis',
1214
+ );
1215
+ if (!['reviewed-owner-targets', 'none'].includes(scoring.basis.type)) {
1216
+ throw new VerdictReportError('report.scoring.basis.type is invalid');
1217
+ }
1218
+ if (
1219
+ scoring.basis.targetHash !== null &&
1220
+ !/^sha256:[a-f0-9]{64}$/.test(scoring.basis.targetHash)
1221
+ ) {
1222
+ throw new VerdictReportError('report.scoring.basis.targetHash is invalid');
1223
+ }
1224
+ if (
1225
+ (scoring.basis.type === 'none') !==
1226
+ (scoring.basis.targetHash === null)
1227
+ ) {
1228
+ throw new VerdictReportError('report.scoring.basis is inconsistent');
1229
+ }
1230
+ if (!Array.isArray(scoring.journeys) || !Array.isArray(scoring.useCases)) {
1231
+ throw new VerdictReportError(
1232
+ 'report.scoring useCases and journeys must be arrays',
1233
+ );
1234
+ }
1235
+ const journeys = new Map();
1236
+ for (const [index, journey] of scoring.journeys.entries()) {
1237
+ const path = `report.scoring.journeys[${index}]`;
1238
+ assertMap(journey, path);
1239
+ assertExactKeys(
1240
+ journey,
1241
+ [
1242
+ 'journeyRef',
1243
+ 'useCaseId',
1244
+ 'status',
1245
+ 'score',
1246
+ 'configuredMetrics',
1247
+ 'scoredMetrics',
1248
+ 'reason',
1249
+ 'metrics',
1250
+ ],
1251
+ path,
1252
+ );
1253
+ for (const field of ['journeyRef', 'useCaseId', 'reason']) {
1254
+ assertText(journey[field], `${path}.${field}`);
1255
+ }
1256
+ if (
1257
+ !['scored', 'partially-scored', 'not-scored', 'not-targeted'].includes(
1258
+ journey.status,
1259
+ ) ||
1260
+ journeys.has(journey.journeyRef) ||
1261
+ !Array.isArray(journey.metrics)
1262
+ ) {
1263
+ throw new VerdictReportError(`${path} is invalid`);
1264
+ }
1265
+ for (const field of ['configuredMetrics', 'scoredMetrics']) {
1266
+ if (!Number.isSafeInteger(journey[field]) || journey[field] < 0) {
1267
+ throw new VerdictReportError(`${path}.${field} is invalid`);
1268
+ }
1269
+ }
1270
+ const metricScores = [];
1271
+ const metricNames = new Set();
1272
+ for (const [metricIndex, metric] of journey.metrics.entries()) {
1273
+ const metricPath = `${path}.metrics[${metricIndex}]`;
1274
+ assertMap(metric, metricPath);
1275
+ assertExactKeys(
1276
+ metric,
1277
+ ['metric', 'status', 'target', 'actual', 'score', 'reason'],
1278
+ metricPath,
1279
+ );
1280
+ assertText(metric.metric, `${metricPath}.metric`);
1281
+ assertText(metric.reason, `${metricPath}.reason`);
1282
+ if (
1283
+ metricNames.has(metric.metric) ||
1284
+ !['scored', 'not-scored'].includes(metric.status)
1285
+ ) {
1286
+ throw new VerdictReportError(`${metricPath} is invalid`);
1287
+ }
1288
+ metricNames.add(metric.metric);
1289
+ if (!Number.isSafeInteger(metric.target) || metric.target < 0) {
1290
+ throw new VerdictReportError(`${metricPath}.target is invalid`);
1291
+ }
1292
+ if (
1293
+ metric.actual !== null &&
1294
+ (!Number.isSafeInteger(metric.actual) || metric.actual < 0)
1295
+ ) {
1296
+ throw new VerdictReportError(`${metricPath}.actual is invalid`);
1297
+ }
1298
+ if (metric.status === 'scored') {
1299
+ if (
1300
+ metric.actual === null ||
1301
+ metric.score !== atMostScore(metric.actual, metric.target)
1302
+ ) {
1303
+ throw new VerdictReportError(`${metricPath}.score is invalid`);
1304
+ }
1305
+ metricScores.push(metric.score);
1306
+ } else if (metric.score !== null) {
1307
+ throw new VerdictReportError(`${metricPath}.score must be null`);
1308
+ }
1309
+ }
1310
+ const expectedScore = metricScores.length ? Math.min(...metricScores) : null;
1311
+ const expectedStatus =
1312
+ journey.metrics.length === 0
1313
+ ? 'not-targeted'
1314
+ : metricScores.length === 0
1315
+ ? 'not-scored'
1316
+ : metricScores.length === journey.metrics.length
1317
+ ? 'scored'
1318
+ : 'partially-scored';
1319
+ if (
1320
+ journey.configuredMetrics !== journey.metrics.length ||
1321
+ journey.scoredMetrics !== metricScores.length ||
1322
+ journey.score !== expectedScore ||
1323
+ journey.status !== expectedStatus
1324
+ ) {
1325
+ throw new VerdictReportError(`${path} does not match its metric scores`);
1326
+ }
1327
+ journeys.set(journey.journeyRef, journey);
1328
+ }
1329
+ for (const [index, useCase] of scoring.useCases.entries()) {
1330
+ const path = `report.scoring.useCases[${index}]`;
1331
+ assertMap(useCase, path);
1332
+ assertExactKeys(
1333
+ useCase,
1334
+ [
1335
+ 'useCaseId',
1336
+ 'status',
1337
+ 'score',
1338
+ 'requiredJourneys',
1339
+ 'configuredJourneys',
1340
+ 'scoredJourneys',
1341
+ 'journeyRefs',
1342
+ 'reason',
1343
+ ],
1344
+ path,
1345
+ );
1346
+ assertText(useCase.useCaseId, `${path}.useCaseId`);
1347
+ assertText(useCase.reason, `${path}.reason`);
1348
+ if (
1349
+ !['scored', 'partially-scored', 'not-scored'].includes(useCase.status) ||
1350
+ !Array.isArray(useCase.journeyRefs) ||
1351
+ useCase.journeyRefs.some((journeyRef) => !journeys.has(journeyRef))
1352
+ ) {
1353
+ throw new VerdictReportError(`${path} is invalid`);
1354
+ }
1355
+ const required = useCase.journeyRefs.map((journeyRef) =>
1356
+ journeys.get(journeyRef),
1357
+ );
1358
+ const scores = required
1359
+ .map(({ score }) => score)
1360
+ .filter((score) => score !== null);
1361
+ const configured = required.filter(
1362
+ ({ status }) => status !== 'not-targeted',
1363
+ ).length;
1364
+ const expectedStatus =
1365
+ scores.length === 0
1366
+ ? 'not-scored'
1367
+ : scores.length === required.length &&
1368
+ required.every(({ status }) => status === 'scored')
1369
+ ? 'scored'
1370
+ : 'partially-scored';
1371
+ if (
1372
+ useCase.requiredJourneys !== required.length ||
1373
+ useCase.configuredJourneys !== configured ||
1374
+ useCase.scoredJourneys !== scores.length ||
1375
+ useCase.score !== (scores.length ? Math.min(...scores) : null) ||
1376
+ useCase.status !== expectedStatus
1377
+ ) {
1378
+ throw new VerdictReportError(`${path} does not match its journey scores`);
1379
+ }
1380
+ }
1381
+ const scored = scoring.useCases.filter(({ score }) => score !== null).length;
1382
+ const expectedStatus =
1383
+ scored === 0
1384
+ ? 'not-scored'
1385
+ : scoring.useCases.every(({ status }) => status === 'scored')
1386
+ ? 'scored'
1387
+ : 'partially-scored';
1388
+ if (scoring.status !== expectedStatus) {
1389
+ throw new VerdictReportError('report.scoring.status is inconsistent');
1390
+ }
1391
+ }
1392
+
1393
+ function targetRecommendations(attainment) {
1394
+ const recommendations = [];
1395
+ for (const floor of attainment.hardFloors.filter(
1396
+ ({ status }) => status === 'breached',
1397
+ )) {
1398
+ const targetRef = `hard-floor.${kebab(floor.id)}`;
1399
+ recommendations.push({
1400
+ id: `recommendation.target.${targetRef}`,
1401
+ findingRef: null,
1402
+ targetRef,
1403
+ useCaseId: null,
1404
+ severity: 'high',
1405
+ type: 'target',
1406
+ affectedJourneyRefs: [],
1407
+ text: floorRecommendation(floor),
1408
+ });
1409
+ }
1410
+ for (const journey of attainment.journeys) {
1411
+ for (const metric of journey.metrics.filter(
1412
+ ({ status }) => status === 'breached',
1413
+ )) {
1414
+ const targetRef = `${journey.journeyRef}.${metric.metric}`;
1415
+ recommendations.push({
1416
+ id: `recommendation.target.${targetRef}`,
1417
+ findingRef: null,
1418
+ targetRef,
1419
+ useCaseId: journey.useCaseId,
1420
+ severity: 'medium',
1421
+ type: 'target',
1422
+ affectedJourneyRefs: [journey.journeyRef],
1423
+ text: `${metric.operator === 'at-most' ? 'Reduce' : 'Adjust'} ${metric.metric} for ${journey.journeyRef} to ${operatorLabel(metric.operator)} ${metric.target}; the measured value is ${metric.actual}.`,
1424
+ });
1425
+ }
1426
+ }
1427
+ return recommendations;
1428
+ }
1429
+
1430
+ function floorRecommendation(floor) {
1431
+ if (floor.operator === 'at-least') {
1432
+ return `Increase ${floor.id} to at least ${floor.target}; the measured value is ${floor.actual}.`;
1433
+ }
1434
+ return `Reduce ${floor.id} to at most ${floor.target}; the measured value is ${floor.actual}.`;
1435
+ }
1436
+
1437
+ function kebab(value) {
1438
+ return value.replace(/[A-Z]/g, (letter) => `-${letter.toLowerCase()}`);
1439
+ }
1440
+
1441
+ function defaultVisualSummary() {
1442
+ return {
1443
+ rollout: 'advisory',
1444
+ status: 'not-evaluated',
1445
+ candidate: {
1446
+ status: 'unavailable',
1447
+ manifestPath: null,
1448
+ canonicalHash: null,
1449
+ images: 0,
1450
+ repetitions: 0,
1451
+ },
1452
+ baseline: {
1453
+ status: 'not-reviewed',
1454
+ manifestPath: null,
1455
+ canonicalHash: null,
1456
+ },
1457
+ comparison: unavailableVisualComparison('visual evidence was not supplied'),
1458
+ };
1459
+ }
1460
+
1461
+ function normalizeVisualSummary(visuals) {
1462
+ const normalized = structuredClone(visuals);
1463
+ validateVisualSummary(normalized);
1464
+ return normalized;
1465
+ }
1466
+
1467
+ function validateVisualSummary(visuals) {
1468
+ assertMap(visuals, 'report.visuals');
1469
+ assertExactKeys(
1470
+ visuals,
1471
+ ['rollout', 'status', 'candidate', 'baseline', 'comparison'],
1472
+ 'report.visuals',
1473
+ );
1474
+ if (visuals.rollout !== 'advisory') {
1475
+ throw new VerdictReportError('report.visuals.rollout must be advisory');
1476
+ }
1477
+ if (
1478
+ ![
1479
+ 'not-evaluated',
1480
+ 'unchanged',
1481
+ 'added',
1482
+ 'missing',
1483
+ 'changed',
1484
+ 'incompatible',
1485
+ 'error',
1486
+ ].includes(visuals.status)
1487
+ ) {
1488
+ throw new VerdictReportError('report.visuals.status is invalid');
1489
+ }
1490
+ assertMap(visuals.candidate, 'report.visuals.candidate');
1491
+ assertExactKeys(
1492
+ visuals.candidate,
1493
+ ['status', 'manifestPath', 'canonicalHash', 'images', 'repetitions'],
1494
+ 'report.visuals.candidate',
1495
+ );
1496
+ if (!['unavailable', 'available-unapproved'].includes(visuals.candidate.status)) {
1497
+ throw new VerdictReportError('report.visuals.candidate.status is invalid');
1498
+ }
1499
+ for (const field of ['images', 'repetitions']) {
1500
+ if (
1501
+ !Number.isSafeInteger(visuals.candidate[field]) ||
1502
+ visuals.candidate[field] < 0
1503
+ ) {
1504
+ throw new VerdictReportError(`report.visuals.candidate.${field} is invalid`);
1505
+ }
1506
+ }
1507
+ validateOptionalPathAndHash(visuals.candidate, 'report.visuals.candidate');
1508
+ assertMap(visuals.baseline, 'report.visuals.baseline');
1509
+ assertExactKeys(
1510
+ visuals.baseline,
1511
+ ['status', 'manifestPath', 'canonicalHash'],
1512
+ 'report.visuals.baseline',
1513
+ );
1514
+ if (!['not-reviewed', 'reviewed'].includes(visuals.baseline.status)) {
1515
+ throw new VerdictReportError('report.visuals.baseline.status is invalid');
1516
+ }
1517
+ validateOptionalPathAndHash(visuals.baseline, 'report.visuals.baseline');
1518
+ validateVisualComparison(visuals.comparison);
1519
+ if (visuals.status !== visuals.comparison.status) {
1520
+ throw new VerdictReportError('report.visuals status does not match comparison');
1521
+ }
1522
+ }
1523
+
1524
+ function validateOptionalPathAndHash(value, path) {
1525
+ if (value.manifestPath !== null) assertText(value.manifestPath, `${path}.manifestPath`);
1526
+ if (
1527
+ value.canonicalHash !== null &&
1528
+ !/^sha256:[a-f0-9]{64}$/.test(value.canonicalHash)
1529
+ ) {
1530
+ throw new VerdictReportError(`${path}.canonicalHash is invalid`);
1531
+ }
1532
+ }
1533
+
1534
+ function scoringReadiness({ comparison, measurements, readinessEvidence }) {
1535
+ const repetitionsText = measurements.run.adapters.repetitions;
1536
+ const repetitions =
1537
+ typeof repetitionsText === 'string' && /^[1-9]\d*$/.test(repetitionsText)
1538
+ ? Number(repetitionsText)
1539
+ : 1;
1540
+ const canaries = readinessEvidence?.canaries ?? {
1541
+ regression: 'not-recorded',
1542
+ improvement: 'not-recorded',
1543
+ compatibility: 'not-recorded',
1544
+ knownBad: 'not-recorded',
1545
+ };
1546
+ const reviewedBaseline = comparison.compatibility.status === 'compatible';
1547
+ const stableRepetitions =
1548
+ Number.isSafeInteger(repetitions) &&
1549
+ repetitions >= 3 &&
1550
+ (readinessEvidence?.stableRepetitions ?? 0) >= 3;
1551
+ const evidenceComplete =
1552
+ measurements.run.completion.received === measurements.run.completion.expected &&
1553
+ (readinessEvidence?.evidenceComplete ?? false);
1554
+ const canariesPassed = Object.values(canaries).every((status) => status === 'passed');
1555
+ const trustedExecution = readinessEvidence?.trustedExecution === true;
1556
+ const enforcementApproved = readinessEvidence?.enforcementApproved === true;
1557
+ const stable =
1558
+ reviewedBaseline &&
1559
+ stableRepetitions &&
1560
+ evidenceComplete &&
1561
+ canariesPassed &&
1562
+ readinessEvidence?.deterministicRun === true;
1563
+ const state =
1564
+ stable && trustedExecution && enforcementApproved
1565
+ ? 'gate-ready'
1566
+ : stable
1567
+ ? 'stable'
1568
+ : 'provisional';
1569
+ const reasons = [];
1570
+ if (!reviewedBaseline) reasons.push('no compatible reviewed baseline');
1571
+ if (!stableRepetitions) reasons.push('fewer than three attested stable repetitions');
1572
+ if (!evidenceComplete) reasons.push('required evidence is incomplete or unattested');
1573
+ if (!canariesPassed) reasons.push('comparison canaries are not attested in the reviewed artifact');
1574
+ if (!trustedExecution) reasons.push('candidate execution is not pinned/trusted');
1575
+ if (!enforcementApproved) reasons.push('enforcement is not owner-approved');
1576
+ if (reasons.length === 0) reasons.push('all reviewed readiness evidence is present');
1577
+ return {
1578
+ state,
1579
+ reviewedBaseline,
1580
+ stableRepetitions,
1581
+ evidenceComplete,
1582
+ canaries,
1583
+ trustedExecution,
1584
+ enforcementApproved,
1585
+ reasons,
1586
+ };
1587
+ }
1588
+
1589
+ function validateReadiness(readiness) {
1590
+ assertMap(readiness, 'report.readiness');
1591
+ assertExactKeys(
1592
+ readiness,
1593
+ [
1594
+ 'state',
1595
+ 'reviewedBaseline',
1596
+ 'stableRepetitions',
1597
+ 'evidenceComplete',
1598
+ 'canaries',
1599
+ 'trustedExecution',
1600
+ 'enforcementApproved',
1601
+ 'reasons',
1602
+ ],
1603
+ 'report.readiness',
1604
+ );
1605
+ if (!['provisional', 'stable', 'gate-ready'].includes(readiness.state)) {
1606
+ throw new VerdictReportError('report.readiness.state is invalid');
1607
+ }
1608
+ for (const field of [
1609
+ 'reviewedBaseline',
1610
+ 'stableRepetitions',
1611
+ 'evidenceComplete',
1612
+ 'trustedExecution',
1613
+ 'enforcementApproved',
1614
+ ]) {
1615
+ if (typeof readiness[field] !== 'boolean') {
1616
+ throw new VerdictReportError(`report.readiness.${field} must be boolean`);
1617
+ }
1618
+ }
1619
+ assertMap(readiness.canaries, 'report.readiness.canaries');
1620
+ assertExactKeys(
1621
+ readiness.canaries,
1622
+ ['regression', 'improvement', 'compatibility', 'knownBad'],
1623
+ 'report.readiness.canaries',
1624
+ );
1625
+ if (
1626
+ Object.values(readiness.canaries).some(
1627
+ (status) => !['passed', 'not-recorded'].includes(status),
1628
+ )
1629
+ ) {
1630
+ throw new VerdictReportError('report.readiness.canaries is invalid');
1631
+ }
1632
+ if (
1633
+ !Array.isArray(readiness.reasons) ||
1634
+ readiness.reasons.length === 0 ||
1635
+ readiness.reasons.some((reason) => typeof reason !== 'string' || !reason)
1636
+ ) {
1637
+ throw new VerdictReportError('report.readiness.reasons is invalid');
1638
+ }
1639
+ }
1640
+
1641
+ function uniqueIds(records, path) {
1642
+ const ids = new Set();
1643
+ records.forEach((record, index) => {
1644
+ assertMap(record, `${path}[${index}]`);
1645
+ assertText(record.id, `${path}[${index}].id`);
1646
+ if (ids.has(record.id)) throw new VerdictReportError(`${path} repeats ${record.id}`);
1647
+ ids.add(record.id);
1648
+ });
1649
+ return ids;
1650
+ }
1651
+
1652
+ function validateRefs(refs, available, path) {
1653
+ if (
1654
+ !Array.isArray(refs) ||
1655
+ new Set(refs).size !== refs.length ||
1656
+ refs.some((ref) => !available.has(ref))
1657
+ ) {
1658
+ throw new VerdictReportError(`${path} is invalid`);
1659
+ }
1660
+ }
1661
+
1662
+ function compareRecommendation(left, right) {
1663
+ const severity = new Map([
1664
+ ['critical', 0],
1665
+ ['high', 1],
1666
+ ['medium', 2],
1667
+ ['low', 3],
1668
+ ]);
1669
+ return severity.get(left.severity) - severity.get(right.severity) ||
1670
+ (left.useCaseId ?? '').localeCompare(right.useCaseId ?? '') ||
1671
+ left.id.localeCompare(right.id);
1672
+ }
1673
+
1674
+ function variantLabel(report, journeyRef) {
1675
+ return report.journeys.find((journey) => journey.id === journeyRef)?.label ?? journeyRef;
1676
+ }
1677
+
1678
+ function renderFacts(facts) {
1679
+ return facts.map(({ key, value }) => `${key}=${JSON.stringify(value)}`).join(', ');
1680
+ }
1681
+
1682
+ function renderMetrics(metrics) {
1683
+ return Object.entries(metrics)
1684
+ .map(([metric, value]) => `${metric}=${value}`)
1685
+ .join(', ');
1686
+ }
1687
+
1688
+ function comparisonLabel(comparison) {
1689
+ if (comparison.status === 'unavailable') {
1690
+ return `Not evaluated — ${comparison.reason}`;
1691
+ }
1692
+ return `${capitalize(comparison.status)} — ${comparison.reason}`;
1693
+ }
1694
+
1695
+ function targetAttainmentLabel(attainment) {
1696
+ return `${capitalize(attainment.status)} — ${attainment.reason}`;
1697
+ }
1698
+
1699
+ function scoreLabel(scoring) {
1700
+ return `${capitalize(scoring.status)} — ${scoring.reason}`;
1701
+ }
1702
+
1703
+ function operatorLabel(operator) {
1704
+ return {
1705
+ 'at-most': 'at most',
1706
+ 'at-least': 'at least',
1707
+ exactly: 'exactly',
1708
+ }[operator];
1709
+ }
1710
+
1711
+ function visualLabel(visuals) {
1712
+ const candidate =
1713
+ visuals.candidate.status === 'available-unapproved'
1714
+ ? `${visuals.candidate.images} candidate images / ${visuals.candidate.repetitions} stable repetitions`
1715
+ : 'candidate unavailable';
1716
+ return `${capitalize(visuals.status)} — ${candidate}; ${visuals.comparison.reason}`;
1717
+ }
1718
+
1719
+ function statusLabel(status) {
1720
+ return {
1721
+ successful: 'Successful',
1722
+ failed: 'Failed assertion',
1723
+ skipped: 'Skipped',
1724
+ unexecutable: 'Missing product path',
1725
+ 'infrastructure-error': 'Infrastructure error',
1726
+ unmeasured: 'Unmeasured',
1727
+ }[status];
1728
+ }
1729
+
1730
+ function verdictLabel(verdict) {
1731
+ return {
1732
+ incomplete: 'Incomplete',
1733
+ 'needs-improvement': 'Needs improvement',
1734
+ acceptable: 'Acceptable',
1735
+ }[verdict];
1736
+ }
1737
+
1738
+ function capitalize(value) {
1739
+ return `${value.charAt(0).toUpperCase()}${value.slice(1)}`;
1740
+ }
1741
+
1742
+ function assertVerdict(value, path) {
1743
+ if (!QUALITY_VERDICTS.has(value)) {
1744
+ throw new VerdictReportError(`${path} is invalid`);
1745
+ }
1746
+ }
1747
+
1748
+ function assertMap(value, path) {
1749
+ if (value === null || typeof value !== 'object' || Array.isArray(value)) {
1750
+ throw new VerdictReportError(`${path} must be an object`);
1751
+ }
1752
+ }
1753
+
1754
+ function assertExactKeys(value, expected, path) {
1755
+ const actual = Object.keys(value).sort();
1756
+ const wanted = [...expected].sort();
1757
+ if (
1758
+ actual.length !== wanted.length ||
1759
+ actual.some((key, index) => key !== wanted[index])
1760
+ ) {
1761
+ throw new VerdictReportError(`${path} must contain ${wanted.join(', ')} only`);
1762
+ }
1763
+ }
1764
+
1765
+ function assertText(value, path) {
1766
+ if (typeof value !== 'string' || !value.trim()) {
1767
+ throw new VerdictReportError(`${path} must be non-empty text`);
1768
+ }
1769
+ }