@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,463 @@
1
+ import { execFileSync } from 'node:child_process';
2
+ import { lstatSync, readFileSync } from 'node:fs';
3
+ import { dirname, join } from 'node:path';
4
+ import { resolve } from 'node:path';
5
+ import {
6
+ compareJourneyBaseline,
7
+ parseJourneyBaseline,
8
+ unavailableJourneyComparison,
9
+ } from './baselines.mjs';
10
+ import {
11
+ catalogPolicy,
12
+ loadCatalog,
13
+ loadSurfaces,
14
+ validateCatalog,
15
+ } from './catalog.mjs';
16
+ import {
17
+ loadConfig,
18
+ loadTypeScript,
19
+ readTrusted,
20
+ resolveTrustedRevision,
21
+ trustedFileExists,
22
+ } from './config.mjs';
23
+ import { parseJourneyPolicy } from './journey-policy.mjs';
24
+ import { compare, listSourceFiles, scanFiles, validateBaseline } from './patterns.mjs';
25
+ import { canonicalize, policyDigest, resolveRunIdentity } from './run-contract.mjs';
26
+ import {
27
+ aggregateJourneyShards,
28
+ JourneyShardUpgradeError,
29
+ } from './shards.mjs';
30
+ import {
31
+ evaluateTargetAttainment,
32
+ parseOwnerTargets,
33
+ unavailableTargetAttainment,
34
+ } from './targets.mjs';
35
+ import {
36
+ createVerdictReport,
37
+ renderVerdictMarkdown,
38
+ } from './verdicts.mjs';
39
+ import {
40
+ compareVisualManifests,
41
+ parseVisualCheckpointPolicy,
42
+ parseVisualManifest,
43
+ parseVisualProfileSet,
44
+ unavailableVisualComparison,
45
+ VisualContractError,
46
+ } from './visuals.mjs';
47
+ import { ConfigError, parseYamlSubset } from './yaml.mjs';
48
+
49
+ export const AUTHORITATIVE_BUNDLE_KIND = 'ux-guard-authoritative-advisory';
50
+ export const AUTHORITATIVE_BUNDLE_VERSION = 1;
51
+
52
+ export class AuthoritativeUpgradeError extends Error {
53
+ constructor(message) {
54
+ super(message);
55
+ this.name = 'AuthoritativeUpgradeError';
56
+ }
57
+ }
58
+
59
+ export function createAuthoritativeAdvisory({
60
+ root,
61
+ base,
62
+ candidate,
63
+ shards,
64
+ visuals,
65
+ project = 'chromium',
66
+ browser = 'chromium',
67
+ profile = 'Desktop Chrome',
68
+ repetitions = 3,
69
+ } = {}) {
70
+ if (!base) throw new ConfigError('authoritative advisory requires --base');
71
+ if (!candidate) throw new ConfigError('authoritative advisory requires --candidate');
72
+ if (!shards) throw new ConfigError('authoritative advisory requires --shards');
73
+ if (!Number.isSafeInteger(repetitions) || repetitions < 1) {
74
+ throw new ConfigError('authoritative advisory repetitions must be a positive integer');
75
+ }
76
+
77
+ const trust = resolveTrustedRevision(root, base);
78
+ const config = loadConfig(root, trust);
79
+ if (config.visuals && !visuals) {
80
+ throw new ConfigError('authoritative advisory requires --visuals');
81
+ }
82
+ const ts = loadTypeScript();
83
+ const candidateCatalog = validateCatalog(
84
+ loadCatalog(root, config),
85
+ loadSurfaces(ts, root, config),
86
+ );
87
+ const trustedCatalog = catalogPolicy(
88
+ parseYamlSubset(readTrusted(root, config.catalog.path, trust)),
89
+ );
90
+ const catalogFindings = evaluateCatalogBoundary(
91
+ candidateCatalog,
92
+ trustedCatalog.inventory,
93
+ );
94
+ if (catalogFindings.length) {
95
+ throw new ConfigError(
96
+ `candidate catalog violates trusted policy: ${catalogFindings
97
+ .map((finding) => finding.rule)
98
+ .join(', ')}`,
99
+ );
100
+ }
101
+
102
+ const scan = scanFiles(ts, root, config, listSourceFiles(root, config));
103
+ const patternBaseline = parsePatternBaseline(
104
+ readTrusted(root, config.patterns.baseline, trust),
105
+ config.patterns.baseline,
106
+ );
107
+ const patternComparison = compare(scan, patternBaseline);
108
+ const patternSummary = {
109
+ status: patternComparison.findings.length ? 'findings' : 'clean',
110
+ files: scan.files.length,
111
+ findings: patternComparison.findings,
112
+ stale: patternComparison.stale,
113
+ };
114
+
115
+ if (!config.journeys) {
116
+ throw new ConfigError('trusted policy does not configure journey reporting');
117
+ }
118
+ const policy = parseJourneyPolicy(
119
+ readTrusted(root, config.journeys.policy, trust),
120
+ );
121
+ const runIdentity = resolveRunIdentity(root, {
122
+ policy,
123
+ candidateCommit: candidate,
124
+ baseCommit: trust.commit,
125
+ browser: { name: browser, profile },
126
+ adapters: { playwright: '1', repetitions: String(repetitions) },
127
+ });
128
+
129
+ let measurements;
130
+ try {
131
+ measurements = aggregateJourneyShards({
132
+ directory: resolve(shards),
133
+ policy,
134
+ catalog: candidateCatalog,
135
+ runIdentity,
136
+ project,
137
+ repetitions,
138
+ artifactPath: 'candidate-evidence/journey-shards',
139
+ });
140
+ } catch (error) {
141
+ if (error instanceof JourneyShardUpgradeError) {
142
+ throw new AuthoritativeUpgradeError(error.message);
143
+ }
144
+ throw error;
145
+ }
146
+
147
+ const comparisonEvaluation = evaluateComparison({
148
+ root,
149
+ trust,
150
+ config,
151
+ policy,
152
+ report: measurements,
153
+ });
154
+ const targets = evaluateTargets({
155
+ root,
156
+ trust,
157
+ config,
158
+ policy,
159
+ report: measurements,
160
+ });
161
+ const visualSummary = config.visuals
162
+ ? evaluateVisuals({
163
+ root,
164
+ trust,
165
+ config,
166
+ candidateRoot: resolve(visuals),
167
+ })
168
+ : unconfiguredVisuals();
169
+ const readinessEvidence = {
170
+ ...(comparisonEvaluation.readinessEvidence ?? {}),
171
+ trustedExecution: true,
172
+ enforcementApproved:
173
+ comparisonEvaluation.readinessEvidence?.enforcementApproved === true,
174
+ };
175
+ const verdict = createVerdictReport({
176
+ catalog: candidateCatalog,
177
+ policy,
178
+ measurements,
179
+ patterns: patternSummary,
180
+ comparison: comparisonEvaluation.comparison,
181
+ targets,
182
+ readinessEvidence,
183
+ visuals: visualSummary,
184
+ });
185
+
186
+ return canonicalize({
187
+ kind: AUTHORITATIVE_BUNDLE_KIND,
188
+ version: AUTHORITATIVE_BUNDLE_VERSION,
189
+ authority: 'trusted-base-advisory',
190
+ rollout: 'advisory',
191
+ baseCommit: trust.commit,
192
+ candidateCommit: measurements.run.provenance.candidate.commit,
193
+ audit: {
194
+ candidateCatalog: {
195
+ inventory: candidateCatalog.inventory,
196
+ trustedInventory: trustedCatalog.inventory,
197
+ useCases: candidateCatalog.useCases.length,
198
+ surfaces: candidateCatalog.surfaces.length,
199
+ unmapped: candidateCatalog.unmapped.length,
200
+ findings: catalogFindings,
201
+ },
202
+ candidateSource: {
203
+ files: scan.files.length,
204
+ patternFindings: patternComparison.findings,
205
+ stalePatternEntries: patternComparison.stale,
206
+ },
207
+ candidateVisuals: {
208
+ manifest: visualSummary.candidate.manifestPath,
209
+ canonicalHash: visualSummary.candidate.canonicalHash,
210
+ images: visualSummary.candidate.images,
211
+ comparison: visualSummary.status,
212
+ },
213
+ },
214
+ journeys: measurements,
215
+ verdict,
216
+ markdown: renderAuthoritativeMarkdown(verdict),
217
+ });
218
+ }
219
+
220
+ function evaluateCatalogBoundary(catalog, trustedInventory) {
221
+ const findings = [];
222
+ if (trustedInventory === 'complete' && catalog.inventory !== 'complete') {
223
+ findings.push({ rule: 'catalog-policy-downgrade' });
224
+ }
225
+ if (
226
+ (trustedInventory === 'complete' || catalog.inventory === 'complete') &&
227
+ catalog.unmapped.length > 0
228
+ ) {
229
+ findings.push({
230
+ rule: 'unmapped-complete-inventory',
231
+ count: catalog.unmapped.length,
232
+ });
233
+ }
234
+ return findings;
235
+ }
236
+
237
+ function parsePatternBaseline(text, path) {
238
+ try {
239
+ return validateBaseline(JSON.parse(text));
240
+ } catch (error) {
241
+ if (error instanceof SyntaxError) {
242
+ throw new ConfigError(`${path} is not valid JSON`);
243
+ }
244
+ throw error;
245
+ }
246
+ }
247
+
248
+ function evaluateComparison({ root, trust, config, policy, report }) {
249
+ const path = config.journeys.baseline;
250
+ if (!path) {
251
+ return {
252
+ comparison: unavailableJourneyComparison(
253
+ 'reviewed journey baseline is not configured',
254
+ ),
255
+ readinessEvidence: null,
256
+ };
257
+ }
258
+ if (!trustedFileExists(root, path, trust)) {
259
+ return {
260
+ comparison: unavailableJourneyComparison(
261
+ `reviewed journey baseline is not present at trusted revision ${trust.ref}`,
262
+ ),
263
+ readinessEvidence: null,
264
+ };
265
+ }
266
+ let baseline;
267
+ try {
268
+ baseline = parseJourneyBaseline(readTrusted(root, path, trust));
269
+ } catch (error) {
270
+ throw new ConfigError(`${path}: ${error.message}`);
271
+ }
272
+ return {
273
+ comparison: compareJourneyBaseline({
274
+ baseline,
275
+ report,
276
+ policy,
277
+ trusted: true,
278
+ }),
279
+ readinessEvidence: structuredClone(baseline.readinessEvidence),
280
+ };
281
+ }
282
+
283
+ function evaluateTargets({ root, trust, config, policy, report }) {
284
+ const path = config.journeys.targets;
285
+ if (!path) {
286
+ return unavailableTargetAttainment(
287
+ 'not-configured',
288
+ 'owner targets are not configured',
289
+ );
290
+ }
291
+ if (!trustedFileExists(root, path, trust)) {
292
+ return unavailableTargetAttainment(
293
+ 'not-configured',
294
+ `owner targets are not present at trusted revision ${trust.ref}`,
295
+ );
296
+ }
297
+ let targets;
298
+ try {
299
+ targets = parseOwnerTargets(readTrusted(root, path, trust));
300
+ } catch (error) {
301
+ throw new ConfigError(`${path}: ${error.message}`);
302
+ }
303
+ if (targets.approval.status !== 'reviewed') {
304
+ return unavailableTargetAttainment(
305
+ 'not-evaluated',
306
+ 'owner targets at the trusted revision are not reviewed',
307
+ targets.canonicalHash,
308
+ );
309
+ }
310
+ if (targets.policy.digest !== policyDigest(policy)) {
311
+ return unavailableTargetAttainment(
312
+ 'incompatible',
313
+ 'owner target policy digest differs from the trusted journey policy',
314
+ targets.canonicalHash,
315
+ );
316
+ }
317
+ return evaluateTargetAttainment({ targets, report });
318
+ }
319
+
320
+ function evaluateVisuals({ root, trust, config, candidateRoot }) {
321
+ if (!config.visuals) {
322
+ throw new AuthoritativeUpgradeError(
323
+ 'trusted generation does not configure visual policy',
324
+ );
325
+ }
326
+ const profileSet = parseVisualProfileSet(
327
+ readTrusted(root, config.visuals.profiles, trust),
328
+ );
329
+ const checkpointPolicy = parseVisualCheckpointPolicy(
330
+ readTrusted(root, config.visuals.checkpoints, trust),
331
+ );
332
+ const candidatePath = join(candidateRoot, 'manifest.json');
333
+ let stats;
334
+ try {
335
+ stats = lstatSync(candidatePath);
336
+ } catch {
337
+ throw new VisualContractError('candidate visual manifest is missing');
338
+ }
339
+ if (stats.isSymbolicLink() || !stats.isFile()) {
340
+ throw new VisualContractError(
341
+ 'candidate visual manifest must be a regular file, not a symbolic link',
342
+ );
343
+ }
344
+ const candidate = parseVisualManifest(readFileSync(candidatePath, 'utf8'), {
345
+ profileSet,
346
+ checkpointPolicy,
347
+ bundleRoot: candidateRoot,
348
+ requireFiles: true,
349
+ });
350
+ if (candidate.approval.status !== 'unapproved') {
351
+ throw new VisualContractError('candidate visual manifest cannot claim approval');
352
+ }
353
+ let baseline = null;
354
+ let comparison;
355
+ if (!trustedFileExists(root, config.visuals.baseline, trust)) {
356
+ comparison = unavailableVisualComparison(
357
+ `reviewed visual baseline is not present at trusted revision ${trust.ref}`,
358
+ candidate,
359
+ );
360
+ } else {
361
+ baseline = parseVisualManifest(
362
+ readTrusted(root, config.visuals.baseline, trust),
363
+ {
364
+ profileSet,
365
+ checkpointPolicy,
366
+ readImage: trustedVisualImageReader(
367
+ root,
368
+ trust,
369
+ dirname(config.visuals.baseline),
370
+ ),
371
+ requireFiles: true,
372
+ },
373
+ );
374
+ comparison = compareVisualManifests(baseline, candidate);
375
+ if (comparison.status === 'error') {
376
+ throw new VisualContractError(comparison.reason);
377
+ }
378
+ }
379
+ return {
380
+ rollout: 'advisory',
381
+ status: comparison.status,
382
+ candidate: {
383
+ status: 'available-unapproved',
384
+ manifestPath: 'candidate-visuals/manifest.json',
385
+ canonicalHash: candidate.canonicalHash,
386
+ images: candidate.images.length,
387
+ repetitions: candidate.capture.repetitions,
388
+ },
389
+ baseline: {
390
+ status: baseline ? 'reviewed' : 'not-reviewed',
391
+ manifestPath: config.visuals.baseline,
392
+ canonicalHash: baseline?.canonicalHash ?? null,
393
+ },
394
+ comparison: {
395
+ ...comparison,
396
+ checkpoints: comparison.checkpoints.filter(
397
+ (checkpoint) => checkpoint.status !== 'unchanged',
398
+ ),
399
+ },
400
+ };
401
+ }
402
+
403
+ function unconfiguredVisuals() {
404
+ return {
405
+ rollout: 'advisory',
406
+ status: 'not-evaluated',
407
+ candidate: {
408
+ status: 'unavailable',
409
+ manifestPath: null,
410
+ canonicalHash: null,
411
+ images: 0,
412
+ repetitions: 0,
413
+ },
414
+ baseline: {
415
+ status: 'not-reviewed',
416
+ manifestPath: null,
417
+ canonicalHash: null,
418
+ },
419
+ comparison: unavailableVisualComparison('visual policy is not configured'),
420
+ };
421
+ }
422
+
423
+ function trustedVisualImageReader(root, trust, manifestDirectory) {
424
+ return (imagePath) => {
425
+ const repositoryPath = `${manifestDirectory}/${imagePath}`.replace(/^\.\//, '');
426
+ const record = execFileSync(
427
+ 'git',
428
+ ['ls-tree', trust.commit, '--', repositoryPath],
429
+ { cwd: root, encoding: 'utf8', stdio: ['ignore', 'pipe', 'pipe'] },
430
+ ).trim();
431
+ if (!record.startsWith('100644 blob ') || !record.endsWith(`\t${repositoryPath}`)) {
432
+ throw new VisualContractError(
433
+ `trusted visual image ${repositoryPath} is missing or not a regular file`,
434
+ );
435
+ }
436
+ return execFileSync(
437
+ 'git',
438
+ ['show', `${trust.commit}:${repositoryPath}`],
439
+ {
440
+ cwd: root,
441
+ encoding: 'buffer',
442
+ stdio: ['ignore', 'pipe', 'pipe'],
443
+ maxBuffer: 64 * 1024 * 1024,
444
+ },
445
+ );
446
+ };
447
+ }
448
+
449
+ function renderAuthoritativeMarkdown(verdict) {
450
+ return renderVerdictMarkdown(verdict)
451
+ .replace(
452
+ '# ux-guard advisory verdict report',
453
+ '# ux-guard trusted authoritative advisory report',
454
+ )
455
+ .replace(
456
+ '> Advisory evidence only. Journey and visual results do not change the command exit status.',
457
+ '> Authoritative regeneration used code, policy, baselines, and targets from the immutable trusted base. This remains advisory and is not a required gate.',
458
+ )
459
+ .replace(
460
+ '- **Execution trust:** Candidate ux-guard code produced this diagnostic; only pinned-base authoritative regeneration may create the authoritative advisory artifact.',
461
+ '- **Execution trust:** Trusted-base ux-guard code aggregated candidate shards and regenerated this advisory result.',
462
+ );
463
+ }