@vaultcompass/conductor 0.9.0 → 0.11.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/dist/init.js CHANGED
@@ -64,14 +64,14 @@
64
64
  // repositories in a dogfood run: both would have taken the umbrella hook
65
65
  // and lost it at the next install, with the manifest still recording it
66
66
  // as installed. See detectManagedHook and declaredManagedHooks.
67
- import { execFileSync } from 'node:child_process';
68
- import { chmodSync, closeSync, constants as fsConstants, existsSync, mkdirSync, openSync, readdirSync, realpathSync, rmSync, rmdirSync, statSync, writeFileSync, writeSync, } from 'node:fs';
67
+ import { execFileSync, spawnSync } from 'node:child_process';
68
+ import { chmodSync, closeSync, constants as fsConstants, existsSync, lstatSync, mkdirSync, openSync, readdirSync, realpathSync, rmSync, rmdirSync, statSync, writeFileSync, writeSync, } from 'node:fs';
69
69
  import path from 'node:path';
70
- import { DEP_GUARD_HOOK_MARKER, INTENT_GUARD_HOOK_MARKER, MANAGED_HOOK_MARKER, declaredManagedHooks, detectGateHook, detectGeneratedHook, detectManagedHook, editedManagedGuidance, foreignGuidance, gateHookGuidance, generatedHookGuidance, huskyDirectoryFor, huskyShimPresent, managedHooksGuidance, } from './init-hook-detect.js';
70
+ import { DEP_GUARD_HOOK_MARKER, INTENT_GUARD_HOOK_MARKER, MANAGED_HOOK_MARKER, declaredHusky, declaredManagedHooks, detectGateHook, detectGeneratedHook, detectManagedHook, editedManagedGuidance, foreignGuidance, gateHookGuidance, generatedHookGuidance, huskyDirectoryFor, huskyShimPresent, managedHooksGuidance, } from './init-hook-detect.js';
71
71
  import { MANIFEST_RELATIVE_PATH, manifestPathInsideRepo, readIfExists, readManifest, recordedHookSha, sha256, } from './init-manifest.js';
72
72
  import { POLICY_FILE_NAME, detectGates, renderPolicy } from './init-policy.js';
73
73
  import { frozenNativeContractPath } from './intent-prepare.js';
74
- import { GATE_ROLES, PRODUCT_FOR_ROLE } from './policy.js';
74
+ import { GATE_ROLES, PRODUCT_FOR_ROLE, parsePolicy } from './policy.js';
75
75
  import { profileFor } from './products.js';
76
76
  export { MANAGED_HOOK_MARKER, MANIFEST_RELATIVE_PATH, DEP_GUARD_HOOK_MARKER, INTENT_GUARD_HOOK_MARKER, POLICY_FILE_NAME, renderPolicy, };
77
77
  const HOOK = `#!/bin/sh
@@ -178,6 +178,11 @@ function gitOutput(cwd, args) {
178
178
  function repoRootOf(cwd) {
179
179
  return gitOutput(cwd, ['rev-parse', '--show-toplevel']);
180
180
  }
181
+ /** Whether git tracks anything under .husky/ at the repository root. */
182
+ function trackedHuskyDirectory(cwd) {
183
+ const listed = gitOutput(cwd, ['ls-files', '--full-name', '--', ':/.husky']);
184
+ return listed !== null && listed.length > 0;
185
+ }
181
186
  function effectiveHooksDir(cwd, root) {
182
187
  const gitDir = gitOutput(cwd, ['rev-parse', '--git-dir']);
183
188
  const hooksPath = gitOutput(cwd, ['config', '--get', 'core.hooksPath']) ?? '';
@@ -186,7 +191,7 @@ function effectiveHooksDir(cwd, root) {
186
191
  // somewhere else entirely, so this one resolves against gitDir.
187
192
  const defaultDir = path.join(path.resolve(cwd, gitDir ?? '.git'), 'hooks');
188
193
  if (hooksPath.length === 0) {
189
- return { dir: defaultDir, outside: false, isDefault: true };
194
+ return { dir: defaultDir, outside: false, isDefault: true, configured: false };
190
195
  }
191
196
  // A RELATIVE core.hooksPath resolves against the WORKING-TREE ROOT.
192
197
  // Verified by experiment rather than by reading the documentation that
@@ -194,7 +199,7 @@ function effectiveHooksDir(cwd, root) {
194
199
  const dir = path.isAbsolute(hooksPath) ? hooksPath : path.join(root, hooksPath);
195
200
  const relative = path.relative(root, dir);
196
201
  const outside = relative.startsWith('..') || path.isAbsolute(relative);
197
- return { dir, outside, isDefault: samePath(dir, defaultDir) };
202
+ return { dir, outside, isDefault: samePath(dir, defaultDir), configured: true };
198
203
  }
199
204
  /**
200
205
  * Whether two paths name the same directory.
@@ -300,9 +305,11 @@ export function planInit(options) {
300
305
  // executes (on husky 8 that file IS the tracked hook), and never
301
306
  // conditional on husky's shim being present (a clean deletes it, and the
302
307
  // repository is still husky's).
303
- const huskyDir = huskyDirectoryFor(hooks.dir);
304
- const husky = huskyDir !== null;
305
- if (!husky) {
308
+ let huskyDir = huskyDirectoryFor(hooks.dir);
309
+ // Where husky was recognised from when core.hooksPath does not say so yet:
310
+ // a fresh clone of a husky repository, before its install has run.
311
+ let huskyDeclaredIn = null;
312
+ if (huskyDir === null) {
306
313
  const rel = path.relative(root, executedHookPath).split(path.sep).join('/');
307
314
  if (executedHook !== undefined) {
308
315
  const generatedBy = detectGeneratedHook(executedHook);
@@ -348,7 +355,25 @@ export function planInit(options) {
348
355
  hookManager: managedBy.manager,
349
356
  };
350
357
  }
358
+ // HUSKY ON A FRESH CLONE. core.hooksPath is set by husky's own install
359
+ // (its prepare script), so a clone that has not run it yet looks native,
360
+ // and a hook written to .git/hooks then goes dark the moment the install
361
+ // points git at .husky/_. The declaration is the signal that exists
362
+ // before the install: husky in package.json, or a tracked .husky/
363
+ // directory. Same rule as simple-git-hooks above, the declaration counts
364
+ // on its own, but the answer differs: husky HAS a tracked hook file, and
365
+ // that file is what both husky 8 and husky 9 end up running, so init
366
+ // writes there and says the install still has to run, rather than
367
+ // refusing. Only where git runs .git/hooks: a hooks directory somebody
368
+ // configured is their decision, not a fresh clone.
369
+ if (!hooks.configured) {
370
+ huskyDeclaredIn = declaredHusky(root) ?? (trackedHuskyDirectory(options.cwd) ? 'a tracked .husky/ directory' : null);
371
+ if (huskyDeclaredIn !== null) {
372
+ huskyDir = path.join(root, '.husky');
373
+ }
374
+ }
351
375
  }
376
+ const husky = huskyDir !== null;
352
377
  const hookManager = husky ? 'husky' : 'native';
353
378
  const hookPath = huskyDir === null ? executedHookPath : path.join(huskyDir, 'pre-commit');
354
379
  const relHook = path.relative(root, hookPath).split(path.sep).join('/');
@@ -427,7 +452,16 @@ export function planInit(options) {
427
452
  else if (existingHook !== undefined && existingHook.trim().length > 0) {
428
453
  const gateProduct = detectGateHook(existingHook);
429
454
  if (gateProduct === null) {
430
- conflicts.push({ path: relHook, reason: 'foreign-hook', guidance: foreignGuidance(relHook) });
455
+ conflicts.push({
456
+ path: relHook,
457
+ reason: 'foreign-hook',
458
+ guidance: foreignGuidance(relHook) +
459
+ // On a fresh husky clone the tracked hook is not run by anything yet.
460
+ (huskyDeclaredIn === null
461
+ ? ''
462
+ : ' Note that husky is not installed in this clone (core.hooksPath is not set), so that hook ' +
463
+ "does not run at all until the install (husky's prepare script) has run."),
464
+ });
431
465
  return { ...base, repoRoot: root, hookPath, hookManager };
432
466
  }
433
467
  if (!options.adopt) {
@@ -456,14 +490,18 @@ export function planInit(options) {
456
490
  // the one core.hooksPath points at. The shim's state is reported
457
491
  // here, where it informs, rather than tested in the rule, where it
458
492
  // would send a cleaned repository back into the trap.
459
- detail: husky
460
- ? `${created}: husky runs ${path
461
- .relative(root, executedHookPath)
462
- .split(path.sep)
463
- .join('/')}, which execs this tracked file${huskyShimPresent(hooks.dir)
464
- ? ''
465
- : ' (husky is not installed right now: its generated directory is empty or gone, and the next install restores it)'}`
466
- : created,
493
+ detail: huskyDeclaredIn !== null
494
+ ? `${created}: husky is declared in ${huskyDeclaredIn} but has not been installed in this ` +
495
+ 'clone (core.hooksPath is not set), so git runs nothing from here yet. Run your install ' +
496
+ "(husky's prepare script) and husky will run this tracked file; .git/hooks would be bypassed then"
497
+ : husky
498
+ ? `${created}: husky runs ${path
499
+ .relative(root, executedHookPath)
500
+ .split(path.sep)
501
+ .join('/')}, which execs this tracked file${huskyShimPresent(hooks.dir)
502
+ ? ''
503
+ : ' (husky is not installed right now: its generated directory is empty or gone, and the next install restores it)'}`
504
+ : created,
467
505
  });
468
506
  writes.push({ path: hookPath, content: HOOK, executable: true, kind: 'hook' });
469
507
  }
@@ -498,9 +536,11 @@ function finishPlan(options, root, policyPath, base, actions, writes, records, h
498
536
  const external = GATE_ROLES.filter((role) => detected.has(role) && !profileFor(PRODUCT_FOR_ROLE[role]).managed).map((role) => `${role} (${PRODUCT_FOR_ROLE[role]})`);
499
537
  if (external.length > 0) {
500
538
  const one = external.length === 1;
501
- notes.push(`Note: ${external.join(' and ')} ${one ? 'is' : 'are'} enabled because ` +
539
+ notes.push(`WARNING: ${external.join(' and ')} ${one ? 'is' : 'are'} enabled only because ` +
502
540
  `${one ? 'its tool was' : 'their tools were'} found on this machine's PATH; your CI ` +
503
- `workflow must install ${one ? 'it' : 'them'} too, conductor does not.`);
541
+ `workflow must install ${one ? 'it' : 'them'} too, conductor does not. A teammate or a CI ` +
542
+ `job without ${one ? 'it' : 'them'} gets conductor/gate-missing and exit 2; set enabled: ` +
543
+ `false in ${POLICY_FILE_NAME} if that is not wanted.`);
504
544
  }
505
545
  }
506
546
  else {
@@ -511,6 +551,7 @@ function finishPlan(options, root, policyPath, base, actions, writes, records, h
511
551
  path: POLICY_FILE_NAME,
512
552
  detail: 'already present, left exactly as it is',
513
553
  });
554
+ notes.push(...missingRoleNotes(existingPolicy));
514
555
  }
515
556
  // A record with nothing to write is still work: the manifest has to be
516
557
  // rebuilt, so this is not an "already installed, nothing to do" run.
@@ -518,10 +559,27 @@ function finishPlan(options, root, policyPath, base, actions, writes, records, h
518
559
  if (!alreadyInstalled) {
519
560
  actions.push({ kind: 'write', path: MANIFEST_RELATIVE_PATH, detail: 'record what init wrote' });
520
561
  }
562
+ // The manifest names absolute paths on this machine, so it is never meant
563
+ // to be committed. Appended to .gitignore when that can be done without
564
+ // touching a single existing line; otherwise the line to add is printed.
565
+ const ignore = alreadyInstalled ? null : planGitignore(root);
566
+ if (ignore !== null && ignore.kind === 'append') {
567
+ actions.push({
568
+ kind: 'write',
569
+ path: '.gitignore',
570
+ detail: `append "${GITIGNORE_LINE}" (the per-machine manifest); no other line is changed, and --revert leaves it`,
571
+ });
572
+ }
573
+ else if (ignore !== null) {
574
+ notes.push(`Note: ${MANIFEST_RELATIVE_PATH} is not ignored by git and init did not change .gitignore ` +
575
+ `(${ignore.why}). Add the line "${GITIGNORE_LINE}" to it yourself: the manifest records ` +
576
+ 'paths on this machine and is not meant to be committed.');
577
+ }
521
578
  return {
522
579
  ...base,
523
580
  ok: true,
524
581
  alreadyInstalled,
582
+ ...(ignore !== null && ignore.kind === 'append' ? { gitignoreAppend: ignore.path } : {}),
525
583
  hookPath: hook.hookPath,
526
584
  hookManager: hook.hookManager,
527
585
  repoRoot: root,
@@ -531,6 +589,89 @@ function finishPlan(options, root, policyPath, base, actions, writes, records, h
531
589
  notes,
532
590
  };
533
591
  }
592
+ /** The line init adds to .gitignore for the per-machine manifest. */
593
+ export const GITIGNORE_LINE = '.guardrails/';
594
+ /**
595
+ * Whether init can append GITIGNORE_LINE to .gitignore, or why not, or null
596
+ * when git already ignores the manifest (by any rule, in any ignore file).
597
+ *
598
+ * APPEND ONLY. Init never rewrites a file it did not write: the line goes at
599
+ * the end of an existing .gitignore, after a newline if the file lacks a
600
+ * final one, or into a new .gitignore. A .gitignore that is a symbolic link,
601
+ * not a regular file, or resolves outside the repository is left alone and
602
+ * the line is printed instead. Not recorded in the manifest, so --revert
603
+ * never removes or rewrites .gitignore.
604
+ */
605
+ function planGitignore(root) {
606
+ const probe = spawnSync('git', ['check-ignore', '-q', '--no-index', MANIFEST_RELATIVE_PATH], {
607
+ cwd: root,
608
+ stdio: 'ignore',
609
+ });
610
+ if (probe.status === 0) {
611
+ return null;
612
+ }
613
+ if (probe.status !== 1) {
614
+ return { kind: 'print', why: 'git could not say whether it is already ignored' };
615
+ }
616
+ const target = path.join(root, '.gitignore');
617
+ let info;
618
+ try {
619
+ info = lstatSync(target);
620
+ }
621
+ catch (err) {
622
+ if (err.code === 'ENOENT') {
623
+ return { kind: 'append', path: target };
624
+ }
625
+ return { kind: 'print', why: '.gitignore could not be read' };
626
+ }
627
+ if (info.isSymbolicLink()) {
628
+ return { kind: 'print', why: '.gitignore is a symbolic link' };
629
+ }
630
+ if (!info.isFile()) {
631
+ return { kind: 'print', why: '.gitignore is not a regular file' };
632
+ }
633
+ return { kind: 'append', path: target };
634
+ }
635
+ /** Appends the line without following a link swapped in after planning. */
636
+ function appendGitignore(target) {
637
+ const existing = readIfExists(target);
638
+ const lead = existing !== undefined && existing.length > 0 && !existing.endsWith('\n') ? '\n' : '';
639
+ const noFollow = fsConstants.O_NOFOLLOW ?? 0;
640
+ const fd = openSync(target, fsConstants.O_WRONLY | fsConstants.O_CREAT | fsConstants.O_APPEND | noFollow, 0o666);
641
+ try {
642
+ writeSync(fd, `${lead}${GITIGNORE_LINE}\n`);
643
+ }
644
+ finally {
645
+ closeSync(fd);
646
+ }
647
+ }
648
+ /**
649
+ * On an existing policy file, the roles it has no entry for, with the two
650
+ * lines that add each. The file itself is never touched; this only says what
651
+ * a newer conductor knows about that an older init did not write.
652
+ */
653
+ function missingRoleNotes(text) {
654
+ let policy;
655
+ try {
656
+ policy = parsePolicy(text, POLICY_FILE_NAME);
657
+ }
658
+ catch {
659
+ return [
660
+ `Note: ${POLICY_FILE_NAME} does not parse, so init could not list the gate roles it lacks. ` +
661
+ '"conductor run" says why.',
662
+ ];
663
+ }
664
+ const missing = GATE_ROLES.filter((role) => policy.gates[role] === undefined);
665
+ if (missing.length === 0) {
666
+ return [];
667
+ }
668
+ return [
669
+ `Note: ${POLICY_FILE_NAME} has no entry for ${missing.length} gate role(s): ${missing.join(', ')}. ` +
670
+ 'To add one, put its two lines under "gates:" (a role listed is enabled unless it also says ' +
671
+ 'enabled: false):',
672
+ ...missing.flatMap((role) => [` ${role}:`, ` product: ${PRODUCT_FOR_ROLE[role]}`]),
673
+ ];
674
+ }
534
675
  /**
535
676
  * The whole plan when --hook was not given: no hook is detected, no hook
536
677
  * manager is consulted, and no hook conflict can block the policy file from
@@ -658,6 +799,11 @@ export function applyInit(plan, options) {
658
799
  const manifestPath = path.join(plan.repoRoot, MANIFEST_RELATIVE_PATH);
659
800
  mkdirSync(path.dirname(manifestPath), { recursive: true });
660
801
  writeManifestFile(manifestPath, `${JSON.stringify(manifest, null, 2)}\n`);
802
+ // Last, and contained like every other write: a .gitignore resolving
803
+ // outside the repository is never appended to.
804
+ if (plan.gitignoreAppend !== undefined && manifestPathInsideRepo(plan.repoRoot, plan.gitignoreAppend)) {
805
+ appendGitignore(plan.gitignoreAppend);
806
+ }
661
807
  }
662
808
  catch (err) {
663
809
  return {
@@ -1,3 +1,4 @@
1
+ import type { ConventionMatch, SelectionMiss } from './intent-spec.js';
1
2
  import type { ResolvedBinary } from './resolve.js';
2
3
  /** Prefix of the per-run directory, exported so a test can count leaks. */
3
4
  export declare const TEMP_PREFIX = "conductor-intent-";
@@ -51,9 +52,32 @@ export type ContractSource =
51
52
  spec: string;
52
53
  plan: string | null;
53
54
  ref?: string;
55
+ /**
56
+ * Set only when the branch-name convention chose the spec. Its presence
57
+ * is how every renderer knows the branch name chose it; nothing
58
+ * recomputes that from the policy or the path.
59
+ */
60
+ match?: ReportedMatch;
54
61
  } | {
55
62
  kind: 'none';
56
63
  };
64
+ /**
65
+ * A convention match as the report carries it: how the spec was chosen, plus
66
+ * which remedy the weak-match line names. `pr-body` on a run with a pull
67
+ * request event (a "Spec:" line), `spec-flag` locally (--spec).
68
+ */
69
+ export type ReportedMatch = ConventionMatch & {
70
+ remedy: 'pr-body' | 'spec-flag';
71
+ };
72
+ /** How many tied specs a report sentence names before "and N more". */
73
+ export declare const TIED_SHOWN = 5;
74
+ /**
75
+ * The legacy clause for a branch 0.10.0 bound and this release does not.
76
+ * Reporting only, for one minor release.
77
+ */
78
+ export declare function legacyNoneSentence(legacy: string): string;
79
+ /** The legacy clause for a branch whose chosen spec changed this release. */
80
+ export declare function legacyChangedSentence(legacy: string): string;
57
81
  export interface IntentPreparation {
58
82
  contractSource: ContractSource;
59
83
  /** The ref the change set was measured against, or null for a staged run. */
@@ -112,14 +136,33 @@ export type IntentPrepareResult = {
112
136
  */
113
137
  | {
114
138
  kind: 'skip';
115
- reason: 'no-contract' | 'contract-waived';
139
+ /**
140
+ * `spec-ambiguous`: two or more specs matched the branch name equally,
141
+ * so none was chosen. Its own reason because its remedy differs (a
142
+ * spec exists; choose one) and because a tie that 0.10.0 silently
143
+ * broke must not file itself under "nobody wrote one".
144
+ */
145
+ reason: 'no-contract' | 'contract-waived' | 'spec-ambiguous';
116
146
  detail: string;
117
147
  /** As on IntentPreparation: what this pull request proposes. */
118
148
  proposals?: string[];
149
+ /** What the branch-name convention said, for the details bag. */
150
+ selection?: SelectionMiss;
119
151
  } | {
120
152
  kind: 'failed';
121
153
  step: PrepareStep;
122
154
  detail: string;
155
+ }
156
+ /**
157
+ * A preparation spawn was stopped at the intent gate's time limit (spawn
158
+ * error ETIMEDOUT, checked before the status). Not `failed`: the caller
159
+ * reports it as the timed-out could-not-run reason.
160
+ */
161
+ | {
162
+ kind: 'timed-out';
163
+ step: 'import-spec' | 'freeze';
164
+ elapsedMs: number;
165
+ signal: string | null;
123
166
  };
124
167
  export interface IntentPrepareOptions {
125
168
  repoRoot: string;
@@ -133,7 +176,13 @@ export interface IntentPrepareOptions {
133
176
  * it when no --base and no GITHUB_BASE_REF names another base.
134
177
  */
135
178
  trustBase?: string;
136
- timeoutMs?: number;
179
+ /**
180
+ * The intent gate's resolved time limit (`resolveTimeLimit` in
181
+ * src/gate-runner.ts), given in full to each preparation spawn. REQUIRED,
182
+ * with no fallback here, so the type checker holds the preparation to the
183
+ * one resolver.
184
+ */
185
+ timeoutMs: number;
137
186
  /**
138
187
  * The directory the per-run temporary project is created under.
139
188
  *
@@ -37,7 +37,7 @@ import { parse as parseYaml } from 'yaml';
37
37
  import { gitComplaint, runGit } from './git.js';
38
38
  import { changedPathsSince, currentBranch, orderForPathsFlag, pathsFlagRefusal, resolveBaseRefInRepo, } from './intent-base.js';
39
39
  import { summariseStderr } from './normalize.js';
40
- import { PLAN_DIR, SPEC_DIR, SPEC_WAIVER_TOKEN, bestMatch, branchSlug, discoverSpec, normalizeStem, prBodyFromEvent, specFromPrBody, } from './intent-spec.js';
40
+ import { PLAN_DIR, SPEC_DIR, SPEC_WAIVER_TOKEN, discoverSpec, matchOf, normalizeStem, prBodyFromEvent, selectByBranch, specFromPrBody, } from './intent-spec.js';
41
41
  import { readFileAtRef, unreadableBaseRemedy } from './trust-base.js';
42
42
  /** Prefix of the per-run directory, exported so a test can count leaks. */
43
43
  export const TEMP_PREFIX = 'conductor-intent-';
@@ -80,6 +80,82 @@ export const NATIVE_CONTRACT_PATHS = [
80
80
  export function isLegacyContractPath(contractPath) {
81
81
  return contractPath === LEGACY_NATIVE_CONTRACT_PATH;
82
82
  }
83
+ /** How many tied specs a report sentence names before "and N more". */
84
+ export const TIED_SHOWN = 5;
85
+ /** The tied specs, as repository paths, capped for a report sentence. */
86
+ function tiedList(tied) {
87
+ const shown = tied.slice(0, TIED_SHOWN).map((name) => `${SPEC_DIR}/${name}`);
88
+ const more = tied.length - shown.length;
89
+ return more > 0 ? `${shown.join(', ')}, and ${more} more` : shown.join(', ');
90
+ }
91
+ /** The skip detail when two or more specs match the branch equally (5.2). */
92
+ function ambiguousDetail(branch, tied, ref) {
93
+ return (`No spec was chosen: the branch name "${branch}" matches ${tied.length} specs equally` +
94
+ `${ref === undefined ? '' : ` on "${ref}"`} (${tiedList(tied)}), and conductor does not ` +
95
+ 'guess between them. Add a "Spec: <path>" line to the pull request body or pass --spec, ' +
96
+ "or rename the branch to one spec's name.");
97
+ }
98
+ /**
99
+ * The legacy clause for a branch 0.10.0 bound and this release does not.
100
+ * Reporting only, for one minor release.
101
+ */
102
+ export function legacyNoneSentence(legacy) {
103
+ return (`Before conductor 0.11.0 this branch name chose ${SPEC_DIR}/${legacy} by a partial-word ` +
104
+ 'match; it no longer does.');
105
+ }
106
+ /** The legacy clause for a branch whose chosen spec changed this release. */
107
+ export function legacyChangedSentence(legacy) {
108
+ return (`Before conductor 0.11.0 this branch name chose ${SPEC_DIR}/${legacy}; it now chooses this ` +
109
+ 'spec, which matches it on whole words.');
110
+ }
111
+ /** The sentences a no-contract skip gains from the convention's answer. */
112
+ function selectionSuffix(branch, selection) {
113
+ if (selection === undefined) {
114
+ return '';
115
+ }
116
+ const sentences = [];
117
+ if (selection.why === 'no-usable-token' && branch !== null) {
118
+ sentences.push(`The branch name "${branch}" has no word of three or more letters that is not a common ` +
119
+ 'branch word (fix, feat, wip, ...), so it cannot choose a spec.');
120
+ }
121
+ if (selection.legacy !== null) {
122
+ sentences.push(legacyNoneSentence(selection.legacy));
123
+ }
124
+ return sentences.map((sentence) => ` ${sentence}`).join('');
125
+ }
126
+ /**
127
+ * The selection a skip carries for its details bag, or undefined when it
128
+ * says nothing the ordinary adoption-ramp skip does not: a usable branch name
129
+ * that matched no spec, under either rule, keeps its 0.10.0 shape exactly.
130
+ */
131
+ function reportedSelection(selection) {
132
+ if (selection === undefined || (selection.why === 'no-candidate' && selection.legacy === null)) {
133
+ return undefined;
134
+ }
135
+ return selection;
136
+ }
137
+ /** The skip for a convention that found nothing, on either path. */
138
+ function noSpecChosen(branch, selection, noContractDetail, proposals, ref) {
139
+ const reported = reportedSelection(selection);
140
+ const withProposals = proposals.length === 0 ? {} : { proposals };
141
+ if (selection !== undefined && selection.why === 'ambiguous' && branch !== null) {
142
+ return {
143
+ kind: 'skip',
144
+ reason: 'spec-ambiguous',
145
+ detail: ambiguousDetail(branch, selection.tied, ref) +
146
+ (selection.legacy === null ? '' : ` ${legacyNoneSentence(selection.legacy)}`),
147
+ selection,
148
+ ...withProposals,
149
+ };
150
+ }
151
+ return {
152
+ kind: 'skip',
153
+ reason: 'no-contract',
154
+ detail: noContractDetail + selectionSuffix(branch, selection),
155
+ ...(reported === undefined ? {} : { selection: reported }),
156
+ ...withProposals,
157
+ };
158
+ }
83
159
  /**
84
160
  * Whether a contract on disk has been approved.
85
161
  *
@@ -274,6 +350,7 @@ function subcommand(binary, name) {
274
350
  return { command: binary.command, argv: [...prefix.slice(0, -1), name] };
275
351
  }
276
352
  function run(command, argv, cwd, timeoutMs) {
353
+ const started = Date.now();
277
354
  const child = spawnSync(command, argv, {
278
355
  cwd,
279
356
  encoding: 'utf8',
@@ -285,8 +362,17 @@ function run(command, argv, cwd, timeoutMs) {
285
362
  stdout: child.stdout ?? '',
286
363
  stderr: child.stderr ?? '',
287
364
  errorMessage: child.error === undefined ? null : child.error.message,
365
+ errorCode: child.error === undefined ? null : (child.error.code ?? null),
366
+ signal: child.signal ?? null,
367
+ elapsedMs: Date.now() - started,
288
368
  };
289
369
  }
370
+ /** A preparation spawn stopped at the limit, as a result; null for any other outcome. */
371
+ function timedOutStep(result, step) {
372
+ return result.errorCode === 'ETIMEDOUT'
373
+ ? { kind: 'timed-out', step, elapsedMs: result.elapsedMs, signal: result.signal }
374
+ : null;
375
+ }
290
376
  /**
291
377
  * Everything the child complained with, trimmed and capped.
292
378
  *
@@ -383,17 +469,21 @@ export function prepareIntent(options) {
383
469
  else if (discovery.kind === 'none') {
384
470
  source = { kind: 'none' };
385
471
  }
472
+ else if (discovery.kind === 'convention') {
473
+ source = {
474
+ kind: 'imported',
475
+ spec: discovery.spec,
476
+ plan: discovery.plan,
477
+ match: { ...discovery.match, remedy: eventPath === undefined ? 'spec-flag' : 'pr-body' },
478
+ };
479
+ }
386
480
  else {
387
481
  source = { kind: 'imported', spec: discovery.spec, plan: discovery.plan };
388
482
  }
389
483
  if (source.kind === 'none') {
390
- return {
391
- kind: 'skip',
392
- reason: 'no-contract',
393
- detail: `No frozen ${NATIVE_CONTRACT_PATHS.join(' or ')} and no spec under ${SPEC_DIR} matching ` +
394
- `${branch === null ? 'this branch' : `branch "${branch}"`}. ` +
395
- 'Name one with a "Spec: <path>" line in the pull request body, or pass --spec.',
396
- };
484
+ return noSpecChosen(branch, discovery.kind === 'none' ? discovery.selection : undefined, `No frozen ${NATIVE_CONTRACT_PATHS.join(' or ')} and no spec under ${SPEC_DIR} matching ` +
485
+ `${branch === null ? 'this branch' : `branch "${branch}"`}. ` +
486
+ 'Name one with a "Spec: <path>" line in the pull request body, or pass --spec.', []);
397
487
  }
398
488
  return finishPreparation(options, source, null, []);
399
489
  }
@@ -403,8 +493,7 @@ export function prepareIntent(options) {
403
493
  * so the change set and the chain cannot differ between them.
404
494
  */
405
495
  function finishPreparation(options, source, importInput, proposals, note) {
406
- const { repoRoot, env } = options;
407
- const timeoutMs = options.timeoutMs ?? 120_000;
496
+ const { repoRoot, env, timeoutMs } = options;
408
497
  const resolvedBase = resolveBaseRefInRepo(repoRoot, {
409
498
  ...(options.base === undefined ? {} : { base: options.base }),
410
499
  ...(options.trustBase === undefined ? {} : { trustBase: options.trustBase }),
@@ -510,6 +599,13 @@ function finishPreparation(options, source, importInput, proposals, note) {
510
599
  ...(source.plan === null ? [] : ['--plan', path.join(readRoot, source.plan)]),
511
600
  '--dry-run',
512
601
  ], readRoot, timeoutMs);
602
+ // The time limit first, before the status, as in the runner: a stopped
603
+ // child's status is not an answer.
604
+ const importStopped = timedOutStep(importResult, 'import-spec');
605
+ if (importStopped !== null) {
606
+ discard();
607
+ return importStopped;
608
+ }
513
609
  if (importResult.errorMessage !== null) {
514
610
  discard();
515
611
  return { kind: 'failed', step: 'import-spec', detail: importResult.errorMessage };
@@ -588,6 +684,11 @@ function finishPreparation(options, source, importInput, proposals, note) {
588
684
  '--yes',
589
685
  '--json',
590
686
  ], readRoot, timeoutMs);
687
+ const freezeStopped = timedOutStep(freezeResult, 'freeze');
688
+ if (freezeStopped !== null) {
689
+ cleanup();
690
+ return freezeStopped;
691
+ }
591
692
  if (freezeResult.errorMessage !== null || freezeResult.status !== 0) {
592
693
  cleanup();
593
694
  return {
@@ -764,12 +865,19 @@ function planAtRef(repoRoot, ref, spec) {
764
865
  * failure, never "no spec".
765
866
  */
766
867
  function discoverSpecAtRef(repoRoot, ref, inputs) {
767
- const found = (spec, specText) => {
868
+ const found = (spec, specText, match) => {
768
869
  const plan = planAtRef(repoRoot, ref, spec);
769
870
  if (!plan.ok) {
770
871
  return { kind: 'failed', detail: plan.detail };
771
872
  }
772
- return { kind: 'found', spec, specText, plan: plan.plan, planText: plan.planText };
873
+ return {
874
+ kind: 'found',
875
+ spec,
876
+ specText,
877
+ plan: plan.plan,
878
+ planText: plan.planText,
879
+ ...(match === undefined ? {} : { match }),
880
+ };
773
881
  };
774
882
  if (inputs.spec !== undefined) {
775
883
  const relative = toRepoRelative(repoRoot, inputs.spec);
@@ -816,18 +924,25 @@ function discoverSpecAtRef(repoRoot, ref, inputs) {
816
924
  if (!listed.ok) {
817
925
  return { kind: 'failed', detail: listed.detail };
818
926
  }
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);
927
+ // The same selector as the working tree, over the names listed AT THE
928
+ // BASE: a head branch name only ever chooses among the base's specs.
929
+ const selection = selectByBranch(listed.names, inputs.branch);
930
+ if (selection.kind === 'none') {
931
+ return {
932
+ kind: 'none',
933
+ flagOnHead: null,
934
+ selection: { why: selection.why, tied: selection.tied, legacy: selection.legacy },
935
+ };
936
+ }
937
+ const relative = `${SPEC_DIR}/${selection.name}`;
938
+ const read = readFileAtRef(repoRoot, ref, relative);
939
+ if (read.kind !== 'file') {
940
+ return {
941
+ kind: 'failed',
942
+ detail: read.kind === 'error' ? read.detail : `${relative} was listed at "${ref}" but not found`,
943
+ };
830
944
  }
945
+ return found(relative, read.text, matchOf(selection));
831
946
  }
832
947
  return { kind: 'none', flagOnHead: null };
833
948
  }
@@ -922,7 +1037,22 @@ function prepareAgainstTrustBase(options, trustBase) {
922
1037
  files.push({ path: atBase.plan, baseText: atBase.planText });
923
1038
  }
924
1039
  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);
1040
+ return finishPreparation(options, {
1041
+ kind: 'imported',
1042
+ spec: atBase.spec,
1043
+ plan: atBase.plan,
1044
+ ref: trustBase,
1045
+ ...(atBase.match === undefined
1046
+ ? {}
1047
+ : { match: { ...atBase.match, remedy: eventPath === undefined ? 'spec-flag' : 'pr-body' } }),
1048
+ }, { ref: trustBase, specText: atBase.specText, planText: atBase.planText }, proposals);
1049
+ }
1050
+ // The base carries SEVERAL specs the branch name matches equally. Saying
1051
+ // the base has no spec for the branch would be false, so this returns
1052
+ // before the head-spec proposal below: no spec is proposed when the base
1053
+ // already has candidates. The proposals already collected are kept.
1054
+ if (atBase.selection?.why === 'ambiguous') {
1055
+ return noSpecChosen(branch, atBase.selection, '', proposals, trustBase);
926
1056
  }
927
1057
  // Nothing on the base. A spec the head carries is a proposal, and a --spec
928
1058
  // that names a file neither side has is still reported as missing.
@@ -948,15 +1078,10 @@ function prepareAgainstTrustBase(options, trustBase) {
948
1078
  proposals.push(`${headSpec} is a spec in this pull request but not on "${trustBase}": it is a proposal, ` +
949
1079
  'and pull requests are judged against it once it is on the base branch.');
950
1080
  }
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 }),
961
- };
1081
+ return noSpecChosen(branch, atBase.selection, `No contract on the base: "${trustBase}" carries no frozen ` +
1082
+ `${NATIVE_CONTRACT_PATHS.join(' or ')} and no spec under ${SPEC_DIR} for ` +
1083
+ `${branch === null ? 'this branch' : `branch "${branch}"`}. On a pull-request run the ` +
1084
+ 'intent contract comes from the base ref only, so nothing in this pull request can ' +
1085
+ 'become it; once a contract or spec is on the base branch, the next pull request is ' +
1086
+ 'judged against it.', proposals, trustBase);
962
1087
  }