@vaultcompass/conductor 0.2.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/policy.js ADDED
@@ -0,0 +1,328 @@
1
+ // The one policy file.
2
+ //
3
+ // Gates are keyed by the ROLE they fill (dependencies, secrets, intent) and
4
+ // name the product filling it in a `product` field. That indirection is
5
+ // worth the extra line: a product rename, or swapping one gate for another,
6
+ // becomes a one-line edit instead of a rename of the key a repository wrote
7
+ // its CI around, and a fourth role can arrive without the schema moving.
8
+ //
9
+ // Two rules this file exists to enforce, both of them decisions rather than
10
+ // mechanics:
11
+ //
12
+ // 1. THERE IS NO SHARED SEVERITY THRESHOLD. Two of the three products
13
+ // happen to share a four-level scale; the third scores a weighted
14
+ // rubric from 0 to 100 and has no per-finding severity at all. A single
15
+ // `failOn` at the top of the file would read as one decision and mean
16
+ // three different things, so a top-level `failOn` is rejected outright
17
+ // rather than silently ignored. Each gate keeps its own threshold in
18
+ // its own passthrough block, spelled the way that gate spells it.
19
+ //
20
+ // 2. THE PASSTHROUGH IS ACTUALLY A PASSTHROUGH. `options` keys are the
21
+ // gate's own long-flag names with the dashes stripped, and this file
22
+ // never maps, renames, or interprets one. That is what keeps the
23
+ // umbrella from growing a second, drifting copy of three CLIs, and it
24
+ // is why a gate gains a flag without this package needing a release.
25
+ // The only keys rejected are the handful the umbrella itself passes,
26
+ // because two writers of the same flag is a fight the user would have
27
+ // to debug from a stack trace.
28
+ // The 2020-12 dialect entry point, not ajv's default export: the default is
29
+ // still draft-07 and refuses a schema whose $schema names 2020-12, which is
30
+ // the dialect the shipped schema file declares.
31
+ import Ajv2020 from 'ajv/dist/2020.js';
32
+ import { readFileSync } from 'node:fs';
33
+ import path from 'node:path';
34
+ import { fileURLToPath } from 'node:url';
35
+ import { parse as parseYaml } from 'yaml';
36
+ export const POLICY_FILE_NAME = '.guardrails.yaml';
37
+ export const GATE_ROLES = ['dependencies', 'secrets', 'intent'];
38
+ export const PRODUCTS = ['dep-guard', 'vault-guard', 'intent-guard'];
39
+ /**
40
+ * When a gate runs, in order, earliest first.
41
+ *
42
+ * Stages are CUMULATIVE: a gate runs at its own stage and at every later
43
+ * one, so a run at `ci` runs everything that is enabled. The order of this
44
+ * array is the whole rule, which is why it is one array rather than three
45
+ * booleans: adding a fourth stopping point is an entry here and nothing
46
+ * else.
47
+ */
48
+ export const GATE_STAGES = ['commit', 'push', 'ci'];
49
+ /**
50
+ * Where each gate sits when the policy file does not say.
51
+ *
52
+ * Runtime is not what decides this. All three gates together take under a
53
+ * second on a staged commit; the cost is CEREMONY, and only the intent gate
54
+ * has any, because it wants a contract approved before the work starts.
55
+ * The other two are silent until they find something, and a secret that
56
+ * reaches a pull request is already on a remote, so the earliest stage is
57
+ * the only honest place for them.
58
+ */
59
+ export const DEFAULT_STAGE_FOR_ROLE = {
60
+ dependencies: 'commit',
61
+ secrets: 'commit',
62
+ intent: 'ci',
63
+ };
64
+ /** Whether a gate at `gateStage` runs during a run asked for at `requested`. */
65
+ export function runsAtStage(gateStage, requested) {
66
+ return GATE_STAGES.indexOf(gateStage) <= GATE_STAGES.indexOf(requested);
67
+ }
68
+ /**
69
+ * Which product fills which role today. Enforced on load: a policy that
70
+ * puts dep-guard in the `secrets` role is a mistake with a confusing
71
+ * failure mode (the secrets section of the report would carry dependency
72
+ * findings), so it is rejected at parse time instead.
73
+ *
74
+ * This map is the single place a rename lands. It is not the same thing as
75
+ * the roles being closed forever: a role gains a product by gaining an
76
+ * entry here and an adapter, and nothing else in the schema moves.
77
+ */
78
+ export const PRODUCT_FOR_ROLE = {
79
+ dependencies: 'dep-guard',
80
+ secrets: 'vault-guard',
81
+ intent: 'intent-guard',
82
+ };
83
+ /**
84
+ * Flags the umbrella supplies itself, per product. A policy that also sets
85
+ * one would put two writers on the same flag, and which one won would
86
+ * depend on that CLI's argument parser rather than on anything the user
87
+ * could read in their own policy file.
88
+ */
89
+ export const RESERVED_OPTIONS = {
90
+ 'dep-guard': ['format', 'staged', 'base'],
91
+ 'vault-guard': ['format', 'f', 'staged'],
92
+ // `base` is reserved even though the umbrella never passes it to this gate,
93
+ // and that is the point. The umbrella works the changed-path set out itself
94
+ // and hands over `--paths`, because `--project` may be a temporary
95
+ // directory holding nothing but a contract. A policy that also sets `base`
96
+ // sends intent-guard looking for git THERE, and the run exits 2 blaming git
97
+ // for a line in the policy file. Rejecting the key at load time is the only
98
+ // place that failure can be explained by the thing that caused it.
99
+ 'intent-guard': ['json', 'staged', 'project', 'paths', 'base'],
100
+ };
101
+ export class PolicyError extends Error {
102
+ constructor(message) {
103
+ super(message);
104
+ this.name = 'PolicyError';
105
+ }
106
+ }
107
+ const SCHEMA_PATH = path.join(path.dirname(fileURLToPath(import.meta.url)), '..', 'schema', 'guardrails.schema.json');
108
+ let validator;
109
+ function policyValidator() {
110
+ if (validator === undefined) {
111
+ // Ajv ships as CommonJS with an interop default; under NodeNext the
112
+ // namespace object is what an `import` binds, so the constructor has to
113
+ // be reached through `.default` when it is there. The cast is the price
114
+ // of that interop, and it is kept to this one line.
115
+ const imported = Ajv2020;
116
+ const AjvCtor = (imported.default ?? Ajv2020);
117
+ const ajv = new AjvCtor({ allErrors: true, strict: false, useDefaults: false });
118
+ const schema = JSON.parse(readFileSync(SCHEMA_PATH, 'utf8'));
119
+ validator = ajv.compile(schema);
120
+ }
121
+ return validator;
122
+ }
123
+ function describeErrors(errors, source) {
124
+ const lines = (errors ?? []).map((error) => {
125
+ const where = error.instancePath === '' ? '(root)' : error.instancePath;
126
+ // Name the offending key. Ajv puts it in a different param depending on
127
+ // which keyword failed, and an error that says only "property name must
128
+ // be valid" makes the user hunt for which one, which is exactly the
129
+ // moment a config-file error is most annoying.
130
+ const params = (error.params ?? {});
131
+ const offender = params.additionalProperty ?? params.propertyName;
132
+ const extra = offender === undefined ? '' : `: ${String(offender)}`;
133
+ return ` ${where} ${error.message ?? 'is invalid'}${extra}`;
134
+ });
135
+ return `${source} is not a valid policy file:\n${lines.join('\n')}`;
136
+ }
137
+ /**
138
+ * Why one reserved key is reserved.
139
+ *
140
+ * The general sentence, at the bottom, is that the umbrella writes that exact
141
+ * flag itself, and it is true of most of these keys. Three of them are
142
+ * reserved for other reasons, and a message giving the wrong reason sends
143
+ * somebody to the wrong fix: they go looking in the command line for a flag
144
+ * the umbrella never writes, find nothing, and conclude the rejection is a
145
+ * bug in this tool. A test in policy.test.ts derives the flags gateArgs
146
+ * actually writes and holds this list of exceptions to exactly those three,
147
+ * so a fourth cannot be added without saying why.
148
+ */
149
+ function reservedReason(product, key) {
150
+ if (product === 'intent-guard' && key === 'base') {
151
+ return ('The umbrella works the changed-path set out itself and passes --paths, because ' +
152
+ '--project may be a temporary directory holding only a contract. A --base here ' +
153
+ 'would be resolved against that directory, where there is no repository. ' +
154
+ "Use the umbrella's own --base instead.");
155
+ }
156
+ if (product === 'dep-guard' && key === 'base') {
157
+ return ('The umbrella never passes --base to this gate; it passes --staged, and a base here ' +
158
+ 'would fight it over which change set is being scanned. Use the umbrella own --staged, ' +
159
+ 'or leave it off to scan the working tree.');
160
+ }
161
+ if (product === 'vault-guard' && key === 'format') {
162
+ return ('The umbrella writes this option itself under its short name, -f json. A --format here ' +
163
+ 'is a second writer of the same option, and which one wins depends on that CLI argument ' +
164
+ 'parser. The report format is chosen with the umbrella own --format.');
165
+ }
166
+ return (`The umbrella passes that flag to ${product} itself, and two writers of one flag ` +
167
+ 'would resolve differently depending on that CLI argument parser.');
168
+ }
169
+ /**
170
+ * Parses and validates policy YAML.
171
+ *
172
+ * `source` is only used in error messages, so the same function serves the
173
+ * file loader and the tests without either needing a temporary directory.
174
+ */
175
+ export function parsePolicy(text, source) {
176
+ let raw;
177
+ try {
178
+ raw = parseYaml(text);
179
+ }
180
+ catch (err) {
181
+ throw new PolicyError(`${source} is not valid YAML: ${err.message}`);
182
+ }
183
+ if (raw === null || typeof raw !== 'object' || Array.isArray(raw)) {
184
+ throw new PolicyError(`${source} must contain a mapping at the top level.`);
185
+ }
186
+ const validate = policyValidator();
187
+ if (!validate(raw)) {
188
+ throw new PolicyError(describeErrors(validate.errors, source));
189
+ }
190
+ const document = raw;
191
+ const gates = {};
192
+ for (const role of GATE_ROLES) {
193
+ const entry = document.gates[role];
194
+ if (entry === undefined) {
195
+ continue;
196
+ }
197
+ const product = entry.product;
198
+ if (PRODUCT_FOR_ROLE[role] !== product) {
199
+ throw new PolicyError(`${source}: the "${role}" role is filled by ${PRODUCT_FOR_ROLE[role]}, not ${product}. ` +
200
+ 'Gates are keyed by role; put the product in the role it fills.');
201
+ }
202
+ const options = (entry.options ?? {});
203
+ for (const key of Object.keys(options)) {
204
+ if (RESERVED_OPTIONS[product].includes(key)) {
205
+ throw new PolicyError(`${source}: "${key}" under gates.${role}.options is reserved. ` +
206
+ reservedReason(product, key));
207
+ }
208
+ }
209
+ const command = entry.command;
210
+ if (command !== undefined && !path.isAbsolute(command)) {
211
+ throw new PolicyError(`${source}: gates.${role}.command must be an absolute path, got "${command}". ` +
212
+ 'A bare name would be resolved against PATH, which is what resolution already does; ' +
213
+ 'the override exists to name a build PATH cannot reach.');
214
+ }
215
+ gates[role] = {
216
+ role,
217
+ product,
218
+ enabled: entry.enabled === undefined ? true : Boolean(entry.enabled),
219
+ // The schema has already refused anything outside the enum, so the
220
+ // only two cases left are "the file said one" and "it did not".
221
+ stage: entry.stage ?? DEFAULT_STAGE_FOR_ROLE[role],
222
+ // Defaults to true, and the schema has already refused anything that
223
+ // is not a boolean. Enforcement is the state a gate is in unless
224
+ // somebody wrote down that it is not.
225
+ enforce: entry.enforce === undefined ? true : Boolean(entry.enforce),
226
+ // Nothing on the command line has been read at this point, so no gate
227
+ // can have been excluded by one yet.
228
+ excludedByCli: false,
229
+ ...(command === undefined ? {} : { command }),
230
+ ...(entry.args === undefined ? {} : { args: entry.args }),
231
+ options,
232
+ };
233
+ }
234
+ return {
235
+ version: 1,
236
+ gates,
237
+ report: { format: document.report?.format ?? 'text' },
238
+ };
239
+ }
240
+ /** Reads the policy file at a repository root. */
241
+ export function loadPolicy(repoRoot) {
242
+ const filePath = path.join(repoRoot, POLICY_FILE_NAME);
243
+ let text;
244
+ try {
245
+ text = readFileSync(filePath, 'utf8');
246
+ }
247
+ catch {
248
+ throw new PolicyError(`No ${POLICY_FILE_NAME} in ${repoRoot}. Run "conductor init" to write one. ` +
249
+ 'The umbrella deliberately has no implicit default policy: a run that gates a commit ' +
250
+ 'should be explainable from a file in the repository, not from a built-in.');
251
+ }
252
+ return parsePolicy(text, POLICY_FILE_NAME);
253
+ }
254
+ /**
255
+ * Layer three of the precedence chain.
256
+ *
257
+ * Layer one is each product's own config file, which the umbrella never
258
+ * writes or reads. Layer two is this policy file, delivered to the child as
259
+ * command-line flags, which every one of the three treats as higher
260
+ * precedence than its own config. Layer three is a flag on the umbrella's
261
+ * own command line, and in v0.1 that is exactly one thing: restricting the
262
+ * run to named roles. There is deliberately no umbrella flag that rewrites
263
+ * a gate's threshold, because a threshold means something different in each
264
+ * product and a single flag would have to pick one meaning silently.
265
+ */
266
+ export function applyCliOverrides(policy, overrides) {
267
+ if (overrides.gates === undefined) {
268
+ return policy;
269
+ }
270
+ for (const role of overrides.gates) {
271
+ if (policy.gates[role] === undefined) {
272
+ throw new PolicyError(`--gate ${role} was asked for, but ${POLICY_FILE_NAME} declares no "${role}" gate.`);
273
+ }
274
+ }
275
+ const gates = {};
276
+ for (const role of GATE_ROLES) {
277
+ const gate = policy.gates[role];
278
+ if (gate === undefined) {
279
+ continue;
280
+ }
281
+ const named = overrides.gates.includes(role);
282
+ gates[role] = {
283
+ ...gate,
284
+ enabled: named,
285
+ // Only a gate that WAS on and is not now. A gate the policy file had
286
+ // already switched off was not excluded by this flag, and reporting it
287
+ // as such would read the user's own standing decision back to them as
288
+ // something the command line did.
289
+ excludedByCli: !named && gate.enabled,
290
+ };
291
+ }
292
+ return { ...policy, gates };
293
+ }
294
+ /** Enabled gates in role order, so a report's section order never depends on file order. */
295
+ export function enabledGates(policy) {
296
+ return GATE_ROLES.map((role) => policy.gates[role]).filter((gate) => gate !== undefined && gate.enabled);
297
+ }
298
+ /**
299
+ * Renders a passthrough option bag as child-process arguments.
300
+ *
301
+ * Keys are sorted so two policy files that differ only in key order produce
302
+ * the same command line, which is what makes a run reproducible and a
303
+ * report diffable.
304
+ */
305
+ export function renderOptionFlags(options) {
306
+ const args = [];
307
+ for (const key of Object.keys(options).sort()) {
308
+ const value = options[key];
309
+ if (value === true) {
310
+ args.push(`--${key}`);
311
+ }
312
+ else if (value === false) {
313
+ // Both dep-guard and intent-guard spell a negated boolean this way,
314
+ // and it is commander's own convention, so it is the one negation
315
+ // rendering that is right without the umbrella knowing the flag.
316
+ args.push(`--no-${key}`);
317
+ }
318
+ else if (Array.isArray(value)) {
319
+ for (const item of value) {
320
+ args.push(`--${key}`, String(item));
321
+ }
322
+ }
323
+ else {
324
+ args.push(`--${key}`, String(value));
325
+ }
326
+ }
327
+ return args;
328
+ }
@@ -0,0 +1,52 @@
1
+ import type { GatePolicy, Product } from './policy.js';
2
+ export type ResolutionSource = 'policy' | 'path' | 'node_modules';
3
+ export interface Candidate {
4
+ /** Executable name. */
5
+ name: string;
6
+ /** Arguments this binary needs before the umbrella's own. */
7
+ prefix: string[];
8
+ /**
9
+ * Whether `<name> --version` can be relied on to print a version instead
10
+ * of doing work. False for the per-command binaries, per rule 2 above: no
11
+ * published version under the names resolved here ignores the flag, so
12
+ * this is a guard against the class of bug rather than against a release
13
+ * anybody can install.
14
+ */
15
+ versionSafe: boolean;
16
+ }
17
+ export interface VersionProbe {
18
+ command: string;
19
+ argv: string[];
20
+ }
21
+ export interface ResolvedBinary {
22
+ /** What to spawn. */
23
+ command: string;
24
+ /** Arguments placed before the ones the umbrella adds. */
25
+ argvPrefix: string[];
26
+ source: ResolutionSource;
27
+ /** The candidate name this matched, for the report's gate header. */
28
+ candidate: string;
29
+ /** A safe way to ask this product its version, or null when there is none. */
30
+ versionProbe: VersionProbe | null;
31
+ }
32
+ export declare const CANDIDATES: Record<Product, Candidate[]>;
33
+ export declare class ResolveError extends Error {
34
+ constructor(message: string);
35
+ }
36
+ /**
37
+ * Resolves the binary for one gate.
38
+ *
39
+ * `pathValue` is passed in rather than read from the environment so tests
40
+ * can put a shim directory in front of whatever the machine has installed,
41
+ * without mutating process.env for every other test in the file.
42
+ *
43
+ * Returns null when nothing resolves. That is not an error here: the caller
44
+ * turns it into the umbrella's own blocking finding, which is a better
45
+ * failure than a thrown exception that takes the other gates' reports with
46
+ * it. A CONFIGURED command that does not exist does throw, because the user
47
+ * named one specific file and falling back to something else would run a
48
+ * different tool than the one they asked for.
49
+ */
50
+ export declare function resolveGateBinary(gate: GatePolicy, repoRoot: string, pathValue: string): ResolvedBinary | null;
51
+ /** Every name resolution would try, for the missing-gate finding's message. */
52
+ export declare function candidateNames(product: Product): string[];
@@ -0,0 +1,207 @@
1
+ // Finding each gate's binary.
2
+ //
3
+ // Three rules, each of which came out of the products rather than out of a
4
+ // preference:
5
+ //
6
+ // 1. The CURRENT name wins over an older one wherever each is installed.
7
+ // The obvious loop is location-major (search all of PATH, then all of
8
+ // node_modules) but that pins a repository to whatever name happens to
9
+ // be global: a machine with a leftover pre-rename install on PATH would
10
+ // beat the repository's own current-name dev dependency, silently and
11
+ // for as long as the old package stayed installed. So the outer loop is
12
+ // the candidate list, and only the inner loop is location.
13
+ //
14
+ // 1b. Within one name, the REPOSITORY'S OWN COPY wins over a global
15
+ // install. This was the other way round until a dogfood run found a
16
+ // global vault-guard 1.4.3 running over the repository's pinned 1.4.1,
17
+ // silently, with the report naming a version that repository had
18
+ // deliberately not chosen. `pnpm exec` in the same repository runs the
19
+ // pin, so PATH-first meant the umbrella and the package manager
20
+ // disagreed about which copy of a gate a repository means, and the
21
+ // package manager is the one the repository's lockfile agrees with.
22
+ // Note that this is the opposite ordering from rule 1, and deliberately
23
+ // so: a NAME is a statement about which product, and the repository has
24
+ // no say in that; a LOCATION is a statement about which build, and the
25
+ // repository does.
26
+ //
27
+ // 2. Only a unified binary is asked for its version. `intent-guard`
28
+ // answers --version; a per-command binary once did not parse the flag at
29
+ // all and RAN THE GATE against the current directory instead, and a
30
+ // version probe that runs a gate is not a probe.
31
+ //
32
+ // That is fixed, and NO PUBLISHED VERSION OF THE NAMES RESOLVED HERE
33
+ // has the bug: the fix is the commit v1.2.0 points at, only 1.2.0 and
34
+ // 1.2.1 were ever published under these names, and the releases that
35
+ // had it were the pre-rename packages this file already refuses to
36
+ // resolve at all. So this is belt and braces against a class of bug
37
+ // rather than a live hazard. It is kept because it costs one field on a
38
+ // candidate and a fallback nobody exercises, and because the failure it
39
+ // prevents is silent and happens in the user's own repository: when the
40
+ // resolved binary is a per-command one, the unified binary of the same
41
+ // product is resolved separately and asked instead, and when that is not
42
+ // installed either the version is reported unknown rather than guessed.
43
+ //
44
+ // 3. There is no npx fallback. The draft proposed `npx --no-install` as a
45
+ // last resort, and it is dropped here on purpose: it makes what ran
46
+ // depend on a package cache the report cannot describe, and a gate that
47
+ // "ran" from an unknown version is worse than one that is honestly
48
+ // reported missing.
49
+ import { accessSync, constants, statSync } from 'node:fs';
50
+ import path from 'node:path';
51
+ export const CANDIDATES = {
52
+ 'dep-guard': [{ name: 'dep-guard', prefix: ['scan'], versionSafe: true }],
53
+ 'vault-guard': [{ name: 'vault-guard', prefix: ['scan'], versionSafe: true }],
54
+ // intent-guard-check is a per-command binary intent-guard shipped before
55
+ // 1.2.0, marked unsafe to ask for a version, per rule 2 above. The
56
+ // pre-rename conductor and conductor-check names are not resolved here:
57
+ // those packages are deprecated and had no users, so a pre-rename install
58
+ // is not a supported target, and the umbrella's own binary now carries
59
+ // the name conductor.
60
+ 'intent-guard': [
61
+ { name: 'intent-guard', prefix: ['check'], versionSafe: true },
62
+ { name: 'intent-guard-check', prefix: [], versionSafe: false },
63
+ ],
64
+ };
65
+ export class ResolveError extends Error {
66
+ constructor(message) {
67
+ super(message);
68
+ this.name = 'ResolveError';
69
+ }
70
+ }
71
+ function isExecutableFile(candidate) {
72
+ try {
73
+ if (!statSync(candidate).isFile()) {
74
+ return false;
75
+ }
76
+ accessSync(candidate, constants.X_OK);
77
+ return true;
78
+ }
79
+ catch {
80
+ return false;
81
+ }
82
+ }
83
+ function existsAsFile(candidate) {
84
+ try {
85
+ return statSync(candidate).isFile();
86
+ }
87
+ catch {
88
+ return false;
89
+ }
90
+ }
91
+ function findOnPath(name, pathValue) {
92
+ for (const dir of pathValue.split(path.delimiter)) {
93
+ if (dir.length === 0) {
94
+ continue;
95
+ }
96
+ const full = path.join(dir, name);
97
+ if (isExecutableFile(full)) {
98
+ return full;
99
+ }
100
+ }
101
+ return null;
102
+ }
103
+ function findInNodeModules(name, repoRoot) {
104
+ const full = path.join(repoRoot, 'node_modules', '.bin', name);
105
+ return isExecutableFile(full) ? full : null;
106
+ }
107
+ function locate(name, repoRoot, pathValue) {
108
+ // The repository's own copy first: a project pin beats a global install,
109
+ // which is what "pnpm exec <name>" does in the same repository.
110
+ const local = findInNodeModules(name, repoRoot);
111
+ if (local !== null) {
112
+ return { command: local, source: 'node_modules' };
113
+ }
114
+ const onPath = findOnPath(name, pathValue);
115
+ if (onPath !== null) {
116
+ return { command: onPath, source: 'path' };
117
+ }
118
+ return null;
119
+ }
120
+ /** The candidate whose --version can be asked without running anything. */
121
+ function versionProbeFor(product, resolvedCandidate, resolvedCommand, repoRoot, pathValue) {
122
+ if (resolvedCandidate.versionSafe) {
123
+ return { command: resolvedCommand, argv: ['--version'] };
124
+ }
125
+ for (const candidate of CANDIDATES[product]) {
126
+ if (!candidate.versionSafe) {
127
+ continue;
128
+ }
129
+ const found = locate(candidate.name, repoRoot, pathValue);
130
+ if (found !== null) {
131
+ return { command: found.command, argv: ['--version'] };
132
+ }
133
+ }
134
+ return null;
135
+ }
136
+ /** Strips a script extension so "intent-guard.js" matches the candidate table. */
137
+ function baseName(file) {
138
+ return path.basename(file).replace(/\.(?:js|mjs|cjs)$/, '');
139
+ }
140
+ /**
141
+ * Resolves the binary for one gate.
142
+ *
143
+ * `pathValue` is passed in rather than read from the environment so tests
144
+ * can put a shim directory in front of whatever the machine has installed,
145
+ * without mutating process.env for every other test in the file.
146
+ *
147
+ * Returns null when nothing resolves. That is not an error here: the caller
148
+ * turns it into the umbrella's own blocking finding, which is a better
149
+ * failure than a thrown exception that takes the other gates' reports with
150
+ * it. A CONFIGURED command that does not exist does throw, because the user
151
+ * named one specific file and falling back to something else would run a
152
+ * different tool than the one they asked for.
153
+ */
154
+ export function resolveGateBinary(gate, repoRoot, pathValue) {
155
+ const table = CANDIDATES[gate.product];
156
+ if (gate.command !== undefined) {
157
+ if (!existsAsFile(gate.command)) {
158
+ throw new ResolveError(`gates.${gate.role}.command points at "${gate.command}", which is not a file. ` +
159
+ 'Fix the path or remove the override; the umbrella will not quietly run something else.');
160
+ }
161
+ const inferred = table.find((candidate) => candidate.name === baseName(gate.command));
162
+ const prefix = gate.args ?? inferred?.prefix ?? table[0].prefix;
163
+ const candidateName = inferred?.name ?? baseName(gate.command);
164
+ const candidate = inferred ?? table[0];
165
+ // A build directory holds plain .js files with a shebang but no
166
+ // executable bit surprisingly often (a fresh tsc output, a file copied
167
+ // out of a tarball). Running it through this same Node is exactly what
168
+ // the shebang asks for and keeps the override usable for the case it
169
+ // exists to serve: pointing at a build that is not installed anywhere.
170
+ if (!isExecutableFile(gate.command) && /\.(?:js|mjs|cjs)$/.test(gate.command)) {
171
+ return {
172
+ command: process.execPath,
173
+ argvPrefix: [gate.command, ...prefix],
174
+ source: 'policy',
175
+ candidate: candidateName,
176
+ versionProbe: candidate.versionSafe
177
+ ? { command: process.execPath, argv: [gate.command, '--version'] }
178
+ : versionProbeFor(gate.product, candidate, gate.command, repoRoot, pathValue),
179
+ };
180
+ }
181
+ return {
182
+ command: gate.command,
183
+ argvPrefix: prefix,
184
+ source: 'policy',
185
+ candidate: candidateName,
186
+ versionProbe: versionProbeFor(gate.product, candidate, gate.command, repoRoot, pathValue),
187
+ };
188
+ }
189
+ for (const candidate of table) {
190
+ const found = locate(candidate.name, repoRoot, pathValue);
191
+ if (found === null) {
192
+ continue;
193
+ }
194
+ return {
195
+ command: found.command,
196
+ argvPrefix: [...candidate.prefix],
197
+ source: found.source,
198
+ candidate: candidate.name,
199
+ versionProbe: versionProbeFor(gate.product, candidate, found.command, repoRoot, pathValue),
200
+ };
201
+ }
202
+ return null;
203
+ }
204
+ /** Every name resolution would try, for the missing-gate finding's message. */
205
+ export function candidateNames(product) {
206
+ return CANDIDATES[product].map((candidate) => candidate.name);
207
+ }