@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.
package/lib/cli.mjs ADDED
@@ -0,0 +1,1980 @@
1
+ import { execFileSync } from 'node:child_process';
2
+ import { existsSync, lstatSync, mkdirSync, readFileSync, unlinkSync, writeFileSync } from 'node:fs';
3
+ import { dirname, join, relative, resolve, sep } from 'node:path';
4
+ import {
5
+ AuthoritativeUpgradeError,
6
+ createAuthoritativeAdvisory,
7
+ } from './authoritative.mjs';
8
+ import {
9
+ JourneyBaselineError,
10
+ compareJourneyBaseline,
11
+ compareJourneyBaselineEnvelopes,
12
+ createJourneyBaselineCandidate,
13
+ parseJourneyBaseline,
14
+ promoteJourneyBaseline,
15
+ renderJourneyBaselineMarkdown,
16
+ renderJourneyComparisonMarkdown,
17
+ serializeJourneyBaseline,
18
+ serializeJourneyComparison,
19
+ unavailableJourneyComparison,
20
+ runJourneyComparisonCanaries,
21
+ } from './baselines.mjs';
22
+ import { catalogPolicy, loadCatalog, loadSurfaces, renderCatalog, validateCatalog } from './catalog.mjs';
23
+ import {
24
+ CONFIG_FILE,
25
+ loadConfig,
26
+ loadTypeScript,
27
+ readTrusted,
28
+ resolveRepositoryPath,
29
+ resolveTrustedRevision,
30
+ trustedFileExists,
31
+ validateConfig,
32
+ } from './config.mjs';
33
+ import {
34
+ candidateFromDiscovery,
35
+ discoverProject,
36
+ renderDiscovery,
37
+ setupProposalFromDiscovery,
38
+ } from './discovery.mjs';
39
+ import {
40
+ createJourneyArtifact,
41
+ parseJourneyPolicy,
42
+ } from './journey-policy.mjs';
43
+ import {
44
+ createJourneyReport,
45
+ parseJourneyReport,
46
+ } from './journeys.mjs';
47
+ import {
48
+ DEBT_RULES,
49
+ baselineFromScan,
50
+ compare,
51
+ listSourceFiles,
52
+ renderComparison,
53
+ scanFiles,
54
+ scanSource,
55
+ validateBaseline,
56
+ } from './patterns.mjs';
57
+ import {
58
+ createVerdictReport,
59
+ renderVerdictMarkdown,
60
+ serializeVerdictReport,
61
+ } from './verdicts.mjs';
62
+ import {
63
+ createRunEnvelope,
64
+ policyDigest,
65
+ resolveRunIdentity,
66
+ sha256,
67
+ } from './run-contract.mjs';
68
+ import {
69
+ OwnerTargetsError,
70
+ evaluateTargetAttainment,
71
+ parseOwnerTargets,
72
+ unavailableTargetAttainment,
73
+ } from './targets.mjs';
74
+ import {
75
+ compareVisualManifests,
76
+ parseVisualCheckpointPolicy,
77
+ parseVisualManifest,
78
+ parseVisualProfileSet,
79
+ promoteVisualBundle,
80
+ renderVisualComparisonMarkdown,
81
+ renderVisualManifestMarkdown,
82
+ runVisualComparisonCanaries,
83
+ unavailableVisualComparison,
84
+ VisualContractError,
85
+ } from './visuals.mjs';
86
+ import { ConfigError, parseYamlSubset } from './yaml.mjs';
87
+
88
+ const DEFAULT_SETUP_PROPOSAL = 'ux-guard/setup-proposal.json';
89
+ const SETUP_SIGNAL_LABELS = {
90
+ 'inline-style': 'inline styles',
91
+ 'hard-coded-color': 'hard-coded colors',
92
+ 'px-literal': 'pixel literals',
93
+ 'raw-button': 'raw button elements',
94
+ 'icon-library': 'icon-library uses',
95
+ };
96
+
97
+ const USAGE = `usage: ux-guard <command> [options]
98
+
99
+ commands:
100
+ setup inspect this repo and suggest reviewed next steps
101
+ check compare current UI code with reviewed UX policy
102
+ report explain UX evidence, gaps, and recommendations
103
+
104
+ help:
105
+ ux-guard setup --help
106
+ ux-guard check --help
107
+ ux-guard report --help
108
+ ux-guard help advanced
109
+
110
+ common options:
111
+ --root <dir> repository root (default: current directory)
112
+ --base <ref> use reviewed policy from a trusted Git revision
113
+ --format text|json human-readable or machine-readable output
114
+ `;
115
+
116
+ const SETUP_HELP = `usage: ux-guard setup [options]
117
+
118
+ Inspect UI source without approving it, report good observations, potential
119
+ problems, and unknowns, then suggest tailored next steps. A supporting review
120
+ file records the observed source roots, components, pattern counts, and
121
+ unresolved choices. Setup never creates active policy, a reviewed baseline, a
122
+ waiver, or enforcement.
123
+
124
+ options:
125
+ --root <dir> repository root (default: current directory)
126
+ --proposal <path> repository-local supporting review file
127
+ --format text|json human-readable or machine-readable output
128
+ --typescript <path> advanced: explicit TypeScript package path
129
+ `;
130
+
131
+ const CHECK_HELP = `usage: ux-guard check [options]
132
+
133
+ Compare current UI code with reviewed policy. Findings use exit code 1;
134
+ missing, malformed, or unsafe inputs use exit code 2.
135
+
136
+ options:
137
+ --root <dir> repository root (default: current directory)
138
+ --base <ref> use reviewed policy from a trusted Git revision
139
+ --strict require every navigation surface to be catalogued
140
+ --format text|json human-readable or machine-readable output
141
+ `;
142
+
143
+ const REPORT_HELP = `usage: ux-guard report [options]
144
+
145
+ Explain configured journey evidence, UX quality, target attainment, regression,
146
+ and recommendations. Missing evidence stays unknown; it is never reported as
147
+ success. A successfully rendered report exits 0 even when advisory findings,
148
+ target breaches, or backslide need attention; report does not enforce merges.
149
+
150
+ options:
151
+ --root <dir> repository root (default: current directory)
152
+ --base <ref> compare with reviewed evidence from a trusted Git revision
153
+ --format json|markdown
154
+ machine-readable output or a human review document
155
+ `;
156
+
157
+ const ADVANCED_USAGE = `usage: ux-guard <advanced-command> [options]
158
+
159
+ advanced policy and evidence lifecycle:
160
+ authoritative aggregate shards and regenerate trusted advisory artifacts
161
+ discover audit observed UI conventions and emit review candidates
162
+ discover write-candidate --candidate <path>
163
+ write a new, explicitly unapproved review artifact
164
+ discover promote --candidate <path>
165
+ install a human-approved candidate without overwriting
166
+ baseline propose --candidate <path>
167
+ write an unapproved snapshot from the completed report
168
+ baseline inspect --candidate <path>
169
+ validate and render a candidate for human review
170
+ baseline diff --candidate <path> [--baseline <path>]
171
+ compare a candidate with a reviewed snapshot
172
+ baseline promote --candidate <path> --reviewer <id> --reviewed-at <UTC> --rationale <text>
173
+ create the configured reviewed baseline without overwriting
174
+ baseline canary prove regression, improvement, compatibility, and known-bad behavior
175
+ visual inspect --candidate <path>
176
+ validate and render an unapproved visual bundle
177
+ visual diff --candidate <path> [--baseline <path>]
178
+ compare visual manifests checkpoint by checkpoint
179
+ visual promote --candidate <path> --reviewer <id> --reviewed-at <UTC> --rationale <text>
180
+ create a reviewed visual baseline without overwriting
181
+ visual canary prove visual change and fail-closed behavior
182
+ catalog [--strict] validate the use-case catalog and list unmapped surfaces
183
+ patterns scan compare UI patterns with the baseline
184
+ patterns update rewrite the baseline; refuses growth without --accept-growth
185
+ patterns init create the baseline when none exists
186
+ patterns canary prove a known-bad file is rejected
187
+
188
+ options:
189
+ --root <dir> repository root (default: current directory)
190
+ --base <ref> load policy and baseline from a trusted git revision
191
+ --typescript <path> TypeScript package path for discovery only
192
+ --shards <path> candidate shard directory for authoritative regeneration
193
+ --visuals <path> candidate visual bundle for authoritative validation
194
+ --candidate-sha <sha> candidate commit expected in authoritative shards
195
+ --project <id> expected journey project (default: chromium)
196
+ --browser <name> expected browser name (default: chromium)
197
+ --profile <name> expected browser profile (default: Desktop Chrome)
198
+ --repetitions <count> expected stable repetitions (default: 3)
199
+ --candidate <path> discovery lifecycle artifact (repository-relative)
200
+ --baseline <path> reviewed baseline used by baseline diff
201
+ --reviewer <id> explicit baseline approval identity
202
+ --reviewed-at <UTC> explicit deterministic approval timestamp
203
+ --rationale <text> explicit baseline approval rationale
204
+ --format json|markdown
205
+ machine-readable output, or Markdown for report
206
+ `;
207
+
208
+ export async function main(argv, io = { out: process.stdout, err: process.stderr }) {
209
+ let options;
210
+ try {
211
+ options = parseArgs(argv);
212
+ } catch (error) {
213
+ writeCliError(error, argv, io);
214
+ return 2;
215
+ }
216
+ try {
217
+ return run(options, io);
218
+ } catch (error) {
219
+ if (error instanceof AuthoritativeUpgradeError) {
220
+ io.err.write(`ux-guard: upgrade required: ${error.message}\n`);
221
+ return 3;
222
+ }
223
+ if (
224
+ error instanceof ConfigError ||
225
+ error instanceof JourneyBaselineError ||
226
+ error instanceof OwnerTargetsError ||
227
+ error instanceof VisualContractError
228
+ ) {
229
+ writeCliError(error, argv, io);
230
+ return 2;
231
+ }
232
+ throw error;
233
+ }
234
+ }
235
+
236
+ function writeCliError(error, argv, io) {
237
+ const command = ['setup', 'check', 'report'].find((name) => argv.includes(name));
238
+ const guidance = errorGuidance(command, error.message);
239
+ if (
240
+ command === 'setup' &&
241
+ argv.some((value, index) => value === '--format' && argv[index + 1] === 'json')
242
+ ) {
243
+ io.err.write(
244
+ `${JSON.stringify(
245
+ {
246
+ kind: 'ux-guard-setup-error',
247
+ version: 1,
248
+ command: 'setup',
249
+ status: 'error',
250
+ exitCode: 2,
251
+ error: error.message,
252
+ nextAction: guidance,
253
+ },
254
+ null,
255
+ 2,
256
+ )}\n`,
257
+ );
258
+ return;
259
+ }
260
+ io.err.write(`ux-guard: ${error.message}\n${guidance}\n`);
261
+ }
262
+
263
+ function errorGuidance(command, message) {
264
+ if (command === 'setup') {
265
+ if (message.includes(`${CONFIG_FILE} already exists`)) {
266
+ return 'Next: run ux-guard check. Setup will not replace the repository’s active policy.';
267
+ }
268
+ if (message.includes('already exists; refusing to overwrite')) {
269
+ return 'Next: review the existing supporting setup file, which records observations and unresolved choices, or deliberately choose a different repository-local path.';
270
+ }
271
+ return 'Next: fix the reported input or choose a new supporting review file path, then run ux-guard setup again. Setup never overwrites files.';
272
+ }
273
+ if (command === 'check') {
274
+ if (message.includes(CONFIG_FILE)) {
275
+ return 'Next: run ux-guard setup, review its findings and supporting file, and activate policy only after explicit human approval.';
276
+ }
277
+ return 'Next: run ux-guard check --help, correct the reported input, and retry.';
278
+ }
279
+ if (command === 'report') {
280
+ if (message.includes(CONFIG_FILE)) {
281
+ return 'Next: run ux-guard setup, complete human review of policy and baseline decisions, then configure reviewed journey evidence. Reporting remains unavailable until those reviews are complete.';
282
+ }
283
+ if (message.includes('journey reporting is not configured')) {
284
+ return 'Next: keep using ux-guard check, and configure reviewed journey evidence before asking for a report.';
285
+ }
286
+ return 'Next: run ux-guard report --help, correct the reported evidence or policy input, and retry.';
287
+ }
288
+ return 'Next: run ux-guard --help for the primary workflow or ux-guard help advanced for reference commands.';
289
+ }
290
+
291
+ function parseArgs(argv) {
292
+ const options = {
293
+ positional: [],
294
+ root: process.cwd(),
295
+ base: null,
296
+ typescript: null,
297
+ format: 'text',
298
+ strict: false,
299
+ acceptGrowth: false,
300
+ candidate: null,
301
+ baseline: null,
302
+ reviewer: null,
303
+ reviewedAt: null,
304
+ rationale: null,
305
+ proposal: DEFAULT_SETUP_PROPOSAL,
306
+ proposalExplicit: false,
307
+ shards: null,
308
+ visuals: null,
309
+ candidateSha: null,
310
+ project: 'chromium',
311
+ browser: 'chromium',
312
+ profile: 'Desktop Chrome',
313
+ repetitions: 3,
314
+ help: false,
315
+ };
316
+ for (let index = 0; index < argv.length; index += 1) {
317
+ const arg = argv[index];
318
+ const value = () => {
319
+ const next = argv[index + 1];
320
+ if (next === undefined || next.startsWith('--')) throw new Error(`${arg} needs a value`);
321
+ index += 1;
322
+ return next;
323
+ };
324
+ if (arg === '--root') options.root = resolve(value());
325
+ else if (arg === '--base') options.base = value();
326
+ else if (arg === '--typescript') options.typescript = value();
327
+ else if (arg === '--candidate') options.candidate = value();
328
+ else if (arg === '--baseline') options.baseline = value();
329
+ else if (arg === '--reviewer') options.reviewer = value();
330
+ else if (arg === '--reviewed-at') options.reviewedAt = value();
331
+ else if (arg === '--rationale') options.rationale = value();
332
+ else if (arg === '--proposal') {
333
+ options.proposal = value();
334
+ options.proposalExplicit = true;
335
+ }
336
+ else if (arg === '--shards') options.shards = value();
337
+ else if (arg === '--visuals') options.visuals = value();
338
+ else if (arg === '--candidate-sha') options.candidateSha = value();
339
+ else if (arg === '--project') options.project = value();
340
+ else if (arg === '--browser') options.browser = value();
341
+ else if (arg === '--profile') options.profile = value();
342
+ else if (arg === '--repetitions') {
343
+ const parsed = Number(value());
344
+ if (!Number.isSafeInteger(parsed) || parsed < 1) {
345
+ throw new Error('--repetitions must be a positive integer');
346
+ }
347
+ options.repetitions = parsed;
348
+ }
349
+ else if (arg === '--format') options.format = value();
350
+ else if (arg === '--help' || arg === '-h') options.help = true;
351
+ else if (arg === '--strict') options.strict = true;
352
+ else if (arg === '--accept-growth') options.acceptGrowth = true;
353
+ else if (arg.startsWith('--')) throw new Error(`unknown option ${arg}`);
354
+ else options.positional.push(arg);
355
+ }
356
+ if (!['text', 'json', 'markdown'].includes(options.format)) {
357
+ throw new Error('--format must be text, json, or markdown');
358
+ }
359
+ return options;
360
+ }
361
+
362
+ function run(options, io) {
363
+ const [command, sub, ...extra] = options.positional;
364
+ if (extra.length) throw new ConfigError(`unexpected argument ${extra[0]}`);
365
+ if (command === 'help') {
366
+ if (sub === 'advanced') io.out.write(ADVANCED_USAGE);
367
+ else if (sub === 'setup') io.out.write(SETUP_HELP);
368
+ else if (sub === 'check') io.out.write(CHECK_HELP);
369
+ else if (sub === 'report') io.out.write(REPORT_HELP);
370
+ else if (sub) throw new ConfigError(`unknown help topic ${sub}`);
371
+ else io.out.write(USAGE);
372
+ return 0;
373
+ }
374
+ if (options.help) {
375
+ if (!command) io.out.write(USAGE);
376
+ else if (command === 'setup') io.out.write(SETUP_HELP);
377
+ else if (command === 'check') io.out.write(CHECK_HELP);
378
+ else if (command === 'report') io.out.write(REPORT_HELP);
379
+ else io.out.write(ADVANCED_USAGE);
380
+ return 0;
381
+ }
382
+ if (command === 'setup') return setupCommand(options, io);
383
+ if (options.proposalExplicit) {
384
+ throw new ConfigError('--proposal is only valid with setup');
385
+ }
386
+ if (command === 'discover') return discoverCommand(options, io);
387
+ if (command === 'baseline') return baselineCommand(options, io);
388
+ if (command === 'visual') return visualCommand(options, io);
389
+ if (command === 'authoritative') return authoritativeCommand(options, io);
390
+ if (!['catalog', 'patterns', 'check', 'report'].includes(command)) {
391
+ throw new ConfigError(`unknown command ${command ?? '(none)'}\n${USAGE}`);
392
+ }
393
+ if ((command === 'catalog' || command === 'check' || command === 'report') && sub) {
394
+ throw new ConfigError(`unexpected argument ${sub}`);
395
+ }
396
+ if (options.typescript) {
397
+ throw new ConfigError('--typescript is only valid with discover');
398
+ }
399
+ if (options.format === 'markdown' && command !== 'report') {
400
+ throw new ConfigError('--format markdown is only valid with report or baseline inspect/diff');
401
+ }
402
+ if (options.candidate) throw new ConfigError('--candidate is only valid with discover');
403
+ if (options.baseline) throw new ConfigError('--baseline is only valid with baseline diff');
404
+ if (options.reviewer || options.reviewedAt || options.rationale) {
405
+ throw new ConfigError('approval options are only valid with baseline promote');
406
+ }
407
+ if (options.strict && command !== 'catalog' && command !== 'check') {
408
+ throw new ConfigError('--strict is only valid with catalog or check');
409
+ }
410
+ if (options.acceptGrowth && !(command === 'patterns' && sub === 'update')) {
411
+ throw new ConfigError('--accept-growth is only valid with patterns update');
412
+ }
413
+ if (
414
+ options.shards ||
415
+ options.visuals ||
416
+ options.candidateSha ||
417
+ options.project !== 'chromium' ||
418
+ options.browser !== 'chromium' ||
419
+ options.profile !== 'Desktop Chrome' ||
420
+ options.repetitions !== 3
421
+ ) {
422
+ throw new ConfigError('authoritative run options are only valid with authoritative');
423
+ }
424
+ const trust = resolveTrustedRevision(options.root, options.base);
425
+ const config = loadConfig(options.root, trust);
426
+ const ts = loadTypeScript();
427
+ switch (command) {
428
+ case 'catalog':
429
+ return catalogCommand(ts, config, trust, options, io);
430
+ case 'patterns':
431
+ return patternsCommand(sub, ts, config, trust, options, io);
432
+ case 'check':
433
+ return checkCommand(ts, config, trust, options, io);
434
+ case 'report':
435
+ return reportCommand(ts, config, trust, options, io);
436
+ }
437
+ throw new ConfigError(`unknown command ${command}`);
438
+ }
439
+
440
+ function authoritativeCommand(options, io) {
441
+ const [, sub] = options.positional;
442
+ if (sub) throw new ConfigError(`unexpected argument ${sub}`);
443
+ if (options.format !== 'json') {
444
+ throw new ConfigError('authoritative requires --format json');
445
+ }
446
+ if (
447
+ options.typescript ||
448
+ options.strict ||
449
+ options.acceptGrowth ||
450
+ options.candidate ||
451
+ options.baseline ||
452
+ options.reviewer ||
453
+ options.reviewedAt ||
454
+ options.rationale
455
+ ) {
456
+ throw new ConfigError('authoritative accepts only trusted run options');
457
+ }
458
+ try {
459
+ const bundle = createAuthoritativeAdvisory({
460
+ root: options.root,
461
+ base: options.base,
462
+ candidate: options.candidateSha,
463
+ shards: options.shards,
464
+ visuals: options.visuals,
465
+ project: options.project,
466
+ browser: options.browser,
467
+ profile: options.profile,
468
+ repetitions: options.repetitions,
469
+ });
470
+ io.out.write(`${JSON.stringify(bundle, null, 2)}\n`);
471
+ return 0;
472
+ } catch (error) {
473
+ if (error instanceof AuthoritativeUpgradeError) throw error;
474
+ if (error instanceof ConfigError) throw error;
475
+ throw new ConfigError(`authoritative advisory: ${error.message}`);
476
+ }
477
+ }
478
+
479
+ function setupCommand(options, io) {
480
+ const [, sub] = options.positional;
481
+ if (sub) throw new ConfigError(`unexpected argument ${sub}`);
482
+ if (options.base) throw new ConfigError('setup inspects the working tree; do not pass --base');
483
+ if (options.format === 'markdown') {
484
+ throw new ConfigError('--format markdown is not valid with setup; use text or json');
485
+ }
486
+ if (
487
+ options.strict ||
488
+ options.acceptGrowth ||
489
+ options.candidate ||
490
+ options.baseline ||
491
+ options.reviewer ||
492
+ options.reviewedAt ||
493
+ options.rationale ||
494
+ options.shards ||
495
+ options.visuals ||
496
+ options.candidateSha ||
497
+ options.project !== 'chromium' ||
498
+ options.browser !== 'chromium' ||
499
+ options.profile !== 'Desktop Chrome' ||
500
+ options.repetitions !== 3
501
+ ) {
502
+ throw new ConfigError('setup accepts only --root, --proposal, --format, and --typescript');
503
+ }
504
+ if (existsSync(join(options.root, CONFIG_FILE))) {
505
+ throw new ConfigError(
506
+ `${CONFIG_FILE} already exists; setup never replaces active policy. Run ux-guard check instead`,
507
+ );
508
+ }
509
+
510
+ let report;
511
+ try {
512
+ report = discoverProject(options.root, options.typescript);
513
+ } catch (error) {
514
+ if (
515
+ error instanceof ConfigError &&
516
+ [
517
+ 'discover found no tsconfig files',
518
+ 'discover found no non-test JSX or TSX source files',
519
+ ].includes(error.message)
520
+ ) {
521
+ const result = setupEvidenceGap(options.proposal, error.message);
522
+ writeSetupResult(result, options.format, io);
523
+ return 0;
524
+ }
525
+ throw error;
526
+ }
527
+
528
+ const proposal = setupProposalFromDiscovery(report);
529
+ writeCandidate(options.root, options.proposal, proposal, 'setup review file');
530
+ const result = setupResult(report, options.proposal);
531
+ writeSetupResult(result, options.format, io);
532
+ return 0;
533
+ }
534
+
535
+ function setupResult(report, proposalPath) {
536
+ const assessment = assessSetup(report);
537
+ return {
538
+ kind: 'ux-guard-setup-result',
539
+ version: 1,
540
+ command: 'setup',
541
+ status: 'review-required',
542
+ exitCode: 0,
543
+ inspected: {
544
+ status: 'complete',
545
+ uiSourceFiles: report.observed.files,
546
+ sourceRoots: report.observed.sourceRoots.map(
547
+ ({ path, productionFiles }) => ({ path, uiSourceFiles: productionFiles }),
548
+ ),
549
+ tsconfigs: report.inputs.tsconfigs,
550
+ componentLibraries: report.observed.componentLibraries.map(({ module }) => module),
551
+ iconLibraries: report.observed.iconLibraries.map(({ module }) => module),
552
+ signals: ['component use', 'control props', 'icons', 'styling', 'pattern debt'],
553
+ },
554
+ results: assessment,
555
+ proposal: {
556
+ status: 'unapproved',
557
+ path: proposalPath,
558
+ written: true,
559
+ },
560
+ safety: {
561
+ observedUsageApproved: false,
562
+ policyCreated: false,
563
+ baselineCreated: false,
564
+ waiversCreated: false,
565
+ enforcementEnabled: false,
566
+ filesWritten: [proposalPath],
567
+ },
568
+ nextAction: setupNextAction(assessment, proposalPath),
569
+ };
570
+ }
571
+
572
+ function setupEvidenceGap(proposalPath, reason) {
573
+ return {
574
+ kind: 'ux-guard-setup-result',
575
+ version: 1,
576
+ command: 'setup',
577
+ status: 'insufficient-evidence',
578
+ exitCode: 0,
579
+ inspected: {
580
+ status: 'incomplete',
581
+ uiSourceFiles: 0,
582
+ sourceRoots: [],
583
+ tsconfigs: [],
584
+ componentLibraries: [],
585
+ iconLibraries: [],
586
+ signals: [],
587
+ },
588
+ results: {
589
+ good: [],
590
+ needsAttention: [],
591
+ unknown: [
592
+ reason,
593
+ 'UX conventions, workflow coverage, and regression from main could not be evaluated.',
594
+ ],
595
+ },
596
+ proposal: {
597
+ status: 'not-created',
598
+ path: proposalPath,
599
+ written: false,
600
+ },
601
+ safety: {
602
+ observedUsageApproved: false,
603
+ policyCreated: false,
604
+ baselineCreated: false,
605
+ waiversCreated: false,
606
+ enforcementEnabled: false,
607
+ filesWritten: [],
608
+ },
609
+ nextAction: [
610
+ '1. Add or point ux-guard to a TypeScript UI project with non-test JSX or TSX source, then run ux-guard setup again.',
611
+ 'No policy, baseline, waiver, or enforcement was activated.',
612
+ ].join('\n'),
613
+ };
614
+ }
615
+
616
+ function assessSetup(report) {
617
+ const good = [`Inspected ${report.observed.files} non-test UI source files.`];
618
+ const needsAttention = [];
619
+ for (const rule of DEBT_RULES) {
620
+ const locations = Object.entries(report.observed.debt[rule])
621
+ .map(([path, count]) => ({ path, count }))
622
+ .sort((left, right) => left.path.localeCompare(right.path));
623
+ const count = locations.reduce((sum, item) => sum + item.count, 0);
624
+ if (count === 0) {
625
+ good.push(`No ${SETUP_SIGNAL_LABELS[rule]} were observed in the inspected files.`);
626
+ } else {
627
+ needsAttention.push({
628
+ signal: rule,
629
+ summary: `${count} ${SETUP_SIGNAL_LABELS[rule]} observed; review before deciding policy.`,
630
+ count,
631
+ locations,
632
+ });
633
+ }
634
+ }
635
+ const unknown = [
636
+ 'Observed conventions have not been approved as policy.',
637
+ 'No use-case catalog was inspected, so workflow coverage is unknown.',
638
+ 'No trusted baseline was used, so regression from main is unknown.',
639
+ 'Enforcement is not enabled.',
640
+ ];
641
+ for (const diagnostic of report.inputs.diagnostics) {
642
+ unknown.push(`${diagnostic.tsconfig}: ${diagnostic.message}`);
643
+ }
644
+ return { good, needsAttention, unknown };
645
+ }
646
+
647
+ function setupNextAction(assessment, reviewPath) {
648
+ const steps = [];
649
+ const missingCatalog = assessment.unknown.some((item) =>
650
+ item.startsWith('No use-case catalog was inspected'),
651
+ );
652
+ const missingBaseline = assessment.unknown.some((item) =>
653
+ item.startsWith('No trusted baseline was used'),
654
+ );
655
+ if (missingCatalog) {
656
+ steps.push(
657
+ 'Define the important user workflows and use cases. ' +
658
+ 'Agent Skill prompt: "Help me define ux-guard use cases for this repo"',
659
+ );
660
+ }
661
+ if (assessment.needsAttention.length > 0) {
662
+ const findings = plainList(
663
+ assessment.needsAttention.map(({ signal }) => SETUP_SIGNAL_LABELS[signal]),
664
+ );
665
+ steps.push(
666
+ `Review the observed styling and pattern issues (${findings}) and decide which are intentional conventions versus UX debt. ` +
667
+ `Agent Skill prompt: "Review ux-guard's observed ${findings} in this repo and help me decide which are intentional conventions versus UX debt; do not change policy or baselines"`,
668
+ );
669
+ }
670
+ const decision = missingBaseline
671
+ ? 'Decide what should become reviewed policy and prepare the initial baseline.'
672
+ : 'Decide what should become reviewed policy.';
673
+ const approval = missingBaseline
674
+ ? 'Do not activate policy or baseline until a human explicitly approves them.'
675
+ : 'Do not activate policy until a human explicitly approves it.';
676
+ const reviewPrompt = missingBaseline
677
+ ? `Help me review ${reviewPath}, decide what should become reviewed ux-guard policy, and prepare the initial baseline; do not activate anything until I explicitly approve it`
678
+ : `Help me review ${reviewPath} and decide what should become reviewed ux-guard policy; do not activate anything until I explicitly approve it`;
679
+ steps.push(
680
+ `${decision} Use ${reviewPath} as a supporting review file; it contains observed source roots, component and icon usage, pattern counts, and unresolved policy choices. ${approval} ` +
681
+ `Agent Skill prompt: "${reviewPrompt}"`,
682
+ );
683
+ steps.push(
684
+ 'After human approval and activation, run ux-guard check and ux-guard report; report will explain any remaining journey evidence gaps.',
685
+ );
686
+ return [
687
+ ...steps.map((step, index) => `${index + 1}. ${step}`),
688
+ 'No policy, baseline, waiver, or enforcement was activated.',
689
+ ].join('\n');
690
+ }
691
+
692
+ function plainList(items) {
693
+ if (items.length < 2) return items[0] ?? '';
694
+ if (items.length === 2) return `${items[0]} and ${items[1]}`;
695
+ return `${items.slice(0, -1).join(', ')}, and ${items.at(-1)}`;
696
+ }
697
+
698
+ function writeSetupResult(result, format, io) {
699
+ if (format === 'json') {
700
+ io.out.write(`${JSON.stringify(result, null, 2)}\n`);
701
+ return;
702
+ }
703
+ const lines = ['ux-guard setup', '', 'Inspected'];
704
+ if (result.inspected.status === 'complete') {
705
+ lines.push(
706
+ ` ${result.inspected.uiSourceFiles} non-test UI source files across ${result.inspected.sourceRoots.length} source roots.`,
707
+ ` TypeScript projects: ${result.inspected.tsconfigs.join(', ') || '(none)'}.`,
708
+ ` Component libraries: ${result.inspected.componentLibraries.join(', ') || '(none observed)'}.`,
709
+ ` Icon libraries: ${result.inspected.iconLibraries.join(', ') || '(none observed)'}.`,
710
+ ` Signals: ${result.inspected.signals.join(', ')}.`,
711
+ );
712
+ } else {
713
+ lines.push(' No executable UI source evidence was available.');
714
+ }
715
+ lines.push('', 'Good');
716
+ if (result.results.good.length === 0) {
717
+ lines.push(' Nothing can be confirmed from the available evidence.');
718
+ } else {
719
+ for (const item of result.results.good) lines.push(` - ${item}`);
720
+ }
721
+ lines.push('', 'Needs attention');
722
+ if (result.results.needsAttention.length === 0) {
723
+ lines.push(' No potential pattern problems were observed in the inspected files.');
724
+ } else {
725
+ for (const item of result.results.needsAttention) {
726
+ lines.push(` - ${item.summary}`);
727
+ for (const location of item.locations) {
728
+ lines.push(` ${location.path}: ${location.count}`);
729
+ }
730
+ }
731
+ }
732
+ lines.push('', 'Unknown');
733
+ for (const item of result.results.unknown) lines.push(` - ${item}`);
734
+ lines.push(
735
+ '',
736
+ 'Next steps',
737
+ ...result.nextAction.split('\n').map((line) => ` ${line}`),
738
+ );
739
+ io.out.write(`${lines.join('\n')}\n`);
740
+ }
741
+
742
+ function discoverCommand(options, io) {
743
+ if (options.base) throw new ConfigError('discover audits the working tree; do not pass --base');
744
+ if (options.strict || options.acceptGrowth) throw new ConfigError('--strict and --accept-growth are not valid with discover');
745
+ if (options.baseline || options.reviewer || options.reviewedAt || options.rationale) {
746
+ throw new ConfigError('baseline approval options are not valid with discover');
747
+ }
748
+ if (options.format === 'markdown') {
749
+ throw new ConfigError('--format markdown is only valid with report');
750
+ }
751
+ const [, sub] = options.positional;
752
+ if (!sub) {
753
+ if (options.candidate) throw new ConfigError('--candidate requires discover write-candidate or discover promote');
754
+ const report = discoverProject(options.root, options.typescript);
755
+ if (options.format === 'json') io.out.write(`${JSON.stringify({ discovery: report }, null, 2)}\n`);
756
+ else io.out.write(renderDiscovery(report));
757
+ return 0;
758
+ }
759
+ if (sub === 'write-candidate') {
760
+ if (!options.candidate) throw new ConfigError('discover write-candidate requires --candidate <path>');
761
+ const report = discoverProject(options.root, options.typescript);
762
+ const artifact = candidateFromDiscovery(report);
763
+ writeCandidate(options.root, options.candidate, artifact);
764
+ const emitted = structuredClone(report);
765
+ emitted.approval.filesWritten = true;
766
+ emitted.approval.writtenArtifacts = [options.candidate];
767
+ if (options.format === 'json') {
768
+ io.out.write(
769
+ `${JSON.stringify(
770
+ {
771
+ discovery: emitted,
772
+ lifecycle: {
773
+ action: 'write-candidate',
774
+ status: 'unapproved',
775
+ candidate: options.candidate,
776
+ },
777
+ },
778
+ null,
779
+ 2,
780
+ )}\n`,
781
+ );
782
+ } else {
783
+ io.out.write(renderDiscovery(emitted));
784
+ io.out.write(`ux-guard: wrote unapproved candidate ${options.candidate}; human review is required before promotion\n`);
785
+ }
786
+ return 0;
787
+ }
788
+ if (sub === 'promote') {
789
+ if (!options.candidate) throw new ConfigError('discover promote requires --candidate <path>');
790
+ if (options.typescript) throw new ConfigError('discover promote uses the TypeScript path in the reviewed candidate');
791
+ return promoteCandidate(options, io);
792
+ }
793
+ throw new ConfigError(`unknown discover command ${sub}`);
794
+ }
795
+
796
+ function baselineCommand(options, io) {
797
+ const [, sub] = options.positional;
798
+ if (!['propose', 'inspect', 'diff', 'promote', 'canary'].includes(sub)) {
799
+ throw new ConfigError(`unknown baseline command ${sub ?? '(none)'}`);
800
+ }
801
+ if (options.base) {
802
+ throw new ConfigError('baseline lifecycle commands use explicit artifacts; do not pass --base');
803
+ }
804
+ if (options.typescript || options.strict || options.acceptGrowth) {
805
+ throw new ConfigError('baseline commands do not accept TypeScript, strict, or growth options');
806
+ }
807
+ if (sub === 'canary') {
808
+ if (
809
+ options.candidate ||
810
+ options.baseline ||
811
+ options.reviewer ||
812
+ options.reviewedAt ||
813
+ options.rationale ||
814
+ options.format === 'markdown'
815
+ ) {
816
+ throw new ConfigError('baseline canary does not accept artifact or approval options');
817
+ }
818
+ const canaries = runJourneyComparisonCanaries();
819
+ if (options.format === 'json') {
820
+ io.out.write(
821
+ `${JSON.stringify(
822
+ {
823
+ version: 1,
824
+ command: 'baseline canary',
825
+ status: 'passed',
826
+ exitCode: 0,
827
+ canaries,
828
+ },
829
+ null,
830
+ 2,
831
+ )}\n`,
832
+ );
833
+ } else {
834
+ io.out.write(
835
+ 'ux-guard: regression, improvement, compatibility, and known-bad comparison canaries passed\n',
836
+ );
837
+ }
838
+ return 0;
839
+ }
840
+ if (!options.candidate) {
841
+ throw new ConfigError(`baseline ${sub} requires --candidate <path>`);
842
+ }
843
+ if (options.format === 'markdown' && !['inspect', 'diff'].includes(sub)) {
844
+ throw new ConfigError('--format markdown is only valid with baseline inspect or diff');
845
+ }
846
+ if (options.baseline && sub !== 'diff') {
847
+ throw new ConfigError('--baseline is only valid with baseline diff');
848
+ }
849
+ const approvalOptions = [options.reviewer, options.reviewedAt, options.rationale];
850
+ if (sub === 'promote') {
851
+ if (approvalOptions.some((value) => !value)) {
852
+ throw new ConfigError(
853
+ 'baseline promote requires --reviewer, --reviewed-at, and --rationale',
854
+ );
855
+ }
856
+ } else if (approvalOptions.some(Boolean)) {
857
+ throw new ConfigError('approval options are only valid with baseline promote');
858
+ }
859
+
860
+ const config = loadConfig(options.root, null);
861
+ if (!config.journeys?.baseline || !config.journeys?.report) {
862
+ throw new ConfigError('journey baseline and report paths are not configured');
863
+ }
864
+ if (options.candidate === config.journeys.baseline) {
865
+ throw new ConfigError('candidate path must differ from the reviewed baseline path');
866
+ }
867
+
868
+ if (sub === 'propose') {
869
+ const policy = parseJourneyPolicy(
870
+ readTrusted(options.root, config.journeys.policy, null),
871
+ );
872
+ const reportText = readTrusted(options.root, config.journeys.report, null);
873
+ const report = parseJourneyReport(reportText);
874
+ const candidate = createJourneyBaselineCandidate({
875
+ report,
876
+ policy,
877
+ reportPath: config.journeys.report,
878
+ reportSha256: sha256(reportText),
879
+ canaries: runJourneyComparisonCanaries(),
880
+ });
881
+ writeLifecycleArtifact(
882
+ options.root,
883
+ options.candidate,
884
+ serializeJourneyBaseline(candidate),
885
+ 'baseline candidate',
886
+ );
887
+ if (options.format === 'json') {
888
+ io.out.write(
889
+ `${JSON.stringify(
890
+ {
891
+ version: 1,
892
+ command: 'baseline propose',
893
+ status: 'unapproved',
894
+ exitCode: 0,
895
+ candidate: options.candidate,
896
+ canonicalHash: candidate.canonicalHash,
897
+ },
898
+ null,
899
+ 2,
900
+ )}\n`,
901
+ );
902
+ } else {
903
+ io.out.write(
904
+ `ux-guard: wrote unapproved journey baseline candidate ${options.candidate}; owner review is required before promotion\n`,
905
+ );
906
+ }
907
+ return 0;
908
+ }
909
+
910
+ const candidate = readLifecycleBaseline(
911
+ options.root,
912
+ options.candidate,
913
+ 'baseline candidate',
914
+ );
915
+ if (sub === 'inspect') {
916
+ if (options.format === 'json') io.out.write(serializeJourneyBaseline(candidate));
917
+ else io.out.write(renderJourneyBaselineMarkdown(candidate));
918
+ return 0;
919
+ }
920
+ if (sub === 'diff') {
921
+ const baselinePath = options.baseline ?? config.journeys.baseline;
922
+ let comparison;
923
+ if (!trustedFileExists(options.root, baselinePath, null)) {
924
+ comparison = unavailableJourneyComparison(
925
+ `reviewed baseline ${baselinePath} is not available`,
926
+ );
927
+ } else {
928
+ const reviewed = readLifecycleBaseline(
929
+ options.root,
930
+ baselinePath,
931
+ 'reviewed baseline',
932
+ );
933
+ if (reviewed.approval.status !== 'reviewed') {
934
+ throw new ConfigError(`${baselinePath} is not a reviewed baseline`);
935
+ }
936
+ comparison = compareJourneyBaselineEnvelopes(reviewed, candidate);
937
+ }
938
+ if (options.format === 'json') io.out.write(serializeJourneyComparison(comparison));
939
+ else io.out.write(renderJourneyComparisonMarkdown(comparison));
940
+ return 0;
941
+ }
942
+
943
+ const reviewed = promoteJourneyBaseline(candidate, {
944
+ reviewer: options.reviewer,
945
+ reviewedAt: options.reviewedAt,
946
+ rationale: options.rationale,
947
+ });
948
+ if (existsSync(join(options.root, config.journeys.baseline))) {
949
+ throw new ConfigError(
950
+ `${config.journeys.baseline} already exists; promotion never overwrites a reviewed baseline`,
951
+ );
952
+ }
953
+ writeLifecycleArtifact(
954
+ options.root,
955
+ config.journeys.baseline,
956
+ serializeJourneyBaseline(reviewed),
957
+ 'reviewed baseline',
958
+ );
959
+ if (options.format === 'json') {
960
+ io.out.write(
961
+ `${JSON.stringify(
962
+ {
963
+ version: 1,
964
+ command: 'baseline promote',
965
+ status: 'reviewed',
966
+ exitCode: 0,
967
+ source: options.candidate,
968
+ baseline: config.journeys.baseline,
969
+ canonicalHash: reviewed.canonicalHash,
970
+ reviewer: reviewed.approval.reviewer,
971
+ },
972
+ null,
973
+ 2,
974
+ )}\n`,
975
+ );
976
+ } else {
977
+ io.out.write(
978
+ `ux-guard: promoted ${options.candidate}; created reviewed baseline ${config.journeys.baseline}\n`,
979
+ );
980
+ }
981
+ return 0;
982
+ }
983
+
984
+ function visualCommand(options, io) {
985
+ const [, sub] = options.positional;
986
+ if (!['inspect', 'diff', 'promote', 'canary'].includes(sub)) {
987
+ throw new ConfigError(`unknown visual command ${sub ?? '(none)'}`);
988
+ }
989
+ if (options.base || options.typescript || options.strict || options.acceptGrowth) {
990
+ throw new ConfigError('visual lifecycle commands use explicit local artifacts');
991
+ }
992
+ if (sub === 'canary') {
993
+ if (
994
+ options.candidate ||
995
+ options.baseline ||
996
+ options.reviewer ||
997
+ options.reviewedAt ||
998
+ options.rationale ||
999
+ options.format === 'markdown'
1000
+ ) {
1001
+ throw new ConfigError('visual canary does not accept artifact or approval options');
1002
+ }
1003
+ const canaries = runVisualComparisonCanaries();
1004
+ if (options.format === 'json') {
1005
+ io.out.write(
1006
+ `${JSON.stringify(
1007
+ {
1008
+ version: 1,
1009
+ command: 'visual canary',
1010
+ status: 'passed',
1011
+ exitCode: 0,
1012
+ canaries,
1013
+ },
1014
+ null,
1015
+ 2,
1016
+ )}\n`,
1017
+ );
1018
+ } else {
1019
+ io.out.write(
1020
+ 'ux-guard: one-pixel, missing-checkpoint, profile-mismatch, and fail-closed visual canaries passed\n',
1021
+ );
1022
+ }
1023
+ return 0;
1024
+ }
1025
+ if (!options.candidate) {
1026
+ throw new ConfigError(`visual ${sub} requires --candidate <manifest>`);
1027
+ }
1028
+ if (options.format === 'markdown' && !['inspect', 'diff'].includes(sub)) {
1029
+ throw new ConfigError('--format markdown is only valid with visual inspect or diff');
1030
+ }
1031
+ if (options.baseline && sub !== 'diff') {
1032
+ throw new ConfigError('--baseline is only valid with visual diff');
1033
+ }
1034
+ const approvals = [options.reviewer, options.reviewedAt, options.rationale];
1035
+ if (sub === 'promote') {
1036
+ if (approvals.some((value) => !value)) {
1037
+ throw new ConfigError(
1038
+ 'visual promote requires --reviewer, --reviewed-at, and --rationale',
1039
+ );
1040
+ }
1041
+ } else if (approvals.some(Boolean)) {
1042
+ throw new ConfigError('approval options are only valid with visual promote');
1043
+ }
1044
+ const config = loadConfig(options.root, null);
1045
+ if (!config.visuals) throw new ConfigError('visual policy is not configured');
1046
+ const profileSet = parseVisualProfileSet(
1047
+ readTrusted(options.root, config.visuals.profiles, null),
1048
+ );
1049
+ const checkpointPolicy = parseVisualCheckpointPolicy(
1050
+ readTrusted(options.root, config.visuals.checkpoints, null),
1051
+ );
1052
+ const candidate = readLocalVisualManifest(
1053
+ options.root,
1054
+ options.candidate,
1055
+ profileSet,
1056
+ checkpointPolicy,
1057
+ );
1058
+ if (sub === 'inspect') {
1059
+ if (options.format === 'json') {
1060
+ io.out.write(`${JSON.stringify(candidate, null, 2)}\n`);
1061
+ } else {
1062
+ io.out.write(renderVisualManifestMarkdown(candidate));
1063
+ }
1064
+ return 0;
1065
+ }
1066
+ if (sub === 'diff') {
1067
+ const baselinePath = options.baseline ?? config.visuals.baseline;
1068
+ let comparison;
1069
+ if (!existsSync(join(options.root, baselinePath))) {
1070
+ comparison = unavailableVisualComparison(
1071
+ `reviewed visual baseline ${baselinePath} is not available`,
1072
+ candidate,
1073
+ );
1074
+ } else {
1075
+ const baseline = readLocalVisualManifest(
1076
+ options.root,
1077
+ baselinePath,
1078
+ profileSet,
1079
+ checkpointPolicy,
1080
+ );
1081
+ comparison = compareVisualManifests(baseline, candidate);
1082
+ }
1083
+ if (options.format === 'json') {
1084
+ io.out.write(`${JSON.stringify(comparison, null, 2)}\n`);
1085
+ } else {
1086
+ io.out.write(renderVisualComparisonMarkdown(comparison));
1087
+ }
1088
+ return 0;
1089
+ }
1090
+ const promoted = promoteVisualBundle({
1091
+ root: options.root,
1092
+ candidatePath: options.candidate,
1093
+ baselinePath: config.visuals.baseline,
1094
+ reviewer: options.reviewer,
1095
+ reviewedAt: options.reviewedAt,
1096
+ rationale: options.rationale,
1097
+ profileSet,
1098
+ checkpointPolicy,
1099
+ });
1100
+ if (options.format === 'json') {
1101
+ io.out.write(
1102
+ `${JSON.stringify(
1103
+ {
1104
+ version: 1,
1105
+ command: 'visual promote',
1106
+ status: 'reviewed',
1107
+ exitCode: 0,
1108
+ source: options.candidate,
1109
+ baseline: config.visuals.baseline,
1110
+ canonicalHash: promoted.canonicalHash,
1111
+ reviewer: promoted.approval.reviewer,
1112
+ },
1113
+ null,
1114
+ 2,
1115
+ )}\n`,
1116
+ );
1117
+ } else {
1118
+ io.out.write(
1119
+ `ux-guard: promoted ${options.candidate}; created reviewed visual baseline ${config.visuals.baseline}\n`,
1120
+ );
1121
+ }
1122
+ return 0;
1123
+ }
1124
+
1125
+ function readLocalVisualManifest(root, path, profileSet, checkpointPolicy) {
1126
+ const full = resolveRepositoryPath(root, path, 'visual manifest path');
1127
+ ensureLocalDirectory(root, dirname(full), 'visual manifest path', false);
1128
+ let stats;
1129
+ try {
1130
+ stats = lstatSync(full);
1131
+ } catch {
1132
+ throw new ConfigError(`visual manifest ${path} does not exist`);
1133
+ }
1134
+ if (stats.isSymbolicLink() || !stats.isFile()) {
1135
+ throw new ConfigError('visual manifest must be a regular file, not a symbolic link');
1136
+ }
1137
+ return parseVisualManifest(readFileSync(full, 'utf8'), {
1138
+ profileSet,
1139
+ checkpointPolicy,
1140
+ bundleRoot: dirname(full),
1141
+ requireFiles: true,
1142
+ });
1143
+ }
1144
+
1145
+ function readLifecycleBaseline(root, path, label) {
1146
+ const full = resolveRepositoryPath(root, path, `${label} path`);
1147
+ ensureLocalDirectory(root, dirname(full), `${label} path`, false);
1148
+ try {
1149
+ const stats = lstatSync(full);
1150
+ if (stats.isSymbolicLink() || !stats.isFile()) {
1151
+ throw new ConfigError(`${label} must be a regular repository file, not a symbolic link`);
1152
+ }
1153
+ return parseJourneyBaseline(readFileSync(full, 'utf8'));
1154
+ } catch (error) {
1155
+ if (error instanceof ConfigError) throw error;
1156
+ if (error?.code === 'ENOENT') throw new ConfigError(`${label} ${path} does not exist`);
1157
+ throw new ConfigError(`${label} ${path}: ${error.message}`);
1158
+ }
1159
+ }
1160
+
1161
+ function writeLifecycleArtifact(root, path, text, label) {
1162
+ const full = resolveRepositoryPath(root, path, `${label} path`);
1163
+ ensureLocalDirectory(root, dirname(full), `${label} path`, true);
1164
+ try {
1165
+ writeFileSync(full, text, { flag: 'wx', mode: 0o600 });
1166
+ } catch (error) {
1167
+ if (error?.code === 'EEXIST') {
1168
+ throw new ConfigError(`${path} already exists; refusing to overwrite it`);
1169
+ }
1170
+ throw new ConfigError(`${label} ${path} could not be written`);
1171
+ }
1172
+ }
1173
+
1174
+ function writeCandidate(root, path, artifact, label = 'candidate') {
1175
+ if (path === CONFIG_FILE) throw new ConfigError(`${label} path cannot be ${CONFIG_FILE}`);
1176
+ const full = resolveRepositoryPath(root, path, `${label} path`);
1177
+ ensureLocalDirectory(root, dirname(full), `${label} path`, true);
1178
+ try {
1179
+ writeFileSync(full, `${JSON.stringify(artifact, null, 2)}\n`, { flag: 'wx' });
1180
+ } catch (error) {
1181
+ if (error?.code === 'EEXIST') throw new ConfigError(`${label} ${path} already exists; refusing to overwrite it`);
1182
+ throw new ConfigError(`${label} ${path} could not be written`);
1183
+ }
1184
+ }
1185
+
1186
+ function promoteCandidate(options, io) {
1187
+ const artifact = readCandidate(options.root, options.candidate);
1188
+ validateCandidateApproval(artifact);
1189
+ const config = validateConfig(artifact.config);
1190
+ const baselinePath = config.patterns.baseline;
1191
+ if (existsSync(join(options.root, CONFIG_FILE))) {
1192
+ throw new ConfigError(`${CONFIG_FILE} already exists; promotion never overwrites policy`);
1193
+ }
1194
+ if (existsSync(join(options.root, baselinePath))) {
1195
+ throw new ConfigError(`${baselinePath} already exists; promotion never overwrites a baseline`);
1196
+ }
1197
+
1198
+ const ts = loadTypeScript(options.root, config);
1199
+ const catalog = validateCatalog(loadCatalog(options.root, config), loadSurfaces(ts, options.root, config));
1200
+ if (catalog.inventory === 'complete' && catalog.unmapped.length > 0) {
1201
+ throw new ConfigError('candidate policy has a complete catalog with unmapped navigation surfaces');
1202
+ }
1203
+ const scan = scanFiles(ts, options.root, config, listSourceFiles(options.root, config));
1204
+ const baseline = baselineFromScan(scan);
1205
+ writePromotedPolicy(options.root, config, baseline);
1206
+
1207
+ const result = {
1208
+ candidate: options.candidate,
1209
+ reviewer: artifact.approval.reviewer,
1210
+ files: [CONFIG_FILE, baselinePath],
1211
+ };
1212
+ if (options.format === 'json') {
1213
+ io.out.write(
1214
+ `${JSON.stringify(
1215
+ {
1216
+ version: 1,
1217
+ command: 'discover promote',
1218
+ status: 'promoted',
1219
+ exitCode: 0,
1220
+ promotion: result,
1221
+ },
1222
+ null,
1223
+ 2,
1224
+ )}\n`,
1225
+ );
1226
+ } else {
1227
+ io.out.write(`ux-guard: promoted ${options.candidate}; created ${CONFIG_FILE} and ${baselinePath}\n`);
1228
+ }
1229
+ return 0;
1230
+ }
1231
+
1232
+ function readCandidate(root, path) {
1233
+ const full = resolveRepositoryPath(root, path, 'candidate path');
1234
+ ensureLocalDirectory(root, dirname(full), 'candidate path', false);
1235
+ try {
1236
+ if (lstatSync(full).isSymbolicLink()) throw new ConfigError('candidate path cannot be a symbolic link');
1237
+ } catch (error) {
1238
+ if (error instanceof ConfigError) throw error;
1239
+ throw new ConfigError(`candidate ${path} could not be read`);
1240
+ }
1241
+ let artifact;
1242
+ try {
1243
+ artifact = JSON.parse(readFileSync(full, 'utf8'));
1244
+ } catch (error) {
1245
+ if (error instanceof SyntaxError) throw new ConfigError(`candidate ${path} is not valid JSON`);
1246
+ throw new ConfigError(`candidate ${path} could not be read`);
1247
+ }
1248
+ if (
1249
+ artifact?.version !== 1 ||
1250
+ !['ux-guard-policy-candidate', 'ux-guard-setup-proposal'].includes(artifact.kind)
1251
+ ) {
1252
+ throw new ConfigError(`candidate ${path} is not a ux-guard policy candidate`);
1253
+ }
1254
+ return artifact;
1255
+ }
1256
+
1257
+ function validateCandidateApproval(artifact) {
1258
+ const approval = artifact.approval;
1259
+ if (
1260
+ approval?.status !== 'approved' ||
1261
+ typeof approval.reviewer !== 'string' ||
1262
+ !approval.reviewer.trim() ||
1263
+ typeof approval.reviewedAt !== 'string' ||
1264
+ !approval.reviewedAt.trim() ||
1265
+ approval.patternPolicyReviewed !== true
1266
+ ) {
1267
+ throw new ConfigError(
1268
+ 'candidate is unapproved; a human must set status, reviewer, reviewedAt, and patternPolicyReviewed before promotion',
1269
+ );
1270
+ }
1271
+ }
1272
+
1273
+ function writePromotedPolicy(root, config, baseline) {
1274
+ const baselinePath = config.patterns.baseline;
1275
+ const baselineFull = join(root, baselinePath);
1276
+ const configFull = join(root, CONFIG_FILE);
1277
+ ensureLocalDirectory(root, dirname(baselineFull), 'patterns.baseline', true);
1278
+ let baselineWritten = false;
1279
+ try {
1280
+ writeFileSync(baselineFull, `${JSON.stringify(baseline, null, 2)}\n`, { flag: 'wx' });
1281
+ baselineWritten = true;
1282
+ writeFileSync(configFull, `${JSON.stringify(config, null, 2)}\n`, { flag: 'wx' });
1283
+ } catch (error) {
1284
+ if (baselineWritten) {
1285
+ try {
1286
+ unlinkSync(baselineFull);
1287
+ } catch {
1288
+ // The original write error remains the actionable failure.
1289
+ }
1290
+ }
1291
+ if (error?.code === 'EEXIST') throw new ConfigError('promotion target appeared during promotion; nothing was overwritten');
1292
+ throw new ConfigError('promoted policy could not be written');
1293
+ }
1294
+ }
1295
+
1296
+ function ensureLocalDirectory(root, directory, label, create) {
1297
+ const path = relative(root, directory);
1298
+ if (!path) return;
1299
+ let current = root;
1300
+ for (const part of path.split(sep)) {
1301
+ current = join(current, part);
1302
+ if (!existsSync(current)) {
1303
+ if (!create) throw new ConfigError(`${label} parent does not exist`);
1304
+ try {
1305
+ mkdirSync(current);
1306
+ } catch {
1307
+ throw new ConfigError(`${label} parent could not be created safely`);
1308
+ }
1309
+ }
1310
+ let stats;
1311
+ try {
1312
+ stats = lstatSync(current);
1313
+ } catch {
1314
+ throw new ConfigError(`${label} parent could not be inspected`);
1315
+ }
1316
+ if (stats.isSymbolicLink() || !stats.isDirectory()) {
1317
+ throw new ConfigError(`${label} parent must be a repository directory, not a symbolic link`);
1318
+ }
1319
+ }
1320
+ }
1321
+
1322
+ function catalogCommand(ts, config, trust, options, io) {
1323
+ const evaluation = evaluateCatalog(ts, config, trust, options);
1324
+ if (options.format === 'json') {
1325
+ io.out.write(`${JSON.stringify(resultDocument('catalog', evaluation.code, { catalog: evaluation.summary }), null, 2)}\n`);
1326
+ } else {
1327
+ io.out.write(renderCatalog(evaluation.report));
1328
+ }
1329
+ emitCatalogDiagnostics(evaluation.findings, io);
1330
+ return evaluation.code;
1331
+ }
1332
+
1333
+ function evaluateCatalog(ts, config, trust, options) {
1334
+ const report = validateCatalog(loadCatalog(options.root, config), loadSurfaces(ts, options.root, config));
1335
+ let policyInventory = report.inventory;
1336
+ if (trust) {
1337
+ policyInventory = catalogPolicy(parseYamlSubset(readTrusted(options.root, config.catalog.path, trust))).inventory;
1338
+ }
1339
+ const findings = [];
1340
+ if (policyInventory === 'complete' && report.inventory !== 'complete') {
1341
+ findings.push({
1342
+ rule: 'catalog-policy-downgrade',
1343
+ message: 'trusted catalog inventory is complete and the candidate cannot downgrade it to partial',
1344
+ });
1345
+ }
1346
+ const effectiveComplete = policyInventory === 'complete' || report.inventory === 'complete';
1347
+ if (effectiveComplete && report.unmapped.length > 0) {
1348
+ findings.push({
1349
+ rule: 'unmapped-complete-inventory',
1350
+ count: report.unmapped.length,
1351
+ message: 'a complete inventory cannot leave a navigation surface unmapped',
1352
+ });
1353
+ }
1354
+ if (options.strict && report.unmapped.length > 0) {
1355
+ findings.push({
1356
+ rule: 'unmapped-strict',
1357
+ count: report.unmapped.length,
1358
+ message: 'strict mode rejects unmapped navigation surfaces',
1359
+ });
1360
+ }
1361
+ const code = findings.length ? 1 : 0;
1362
+ return {
1363
+ code,
1364
+ findings,
1365
+ report,
1366
+ summary: summarizeCatalog(report, policyInventory, findings),
1367
+ };
1368
+ }
1369
+
1370
+ function emitCatalogDiagnostics(findings, io) {
1371
+ for (const finding of findings) io.err.write(`ux-guard: ${finding.message}\n`);
1372
+ }
1373
+
1374
+ function checkCommand(ts, config, trust, options, io) {
1375
+ const catalog = evaluateCatalog(ts, config, trust, options);
1376
+ const patterns = evaluatePatternScan(ts, config, trust, options);
1377
+ const journeyEvaluation = evaluateJourneys(config, trust, options, catalog.report);
1378
+ const visuals = evaluateVisuals(config, trust, options);
1379
+ const journeys = journeyEvaluation.summary;
1380
+ if (journeyEvaluation.policy) {
1381
+ journeys.verdicts = evaluateVerdicts(
1382
+ catalog.report,
1383
+ journeyEvaluation,
1384
+ patterns.summary,
1385
+ visuals,
1386
+ );
1387
+ }
1388
+ const code = Math.max(catalog.code, patterns.code);
1389
+ if (options.format === 'json') {
1390
+ io.out.write(
1391
+ `${JSON.stringify(
1392
+ resultDocument('check', code, {
1393
+ catalog: catalog.summary,
1394
+ patterns: patterns.summary,
1395
+ journeys,
1396
+ visuals,
1397
+ }),
1398
+ null,
1399
+ 2,
1400
+ )}\n`,
1401
+ );
1402
+ } else {
1403
+ io.out.write(renderCatalog(catalog.report));
1404
+ io.out.write(renderComparison(patterns.scan, patterns.result));
1405
+ io.out.write(renderJourneySummary(journeys));
1406
+ }
1407
+ emitCatalogDiagnostics(catalog.findings, io);
1408
+ return code;
1409
+ }
1410
+
1411
+ function reportCommand(ts, config, trust, options, io) {
1412
+ if (options.strict || options.acceptGrowth || options.candidate) {
1413
+ throw new ConfigError('report does not accept strict, growth, or candidate options');
1414
+ }
1415
+ const catalog = evaluateCatalog(ts, config, trust, { ...options, strict: false });
1416
+ const patterns = evaluatePatternScan(ts, config, trust, options);
1417
+ const journeys = evaluateJourneys(config, trust, options, catalog.report);
1418
+ const visuals = evaluateVisuals(config, trust, options);
1419
+ if (!journeys.policy) {
1420
+ throw new ConfigError('journey reporting is not configured');
1421
+ }
1422
+ const report = evaluateVerdicts(
1423
+ catalog.report,
1424
+ journeys,
1425
+ patterns.summary,
1426
+ visuals,
1427
+ );
1428
+ if (options.format === 'json') io.out.write(serializeVerdictReport(report));
1429
+ else io.out.write(renderVerdictMarkdown(report));
1430
+ return 0;
1431
+ }
1432
+
1433
+ function evaluateVerdicts(catalog, journeys, patterns, visuals) {
1434
+ try {
1435
+ return createVerdictReport({
1436
+ catalog,
1437
+ policy: journeys.policy,
1438
+ measurements: journeys.measurements,
1439
+ patterns,
1440
+ comparison: journeys.comparison,
1441
+ targets: journeys.targets,
1442
+ readinessEvidence: journeys.readinessEvidence,
1443
+ visuals,
1444
+ });
1445
+ } catch (error) {
1446
+ throw new ConfigError(`journey verdict report: ${error.message}`);
1447
+ }
1448
+ }
1449
+
1450
+ function evaluateJourneys(config, trust, options, catalog) {
1451
+ if (!config.journeys) {
1452
+ return {
1453
+ summary: {
1454
+ status: 'unconfigured',
1455
+ rollout: 'measurement-only',
1456
+ },
1457
+ policy: null,
1458
+ measurements: null,
1459
+ comparison: unavailableJourneyComparison('journey reporting is not configured'),
1460
+ targets: unavailableTargetAttainment(
1461
+ 'not-configured',
1462
+ 'owner targets are not configured',
1463
+ ),
1464
+ readinessEvidence: null,
1465
+ };
1466
+ }
1467
+
1468
+ const { policy: policyPath, report: reportPath } = config.journeys;
1469
+ let policy;
1470
+ try {
1471
+ policy = parseJourneyPolicy(readTrusted(options.root, policyPath, trust));
1472
+ } catch (error) {
1473
+ if (error instanceof ConfigError) throw error;
1474
+ throw new ConfigError(`${policyPath}: ${error.message}`);
1475
+ }
1476
+
1477
+ const reportPresent = existsSync(join(options.root, reportPath));
1478
+ let report = null;
1479
+ if (reportPresent) {
1480
+ try {
1481
+ report = parseJourneyReport(readTrusted(options.root, reportPath, null));
1482
+ } catch (error) {
1483
+ if (error instanceof ConfigError) throw error;
1484
+ throw new ConfigError(`${reportPath}: ${error.message}`);
1485
+ }
1486
+ } else {
1487
+ const identity = resolveRunIdentity(options.root, {
1488
+ policy,
1489
+ baseCommit: trust?.commit,
1490
+ browser: { name: 'none', profile: 'not-run' },
1491
+ adapters: { journey: '1' },
1492
+ });
1493
+ report = createJourneyReport([], {
1494
+ catalog,
1495
+ policy,
1496
+ run: createRunEnvelope(identity, { statuses: [] }),
1497
+ });
1498
+ }
1499
+
1500
+ let artifact;
1501
+ try {
1502
+ artifact = createJourneyArtifact({ catalog, policy, report });
1503
+ } catch (error) {
1504
+ throw new ConfigError(`journey measurement: ${error.message}`);
1505
+ }
1506
+ const comparisonEvaluation = evaluateJourneyComparison({
1507
+ config,
1508
+ trust,
1509
+ root: options.root,
1510
+ report,
1511
+ reportPresent,
1512
+ policy,
1513
+ });
1514
+ const targets = evaluateOwnerTargets(
1515
+ config,
1516
+ trust,
1517
+ options.root,
1518
+ policy,
1519
+ report,
1520
+ );
1521
+ return {
1522
+ summary: {
1523
+ status: 'measurement-only',
1524
+ policyPath,
1525
+ reportPath,
1526
+ reportPresent,
1527
+ ...artifact,
1528
+ comparison: comparisonEvaluation.comparison,
1529
+ targets,
1530
+ },
1531
+ policy,
1532
+ measurements: report,
1533
+ comparison: comparisonEvaluation.comparison,
1534
+ targets,
1535
+ readinessEvidence: comparisonEvaluation.readinessEvidence,
1536
+ };
1537
+ }
1538
+
1539
+ function evaluateJourneyComparison({
1540
+ config,
1541
+ trust,
1542
+ root,
1543
+ report,
1544
+ reportPresent,
1545
+ policy,
1546
+ }) {
1547
+ const baselinePath = config.journeys.baseline;
1548
+ if (!baselinePath) {
1549
+ return {
1550
+ comparison: unavailableJourneyComparison('reviewed journey baseline is not configured'),
1551
+ readinessEvidence: null,
1552
+ };
1553
+ }
1554
+ if (!trust) {
1555
+ return {
1556
+ comparison: unavailableJourneyComparison(
1557
+ 'reviewed journey baseline was not evaluated; pass --base with an explicit trusted revision',
1558
+ ),
1559
+ readinessEvidence: null,
1560
+ };
1561
+ }
1562
+ if (!trustedFileExists(root, baselinePath, trust)) {
1563
+ return {
1564
+ comparison: unavailableJourneyComparison(
1565
+ `reviewed journey baseline is not present at trusted revision ${trust.ref}`,
1566
+ ),
1567
+ readinessEvidence: null,
1568
+ };
1569
+ }
1570
+ if (!reportPresent) {
1571
+ return {
1572
+ comparison: unavailableJourneyComparison(
1573
+ 'current deterministic journey report is not available',
1574
+ ),
1575
+ readinessEvidence: null,
1576
+ };
1577
+ }
1578
+ let baseline;
1579
+ try {
1580
+ baseline = parseJourneyBaseline(readTrusted(root, baselinePath, trust));
1581
+ } catch (error) {
1582
+ throw new ConfigError(`${baselinePath}: ${error.message}`);
1583
+ }
1584
+ return {
1585
+ comparison: compareJourneyBaseline({
1586
+ baseline,
1587
+ report,
1588
+ policy,
1589
+ trusted: true,
1590
+ }),
1591
+ readinessEvidence: structuredClone(baseline.readinessEvidence),
1592
+ };
1593
+ }
1594
+
1595
+ function evaluateOwnerTargets(config, trust, root, policy, report) {
1596
+ const targetsPath = config.journeys.targets;
1597
+ if (!targetsPath) {
1598
+ return unavailableTargetAttainment(
1599
+ 'not-configured',
1600
+ 'owner targets are not configured',
1601
+ );
1602
+ }
1603
+ if (!trust) {
1604
+ return unavailableTargetAttainment(
1605
+ 'not-evaluated',
1606
+ 'owner targets require an explicit trusted --base revision',
1607
+ );
1608
+ }
1609
+ if (!trustedFileExists(root, targetsPath, trust)) {
1610
+ return unavailableTargetAttainment(
1611
+ 'not-configured',
1612
+ `owner targets are not present at trusted revision ${trust.ref}`,
1613
+ );
1614
+ }
1615
+ let targets;
1616
+ try {
1617
+ targets = parseOwnerTargets(readTrusted(root, targetsPath, trust));
1618
+ } catch (error) {
1619
+ throw new ConfigError(`${targetsPath}: ${error.message}`);
1620
+ }
1621
+ if (targets.approval.status !== 'reviewed') {
1622
+ return unavailableTargetAttainment(
1623
+ 'not-evaluated',
1624
+ 'owner targets at the trusted revision are not reviewed',
1625
+ targets.canonicalHash,
1626
+ );
1627
+ }
1628
+ if (targets.policy.digest !== policyDigest(policy)) {
1629
+ return unavailableTargetAttainment(
1630
+ 'incompatible',
1631
+ 'owner target policy digest differs from the trusted journey policy',
1632
+ targets.canonicalHash,
1633
+ );
1634
+ }
1635
+ return evaluateTargetAttainment({ targets, report });
1636
+ }
1637
+
1638
+ function evaluateVisuals(config, trust, options) {
1639
+ if (!config.visuals) {
1640
+ return visualSummary({
1641
+ candidatePath: null,
1642
+ baselinePath: null,
1643
+ candidate: null,
1644
+ baseline: null,
1645
+ comparison: unavailableVisualComparison('visual policy is not configured'),
1646
+ });
1647
+ }
1648
+ const { profiles, checkpoints, candidate: candidatePath, baseline: baselinePath } =
1649
+ config.visuals;
1650
+ const profileSet = parseVisualProfileSet(
1651
+ readTrusted(options.root, profiles, trust),
1652
+ );
1653
+ const checkpointPolicy = parseVisualCheckpointPolicy(
1654
+ readTrusted(options.root, checkpoints, trust),
1655
+ );
1656
+ let candidate = null;
1657
+ const candidateFull = join(options.root, candidatePath);
1658
+ if (existsSync(candidateFull)) {
1659
+ candidate = readLocalVisualManifest(
1660
+ options.root,
1661
+ candidatePath,
1662
+ profileSet,
1663
+ checkpointPolicy,
1664
+ );
1665
+ if (candidate.approval.status !== 'unapproved') {
1666
+ throw new VisualContractError('working visual candidate must remain unapproved');
1667
+ }
1668
+ }
1669
+ if (!candidate) {
1670
+ return visualSummary({
1671
+ candidatePath,
1672
+ baselinePath,
1673
+ candidate: null,
1674
+ baseline: null,
1675
+ comparison: unavailableVisualComparison(
1676
+ `visual candidate ${candidatePath} is not available`,
1677
+ ),
1678
+ });
1679
+ }
1680
+ if (!trust) {
1681
+ return visualSummary({
1682
+ candidatePath,
1683
+ baselinePath,
1684
+ candidate,
1685
+ baseline: null,
1686
+ comparison: unavailableVisualComparison(
1687
+ 'visual comparison requires an explicit trusted --base revision',
1688
+ candidate,
1689
+ ),
1690
+ });
1691
+ }
1692
+ if (!trustedFileExists(options.root, baselinePath, trust)) {
1693
+ return visualSummary({
1694
+ candidatePath,
1695
+ baselinePath,
1696
+ candidate,
1697
+ baseline: null,
1698
+ comparison: unavailableVisualComparison(
1699
+ `reviewed visual baseline is not present at trusted revision ${trust.ref}`,
1700
+ candidate,
1701
+ ),
1702
+ });
1703
+ }
1704
+ const baseline = parseVisualManifest(
1705
+ readTrusted(options.root, baselinePath, trust),
1706
+ {
1707
+ profileSet,
1708
+ checkpointPolicy,
1709
+ readImage: trustedVisualImageReader(
1710
+ options.root,
1711
+ trust,
1712
+ dirname(baselinePath),
1713
+ ),
1714
+ requireFiles: true,
1715
+ },
1716
+ );
1717
+ return visualSummary({
1718
+ candidatePath,
1719
+ baselinePath,
1720
+ candidate,
1721
+ baseline,
1722
+ comparison: compareVisualManifests(baseline, candidate),
1723
+ });
1724
+ }
1725
+
1726
+ function trustedVisualImageReader(root, trust, manifestDirectory) {
1727
+ return (imagePath) => {
1728
+ const repositoryPath = `${manifestDirectory}/${imagePath}`.replace(/^\.\//, '');
1729
+ resolveRepositoryPath(root, repositoryPath, 'trusted visual image path');
1730
+ const record = execFileSync(
1731
+ 'git',
1732
+ ['ls-tree', trust.commit, '--', repositoryPath],
1733
+ { cwd: root, encoding: 'utf8', stdio: ['ignore', 'pipe', 'pipe'] },
1734
+ ).trim();
1735
+ if (!record.startsWith('100644 blob ') || !record.endsWith(`\t${repositoryPath}`)) {
1736
+ throw new VisualContractError(
1737
+ `trusted visual image ${repositoryPath} is missing or not a regular file`,
1738
+ );
1739
+ }
1740
+ return execFileSync(
1741
+ 'git',
1742
+ ['show', `${trust.commit}:${repositoryPath}`],
1743
+ {
1744
+ cwd: root,
1745
+ encoding: 'buffer',
1746
+ stdio: ['ignore', 'pipe', 'pipe'],
1747
+ maxBuffer: 64 * 1024 * 1024,
1748
+ },
1749
+ );
1750
+ };
1751
+ }
1752
+
1753
+ function visualSummary({
1754
+ candidatePath,
1755
+ baselinePath,
1756
+ candidate,
1757
+ baseline,
1758
+ comparison,
1759
+ }) {
1760
+ return {
1761
+ rollout: 'advisory',
1762
+ status: comparison.status,
1763
+ candidate: {
1764
+ status: candidate ? 'available-unapproved' : 'unavailable',
1765
+ manifestPath: candidatePath,
1766
+ canonicalHash: candidate?.canonicalHash ?? null,
1767
+ images: candidate?.images.length ?? 0,
1768
+ repetitions: candidate?.capture.repetitions ?? 0,
1769
+ },
1770
+ baseline: {
1771
+ status: baseline ? 'reviewed' : 'not-reviewed',
1772
+ manifestPath: baselinePath,
1773
+ canonicalHash: baseline?.canonicalHash ?? null,
1774
+ },
1775
+ comparison: {
1776
+ ...comparison,
1777
+ checkpoints: comparison.checkpoints.filter(
1778
+ (checkpoint) => checkpoint.status !== 'unchanged',
1779
+ ),
1780
+ },
1781
+ };
1782
+ }
1783
+
1784
+ function renderJourneySummary(journeys) {
1785
+ if (journeys.status === 'unconfigured') {
1786
+ return 'Journey measurement: unconfigured (advisory)\n';
1787
+ }
1788
+ const { coverage } = journeys;
1789
+ const lines = [
1790
+ `Journey measurement: ${coverage.measuredVariants}/${coverage.requiredVariants} required variants measured; ${coverage.successfulVariants} successful across ${coverage.cataloguedUseCases} catalogued use cases (advisory)`,
1791
+ ` Policy: ${journeys.policyPath}`,
1792
+ ` Report: ${journeys.reportPath}${journeys.reportPresent ? '' : ' (not generated)'}`,
1793
+ ];
1794
+ if (coverage.findings.length === 0) {
1795
+ lines.push(' Lifecycle and measurement coverage: complete');
1796
+ } else {
1797
+ lines.push(' Lifecycle and measurement coverage:');
1798
+ for (const finding of coverage.findings) {
1799
+ lines.push(
1800
+ ` - ${finding.useCaseId}${finding.journeyId ? `/${finding.journeyId}` : ''}: ${finding.rule}`,
1801
+ );
1802
+ }
1803
+ }
1804
+ return `${lines.join('\n')}\n`;
1805
+ }
1806
+
1807
+ function summarizeCatalog(report, policyInventory, findings) {
1808
+ return {
1809
+ status: findings.length ? 'findings' : 'clean',
1810
+ inventory: report.inventory,
1811
+ policyInventory,
1812
+ useCases: report.useCases.map(({ id, title, tier, effect }) => ({ id, title, tier, effect })),
1813
+ surfaces: report.surfaces.length,
1814
+ unmapped: report.unmapped.map(({ id, label, route }) => ({ id, label, route })),
1815
+ findings,
1816
+ };
1817
+ }
1818
+
1819
+ function patternsCommand(sub, ts, config, trust, options, io) {
1820
+ if (!['init', 'scan', 'update', 'canary'].includes(sub)) {
1821
+ throw new ConfigError(`unknown patterns command ${sub ?? '(none)'}`);
1822
+ }
1823
+ if (trust && (sub === 'init' || sub === 'update')) {
1824
+ throw new ConfigError(`patterns ${sub} writes the working tree; do not pass --base`);
1825
+ }
1826
+ const scan = scanFiles(ts, options.root, config, listSourceFiles(options.root, config));
1827
+ const baselinePath = config.patterns.baseline;
1828
+ if (sub === 'init') {
1829
+ if (existsSync(join(options.root, baselinePath))) {
1830
+ throw new ConfigError(`${baselinePath} already exists; use patterns update`);
1831
+ }
1832
+ writeBaseline(options.root, baselinePath, baselineFromScan(scan), true);
1833
+ io.out.write(`ux-guard: created ${baselinePath}\n`);
1834
+ return 0;
1835
+ }
1836
+ const baseline = loadBaseline(options.root, baselinePath, trust);
1837
+ if (sub === 'scan') {
1838
+ const evaluation = patternEvaluation(scan, baseline);
1839
+ if (options.format === 'json') {
1840
+ io.out.write(`${JSON.stringify(resultDocument('patterns scan', evaluation.code, { patterns: evaluation.summary }), null, 2)}\n`);
1841
+ } else {
1842
+ io.out.write(renderComparison(scan, evaluation.result));
1843
+ }
1844
+ return evaluation.code;
1845
+ }
1846
+ if (sub === 'update') {
1847
+ const result = compare(scan, baseline);
1848
+ if (result.findings.length && !options.acceptGrowth) {
1849
+ io.out.write(renderComparison(scan, result));
1850
+ io.err.write('ux-guard: baseline growth requires an explicit --accept-growth\n');
1851
+ return 1;
1852
+ }
1853
+ writeBaseline(options.root, baselinePath, baselineFromScan(scan));
1854
+ io.out.write(`ux-guard: updated ${baselinePath} (${result.stale.length} stale entries removed, ${result.findings.length} accepted)\n`);
1855
+ return 0;
1856
+ }
1857
+ if (sub === 'canary') return canary(ts, config, scan, baseline, io);
1858
+ throw new ConfigError(`unknown patterns command ${sub}`);
1859
+ }
1860
+
1861
+ function evaluatePatternScan(ts, config, trust, options) {
1862
+ const scan = scanFiles(ts, options.root, config, listSourceFiles(options.root, config));
1863
+ const baseline = loadBaseline(options.root, config.patterns.baseline, trust);
1864
+ return patternEvaluation(scan, baseline);
1865
+ }
1866
+
1867
+ function patternEvaluation(scan, baseline) {
1868
+ const result = compare(scan, baseline);
1869
+ const code = result.findings.length ? 1 : 0;
1870
+ return {
1871
+ code,
1872
+ result,
1873
+ scan,
1874
+ summary: {
1875
+ status: code ? 'findings' : 'clean',
1876
+ files: scan.files.length,
1877
+ inventory: sortedInventory(scan.inventory),
1878
+ findings: result.findings,
1879
+ stale: result.stale,
1880
+ },
1881
+ };
1882
+ }
1883
+
1884
+ function sortedInventory(inventory) {
1885
+ return Object.fromEntries(
1886
+ Object.entries(inventory)
1887
+ .sort(([a], [b]) => a.localeCompare(b))
1888
+ .map(([key, counts]) => [
1889
+ key,
1890
+ Object.fromEntries(Object.entries(counts).sort(([a], [b]) => a.localeCompare(b))),
1891
+ ]),
1892
+ );
1893
+ }
1894
+
1895
+ function resultDocument(command, code, results) {
1896
+ return {
1897
+ kind: 'ux-guard-command-result',
1898
+ version: 2,
1899
+ command,
1900
+ status: code === 0 ? 'clean' : 'findings',
1901
+ exitCode: code,
1902
+ ...results,
1903
+ };
1904
+ }
1905
+
1906
+ function loadBaseline(root, path, trust) {
1907
+ let parsed;
1908
+ try {
1909
+ parsed = JSON.parse(readTrusted(root, path, trust));
1910
+ } catch (error) {
1911
+ if (error instanceof ConfigError) throw error;
1912
+ throw new ConfigError(`${path} is not valid JSON`);
1913
+ }
1914
+ return validateBaseline(parsed);
1915
+ }
1916
+
1917
+ function writeBaseline(root, path, baseline, exclusive = false) {
1918
+ const full = join(root, path);
1919
+ ensureLocalDirectory(root, dirname(full), 'patterns.baseline', true);
1920
+ if (!exclusive && existsSync(full) && lstatSync(full).isSymbolicLink()) {
1921
+ throw new ConfigError(`${path} is a symbolic link; refusing to overwrite it`);
1922
+ }
1923
+ try {
1924
+ writeFileSync(full, `${JSON.stringify(baseline, null, 2)}\n`, exclusive ? { flag: 'wx' } : undefined);
1925
+ } catch (error) {
1926
+ if (exclusive && error?.code === 'EEXIST') throw new ConfigError(`${path} already exists; use patterns update`);
1927
+ throw new ConfigError(`${path} could not be written`);
1928
+ }
1929
+ }
1930
+
1931
+ export const CANARY_FILE = '__ux-guard-canary__/KnownBad.tsx';
1932
+ export const CANARY_VALUE = 'ux-guard-canary';
1933
+
1934
+ export function canarySource(config) {
1935
+ const { components, icons } = config.patterns;
1936
+ const component = components.names[0];
1937
+ const prop = components.props[0];
1938
+ const icon = icons.modules.find((module) => !icons.allowed.includes(module));
1939
+ if (!icon) throw new ConfigError('canary needs at least one icon module that is not allowed');
1940
+ return [
1941
+ `import { ${component} } from '${components.module}';`,
1942
+ `import { Canary } from '${icon}';`,
1943
+ 'export function KnownBad() {',
1944
+ ' return (',
1945
+ ` <div style={{ width: '13px', color: '#abcdef' }}>`,
1946
+ ` <${component} ${prop}="${CANARY_VALUE}">x</${component}>`,
1947
+ ' <button type="button"><Canary /></button>',
1948
+ ' </div>',
1949
+ ' );',
1950
+ '}',
1951
+ '',
1952
+ ].join('\n');
1953
+ }
1954
+
1955
+ function canary(ts, config, scan, baseline, io) {
1956
+ const injected = scanSource(ts, CANARY_FILE, canarySource(config), config);
1957
+ const combined = structuredClone(scan);
1958
+ for (const { key, value } of injected.controls) {
1959
+ combined.inventory[key] ??= {};
1960
+ combined.inventory[key][value] = (combined.inventory[key][value] ?? 0) + 1;
1961
+ }
1962
+ for (const rule of DEBT_RULES) {
1963
+ if (injected.debt[rule] > 0) combined.debt[rule][CANARY_FILE] = injected.debt[rule];
1964
+ }
1965
+ const { findings } = compare(combined, baseline);
1966
+ const expectedKey = `${config.patterns.components.names[0]}.${config.patterns.components.props[0]}`;
1967
+ const missing = [];
1968
+ if (!findings.some((f) => f.rule === 'new-control-value' && f.key === expectedKey && f.value === CANARY_VALUE)) {
1969
+ missing.push('new-control-value');
1970
+ }
1971
+ for (const rule of DEBT_RULES) {
1972
+ if (!findings.some((f) => f.rule === rule && f.file === CANARY_FILE)) missing.push(rule);
1973
+ }
1974
+ if (missing.length) {
1975
+ io.err.write(`ux-guard: known-bad canary was not rejected for ${missing.join(', ')}\n`);
1976
+ return 1;
1977
+ }
1978
+ io.out.write('ux-guard: known-bad pattern canary was rejected by every rule\n');
1979
+ return 0;
1980
+ }