@edjbarron/ux-guard 0.6.1 → 0.7.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/lib/cli.mjs CHANGED
@@ -1,6 +1,6 @@
1
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';
2
+ import { existsSync, lstatSync, readFileSync, unlinkSync, writeFileSync } from 'node:fs';
3
+ import { dirname, join, resolve } from 'node:path';
4
4
  import {
5
5
  AuthoritativeUpgradeError,
6
6
  createAuthoritativeAdvisory,
@@ -22,6 +22,7 @@ import {
22
22
  import { catalogPolicy, loadCatalog, loadSurfaces, renderCatalog, validateCatalog } from './catalog.mjs';
23
23
  import {
24
24
  CONFIG_FILE,
25
+ ensureLocalDirectory,
25
26
  loadConfig,
26
27
  loadTypeScript,
27
28
  readTrusted,
@@ -59,6 +60,17 @@ import {
59
60
  renderVerdictMarkdown,
60
61
  serializeVerdictReport,
61
62
  } from './verdicts.mjs';
63
+ import {
64
+ createReviewAudit,
65
+ renderReviewAuditMarkdown,
66
+ } from './review-audit.mjs';
67
+ import { previewText } from './review.mjs';
68
+ import {
69
+ DEFAULT_REVIEW_PATHS,
70
+ evaluateReview,
71
+ loadReviewContext,
72
+ readRepositoryFile,
73
+ } from './review-store.mjs';
62
74
  import {
63
75
  createRunEnvelope,
64
76
  policyDigest,
@@ -84,6 +96,7 @@ import {
84
96
  VisualContractError,
85
97
  } from './visuals.mjs';
86
98
  import { ConfigError, parseYamlSubset } from './yaml.mjs';
99
+ import { REVIEW_HELP, reviewCommand, reviewErrorGuidance } from './review-command.mjs';
87
100
 
88
101
  const DEFAULT_SETUP_PROPOSAL = 'ux-guard/setup-proposal.json';
89
102
  const SETUP_SIGNAL_LABELS = {
@@ -93,16 +106,30 @@ const SETUP_SIGNAL_LABELS = {
93
106
  'raw-button': 'raw button elements',
94
107
  'icon-library': 'icon-library uses',
95
108
  };
109
+ const REVIEW_OPTIONS = {
110
+ review: '--review',
111
+ preview: '--preview',
112
+ draft: '--draft',
113
+ catalog: '--catalog',
114
+ replaceCatalogSha256: '--replace-catalog-sha256',
115
+ port: '--port',
116
+ noOpen: '--no-open',
117
+ journeyReport: '--journey-report',
118
+ visualCandidate: '--visual-candidate',
119
+ };
96
120
 
97
121
  const USAGE = `usage: ux-guard <command> [options]
98
122
 
99
123
  commands:
100
124
  setup inspect this repo and suggest reviewed next steps
125
+ review review proposed use cases in a local app
126
+ review review proposed use cases in a local app
101
127
  check compare current UI code with reviewed UX policy
102
128
  report explain UX evidence, gaps, and recommendations
103
129
 
104
130
  help:
105
131
  ux-guard setup --help
132
+ ux-guard review --help
106
133
  ux-guard check --help
107
134
  ux-guard report --help
108
135
  ux-guard help advanced
@@ -214,7 +241,7 @@ export async function main(argv, io = { out: process.stdout, err: process.stderr
214
241
  return 2;
215
242
  }
216
243
  try {
217
- return run(options, io);
244
+ return await run(options, io);
218
245
  } catch (error) {
219
246
  if (error instanceof AuthoritativeUpgradeError) {
220
247
  io.err.write(`ux-guard: upgrade required: ${error.message}\n`);
@@ -234,7 +261,7 @@ export async function main(argv, io = { out: process.stdout, err: process.stderr
234
261
  }
235
262
 
236
263
  function writeCliError(error, argv, io) {
237
- const command = ['setup', 'check', 'report'].find((name) => argv.includes(name));
264
+ const command = ['setup', 'review', 'check', 'report'].find((name) => argv.includes(name));
238
265
  const guidance = errorGuidance(command, error.message);
239
266
  if (
240
267
  command === 'setup' &&
@@ -270,6 +297,7 @@ function errorGuidance(command, message) {
270
297
  }
271
298
  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
299
  }
300
+ if (command === 'review') return reviewErrorGuidance(message);
273
301
  if (command === 'check') {
274
302
  if (message.includes(CONFIG_FILE)) {
275
303
  return 'Next: run ux-guard setup, review its findings and supporting file, and activate policy only after explicit human approval.';
@@ -311,6 +339,15 @@ function parseArgs(argv) {
311
339
  browser: 'chromium',
312
340
  profile: 'Desktop Chrome',
313
341
  repetitions: 3,
342
+ review: null,
343
+ preview: null,
344
+ draft: null,
345
+ catalog: null,
346
+ replaceCatalogSha256: null,
347
+ port: null,
348
+ noOpen: false,
349
+ journeyReport: null,
350
+ visualCandidate: null,
314
351
  help: false,
315
352
  };
316
353
  for (let index = 0; index < argv.length; index += 1) {
@@ -346,6 +383,20 @@ function parseArgs(argv) {
346
383
  }
347
384
  options.repetitions = parsed;
348
385
  }
386
+ else if (arg === '--review') options.review = value();
387
+ else if (arg === '--preview') options.preview = value();
388
+ else if (arg === '--draft') options.draft = value();
389
+ else if (arg === '--catalog') options.catalog = value();
390
+ else if (arg === '--replace-catalog-sha256') options.replaceCatalogSha256 = value();
391
+ else if (arg === '--port') {
392
+ const text = value();
393
+ const parsed = Number(text);
394
+ if (!/^\d+$/.test(text) || parsed > 65535) throw new Error('--port must be an integer from 0 to 65535');
395
+ options.port = parsed;
396
+ }
397
+ else if (arg === '--no-open') options.noOpen = true;
398
+ else if (arg === '--journey-report') options.journeyReport = value();
399
+ else if (arg === '--visual-candidate') options.visualCandidate = value();
349
400
  else if (arg === '--format') options.format = value();
350
401
  else if (arg === '--help' || arg === '-h') options.help = true;
351
402
  else if (arg === '--strict') options.strict = true;
@@ -367,6 +418,7 @@ function run(options, io) {
367
418
  else if (sub === 'setup') io.out.write(SETUP_HELP);
368
419
  else if (sub === 'check') io.out.write(CHECK_HELP);
369
420
  else if (sub === 'report') io.out.write(REPORT_HELP);
421
+ else if (sub === 'review') io.out.write(REVIEW_HELP);
370
422
  else if (sub) throw new ConfigError(`unknown help topic ${sub}`);
371
423
  else io.out.write(USAGE);
372
424
  return 0;
@@ -374,15 +426,22 @@ function run(options, io) {
374
426
  if (options.help) {
375
427
  if (!command) io.out.write(USAGE);
376
428
  else if (command === 'setup') io.out.write(SETUP_HELP);
429
+ else if (command === 'review') io.out.write(REVIEW_HELP);
377
430
  else if (command === 'check') io.out.write(CHECK_HELP);
378
431
  else if (command === 'report') io.out.write(REPORT_HELP);
379
432
  else io.out.write(ADVANCED_USAGE);
380
433
  return 0;
381
434
  }
435
+ if (command !== 'review') {
436
+ const option = Object.keys(REVIEW_OPTIONS).find((name) => options[name] !== null && options[name] !== false);
437
+ if (option) throw new ConfigError(`${REVIEW_OPTIONS[option]} is only valid with review`);
438
+ }
382
439
  if (command === 'setup') return setupCommand(options, io);
383
440
  if (options.proposalExplicit) {
384
441
  throw new ConfigError('--proposal is only valid with setup');
385
442
  }
443
+ if (command === 'review' && sub === 'audit') return reviewAuditCommand(options, io);
444
+ if (command === 'review') return reviewCommand(options, io);
386
445
  if (command === 'discover') return discoverCommand(options, io);
387
446
  if (command === 'baseline') return baselineCommand(options, io);
388
447
  if (command === 'visual') return visualCommand(options, io);
@@ -399,6 +458,12 @@ function run(options, io) {
399
458
  if (options.format === 'markdown' && command !== 'report') {
400
459
  throw new ConfigError('--format markdown is only valid with report or baseline inspect/diff');
401
460
  }
461
+ if (options.journeyReport) {
462
+ throw new ConfigError('--journey-report is only valid with review audit');
463
+ }
464
+ if (options.visualCandidate) {
465
+ throw new ConfigError('--visual-candidate is only valid with review audit');
466
+ }
402
467
  if (options.candidate) throw new ConfigError('--candidate is only valid with discover');
403
468
  if (options.baseline) throw new ConfigError('--baseline is only valid with baseline diff');
404
469
  if (options.reviewer || options.reviewedAt || options.rationale) {
@@ -476,6 +541,148 @@ function authoritativeCommand(options, io) {
476
541
  }
477
542
  }
478
543
 
544
+ function reviewAuditCommand(options, io) {
545
+ const [, sub, extra] = options.positional;
546
+ if (sub !== 'audit' || extra) {
547
+ throw new ConfigError(`unexpected argument ${extra ?? sub ?? '(none)'}`);
548
+ }
549
+ if (!options.base) {
550
+ throw new ConfigError('review audit requires --base with an explicit trusted revision');
551
+ }
552
+ if (!['json', 'markdown'].includes(options.format)) {
553
+ throw new ConfigError('review audit requires --format json or markdown');
554
+ }
555
+ if (
556
+ options.strict ||
557
+ options.acceptGrowth ||
558
+ options.typescript ||
559
+ options.draft ||
560
+ options.catalog ||
561
+ options.replaceCatalogSha256 ||
562
+ options.port !== null ||
563
+ options.noOpen ||
564
+ options.baseline ||
565
+ options.reviewer ||
566
+ options.reviewedAt ||
567
+ options.rationale ||
568
+ options.shards ||
569
+ options.visuals ||
570
+ options.candidateSha ||
571
+ options.project !== 'chromium' ||
572
+ options.browser !== 'chromium' ||
573
+ options.profile !== 'Desktop Chrome' ||
574
+ options.repetitions !== 3
575
+ ) {
576
+ throw new ConfigError('review audit accepts only review paths, --base, evidence paths, and output format');
577
+ }
578
+
579
+ const paths = {
580
+ candidatePath: options.candidate ?? DEFAULT_REVIEW_PATHS.candidate,
581
+ reviewPath: options.review ?? DEFAULT_REVIEW_PATHS.review,
582
+ previewPath: options.preview ?? DEFAULT_REVIEW_PATHS.preview,
583
+ explicitCandidate: options.candidate !== null,
584
+ };
585
+ const context = loadReviewContext(options.root, paths);
586
+ if (context.status === 'no-candidate') {
587
+ throw new ConfigError(`candidate ${paths.candidatePath} does not exist`);
588
+ }
589
+ if (context.reviewSha256 === null) {
590
+ throw new ConfigError('review audit requires a saved review; saving remains a user action');
591
+ }
592
+ const state = evaluateReview(context);
593
+ const previewFile = readRepositoryFile(options.root, context.previewPath, 'preview');
594
+ const expectedPreview = previewText(state);
595
+ if (!previewFile || expectedPreview === null || previewFile.text !== expectedPreview) {
596
+ throw new ConfigError(
597
+ `${context.previewPath} does not exactly match the saved review; do not audit or adopt it until the reviewer saves a current preview`,
598
+ );
599
+ }
600
+
601
+ const trust = resolveTrustedRevision(options.root, options.base);
602
+ const config = loadConfig(options.root, trust);
603
+ if (state.catalog.path !== config.catalog.path) {
604
+ throw new ConfigError(
605
+ `saved preview targets ${state.catalog.path}, but trusted policy uses ${config.catalog.path}; a candidate configuration cannot redefine the audit judge`,
606
+ );
607
+ }
608
+ const ts = loadTypeScript();
609
+ const surfaces = loadSurfaces(ts, options.root, config);
610
+ const trustedCatalogText = readTrusted(options.root, config.catalog.path, trust);
611
+ if (state.catalog.activeSha256 !== sha256(trustedCatalogText)) {
612
+ throw new ConfigError(
613
+ `${config.catalog.path} differs from trusted base ${trust.ref}; keep the active reviewed catalog unchanged and assess catalog changes through the unapproved preview`,
614
+ );
615
+ }
616
+ const trustedCatalogDocument = parseYamlSubset(trustedCatalogText);
617
+ const trustedPolicy = catalogPolicy(trustedCatalogDocument);
618
+ const activeCatalog = evaluateCatalogReport(
619
+ validateCatalog(trustedCatalogDocument, surfaces),
620
+ trustedPolicy.inventory,
621
+ false,
622
+ );
623
+ const previewReport = validateCatalog(parseYamlSubset(state.catalog.text), surfaces);
624
+ const previewCatalog = evaluateCatalogReport(
625
+ previewReport,
626
+ trustedPolicy.inventory,
627
+ false,
628
+ );
629
+ const patterns = evaluatePatternScan(ts, config, trust, options);
630
+ const journeys = evaluateJourneys(
631
+ config,
632
+ trust,
633
+ {
634
+ ...options,
635
+ auditEvidence: true,
636
+ },
637
+ previewReport,
638
+ );
639
+
640
+ let visuals = {
641
+ rollout: 'advisory',
642
+ status: 'not-evaluated',
643
+ reason: 'No explicit current visual candidate was supplied to review audit.',
644
+ };
645
+ if (options.visualCandidate) {
646
+ try {
647
+ visuals = evaluateVisuals(config, trust, options);
648
+ } catch (error) {
649
+ if (!(error instanceof VisualContractError)) throw error;
650
+ visuals = {
651
+ rollout: 'advisory',
652
+ status: 'not-evaluated',
653
+ reason: error.message,
654
+ };
655
+ }
656
+ }
657
+ const verdict =
658
+ journeys.summary.evidence.status === 'compatible'
659
+ ? evaluateVerdicts(
660
+ previewReport,
661
+ journeys,
662
+ patterns.summary,
663
+ visuals.status === 'not-evaluated' ? undefined : visuals,
664
+ )
665
+ : null;
666
+ const audit = createReviewAudit({
667
+ context,
668
+ state,
669
+ trust,
670
+ previewFile,
671
+ activeCatalog,
672
+ previewCatalog,
673
+ patterns,
674
+ journeys,
675
+ visuals,
676
+ verdict,
677
+ });
678
+ if (options.format === 'json') {
679
+ io.out.write(`${JSON.stringify(audit, null, 2)}\n`);
680
+ } else {
681
+ io.out.write(renderReviewAuditMarkdown(audit));
682
+ }
683
+ return 0;
684
+ }
685
+
479
686
  function setupCommand(options, io) {
480
687
  const [, sub] = options.positional;
481
688
  if (sub) throw new ConfigError(`unexpected argument ${sub}`);
@@ -681,7 +888,7 @@ function setupNextAction(assessment, reviewPath) {
681
888
  `Agent Skill prompt: "${reviewPrompt}"`,
682
889
  );
683
890
  steps.push(
684
- 'After human approval and activation, run ux-guard check and ux-guard report; report will explain any remaining journey evidence gaps.',
891
+ 'After human approval and activation, run ux-guard check. Run ux-guard report after reviewed journey policy and a journey report path are configured.',
685
892
  );
686
893
  return [
687
894
  ...steps.map((step, index) => `${index + 1}. ${step}`),
@@ -1293,32 +1500,6 @@ function writePromotedPolicy(root, config, baseline) {
1293
1500
  }
1294
1501
  }
1295
1502
 
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
1503
  function catalogCommand(ts, config, trust, options, io) {
1323
1504
  const evaluation = evaluateCatalog(ts, config, trust, options);
1324
1505
  if (options.format === 'json') {
@@ -1336,6 +1517,10 @@ function evaluateCatalog(ts, config, trust, options) {
1336
1517
  if (trust) {
1337
1518
  policyInventory = catalogPolicy(parseYamlSubset(readTrusted(options.root, config.catalog.path, trust))).inventory;
1338
1519
  }
1520
+ return evaluateCatalogReport(report, policyInventory, options.strict);
1521
+ }
1522
+
1523
+ function evaluateCatalogReport(report, policyInventory, strict) {
1339
1524
  const findings = [];
1340
1525
  if (policyInventory === 'complete' && report.inventory !== 'complete') {
1341
1526
  findings.push({
@@ -1351,7 +1536,7 @@ function evaluateCatalog(ts, config, trust, options) {
1351
1536
  message: 'a complete inventory cannot leave a navigation surface unmapped',
1352
1537
  });
1353
1538
  }
1354
- if (options.strict && report.unmapped.length > 0) {
1539
+ if (strict && report.unmapped.length > 0) {
1355
1540
  findings.push({
1356
1541
  rule: 'unmapped-strict',
1357
1542
  count: report.unmapped.length,
@@ -1449,10 +1634,20 @@ function evaluateVerdicts(catalog, journeys, patterns, visuals) {
1449
1634
 
1450
1635
  function evaluateJourneys(config, trust, options, catalog) {
1451
1636
  if (!config.journeys) {
1637
+ if (options.journeyReport) {
1638
+ throw new ConfigError('--journey-report cannot be used because journey reporting is not configured');
1639
+ }
1452
1640
  return {
1453
1641
  summary: {
1454
1642
  status: 'unconfigured',
1455
1643
  rollout: 'measurement-only',
1644
+ evidence: {
1645
+ path: null,
1646
+ sha256: null,
1647
+ present: false,
1648
+ status: 'unconfigured',
1649
+ reason: 'Journey reporting is not configured.',
1650
+ },
1456
1651
  },
1457
1652
  policy: null,
1458
1653
  measurements: null,
@@ -1465,7 +1660,8 @@ function evaluateJourneys(config, trust, options, catalog) {
1465
1660
  };
1466
1661
  }
1467
1662
 
1468
- const { policy: policyPath, report: reportPath } = config.journeys;
1663
+ const policyPath = config.journeys.policy;
1664
+ const reportPath = options.journeyReport ?? config.journeys.report;
1469
1665
  let policy;
1470
1666
  try {
1471
1667
  policy = parseJourneyPolicy(readTrusted(options.root, policyPath, trust));
@@ -1474,16 +1670,24 @@ function evaluateJourneys(config, trust, options, catalog) {
1474
1670
  throw new ConfigError(`${policyPath}: ${error.message}`);
1475
1671
  }
1476
1672
 
1477
- const reportPresent = existsSync(join(options.root, reportPath));
1673
+ const reportPresent = trustedFileExists(options.root, reportPath, null);
1478
1674
  let report = null;
1675
+ let reportSha256 = null;
1676
+ let evidenceError = null;
1479
1677
  if (reportPresent) {
1678
+ const reportText = readTrusted(options.root, reportPath, null);
1679
+ reportSha256 = sha256(reportText);
1480
1680
  try {
1481
- report = parseJourneyReport(readTrusted(options.root, reportPath, null));
1681
+ report = parseJourneyReport(reportText);
1482
1682
  } catch (error) {
1483
1683
  if (error instanceof ConfigError) throw error;
1484
- throw new ConfigError(`${reportPath}: ${error.message}`);
1684
+ if (!options.auditEvidence) {
1685
+ throw new ConfigError(`${reportPath}: ${error.message}`);
1686
+ }
1687
+ evidenceError = error;
1485
1688
  }
1486
- } else {
1689
+ }
1690
+ if (!report) {
1487
1691
  const identity = resolveRunIdentity(options.root, {
1488
1692
  policy,
1489
1693
  baseCommit: trust?.commit,
@@ -1503,14 +1707,31 @@ function evaluateJourneys(config, trust, options, catalog) {
1503
1707
  } catch (error) {
1504
1708
  throw new ConfigError(`journey measurement: ${error.message}`);
1505
1709
  }
1506
- const comparisonEvaluation = evaluateJourneyComparison({
1507
- config,
1508
- trust,
1509
- root: options.root,
1510
- report,
1511
- reportPresent,
1512
- policy,
1513
- });
1710
+ const evidenceStatus = evidenceError
1711
+ ? evidenceCompatibilityStatus(evidenceError)
1712
+ : reportPresent
1713
+ ? 'compatible'
1714
+ : 'missing';
1715
+ const evidenceReason = evidenceError
1716
+ ? evidenceError.message
1717
+ : reportPresent
1718
+ ? 'The journey report is compatible with this ux-guard version and trusted policy.'
1719
+ : `Journey evidence ${reportPath} is not available.`;
1720
+ const comparisonEvaluation = evidenceError
1721
+ ? {
1722
+ comparison: unavailableJourneyComparison(
1723
+ `current journey evidence is ${evidenceStatus}: ${evidenceReason}`,
1724
+ ),
1725
+ readinessEvidence: null,
1726
+ }
1727
+ : evaluateJourneyComparison({
1728
+ config,
1729
+ trust,
1730
+ root: options.root,
1731
+ report,
1732
+ reportPresent,
1733
+ policy,
1734
+ });
1514
1735
  const targets = evaluateOwnerTargets(
1515
1736
  config,
1516
1737
  trust,
@@ -1524,6 +1745,13 @@ function evaluateJourneys(config, trust, options, catalog) {
1524
1745
  policyPath,
1525
1746
  reportPath,
1526
1747
  reportPresent,
1748
+ evidence: {
1749
+ path: reportPath,
1750
+ sha256: reportSha256,
1751
+ present: reportPresent,
1752
+ status: evidenceStatus,
1753
+ reason: evidenceReason,
1754
+ },
1527
1755
  ...artifact,
1528
1756
  comparison: comparisonEvaluation.comparison,
1529
1757
  targets,
@@ -1536,6 +1764,19 @@ function evaluateJourneys(config, trust, options, catalog) {
1536
1764
  };
1537
1765
  }
1538
1766
 
1767
+ function evidenceCompatibilityStatus(error) {
1768
+ const message = error.message.toLowerCase();
1769
+ return [
1770
+ 'version',
1771
+ 'not this ux-guard version',
1772
+ 'policy digest',
1773
+ 'profile differs',
1774
+ 'adapter',
1775
+ ].some((signal) => message.includes(signal))
1776
+ ? 'incompatible'
1777
+ : 'invalid';
1778
+ }
1779
+
1539
1780
  function evaluateJourneyComparison({
1540
1781
  config,
1541
1782
  trust,
@@ -1645,8 +1886,9 @@ function evaluateVisuals(config, trust, options) {
1645
1886
  comparison: unavailableVisualComparison('visual policy is not configured'),
1646
1887
  });
1647
1888
  }
1648
- const { profiles, checkpoints, candidate: candidatePath, baseline: baselinePath } =
1889
+ const { profiles, checkpoints, baseline: baselinePath } =
1649
1890
  config.visuals;
1891
+ const candidatePath = options.visualCandidate ?? config.visuals.candidate;
1650
1892
  const profileSet = parseVisualProfileSet(
1651
1893
  readTrusted(options.root, profiles, trust),
1652
1894
  );
package/lib/config.mjs CHANGED
@@ -1,5 +1,5 @@
1
1
  import { execFileSync } from 'node:child_process';
2
- import { existsSync, readFileSync, realpathSync } from 'node:fs';
2
+ import { existsSync, lstatSync, mkdirSync, readFileSync, realpathSync } from 'node:fs';
3
3
  import { createRequire } from 'node:module';
4
4
  import { isAbsolute, join, relative, resolve, sep } from 'node:path';
5
5
  import { ConfigError } from './yaml.mjs';
@@ -169,6 +169,13 @@ export function resolveRepositoryPath(root, path, label, allowDot = false) {
169
169
  return resolve(root, path);
170
170
  }
171
171
 
172
+ export function assertRepositoryRelativePath(path, label) {
173
+ assertPolicyPath(path, label, (message) => {
174
+ throw new ConfigError(message);
175
+ });
176
+ return path;
177
+ }
178
+
172
179
  export function resolveExistingRepositoryPath(root, path, label, allowDot = false) {
173
180
  const full = resolveRepositoryPath(root, path, label, allowDot);
174
181
  let realRoot;
@@ -186,6 +193,34 @@ export function resolveExistingRepositoryPath(root, path, label, allowDot = fals
186
193
  return full;
187
194
  }
188
195
 
196
+ // ensureLocalDirectory walks every parent below root so a write cannot follow
197
+ // a symbolic link out of the repository.
198
+ export function ensureLocalDirectory(root, directory, label, create) {
199
+ const path = relative(root, directory);
200
+ if (!path) return;
201
+ let current = root;
202
+ for (const part of path.split(sep)) {
203
+ current = join(current, part);
204
+ if (!existsSync(current)) {
205
+ if (!create) throw new ConfigError(`${label} parent does not exist`);
206
+ try {
207
+ mkdirSync(current);
208
+ } catch {
209
+ throw new ConfigError(`${label} parent could not be created safely`);
210
+ }
211
+ }
212
+ let stats;
213
+ try {
214
+ stats = lstatSync(current);
215
+ } catch {
216
+ throw new ConfigError(`${label} parent could not be inspected`);
217
+ }
218
+ if (stats.isSymbolicLink() || !stats.isDirectory()) {
219
+ throw new ConfigError(`${label} parent must be a repository directory, not a symbolic link`);
220
+ }
221
+ }
222
+ }
223
+
189
224
  function assertPolicyPath(value, label, fail, allowDot = false) {
190
225
  if (typeof value !== 'string' || !value || value.includes('\0')) fail(`${label} must be a repository-relative path`);
191
226
  if (isAbsolute(value) || /^[a-z]:[\\/]/i.test(value) || value.startsWith('\\\\')) {