@vaultcompass/conductor 0.8.0 → 0.8.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.
@@ -41,11 +41,16 @@ export type ContractSource =
41
41
  kind: 'native';
42
42
  path: string;
43
43
  }
44
- /** A spec imported and frozen for this run only. Repository-relative paths. */
44
+ /**
45
+ * A spec imported and frozen for this run only. Repository-relative paths.
46
+ * `ref` is set on a run with a trust base: the spec and plan were read from
47
+ * that ref, never from the tree being judged.
48
+ */
45
49
  | {
46
50
  kind: 'imported';
47
51
  spec: string;
48
52
  plan: string | null;
53
+ ref?: string;
49
54
  } | {
50
55
  kind: 'none';
51
56
  };
@@ -54,13 +59,32 @@ export interface IntentPreparation {
54
59
  /** The ref the change set was measured against, or null for a staged run. */
55
60
  baseRef: string | null;
56
61
  /** Whether that ref was asked for or inferred from the CI environment. */
57
- baseSource: 'flag' | 'github' | null;
62
+ baseSource: 'flag' | 'github' | 'trust-base' | null;
58
63
  /** What to hand the gate as --project: "." or an absolute temporary path. */
59
64
  projectDir: string;
60
65
  /** The changed paths, or null to leave v0.1's staged behaviour alone. */
61
66
  paths: string[] | null;
62
67
  /** Removes anything written outside the repository. Safe to call twice. */
63
68
  cleanup: () => void;
69
+ /**
70
+ * On a run with a trust base: intent control files this pull request adds
71
+ * or changes that did not decide this run, one line each. Reported as
72
+ * proposals, never acted on.
73
+ */
74
+ proposals?: string[];
75
+ /**
76
+ * One plain sentence the report prints under the contract line, for an
77
+ * input the person gave that this run did not use: --spec, when the base's
78
+ * frozen contract outranks it.
79
+ */
80
+ note?: string;
81
+ /**
82
+ * Why `paths` cannot be handed over as one --paths value (pathsFlagRefusal
83
+ * in intent-base.ts), on a native contract. The runner then uses the
84
+ * gate's own --base where the gate has it, and refuses with this reason
85
+ * where it does not.
86
+ */
87
+ pathsRefusal?: string;
64
88
  }
65
89
  /** Which link of the chain broke. Carried into the report verbatim. */
66
90
  export type PrepareStep = 'spec' | 'base'
@@ -90,6 +114,8 @@ export type IntentPrepareResult = {
90
114
  kind: 'skip';
91
115
  reason: 'no-contract' | 'contract-waived';
92
116
  detail: string;
117
+ /** As on IntentPreparation: what this pull request proposes. */
118
+ proposals?: string[];
93
119
  } | {
94
120
  kind: 'failed';
95
121
  step: PrepareStep;
@@ -102,6 +128,11 @@ export interface IntentPrepareOptions {
102
128
  env: NodeJS.ProcessEnv;
103
129
  base?: string;
104
130
  spec?: string;
131
+ /**
132
+ * The trust base, on a pull-request run. The change set is measured from
133
+ * it when no --base and no GITHUB_BASE_REF names another base.
134
+ */
135
+ trustBase?: string;
105
136
  timeoutMs?: number;
106
137
  /**
107
138
  * The directory the per-run temporary project is created under.
@@ -34,9 +34,11 @@ import { existsSync, lstatSync, mkdirSync, mkdtempSync, readFileSync, rmSync, st
34
34
  import os from 'node:os';
35
35
  import path from 'node:path';
36
36
  import { parse as parseYaml } from 'yaml';
37
- import { changedPathsSince, currentBranch, resolveBaseRefInRepo } from './intent-base.js';
37
+ import { gitComplaint, runGit } from './git.js';
38
+ import { changedPathsSince, currentBranch, orderForPathsFlag, pathsFlagRefusal, resolveBaseRefInRepo, } from './intent-base.js';
38
39
  import { summariseStderr } from './normalize.js';
39
- import { SPEC_DIR, discoverSpec, prBodyFromEvent } from './intent-spec.js';
40
+ import { PLAN_DIR, SPEC_DIR, SPEC_WAIVER_TOKEN, bestMatch, branchSlug, discoverSpec, normalizeStem, prBodyFromEvent, specFromPrBody, } from './intent-spec.js';
41
+ import { readFileAtRef, unreadableBaseRemedy } from './trust-base.js';
40
42
  /** Prefix of the per-run directory, exported so a test can count leaks. */
41
43
  export const TEMP_PREFIX = 'conductor-intent-';
42
44
  /**
@@ -93,9 +95,20 @@ export function isLegacyContractPath(contractPath) {
93
95
  * down the import path rather than handing the gate something it will reject.
94
96
  */
95
97
  function contractIsFrozenAt(absolutePath) {
98
+ let text;
99
+ try {
100
+ text = readFileSync(absolutePath, 'utf8');
101
+ }
102
+ catch {
103
+ return false;
104
+ }
105
+ return contractTextIsFrozen(text);
106
+ }
107
+ /** The same judgment as `contractIsFrozenAt`, on text already read (from a ref). */
108
+ function contractTextIsFrozen(text) {
96
109
  let parsed;
97
110
  try {
98
- parsed = parseYaml(readFileSync(absolutePath, 'utf8'));
111
+ parsed = parseYaml(text);
99
112
  }
100
113
  catch {
101
114
  return false;
@@ -295,21 +308,20 @@ function complaint(result) {
295
308
  }
296
309
  /** The short commit the contract is attributed to, or a placeholder. */
297
310
  function shortHead(repoRoot) {
298
- const child = spawnSync('git', ['rev-parse', '--short', 'HEAD'], {
299
- cwd: repoRoot,
300
- encoding: 'utf8',
301
- });
302
- const value = (child.stdout ?? '').trim();
311
+ const child = runGit(repoRoot, ['rev-parse', '--short', 'HEAD']);
312
+ const value = child.stdout.trim();
303
313
  return child.status === 0 && value !== '' ? value : 'an unknown commit';
304
314
  }
305
315
  export function prepareIntent(options) {
316
+ if (options.trustBase !== undefined) {
317
+ return prepareAgainstTrustBase(options, options.trustBase);
318
+ }
306
319
  const { repoRoot, env } = options;
307
- const timeoutMs = options.timeoutMs ?? 120_000;
308
- // The contract source is decided FIRST, before git is touched. A repository
309
- // with no spec is never blocked by this gate, and that promise has to hold
310
- // on a shallow checkout too: resolving the base ref first would turn a
311
- // fetch-depth of 1 into exit 2 on a repository the gate was never going to
312
- // check anything in.
320
+ // The contract source is decided FIRST, before the base ref is resolved. A
321
+ // repository with no spec is never blocked by this gate, and that promise
322
+ // has to hold on a shallow checkout too: resolving the base ref first would
323
+ // turn a fetch-depth of 1 into exit 2 on a repository the gate was never
324
+ // going to check anything in.
313
325
  const eventPath = env.GITHUB_EVENT_PATH;
314
326
  const prBody = eventPath === undefined ? null : prBodyFromEvent(eventPath);
315
327
  const branch = currentBranch(repoRoot, env);
@@ -327,6 +339,15 @@ export function prepareIntent(options) {
327
339
  'A spec asked for by name is never replaced by a discovered one.',
328
340
  };
329
341
  }
342
+ if (discovery.kind === 'escaped') {
343
+ return {
344
+ kind: 'failed',
345
+ step: 'spec',
346
+ detail: `${discovery.path} resolves outside the repository (its directory is a symbolic link ` +
347
+ 'pointing out of the checkout), so it was not read, and nothing was checked by this ' +
348
+ 'gate. Replace the link with the directory itself, or name the spec with --spec.',
349
+ };
350
+ }
330
351
  // A repository holding both state directories stops the run before
331
352
  // anything else is decided, INCLUDING before --spec is honoured. The flag
332
353
  // would otherwise take the import path, which runs "import-spec --project ."
@@ -335,16 +356,7 @@ export function prepareIntent(options) {
335
356
  // subcommand. One sentence naming both directories beats that, and it is
336
357
  // the same answer either way.
337
358
  if (stateDirsConflict(repoRoot)) {
338
- return {
339
- kind: 'failed',
340
- step: 'contract-source',
341
- detail: `this repository has both ${STATE_DIR}/ and a ${LEGACY_STATE_DIR}/ holding ` +
342
- `intent-guard state. ${LEGACY_STATE_DIR}/ is the pre-1.3 name for ${STATE_DIR}/, and ` +
343
- 'intent-guard reads one state directory and never merges two, so it refuses every ' +
344
- `command here rather than guessing. Move ${LEGACY_STATE_DIR}/ aside, or move what ` +
345
- `is still needed out of it into ${STATE_DIR}/, and re-run. Nothing was checked by ` +
346
- 'this gate.',
347
- };
359
+ return { kind: 'failed', step: 'contract-source', detail: stateDirsConflictDetail() };
348
360
  }
349
361
  const nativeContract = frozenNativeContracts(repoRoot)[0] ?? null;
350
362
  let source;
@@ -383,8 +395,19 @@ export function prepareIntent(options) {
383
395
  'Name one with a "Spec: <path>" line in the pull request body, or pass --spec.',
384
396
  };
385
397
  }
398
+ return finishPreparation(options, source, null, []);
399
+ }
400
+ /**
401
+ * Everything after the contract source is decided: the change set, then for
402
+ * an imported source the import-and-freeze chain. Shared by both preparations
403
+ * so the change set and the chain cannot differ between them.
404
+ */
405
+ function finishPreparation(options, source, importInput, proposals, note) {
406
+ const { repoRoot, env } = options;
407
+ const timeoutMs = options.timeoutMs ?? 120_000;
386
408
  const resolvedBase = resolveBaseRefInRepo(repoRoot, {
387
409
  ...(options.base === undefined ? {} : { base: options.base }),
410
+ ...(options.trustBase === undefined ? {} : { trustBase: options.trustBase }),
388
411
  env,
389
412
  });
390
413
  if (!resolvedBase.ok) {
@@ -392,12 +415,31 @@ export function prepareIntent(options) {
392
415
  }
393
416
  const base = resolvedBase.base;
394
417
  let paths = null;
418
+ let pathsRefusal = null;
395
419
  if (base !== null) {
396
420
  const changed = changedPathsSince(repoRoot, base.ref);
397
421
  if (!changed.ok) {
398
422
  return { kind: 'failed', step: 'base', detail: changed.detail };
399
423
  }
400
- paths = changed.paths;
424
+ pathsRefusal = pathsFlagRefusal(changed.paths);
425
+ paths = orderForPathsFlag(changed.paths);
426
+ }
427
+ // An imported contract can only take the change set as --paths: its project
428
+ // is a temporary directory, where the gate's own --base has no repository
429
+ // to read. So a change set --paths cannot carry is refused here, with the
430
+ // way to clear it. A native contract carries the reason on to the runner,
431
+ // which knows the gate's version and uses the gate's own --base instead
432
+ // where the gate has it.
433
+ if (pathsRefusal !== null && source.kind === 'imported') {
434
+ return {
435
+ kind: 'failed',
436
+ step: 'base',
437
+ detail: `${pathsRefusal} The contract for this run is imported from a spec, so the change set ` +
438
+ 'can only be handed over as that list, and nothing was checked. To clear it, freeze ' +
439
+ 'the contract and commit it to the base branch (intent-guard import-spec, then ' +
440
+ 'freeze), and use intent-guard 1.8.1 or later, which then reads the change set from ' +
441
+ 'git itself.',
442
+ };
401
443
  }
402
444
  const common = {
403
445
  baseRef: base === null ? null : base.ref,
@@ -415,6 +457,9 @@ export function prepareIntent(options) {
415
457
  // directory.
416
458
  projectDir: '.',
417
459
  cleanup: () => undefined,
460
+ ...(proposals.length === 0 ? {} : { proposals }),
461
+ ...(note === undefined ? {} : { note }),
462
+ ...(pathsRefusal === null ? {} : { pathsRefusal }),
418
463
  },
419
464
  };
420
465
  }
@@ -437,21 +482,40 @@ export function prepareIntent(options) {
437
482
  'subcommand. Importing a spec needs the unified intent-guard binary.',
438
483
  };
439
484
  }
485
+ // ON A RUN WITH A TRUST BASE the spec and plan were read from the base ref,
486
+ // and the importer is pointed at copies of those bytes inside the temporary
487
+ // project, with the temporary project as its --project and its working
488
+ // directory. Nothing in the tree being judged is opened by the import, so
489
+ // an edit the pull request makes to the spec is a proposal, not the
490
+ // contract. Without a trust base the working tree is read, as before.
491
+ const staged = importInput === null ? null : stageBaseCopies(options, source, importInput);
492
+ if (staged !== null && staged.kind === 'failed') {
493
+ return staged.result;
494
+ }
495
+ const stagedDir = staged === null ? null : staged.projectDir;
496
+ const discard = () => {
497
+ if (stagedDir !== null) {
498
+ rmSync(stagedDir, { recursive: true, force: true });
499
+ }
500
+ };
501
+ const readRoot = stagedDir ?? repoRoot;
440
502
  const importResult = run(importCommand.command, [
441
503
  ...importCommand.argv,
442
504
  '--project',
443
- '.',
505
+ stagedDir ?? '.',
444
506
  '--from',
445
507
  'superpowers',
446
508
  '--spec',
447
- path.join(repoRoot, source.spec),
448
- ...(source.plan === null ? [] : ['--plan', path.join(repoRoot, source.plan)]),
509
+ path.join(readRoot, source.spec),
510
+ ...(source.plan === null ? [] : ['--plan', path.join(readRoot, source.plan)]),
449
511
  '--dry-run',
450
- ], repoRoot, timeoutMs);
512
+ ], readRoot, timeoutMs);
451
513
  if (importResult.errorMessage !== null) {
514
+ discard();
452
515
  return { kind: 'failed', step: 'import-spec', detail: importResult.errorMessage };
453
516
  }
454
517
  if (importResult.status !== 0) {
518
+ discard();
455
519
  return {
456
520
  kind: 'failed',
457
521
  step: 'import-spec',
@@ -462,6 +526,7 @@ export function prepareIntent(options) {
462
526
  try {
463
527
  const parsed = JSON.parse(importResult.stdout);
464
528
  if (typeof parsed.contract_yaml !== 'string' || parsed.contract_yaml === '') {
529
+ discard();
465
530
  return {
466
531
  kind: 'failed',
467
532
  step: 'import-spec',
@@ -471,13 +536,14 @@ export function prepareIntent(options) {
471
536
  contractYaml = parsed.contract_yaml;
472
537
  }
473
538
  catch {
539
+ discard();
474
540
  return {
475
541
  kind: 'failed',
476
542
  step: 'import-spec',
477
543
  detail: 'import-spec printed something that is not JSON, so no draft could be read.',
478
544
  };
479
545
  }
480
- const projectDir = mkdtempSync(path.join(options.tempRoot ?? os.tmpdir(), TEMP_PREFIX));
546
+ const projectDir = stagedDir ?? mkdtempSync(path.join(options.tempRoot ?? os.tmpdir(), TEMP_PREFIX));
481
547
  const cleanup = () => {
482
548
  rmSync(projectDir, { recursive: true, force: true });
483
549
  };
@@ -515,11 +581,13 @@ export function prepareIntent(options) {
515
581
  // Says what approved it and against which commit, so the approval is
516
582
  // never mistaken for a person's. The spec path is repository-relative,
517
583
  // because this string ends up in a contract and a machine path in a
518
- // contract is exactly what intent-guard's own docs warn about.
519
- `conductor: ${source.spec} at ${shortHead(repoRoot)}`,
584
+ // contract is exactly what intent-guard's own docs warn about. On a
585
+ // trust-base run the commit named is the base's, which is where the
586
+ // spec was read from.
587
+ `conductor: ${source.spec} at ${importInput === null ? shortHead(repoRoot) : shortCommit(repoRoot, importInput.ref)}`,
520
588
  '--yes',
521
589
  '--json',
522
- ], repoRoot, timeoutMs);
590
+ ], readRoot, timeoutMs);
523
591
  if (freezeResult.errorMessage !== null || freezeResult.status !== 0) {
524
592
  cleanup();
525
593
  return {
@@ -548,6 +616,347 @@ export function prepareIntent(options) {
548
616
  }
549
617
  return {
550
618
  kind: 'ready',
551
- preparation: { ...common, contractSource: source, projectDir, cleanup },
619
+ preparation: {
620
+ ...common,
621
+ contractSource: source,
622
+ projectDir,
623
+ cleanup,
624
+ ...(proposals.length === 0 ? {} : { proposals }),
625
+ },
626
+ };
627
+ }
628
+ /** The short commit a ref resolves to, or a placeholder. */
629
+ function shortCommit(repoRoot, ref) {
630
+ if (ref.startsWith('-')) {
631
+ return 'an unknown commit';
632
+ }
633
+ const child = runGit(repoRoot, ['rev-parse', '--short', '--verify', '--quiet', `${ref}^{commit}`]);
634
+ const value = child.stdout.trim();
635
+ return child.status === 0 && value !== '' ? value : 'an unknown commit';
636
+ }
637
+ /**
638
+ * A temporary project holding the base ref's copies of the spec and plan at
639
+ * their repository-relative paths, ready for the importer. The paths were
640
+ * checked to be plain relative paths before they were read, so every write
641
+ * lands inside the directory made here.
642
+ */
643
+ function stageBaseCopies(options, source, input) {
644
+ const projectDir = mkdtempSync(path.join(options.tempRoot ?? os.tmpdir(), TEMP_PREFIX));
645
+ const copies = [[source.spec, input.specText]];
646
+ if (source.plan !== null && input.planText !== null) {
647
+ copies.push([source.plan, input.planText]);
648
+ }
649
+ try {
650
+ for (const [relative, text] of copies) {
651
+ const target = path.join(projectDir, relative);
652
+ mkdirSync(path.dirname(target), { recursive: true });
653
+ writeFileSync(target, text);
654
+ }
655
+ }
656
+ catch (err) {
657
+ rmSync(projectDir, { recursive: true, force: true });
658
+ return {
659
+ kind: 'failed',
660
+ result: {
661
+ kind: 'failed',
662
+ step: 'import-spec',
663
+ detail: `the base copy of the spec could not be staged for import: ${err.message}`,
664
+ },
665
+ };
666
+ }
667
+ return { kind: 'ok', projectDir };
668
+ }
669
+ /** The refusal sentence for a repository holding both state directories. */
670
+ function stateDirsConflictDetail() {
671
+ return (`this repository has both ${STATE_DIR}/ and a ${LEGACY_STATE_DIR}/ holding ` +
672
+ `intent-guard state. ${LEGACY_STATE_DIR}/ is the pre-1.3 name for ${STATE_DIR}/, and ` +
673
+ 'intent-guard reads one state directory and never merges two, so it refuses every ' +
674
+ `command here rather than guessing. Move ${LEGACY_STATE_DIR}/ aside, or move what ` +
675
+ `is still needed out of it into ${STATE_DIR}/, and re-run. Nothing was checked by ` +
676
+ 'this gate.');
677
+ }
678
+ /** Whether a repository-relative path is plain: not absolute, no "." or ".." segment. */
679
+ function isPlainRelative(relative) {
680
+ if (relative === '' || path.posix.isAbsolute(relative)) {
681
+ return false;
682
+ }
683
+ return relative.split('/').every((segment) => segment !== '' && segment !== '.' && segment !== '..');
684
+ }
685
+ /** A user-given path, repository-relative and with forward slashes. */
686
+ function toRepoRelative(repoRoot, candidate) {
687
+ const relative = path.isAbsolute(candidate)
688
+ ? path.relative(repoRoot, candidate)
689
+ : path.normalize(candidate);
690
+ return relative.split(path.sep).join('/');
691
+ }
692
+ /**
693
+ * The frozen contract at a ref, canonical path first, by the same predicate
694
+ * the working-tree lookup uses. A path git cannot read as a regular file (a
695
+ * symlink, a directory, a submodule, a missing blob) is an ERROR, never "no
696
+ * contract": a base contract that could not be read must not let the pull
697
+ * request decide what it is judged against.
698
+ */
699
+ function frozenContractAtRef(repoRoot, ref) {
700
+ for (const relative of NATIVE_CONTRACT_PATHS) {
701
+ const read = readFileAtRef(repoRoot, ref, relative);
702
+ if (read.kind === 'error') {
703
+ return { kind: 'error', path: relative, detail: read.detail };
704
+ }
705
+ if (read.kind === 'file' && contractTextIsFrozen(read.text)) {
706
+ return { kind: 'frozen', path: relative };
707
+ }
708
+ }
709
+ return { kind: 'none' };
710
+ }
711
+ /** Markdown files directly under `dir` at a ref, sorted. */
712
+ function markdownFilesAtRef(repoRoot, ref, dir) {
713
+ if (ref.startsWith('-')) {
714
+ return { ok: false, detail: `refusing "${ref}": it starts with "-"` };
715
+ }
716
+ const child = runGit(repoRoot, ['ls-tree', '-z', ref, '--', `./${dir}/`]);
717
+ if (child.error !== undefined || child.status !== 0) {
718
+ return { ok: false, detail: `cannot list ${dir} at "${ref}": ${gitComplaint(child)}` };
719
+ }
720
+ const names = [];
721
+ for (const entry of child.stdout.split('\0')) {
722
+ const tab = entry.indexOf('\t');
723
+ if (tab === -1) {
724
+ continue;
725
+ }
726
+ const [mode, type] = entry.slice(0, tab).split(' ');
727
+ const name = entry.slice(tab + 1);
728
+ if (type === 'blob' &&
729
+ (mode === '100644' || mode === '100755') &&
730
+ path.posix.dirname(name) === dir &&
731
+ /\.md$/i.test(name)) {
732
+ names.push(path.posix.basename(name));
733
+ }
734
+ }
735
+ return { ok: true, names: names.sort() };
736
+ }
737
+ /** The plan for a spec at a ref: equal stem, newest name, or null. */
738
+ function planAtRef(repoRoot, ref, spec) {
739
+ const listed = markdownFilesAtRef(repoRoot, ref, PLAN_DIR);
740
+ if (!listed.ok) {
741
+ return listed;
742
+ }
743
+ const stem = normalizeStem(path.posix.basename(spec));
744
+ const matches = listed.names.filter((name) => normalizeStem(name) === stem);
745
+ const newest = matches[matches.length - 1];
746
+ if (newest === undefined) {
747
+ return { ok: true, plan: null, planText: null };
748
+ }
749
+ const plan = `${PLAN_DIR}/${newest}`;
750
+ const read = readFileAtRef(repoRoot, ref, plan);
751
+ if (read.kind !== 'file') {
752
+ return {
753
+ ok: false,
754
+ detail: read.kind === 'error' ? read.detail : `${plan} was listed at "${ref}" but not found`,
755
+ };
756
+ }
757
+ return { ok: true, plan, planText: read.text };
758
+ }
759
+ /**
760
+ * The spec for this run, found AT THE TRUST BASE by the same three sources
761
+ * and the same order as `discoverSpec` uses on the working tree: --spec, a
762
+ * "Spec:" line in the pull request body (or its waiver), then the branch-name
763
+ * convention. Every byte comes from the ref. A read git could not make is a
764
+ * failure, never "no spec".
765
+ */
766
+ function discoverSpecAtRef(repoRoot, ref, inputs) {
767
+ const found = (spec, specText) => {
768
+ const plan = planAtRef(repoRoot, ref, spec);
769
+ if (!plan.ok) {
770
+ return { kind: 'failed', detail: plan.detail };
771
+ }
772
+ return { kind: 'found', spec, specText, plan: plan.plan, planText: plan.planText };
773
+ };
774
+ if (inputs.spec !== undefined) {
775
+ const relative = toRepoRelative(repoRoot, inputs.spec);
776
+ if (!isPlainRelative(relative)) {
777
+ return {
778
+ kind: 'failed',
779
+ detail: `--spec names "${inputs.spec}", which is not a path inside the repository. On a run ` +
780
+ `with a trust base the spec is read from "${ref}", so it has to be a file the base ` +
781
+ 'branch carries: commit it there, or name it by its path inside the repository.',
782
+ };
783
+ }
784
+ const read = readFileAtRef(repoRoot, ref, relative);
785
+ if (read.kind === 'error') {
786
+ return { kind: 'failed', detail: read.detail };
787
+ }
788
+ if (read.kind === 'file') {
789
+ return found(relative, read.text);
790
+ }
791
+ return { kind: 'none', flagOnHead: relative };
792
+ }
793
+ if (inputs.prBody !== null) {
794
+ const named = specFromPrBody(inputs.prBody);
795
+ if (named === SPEC_WAIVER_TOKEN) {
796
+ return { kind: 'waived' };
797
+ }
798
+ if (named !== null) {
799
+ const relative = toRepoRelative(repoRoot, named);
800
+ // An unusable Spec: line falls through to the convention, exactly as
801
+ // on the working tree: a typo in a pull request description must not
802
+ // be able to fail a build.
803
+ if (isPlainRelative(relative)) {
804
+ const read = readFileAtRef(repoRoot, ref, relative);
805
+ if (read.kind === 'error') {
806
+ return { kind: 'failed', detail: read.detail };
807
+ }
808
+ if (read.kind === 'file') {
809
+ return found(relative, read.text);
810
+ }
811
+ }
812
+ }
813
+ }
814
+ if (inputs.branch !== null) {
815
+ const listed = markdownFilesAtRef(repoRoot, ref, SPEC_DIR);
816
+ if (!listed.ok) {
817
+ return { kind: 'failed', detail: listed.detail };
818
+ }
819
+ const best = bestMatch(listed.names, branchSlug(inputs.branch));
820
+ if (best !== undefined) {
821
+ const relative = `${SPEC_DIR}/${best}`;
822
+ const read = readFileAtRef(repoRoot, ref, relative);
823
+ if (read.kind !== 'file') {
824
+ return {
825
+ kind: 'failed',
826
+ detail: read.kind === 'error' ? read.detail : `${relative} was listed at "${ref}" but not found`,
827
+ };
828
+ }
829
+ return found(relative, read.text);
830
+ }
831
+ }
832
+ return { kind: 'none', flagOnHead: null };
833
+ }
834
+ /** One line per file the head carries at a contract path the base has no frozen contract at. */
835
+ function headContractProposals(repoRoot, ref) {
836
+ return NATIVE_CONTRACT_PATHS.filter((relative) => readFileAtRef(repoRoot, 'HEAD', relative).kind !== 'absent').map((relative) => `${relative} is in this pull request, and "${ref}" carries no frozen intent contract: it ` +
837
+ 'is a proposal, and pull requests are judged against it once it is frozen on the base branch.');
838
+ }
839
+ /** One line per imported file (spec, plan) whose head copy differs from the base copy. */
840
+ function importedFileProposals(repoRoot, ref, files) {
841
+ const lines = [];
842
+ for (const file of files) {
843
+ const head = readFileAtRef(repoRoot, 'HEAD', file.path);
844
+ if (head.kind === 'file' && head.text === file.baseText) {
845
+ continue;
846
+ }
847
+ const what = head.kind === 'absent' ? 'is removed in this pull request' : 'changed in this pull request';
848
+ lines.push(`${file.path} ${what}; the copy on "${ref}" was imported, and the change takes effect once ` +
849
+ 'it is on the base branch.');
850
+ }
851
+ return lines;
852
+ }
853
+ /**
854
+ * The intent gate's preparation on a run with a trust base.
855
+ *
856
+ * THE CONTRACT DECISION IS MADE FROM THE BASE ONLY. Whether a frozen contract
857
+ * governs this pull request is a control decision, and the head is the tree
858
+ * under judgment, so nothing the head carries is consulted for it:
859
+ *
860
+ * - The base has a frozen contract: it is used, native, and the gate is
861
+ * handed the trust base. That outranks --spec, a "Spec:" line and the
862
+ * convention. A pull request that edits or deletes the contract is judged
863
+ * against the base's copy, and the gate itself reports the change.
864
+ * - The base has none: nothing on the head may become the contract. A spec
865
+ * on the base (found the usual way, read from the base) is imported from
866
+ * its base copy. Otherwise the gate is skipped with "no contract on the
867
+ * base". A contract or spec the head adds is reported as a proposal, so
868
+ * first adoption merges, and is judged from the next pull request on.
869
+ * - A base contract that cannot be read is could-not-run.
870
+ */
871
+ function prepareAgainstTrustBase(options, trustBase) {
872
+ const { repoRoot, env } = options;
873
+ // Mirrors the gate's own refusal on the tree it is about to run in, so it
874
+ // reads that tree, like the gate.
875
+ if (stateDirsConflict(repoRoot)) {
876
+ return { kind: 'failed', step: 'contract-source', detail: stateDirsConflictDetail() };
877
+ }
878
+ const baseContract = frozenContractAtRef(repoRoot, trustBase);
879
+ if (baseContract.kind === 'error') {
880
+ return {
881
+ kind: 'failed',
882
+ step: 'contract-source',
883
+ detail: `${baseContract.detail}. Whether a frozen intent contract governs this pull request is ` +
884
+ `decided from "${trustBase}" alone, and it could not be read there, so nothing was ` +
885
+ `checked by this gate. ${unreadableBaseRemedy(baseContract.path)}`,
886
+ };
887
+ }
888
+ if (baseContract.kind === 'frozen') {
889
+ // Said in one line, so the person who passed --spec learns which
890
+ // contract the report is about and why.
891
+ const note = options.spec === undefined
892
+ ? undefined
893
+ : `the spec named by --spec (${options.spec}) was not used: "${trustBase}" has a frozen ` +
894
+ `intent contract (${baseContract.path}), and a frozen contract on the base outranks --spec.`;
895
+ return finishPreparation(options, { kind: 'native', path: baseContract.path }, null, [], note);
896
+ }
897
+ const proposals = headContractProposals(repoRoot, trustBase);
898
+ const eventPath = env.GITHUB_EVENT_PATH;
899
+ const prBody = eventPath === undefined ? null : prBodyFromEvent(eventPath);
900
+ const branch = currentBranch(repoRoot, env);
901
+ const atBase = discoverSpecAtRef(repoRoot, trustBase, {
902
+ ...(options.spec === undefined ? {} : { spec: options.spec }),
903
+ prBody,
904
+ branch,
905
+ });
906
+ if (atBase.kind === 'failed') {
907
+ return { kind: 'failed', step: 'spec', detail: atBase.detail };
908
+ }
909
+ if (atBase.kind === 'waived') {
910
+ return {
911
+ kind: 'skip',
912
+ reason: 'contract-waived',
913
+ detail: 'The pull request body waived the spec with a "Spec: none" line, so there was nothing ' +
914
+ `to import, and "${trustBase}" carries no frozen ${NATIVE_CONTRACT_PATHS.join(' or ')} ` +
915
+ 'to fall back on.',
916
+ ...(proposals.length === 0 ? {} : { proposals }),
917
+ };
918
+ }
919
+ if (atBase.kind === 'found') {
920
+ const files = [{ path: atBase.spec, baseText: atBase.specText }];
921
+ if (atBase.plan !== null && atBase.planText !== null) {
922
+ files.push({ path: atBase.plan, baseText: atBase.planText });
923
+ }
924
+ proposals.push(...importedFileProposals(repoRoot, trustBase, files));
925
+ return finishPreparation(options, { kind: 'imported', spec: atBase.spec, plan: atBase.plan, ref: trustBase }, { ref: trustBase, specText: atBase.specText, planText: atBase.planText }, proposals);
926
+ }
927
+ // Nothing on the base. A spec the head carries is a proposal, and a --spec
928
+ // that names a file neither side has is still reported as missing.
929
+ const onHead = discoverSpec({
930
+ repoRoot,
931
+ ...(options.spec === undefined ? {} : { spec: options.spec }),
932
+ ...(prBody === null ? {} : { prBody }),
933
+ ...(branch === null ? {} : { branch }),
934
+ });
935
+ if (options.spec !== undefined && onHead.kind === 'missing-flag') {
936
+ return {
937
+ kind: 'failed',
938
+ step: 'spec',
939
+ detail: `--spec named "${onHead.spec}", which is neither on "${trustBase}" nor in this pull ` +
940
+ 'request. A spec asked for by name is never replaced by a discovered one.',
941
+ };
942
+ }
943
+ const headSpec = atBase.flagOnHead ??
944
+ (onHead.kind === 'flag' || onHead.kind === 'pr-body' || onHead.kind === 'convention'
945
+ ? onHead.spec
946
+ : null);
947
+ if (headSpec !== null) {
948
+ proposals.push(`${headSpec} is a spec in this pull request but not on "${trustBase}": it is a proposal, ` +
949
+ 'and pull requests are judged against it once it is on the base branch.');
950
+ }
951
+ return {
952
+ kind: 'skip',
953
+ reason: 'no-contract',
954
+ detail: `No contract on the base: "${trustBase}" carries no frozen ` +
955
+ `${NATIVE_CONTRACT_PATHS.join(' or ')} and no spec under ${SPEC_DIR} for ` +
956
+ `${branch === null ? 'this branch' : `branch "${branch}"`}. On a pull-request run the ` +
957
+ 'intent contract comes from the base ref only, so nothing in this pull request can ' +
958
+ 'become it; once a contract or spec is on the base branch, the next pull request is ' +
959
+ 'judged against it.',
960
+ ...(proposals.length === 0 ? {} : { proposals }),
552
961
  };
553
962
  }