@vaultcompass/conductor 0.7.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.
@@ -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, resolveBaseRef } 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,17 +395,51 @@ 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
  }
386
- const base = resolveBaseRef({
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;
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
  });
413
+ if (!resolvedBase.ok) {
414
+ return { kind: 'failed', step: 'base', detail: resolvedBase.detail };
415
+ }
416
+ const base = resolvedBase.base;
390
417
  let paths = null;
418
+ let pathsRefusal = null;
391
419
  if (base !== null) {
392
420
  const changed = changedPathsSince(repoRoot, base.ref);
393
421
  if (!changed.ok) {
394
422
  return { kind: 'failed', step: 'base', detail: changed.detail };
395
423
  }
396
- 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
+ };
397
443
  }
398
444
  const common = {
399
445
  baseRef: base === null ? null : base.ref,
@@ -411,6 +457,9 @@ export function prepareIntent(options) {
411
457
  // directory.
412
458
  projectDir: '.',
413
459
  cleanup: () => undefined,
460
+ ...(proposals.length === 0 ? {} : { proposals }),
461
+ ...(note === undefined ? {} : { note }),
462
+ ...(pathsRefusal === null ? {} : { pathsRefusal }),
414
463
  },
415
464
  };
416
465
  }
@@ -433,21 +482,40 @@ export function prepareIntent(options) {
433
482
  'subcommand. Importing a spec needs the unified intent-guard binary.',
434
483
  };
435
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;
436
502
  const importResult = run(importCommand.command, [
437
503
  ...importCommand.argv,
438
504
  '--project',
439
- '.',
505
+ stagedDir ?? '.',
440
506
  '--from',
441
507
  'superpowers',
442
508
  '--spec',
443
- path.join(repoRoot, source.spec),
444
- ...(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)]),
445
511
  '--dry-run',
446
- ], repoRoot, timeoutMs);
512
+ ], readRoot, timeoutMs);
447
513
  if (importResult.errorMessage !== null) {
514
+ discard();
448
515
  return { kind: 'failed', step: 'import-spec', detail: importResult.errorMessage };
449
516
  }
450
517
  if (importResult.status !== 0) {
518
+ discard();
451
519
  return {
452
520
  kind: 'failed',
453
521
  step: 'import-spec',
@@ -458,6 +526,7 @@ export function prepareIntent(options) {
458
526
  try {
459
527
  const parsed = JSON.parse(importResult.stdout);
460
528
  if (typeof parsed.contract_yaml !== 'string' || parsed.contract_yaml === '') {
529
+ discard();
461
530
  return {
462
531
  kind: 'failed',
463
532
  step: 'import-spec',
@@ -467,13 +536,14 @@ export function prepareIntent(options) {
467
536
  contractYaml = parsed.contract_yaml;
468
537
  }
469
538
  catch {
539
+ discard();
470
540
  return {
471
541
  kind: 'failed',
472
542
  step: 'import-spec',
473
543
  detail: 'import-spec printed something that is not JSON, so no draft could be read.',
474
544
  };
475
545
  }
476
- const projectDir = mkdtempSync(path.join(options.tempRoot ?? os.tmpdir(), TEMP_PREFIX));
546
+ const projectDir = stagedDir ?? mkdtempSync(path.join(options.tempRoot ?? os.tmpdir(), TEMP_PREFIX));
477
547
  const cleanup = () => {
478
548
  rmSync(projectDir, { recursive: true, force: true });
479
549
  };
@@ -511,11 +581,13 @@ export function prepareIntent(options) {
511
581
  // Says what approved it and against which commit, so the approval is
512
582
  // never mistaken for a person's. The spec path is repository-relative,
513
583
  // because this string ends up in a contract and a machine path in a
514
- // contract is exactly what intent-guard's own docs warn about.
515
- `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)}`,
516
588
  '--yes',
517
589
  '--json',
518
- ], repoRoot, timeoutMs);
590
+ ], readRoot, timeoutMs);
519
591
  if (freezeResult.errorMessage !== null || freezeResult.status !== 0) {
520
592
  cleanup();
521
593
  return {
@@ -544,6 +616,347 @@ export function prepareIntent(options) {
544
616
  }
545
617
  return {
546
618
  kind: 'ready',
547
- 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 }),
548
961
  };
549
962
  }
@@ -15,6 +15,16 @@ export type SpecDiscovery =
15
15
  /** The pull request body said `Spec: none`: there is nothing to import. */
16
16
  | {
17
17
  kind: 'waived';
18
+ }
19
+ /**
20
+ * The convention spec, or the plan for any spec, resolves outside the
21
+ * repository (its directory is a symlink pointing out of the checkout).
22
+ * Refused rather than read, and rather than dropped: the gate is reported
23
+ * as unable to run, never as having nothing to check.
24
+ */
25
+ | {
26
+ kind: 'escaped';
27
+ path: string;
18
28
  } | {
19
29
  kind: 'none';
20
30
  };
@@ -72,4 +82,22 @@ export declare function stemMatches(stem: string, slug: string): boolean;
72
82
  export declare function specFromPrBody(body: string): string | null;
73
83
  /** `pull_request.body` out of a GitHub event payload, or null. */
74
84
  export declare function prBodyFromEvent(eventPath: string): string | null;
85
+ /**
86
+ * The best of the candidates whose stem relates to `target`, or undefined.
87
+ *
88
+ * `stemMatches` decides who is a CANDIDATE; this decides who wins, and the
89
+ * two are different questions. Ranking on the lexically newest filename alone
90
+ * was answering the second with the first: a loose candidate carrying a later
91
+ * date beat the spec whose stem was the branch slug exactly, and an undated
92
+ * name beat everything because it sorts after every date. A pull request was
93
+ * then measured against a different feature's requirements, with nothing in
94
+ * the report saying so, since naming the spec it used is exactly what the
95
+ * report does.
96
+ *
97
+ * So: an exact stem first, then the most specific stem, and only then the
98
+ * newest name. Specificity is stem LENGTH, which is crude but is the property
99
+ * the failure actually had: "superpowers" beat
100
+ * "1.2.1-base-and-superpowers" by being shorter and vaguer.
101
+ */
102
+ export declare function bestMatch(names: string[], target: string): string | undefined;
75
103
  export declare function discoverSpec(options: SpecDiscoveryOptions): SpecDiscovery;