@edjbarron/ux-guard 0.0.0-stage → 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.
@@ -0,0 +1,900 @@
1
+ import {
2
+ createObservation,
3
+ evaluateObservationPolicy,
4
+ journeyRecordId,
5
+ validateObservation,
6
+ } from './observations.mjs';
7
+ import { canonicalize, validateRunEnvelope } from './run-contract.mjs';
8
+
9
+ export const JOURNEY_REPORT_KIND = 'ux-guard-journey-report';
10
+ export const JOURNEY_REPORT_VERSION = 5;
11
+
12
+ const JOURNEY_STATUSES = new Set([
13
+ 'successful',
14
+ 'failed',
15
+ 'skipped',
16
+ 'unexecutable',
17
+ 'infrastructure-error',
18
+ ]);
19
+ const METRIC_DEFINITIONS = Object.freeze({
20
+ clicks: { aggregation: 'sum' },
21
+ keystrokes: { aggregation: 'sum' },
22
+ editedFields: { aggregation: 'sum' },
23
+ routeChanges: { aggregation: 'sum' },
24
+ modalDepth: { aggregation: 'max' },
25
+ scrollDistance: { aggregation: 'sum' },
26
+ decisions: { aggregation: 'sum' },
27
+ steps: { aggregation: 'sum', derived: true },
28
+ elapsedMs: { aggregation: 'sum' },
29
+ });
30
+ export const JOURNEY_METRICS = Object.freeze(Object.keys(METRIC_DEFINITIONS));
31
+ export const RECORDABLE_JOURNEY_METRICS = Object.freeze(
32
+ JOURNEY_METRICS.filter((metric) => !METRIC_DEFINITIONS[metric].derived),
33
+ );
34
+ export const STANDARD_JOURNEY_METRICS = Object.freeze([
35
+ 'clicks',
36
+ 'keystrokes',
37
+ 'editedFields',
38
+ 'routeChanges',
39
+ 'steps',
40
+ ]);
41
+ export const EXPLICIT_JOURNEY_METRICS = Object.freeze([
42
+ 'modalDepth',
43
+ 'scrollDistance',
44
+ 'decisions',
45
+ 'elapsedMs',
46
+ ]);
47
+
48
+ const ADDITIVE_METRICS = new Set(
49
+ RECORDABLE_JOURNEY_METRICS.filter((metric) => metric !== 'modalDepth' && metric !== 'elapsedMs'),
50
+ );
51
+ const STANDARD_RECORDABLE_METRICS = STANDARD_JOURNEY_METRICS.filter(
52
+ (metric) => !METRIC_DEFINITIONS[metric].derived,
53
+ );
54
+ const ELAPSED_SOURCES = new Set(['mocked', 'logical', 'wall-clock']);
55
+ const USE_CASE_ID = /^[a-z0-9]+(?:-[a-z0-9]+)*$/;
56
+ const ID = /^[a-z0-9]+(?:[._-][a-z0-9]+)*$/;
57
+
58
+ export class JourneyReportError extends Error {
59
+ constructor(message) {
60
+ super(message);
61
+ this.name = 'JourneyReportError';
62
+ }
63
+ }
64
+
65
+ export const JOURNEY_REPORT_SCHEMA = Object.freeze({
66
+ $schema: 'https://json-schema.org/draft/2020-12/schema',
67
+ $id: 'urn:ux-guard:journey-report:v5',
68
+ type: 'object',
69
+ additionalProperties: false,
70
+ required: ['kind', 'version', 'run', 'journeys', 'findings', 'details'],
71
+ properties: {
72
+ kind: { const: JOURNEY_REPORT_KIND },
73
+ version: { const: JOURNEY_REPORT_VERSION },
74
+ run: { $ref: 'urn:ux-guard:run-envelope:v1' },
75
+ journeys: { type: 'array' },
76
+ findings: { type: 'array' },
77
+ details: {
78
+ type: 'object',
79
+ additionalProperties: false,
80
+ required: ['steps', 'observations'],
81
+ properties: {
82
+ steps: { type: 'array' },
83
+ observations: { type: 'array' },
84
+ },
85
+ },
86
+ },
87
+ });
88
+
89
+ export function createJourneyFinding() {
90
+ throw new JourneyReportError(
91
+ 'bindings cannot inject findings, severity, verdicts, or recommendations; emit typed observations',
92
+ );
93
+ }
94
+
95
+ export function createJourneyRecorder({ useCaseId, journeyId, metrics = [], elapsed = null } = {}) {
96
+ assertId(useCaseId, USE_CASE_ID, 'useCaseId');
97
+ assertId(journeyId, ID, 'journeyId');
98
+ const enabled = normalizeMetricSelection(metrics);
99
+ for (const metric of STANDARD_RECORDABLE_METRICS) enabled.add(metric);
100
+ const timing = normalizeElapsed(elapsed);
101
+ if (enabled.has('elapsedMs') && !timing) {
102
+ throw new JourneyReportError('elapsedMs needs explicit elapsed source metadata');
103
+ }
104
+ if (timing) enabled.add('elapsedMs');
105
+ const now = timing?.clock ?? null;
106
+ const steps = [];
107
+ const observations = [];
108
+ const stepIds = new Set();
109
+ let current = null;
110
+ let finished = false;
111
+
112
+ const ensureOpen = () => {
113
+ if (finished) throw new JourneyReportError('journey recorder is already finished');
114
+ };
115
+ const ensureCurrent = () => {
116
+ ensureOpen();
117
+ if (!current) throw new JourneyReportError('begin a step before recording evidence');
118
+ return current;
119
+ };
120
+ const ensureEnabled = (metric) => {
121
+ if (!enabled.has(metric)) {
122
+ throw new JourneyReportError(`${metric} is not enabled for this journey`);
123
+ }
124
+ };
125
+
126
+ return Object.freeze({
127
+ useCaseId,
128
+ journeyId,
129
+ metrics: Object.freeze([...enabled]),
130
+
131
+ beginStep(id) {
132
+ ensureOpen();
133
+ if (current) throw new JourneyReportError(`step ${current.value.id} is still active`);
134
+ assertId(id, ID, 'step id');
135
+ if (stepIds.has(id)) throw new JourneyReportError(`duplicate step id ${id}`);
136
+ stepIds.add(id);
137
+ const stepMetrics = {};
138
+ for (const metric of JOURNEY_METRICS) {
139
+ if (metric === 'steps') stepMetrics.steps = 1;
140
+ else if (enabled.has(metric)) stepMetrics[metric] = 0;
141
+ }
142
+ current = {
143
+ value: { id, metrics: stepMetrics },
144
+ startedAt: enabled.has('elapsedMs') && now ? readClock(now) : null,
145
+ observationCount: 0,
146
+ };
147
+ },
148
+
149
+ record(metric, amount = 1) {
150
+ const step = ensureCurrent();
151
+ if (!ADDITIVE_METRICS.has(metric)) {
152
+ throw new JourneyReportError(
153
+ `${String(metric)} is not additive; use observeModalDepth or endStep`,
154
+ );
155
+ }
156
+ ensureEnabled(metric);
157
+ assertMeasurement(amount, metric);
158
+ step.value.metrics[metric] += amount;
159
+ },
160
+
161
+ observeModalDepth(depth) {
162
+ const step = ensureCurrent();
163
+ ensureEnabled('modalDepth');
164
+ assertMeasurement(depth, 'modalDepth');
165
+ step.value.metrics.modalDepth = Math.max(step.value.metrics.modalDepth, depth);
166
+ },
167
+
168
+ observe(type, data) {
169
+ const step = ensureCurrent();
170
+ step.observationCount += 1;
171
+ const observation = createObservation({
172
+ id: `observation.${useCaseId}.${journeyId}.${step.value.id}.${step.observationCount}`,
173
+ version: 1,
174
+ type,
175
+ stepId: step.value.id,
176
+ data,
177
+ });
178
+ observations.push(observation);
179
+ return observation.id;
180
+ },
181
+
182
+ endStep(options = {}) {
183
+ const step = ensureCurrent();
184
+ assertOptionKeys(options, ['elapsedMs'], 'endStep options');
185
+ const hasExplicitElapsed = Object.hasOwn(options, 'elapsedMs');
186
+ if (enabled.has('elapsedMs')) {
187
+ let value;
188
+ if (hasExplicitElapsed) value = options.elapsedMs;
189
+ else if (now) value = readClock(now) - step.startedAt;
190
+ else {
191
+ throw new JourneyReportError(
192
+ 'elapsedMs needs an injected clock or an explicit endStep({ elapsedMs }) value',
193
+ );
194
+ }
195
+ assertMeasurement(value, 'elapsedMs');
196
+ step.value.metrics.elapsedMs = value;
197
+ } else if (hasExplicitElapsed) {
198
+ throw new JourneyReportError('elapsedMs is not enabled for this journey');
199
+ }
200
+ steps.push(step.value);
201
+ current = null;
202
+ },
203
+
204
+ finish(options = {}) {
205
+ ensureOpen();
206
+ assertOptionKeys(options, ['status'], 'finish options');
207
+ if (current) throw new JourneyReportError(`step ${current.value.id} is still active`);
208
+ if (steps.length === 0) throw new JourneyReportError('journey must contain at least one step');
209
+ const status = options.status ?? 'successful';
210
+ if (!['successful', 'unexecutable'].includes(status)) {
211
+ throw new JourneyReportError(
212
+ 'recorded journey status must be successful or unexecutable',
213
+ );
214
+ }
215
+ finished = true;
216
+ const value = {
217
+ useCaseId,
218
+ journeyId,
219
+ status,
220
+ timing: timing
221
+ ? { source: timing.source, deterministic: timing.source !== 'wall-clock' }
222
+ : null,
223
+ metrics: aggregateSteps(steps),
224
+ steps: structuredClone(steps),
225
+ observations: structuredClone(observations),
226
+ };
227
+ validateRawJourney(value, 'journey');
228
+ return value;
229
+ },
230
+ });
231
+ }
232
+
233
+ export function createLifecycleJourney({ useCaseId, journeyId, status } = {}) {
234
+ assertId(useCaseId, USE_CASE_ID, 'useCaseId');
235
+ assertId(journeyId, ID, 'journeyId');
236
+ if (!['failed', 'skipped', 'infrastructure-error'].includes(status)) {
237
+ throw new JourneyReportError('lifecycle-only journey status is invalid');
238
+ }
239
+ return {
240
+ useCaseId,
241
+ journeyId,
242
+ status,
243
+ timing: null,
244
+ metrics: null,
245
+ steps: [],
246
+ observations: [],
247
+ };
248
+ }
249
+
250
+ export function createJourneyReport(journeys, { catalog, policy, run } = {}) {
251
+ if (!Array.isArray(journeys)) throw new JourneyReportError('journeys must be an array');
252
+ validateRunEnvelope(run);
253
+ const raw = structuredClone(journeys).sort(compareJourneyIdentity);
254
+ const identities = new Set();
255
+ for (const [index, journey] of raw.entries()) {
256
+ validateRawJourney(journey, `journeys[${index}]`);
257
+ const identity = `${journey.useCaseId}\0${journey.journeyId}`;
258
+ if (identities.has(identity)) {
259
+ throw new JourneyReportError(`duplicate journey ${journey.useCaseId}/${journey.journeyId}`);
260
+ }
261
+ identities.add(identity);
262
+ }
263
+ if (catalog !== undefined) validateRawJourneyCatalog(raw, catalog);
264
+ const findings = policy ? evaluateObservationPolicy(policy, raw) : [];
265
+ const steps = raw.flatMap((journey) =>
266
+ journey.steps.map((step) => ({
267
+ id: stepRecordId(journey.useCaseId, journey.journeyId, step.id),
268
+ journeyRef: journeyRecordId(journey.useCaseId, journey.journeyId),
269
+ stepId: step.id,
270
+ metrics: step.metrics,
271
+ })),
272
+ );
273
+ const observations = raw.flatMap((journey) =>
274
+ journey.observations.map((observation) => ({
275
+ ...observation,
276
+ journeyRef: journeyRecordId(journey.useCaseId, journey.journeyId),
277
+ stepRef: stepRecordId(journey.useCaseId, journey.journeyId, observation.stepId),
278
+ })),
279
+ );
280
+ const normalizedJourneys = raw.map((journey) => {
281
+ const id = journeyRecordId(journey.useCaseId, journey.journeyId);
282
+ return {
283
+ id,
284
+ useCaseId: journey.useCaseId,
285
+ journeyId: journey.journeyId,
286
+ status: journey.status,
287
+ timing: journey.timing,
288
+ metrics: journey.metrics,
289
+ stepRefs: journey.steps.map((step) =>
290
+ stepRecordId(journey.useCaseId, journey.journeyId, step.id),
291
+ ),
292
+ observationRefs: journey.observations.map(({ id: observationId }) => observationId),
293
+ findingRefs: findings
294
+ .filter((finding) => finding.journeyRefs.includes(id))
295
+ .map((finding) => finding.id)
296
+ .sort(),
297
+ };
298
+ });
299
+ const report = {
300
+ kind: JOURNEY_REPORT_KIND,
301
+ version: JOURNEY_REPORT_VERSION,
302
+ run: structuredClone(run),
303
+ journeys: normalizedJourneys,
304
+ findings,
305
+ details: {
306
+ steps: steps.sort((left, right) => left.id.localeCompare(right.id)),
307
+ observations: observations.sort((left, right) => left.id.localeCompare(right.id)),
308
+ },
309
+ };
310
+ return validateJourneyReport(report);
311
+ }
312
+
313
+ export function validateJourneyReport(report) {
314
+ assertMap(report, 'report');
315
+ assertExactKeys(report, ['kind', 'version', 'run', 'journeys', 'findings', 'details'], 'report');
316
+ if (report.kind !== JOURNEY_REPORT_KIND) {
317
+ throw new JourneyReportError(`report.kind must be ${JOURNEY_REPORT_KIND}`);
318
+ }
319
+ if (report.version !== JOURNEY_REPORT_VERSION) {
320
+ throw new JourneyReportError(
321
+ `unsupported journey report version ${String(report.version)}; migrate to version ${JOURNEY_REPORT_VERSION}`,
322
+ );
323
+ }
324
+ validateRunEnvelope(report.run);
325
+ if (!Array.isArray(report.journeys) || !Array.isArray(report.findings)) {
326
+ throw new JourneyReportError('report journeys and findings must be arrays');
327
+ }
328
+ assertMap(report.details, 'report.details');
329
+ assertExactKeys(report.details, ['steps', 'observations'], 'report.details');
330
+ if (!Array.isArray(report.details.steps) || !Array.isArray(report.details.observations)) {
331
+ throw new JourneyReportError('report.details steps and observations must be arrays');
332
+ }
333
+
334
+ const steps = new Map();
335
+ for (const [index, step] of report.details.steps.entries()) {
336
+ const path = `report.details.steps[${index}]`;
337
+ assertMap(step, path);
338
+ assertExactKeys(step, ['id', 'journeyRef', 'stepId', 'metrics'], path);
339
+ assertId(step.id, ID, `${path}.id`);
340
+ if (steps.has(step.id)) throw new JourneyReportError(`duplicate step record ${step.id}`);
341
+ assertId(step.journeyRef, ID, `${path}.journeyRef`);
342
+ assertId(step.stepId, ID, `${path}.stepId`);
343
+ validateMetrics(step.metrics, `${path}.metrics`);
344
+ if (step.metrics.steps !== 1) throw new JourneyReportError(`${path}.metrics.steps must be 1`);
345
+ steps.set(step.id, step);
346
+ }
347
+ const observations = new Map();
348
+ for (const [index, observation] of report.details.observations.entries()) {
349
+ const path = `report.details.observations[${index}]`;
350
+ assertMap(observation, path);
351
+ assertExactKeys(
352
+ observation,
353
+ ['id', 'version', 'type', 'stepId', 'data', 'journeyRef', 'stepRef'],
354
+ path,
355
+ );
356
+ if (observations.has(observation.id)) {
357
+ throw new JourneyReportError(`duplicate observation ${observation.id}`);
358
+ }
359
+ const raw = {
360
+ id: observation.id,
361
+ version: observation.version,
362
+ type: observation.type,
363
+ stepId: observation.stepId,
364
+ data: observation.data,
365
+ };
366
+ validateObservation(raw, path);
367
+ assertId(observation.journeyRef, ID, `${path}.journeyRef`);
368
+ assertId(observation.stepRef, ID, `${path}.stepRef`);
369
+ if (!steps.has(observation.stepRef)) {
370
+ throw new JourneyReportError(`${path}.stepRef names an unknown step`);
371
+ }
372
+ observations.set(observation.id, observation);
373
+ }
374
+
375
+ const journeyIds = new Set();
376
+ for (const [index, journey] of report.journeys.entries()) {
377
+ const path = `report.journeys[${index}]`;
378
+ validateNormalizedJourney(journey, path, steps, observations);
379
+ if (journeyIds.has(journey.id)) throw new JourneyReportError(`duplicate journey ${journey.id}`);
380
+ journeyIds.add(journey.id);
381
+ }
382
+ const findingIds = new Set();
383
+ for (const [index, finding] of report.findings.entries()) {
384
+ validateFinding(finding, `report.findings[${index}]`, journeyIds, observations);
385
+ if (findingIds.has(finding.id)) throw new JourneyReportError(`duplicate finding ${finding.id}`);
386
+ findingIds.add(finding.id);
387
+ }
388
+ for (const journey of report.journeys) {
389
+ for (const findingRef of journey.findingRefs) {
390
+ const finding = report.findings.find((candidate) => candidate.id === findingRef);
391
+ if (!finding || !finding.journeyRefs.includes(journey.id)) {
392
+ throw new JourneyReportError(`${journey.id} has an invalid finding reference`);
393
+ }
394
+ }
395
+ }
396
+ const statuses = report.journeys.map((journey) => journey.status);
397
+ const completion = report.run.completion;
398
+ const expectedCounts = {
399
+ successful: statuses.filter((status) => status === 'successful').length,
400
+ failed: statuses.filter((status) => status === 'failed').length,
401
+ skipped: statuses.filter((status) => status === 'skipped').length,
402
+ unexecutable: statuses.filter((status) => status === 'unexecutable').length,
403
+ infrastructureError: statuses.filter((status) => status === 'infrastructure-error').length,
404
+ };
405
+ if (
406
+ completion.received !== report.journeys.length ||
407
+ Object.entries(expectedCounts).some(([key, value]) => completion[key] !== value)
408
+ ) {
409
+ throw new JourneyReportError('run completion does not match journey lifecycle records');
410
+ }
411
+ return report;
412
+ }
413
+
414
+ export function validateJourneyCatalog(report, catalog) {
415
+ validateJourneyReport(report);
416
+ const ids = catalogIds(catalog);
417
+ const unknown = [
418
+ ...new Set(
419
+ report.journeys
420
+ .map((journey) => journey.useCaseId)
421
+ .filter((useCaseId) => !ids.has(useCaseId)),
422
+ ),
423
+ ].sort();
424
+ if (unknown.length) {
425
+ throw new JourneyReportError(`journey report names uncatalogued use cases: ${unknown.join(', ')}`);
426
+ }
427
+ return report;
428
+ }
429
+
430
+ export function parseJourneyReport(text) {
431
+ if (typeof text !== 'string') throw new JourneyReportError('journey report must be JSON text');
432
+ let report;
433
+ try {
434
+ report = JSON.parse(text);
435
+ } catch {
436
+ throw new JourneyReportError('journey report is not valid JSON');
437
+ }
438
+ if (report?.kind === JOURNEY_REPORT_KIND && report.version !== JOURNEY_REPORT_VERSION) {
439
+ throw new JourneyReportError(
440
+ `unsupported journey report version ${String(report.version)}; migrate to version ${JOURNEY_REPORT_VERSION}`,
441
+ );
442
+ }
443
+ return validateJourneyReport(report);
444
+ }
445
+
446
+ export function serializeJourneyReport(report) {
447
+ validateJourneyReport(report);
448
+ return `${JSON.stringify(canonicalize(report), null, 2)}\n`;
449
+ }
450
+
451
+ export function aggregateJourneyReport(report) {
452
+ validateJourneyReport(report);
453
+ const metrics = {};
454
+ for (const metric of JOURNEY_METRICS) {
455
+ const measured = report.journeys.filter(
456
+ (journey) => journey.metrics && Object.hasOwn(journey.metrics, metric),
457
+ );
458
+ if (measured.length === 0) continue;
459
+ const aggregation = METRIC_DEFINITIONS[metric].aggregation;
460
+ metrics[metric] = {
461
+ value:
462
+ aggregation === 'max'
463
+ ? Math.max(...measured.map((journey) => journey.metrics[metric]))
464
+ : measured.reduce((total, journey) => total + journey.metrics[metric], 0),
465
+ aggregation,
466
+ journeysMeasured: measured.length,
467
+ journeysTotal: report.journeys.length,
468
+ };
469
+ }
470
+ return {
471
+ kind: 'ux-guard-journey-aggregate',
472
+ version: JOURNEY_REPORT_VERSION,
473
+ useCases: new Set(report.journeys.map((journey) => journey.useCaseId)).size,
474
+ journeys: report.journeys.length,
475
+ metrics,
476
+ };
477
+ }
478
+
479
+ export function compareJourneyReports(before, after) {
480
+ validateJourneyReport(before);
481
+ validateJourneyReport(after);
482
+ const beforeById = new Map(before.journeys.map((journey) => [journey.id, journey]));
483
+ const afterById = new Map(after.journeys.map((journey) => [journey.id, journey]));
484
+ const journeys = [...beforeById.keys()]
485
+ .filter((id) => afterById.has(id))
486
+ .sort()
487
+ .map((id) => compareJourney(beforeById.get(id), afterById.get(id)));
488
+ return {
489
+ kind: 'ux-guard-journey-comparison',
490
+ version: JOURNEY_REPORT_VERSION,
491
+ regressionStatus: 'not-evaluated',
492
+ addedJourneyRefs: [...afterById.keys()].filter((id) => !beforeById.has(id)).sort(),
493
+ removedJourneyRefs: [...beforeById.keys()].filter((id) => !afterById.has(id)).sort(),
494
+ journeys,
495
+ };
496
+ }
497
+
498
+ function validateRawJourney(journey, path) {
499
+ assertMap(journey, path);
500
+ assertExactKeys(
501
+ journey,
502
+ ['useCaseId', 'journeyId', 'status', 'timing', 'metrics', 'steps', 'observations'],
503
+ path,
504
+ );
505
+ assertId(journey.useCaseId, USE_CASE_ID, `${path}.useCaseId`);
506
+ assertId(journey.journeyId, ID, `${path}.journeyId`);
507
+ if (!JOURNEY_STATUSES.has(journey.status)) {
508
+ throw new JourneyReportError(`${path}.status is invalid`);
509
+ }
510
+ if (['failed', 'skipped', 'infrastructure-error'].includes(journey.status)) {
511
+ if (
512
+ journey.timing !== null ||
513
+ journey.metrics !== null ||
514
+ !Array.isArray(journey.steps) ||
515
+ journey.steps.length !== 0 ||
516
+ !Array.isArray(journey.observations) ||
517
+ journey.observations.length !== 0
518
+ ) {
519
+ throw new JourneyReportError(`${path} lifecycle-only status cannot claim measurements`);
520
+ }
521
+ return;
522
+ }
523
+ validateMetrics(journey.metrics, `${path}.metrics`);
524
+ validateTiming(journey.timing, journey.metrics, `${path}.timing`);
525
+ if (!Array.isArray(journey.steps) || journey.steps.length === 0) {
526
+ throw new JourneyReportError(`${path}.steps must be a non-empty array`);
527
+ }
528
+ const stepIds = new Set();
529
+ const metricKeys = Object.keys(journey.metrics).sort();
530
+ for (const [index, step] of journey.steps.entries()) {
531
+ const stepPath = `${path}.steps[${index}]`;
532
+ assertMap(step, stepPath);
533
+ assertExactKeys(step, ['id', 'metrics'], stepPath);
534
+ assertId(step.id, ID, `${stepPath}.id`);
535
+ if (stepIds.has(step.id)) throw new JourneyReportError(`${path} repeats step ${step.id}`);
536
+ stepIds.add(step.id);
537
+ validateMetrics(step.metrics, `${stepPath}.metrics`);
538
+ if (step.metrics.steps !== 1) throw new JourneyReportError(`${stepPath}.metrics.steps must be 1`);
539
+ if (!sameStrings(metricKeys, Object.keys(step.metrics).sort())) {
540
+ throw new JourneyReportError(`${stepPath}.metrics does not match journey metrics`);
541
+ }
542
+ }
543
+ const aggregate = aggregateSteps(journey.steps);
544
+ for (const metric of metricKeys) {
545
+ if (aggregate[metric] !== journey.metrics[metric]) {
546
+ throw new JourneyReportError(`${path}.metrics.${metric} is not the step aggregate`);
547
+ }
548
+ }
549
+ if (!Array.isArray(journey.observations)) {
550
+ throw new JourneyReportError(`${path}.observations must be an array`);
551
+ }
552
+ const observationIds = new Set();
553
+ for (const [index, observation] of journey.observations.entries()) {
554
+ validateObservation(observation, `${path}.observations[${index}]`);
555
+ if (observationIds.has(observation.id)) {
556
+ throw new JourneyReportError(`${path} repeats observation ${observation.id}`);
557
+ }
558
+ observationIds.add(observation.id);
559
+ if (!stepIds.has(observation.stepId)) {
560
+ throw new JourneyReportError(`${path} observation names unknown step ${observation.stepId}`);
561
+ }
562
+ }
563
+ }
564
+
565
+ function validateNormalizedJourney(journey, path, steps, observations) {
566
+ assertMap(journey, path);
567
+ assertExactKeys(
568
+ journey,
569
+ [
570
+ 'id',
571
+ 'useCaseId',
572
+ 'journeyId',
573
+ 'status',
574
+ 'timing',
575
+ 'metrics',
576
+ 'stepRefs',
577
+ 'observationRefs',
578
+ 'findingRefs',
579
+ ],
580
+ path,
581
+ );
582
+ assertId(journey.id, ID, `${path}.id`);
583
+ if (journey.id !== journeyRecordId(journey.useCaseId, journey.journeyId)) {
584
+ throw new JourneyReportError(`${path}.id is not derived from its policy ids`);
585
+ }
586
+ assertId(journey.useCaseId, USE_CASE_ID, `${path}.useCaseId`);
587
+ assertId(journey.journeyId, ID, `${path}.journeyId`);
588
+ if (!JOURNEY_STATUSES.has(journey.status)) throw new JourneyReportError(`${path}.status is invalid`);
589
+ for (const field of ['stepRefs', 'observationRefs', 'findingRefs']) {
590
+ if (
591
+ !Array.isArray(journey[field]) ||
592
+ journey[field].some((id) => typeof id !== 'string' || !ID.test(id)) ||
593
+ new Set(journey[field]).size !== journey[field].length
594
+ ) {
595
+ throw new JourneyReportError(`${path}.${field} is invalid`);
596
+ }
597
+ }
598
+ if (['failed', 'skipped', 'infrastructure-error'].includes(journey.status)) {
599
+ if (
600
+ journey.timing !== null ||
601
+ journey.metrics !== null ||
602
+ journey.stepRefs.length ||
603
+ journey.observationRefs.length ||
604
+ journey.findingRefs.length
605
+ ) {
606
+ throw new JourneyReportError(`${path} lifecycle-only status cannot reference evidence`);
607
+ }
608
+ return;
609
+ }
610
+ validateMetrics(journey.metrics, `${path}.metrics`);
611
+ validateTiming(journey.timing, journey.metrics, `${path}.timing`);
612
+ if (journey.stepRefs.length === 0) throw new JourneyReportError(`${path}.stepRefs is empty`);
613
+ const journeySteps = journey.stepRefs.map((id) => {
614
+ const step = steps.get(id);
615
+ if (!step || step.journeyRef !== journey.id) {
616
+ throw new JourneyReportError(`${path}.stepRefs names an invalid step`);
617
+ }
618
+ return { id: step.stepId, metrics: step.metrics };
619
+ });
620
+ const aggregate = aggregateSteps(journeySteps);
621
+ for (const metric of Object.keys(journey.metrics)) {
622
+ if (aggregate[metric] !== journey.metrics[metric]) {
623
+ throw new JourneyReportError(`${path}.metrics.${metric} is inconsistent`);
624
+ }
625
+ }
626
+ for (const id of journey.observationRefs) {
627
+ const observation = observations.get(id);
628
+ if (!observation || observation.journeyRef !== journey.id) {
629
+ throw new JourneyReportError(`${path}.observationRefs names invalid evidence`);
630
+ }
631
+ }
632
+ }
633
+
634
+ function validateFinding(finding, path, journeys, observations) {
635
+ assertMap(finding, path);
636
+ assertExactKeys(
637
+ finding,
638
+ [
639
+ 'id',
640
+ 'ruleId',
641
+ 'severity',
642
+ 'dimension',
643
+ 'type',
644
+ 'summary',
645
+ 'policy',
646
+ 'recommendation',
647
+ 'journeyRefs',
648
+ 'evidence',
649
+ ],
650
+ path,
651
+ );
652
+ assertId(finding.id, ID, `${path}.id`);
653
+ assertId(finding.ruleId, ID, `${path}.ruleId`);
654
+ if (!['low', 'medium', 'high', 'critical'].includes(finding.severity)) {
655
+ throw new JourneyReportError(`${path}.severity is invalid`);
656
+ }
657
+ if (
658
+ !['efficiency', 'clarity', 'feedback-and-recovery', 'accessibility', 'consistency'].includes(
659
+ finding.dimension,
660
+ )
661
+ ) {
662
+ throw new JourneyReportError(`${path}.dimension is invalid`);
663
+ }
664
+ if (!['requirement', 'recommendation'].includes(finding.type)) {
665
+ throw new JourneyReportError(`${path}.type is invalid`);
666
+ }
667
+ assertText(finding.summary, `${path}.summary`);
668
+ assertText(finding.recommendation, `${path}.recommendation`);
669
+ if (
670
+ !Array.isArray(finding.journeyRefs) ||
671
+ finding.journeyRefs.length === 0 ||
672
+ finding.journeyRefs.some((id) => !journeys.has(id))
673
+ ) {
674
+ throw new JourneyReportError(`${path}.journeyRefs is invalid`);
675
+ }
676
+ if (!Array.isArray(finding.policy) || finding.policy.length === 0) {
677
+ throw new JourneyReportError(`${path}.policy is invalid`);
678
+ }
679
+ for (const [index, reference] of finding.policy.entries()) {
680
+ const referencePath = `${path}.policy[${index}]`;
681
+ assertMap(reference, referencePath);
682
+ assertExactKeys(reference, ['source', 'field', 'statement'], referencePath);
683
+ assertText(reference.source, `${referencePath}.source`);
684
+ assertText(reference.field, `${referencePath}.field`);
685
+ assertText(reference.statement, `${referencePath}.statement`);
686
+ }
687
+ if (!Array.isArray(finding.evidence) || finding.evidence.length === 0) {
688
+ throw new JourneyReportError(`${path}.evidence is invalid`);
689
+ }
690
+ const ids = new Set();
691
+ for (const [index, evidence] of finding.evidence.entries()) {
692
+ const evidencePath = `${path}.evidence[${index}]`;
693
+ assertMap(evidence, evidencePath);
694
+ assertExactKeys(
695
+ evidence,
696
+ ['id', 'journeyRef', 'observationRef', 'stepId', 'facts'],
697
+ evidencePath,
698
+ );
699
+ assertId(evidence.id, ID, `${evidencePath}.id`);
700
+ if (ids.has(evidence.id)) throw new JourneyReportError(`${path} repeats evidence id`);
701
+ ids.add(evidence.id);
702
+ if (!finding.journeyRefs.includes(evidence.journeyRef)) {
703
+ throw new JourneyReportError(`${evidencePath}.journeyRef is invalid`);
704
+ }
705
+ const observation = observations.get(evidence.observationRef);
706
+ if (
707
+ !observation ||
708
+ observation.journeyRef !== evidence.journeyRef ||
709
+ observation.stepId !== evidence.stepId
710
+ ) {
711
+ throw new JourneyReportError(`${evidencePath} does not reference its observation`);
712
+ }
713
+ if (!Array.isArray(evidence.facts) || evidence.facts.length === 0) {
714
+ throw new JourneyReportError(`${evidencePath}.facts is invalid`);
715
+ }
716
+ }
717
+ }
718
+
719
+ function validateMetrics(metrics, path) {
720
+ assertMap(metrics, path);
721
+ for (const metric of STANDARD_JOURNEY_METRICS) {
722
+ if (!Object.hasOwn(metrics, metric)) {
723
+ throw new JourneyReportError(`${path}.${metric} is a standard required measurement`);
724
+ }
725
+ }
726
+ for (const [metric, value] of Object.entries(metrics)) {
727
+ if (!Object.hasOwn(METRIC_DEFINITIONS, metric)) {
728
+ throw new JourneyReportError(`${path} has unknown metric ${metric}`);
729
+ }
730
+ assertMeasurement(value, `${path}.${metric}`);
731
+ }
732
+ }
733
+
734
+ function validateTiming(timing, metrics, path) {
735
+ const hasElapsed = Object.hasOwn(metrics, 'elapsedMs');
736
+ if (!hasElapsed) {
737
+ if (timing !== null) throw new JourneyReportError(`${path} must be null without elapsedMs`);
738
+ return;
739
+ }
740
+ assertMap(timing, path);
741
+ assertExactKeys(timing, ['source', 'deterministic'], path);
742
+ if (!ELAPSED_SOURCES.has(timing.source)) throw new JourneyReportError(`${path}.source is invalid`);
743
+ if (timing.deterministic !== (timing.source !== 'wall-clock')) {
744
+ throw new JourneyReportError(`${path}.deterministic does not match its source`);
745
+ }
746
+ }
747
+
748
+ function aggregateSteps(steps) {
749
+ const measured = new Set(steps.flatMap((step) => Object.keys(step.metrics)));
750
+ const metrics = {};
751
+ for (const metric of JOURNEY_METRICS) {
752
+ if (!measured.has(metric)) continue;
753
+ metrics[metric] =
754
+ METRIC_DEFINITIONS[metric].aggregation === 'max'
755
+ ? Math.max(...steps.map((step) => step.metrics[metric]))
756
+ : steps.reduce((total, step) => total + step.metrics[metric], 0);
757
+ }
758
+ return metrics;
759
+ }
760
+
761
+ function compareJourney(before, after) {
762
+ const metrics = {};
763
+ for (const metric of JOURNEY_METRICS) {
764
+ if (
765
+ before.metrics &&
766
+ after.metrics &&
767
+ Object.hasOwn(before.metrics, metric) &&
768
+ Object.hasOwn(after.metrics, metric)
769
+ ) {
770
+ metrics[metric] = {
771
+ before: before.metrics[metric],
772
+ after: after.metrics[metric],
773
+ delta: after.metrics[metric] - before.metrics[metric],
774
+ };
775
+ }
776
+ }
777
+ return {
778
+ journeyRef: before.id,
779
+ status: {
780
+ before: before.status,
781
+ after: after.status,
782
+ changed: before.status !== after.status,
783
+ },
784
+ metrics,
785
+ };
786
+ }
787
+
788
+ function normalizeMetricSelection(metrics) {
789
+ if (!Array.isArray(metrics)) throw new JourneyReportError('metrics must be an array');
790
+ const selected = new Set();
791
+ for (const metric of metrics) {
792
+ if (!RECORDABLE_JOURNEY_METRICS.includes(metric)) {
793
+ throw new JourneyReportError(`unknown or derived journey metric ${String(metric)}`);
794
+ }
795
+ selected.add(metric);
796
+ }
797
+ return selected;
798
+ }
799
+
800
+ function normalizeElapsed(elapsed) {
801
+ if (elapsed === null) return null;
802
+ assertMap(elapsed, 'elapsed');
803
+ const keys = Object.keys(elapsed);
804
+ if (
805
+ !keys.every((key) => key === 'source' || key === 'clock') ||
806
+ !Object.hasOwn(elapsed, 'source')
807
+ ) {
808
+ throw new JourneyReportError('elapsed accepts source and optional clock only');
809
+ }
810
+ if (!ELAPSED_SOURCES.has(elapsed.source)) {
811
+ throw new JourneyReportError('elapsed.source must be mocked, logical, or wall-clock');
812
+ }
813
+ if (elapsed.clock === undefined) return { source: elapsed.source, clock: null };
814
+ const now = typeof elapsed.clock === 'function' ? elapsed.clock : elapsed.clock?.now;
815
+ if (typeof now !== 'function') {
816
+ throw new JourneyReportError('elapsed.clock must be a function or an object with now()');
817
+ }
818
+ return {
819
+ source: elapsed.source,
820
+ clock: now.bind(typeof elapsed.clock === 'object' ? elapsed.clock : undefined),
821
+ };
822
+ }
823
+
824
+ function readClock(now) {
825
+ const value = now();
826
+ if (!Number.isSafeInteger(value) || value < 0) {
827
+ throw new JourneyReportError('clock.now() must return a non-negative safe integer');
828
+ }
829
+ return value;
830
+ }
831
+
832
+ function validateRawJourneyCatalog(journeys, catalog) {
833
+ const ids = catalogIds(catalog);
834
+ const unknown = [...new Set(journeys.map(({ useCaseId }) => useCaseId).filter((id) => !ids.has(id)))];
835
+ if (unknown.length) {
836
+ throw new JourneyReportError(`journey report names uncatalogued use cases: ${unknown.sort().join(', ')}`);
837
+ }
838
+ }
839
+
840
+ function catalogIds(catalog) {
841
+ let entries;
842
+ if (catalog instanceof Set || Array.isArray(catalog)) entries = [...catalog];
843
+ else if (Array.isArray(catalog?.use_cases)) entries = catalog.use_cases.map((entry) => entry?.id);
844
+ else if (Array.isArray(catalog?.useCases)) entries = catalog.useCases.map((entry) => entry?.id);
845
+ else throw new JourneyReportError('catalog must contain use-case ids');
846
+ if (entries.some((entry) => typeof entry !== 'string' || !USE_CASE_ID.test(entry))) {
847
+ throw new JourneyReportError('catalog contains an invalid use-case id');
848
+ }
849
+ return new Set(entries);
850
+ }
851
+
852
+ function stepRecordId(useCaseId, journeyId, stepId) {
853
+ return `step.${useCaseId}.${journeyId}.${stepId}`;
854
+ }
855
+
856
+ function compareJourneyIdentity(left, right) {
857
+ return left.useCaseId.localeCompare(right.useCaseId) || left.journeyId.localeCompare(right.journeyId);
858
+ }
859
+
860
+ function assertMap(value, path) {
861
+ if (value === null || typeof value !== 'object' || Array.isArray(value)) {
862
+ throw new JourneyReportError(`${path} must be an object`);
863
+ }
864
+ }
865
+
866
+ function assertExactKeys(value, expected, path) {
867
+ const actual = Object.keys(value).sort();
868
+ const wanted = [...expected].sort();
869
+ if (!sameStrings(actual, wanted)) {
870
+ throw new JourneyReportError(`${path} must contain ${wanted.join(', ')} only`);
871
+ }
872
+ }
873
+
874
+ function assertOptionKeys(value, allowed, path) {
875
+ assertMap(value, path);
876
+ const unknown = Object.keys(value).filter((key) => !allowed.includes(key));
877
+ if (unknown.length) throw new JourneyReportError(`${path} has unknown field ${unknown[0]}`);
878
+ }
879
+
880
+ function assertId(value, pattern, path) {
881
+ if (typeof value !== 'string' || !pattern.test(value)) {
882
+ throw new JourneyReportError(`${path} has invalid id ${JSON.stringify(value)}`);
883
+ }
884
+ }
885
+
886
+ function assertMeasurement(value, path) {
887
+ if (!Number.isSafeInteger(value) || value < 0) {
888
+ throw new JourneyReportError(`${path} must be a non-negative safe integer`);
889
+ }
890
+ }
891
+
892
+ function assertText(value, path) {
893
+ if (typeof value !== 'string' || !value.trim()) {
894
+ throw new JourneyReportError(`${path} must be non-empty text`);
895
+ }
896
+ }
897
+
898
+ function sameStrings(left, right) {
899
+ return left.length === right.length && left.every((value, index) => value === right[index]);
900
+ }