@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/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Vault & Compass
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,412 @@
1
+ # conductor
2
+
3
+ conductor is the optional layer over three guardrail gates that each work on
4
+ their own. All it adds is one policy file, one init, one hook and one report.
5
+ Delete it and every gate still runs, with exactly the configuration it had.
6
+
7
+ <!-- guardrails-family: shared block, keep it identical in dep-guard, vault-guard, intent-guard and conductor -->
8
+ The Vault & Compass guardrails are three gates over an AI-assisted coding
9
+ session: [dep-guard](https://www.npmjs.com/package/@vaultcompass/dep-guard)
10
+ checks what comes in (hallucinated package names, typosquats, tampered
11
+ lockfile entries),
12
+ [vault-guard](https://www.npmjs.com/package/@vaultcompass/vault-guard) checks
13
+ what goes out (credentials about to be committed), and
14
+ [intent-guard](https://www.npmjs.com/package/@vaultcompass/intent-guard)
15
+ checks the change against what was approved (drift from a frozen intent
16
+ contract, and change budgets). Each one installs, configures and runs on its
17
+ own;
18
+ [conductor](https://www.npmjs.com/package/@vaultcompass/conductor) is the
19
+ optional umbrella that runs them from one policy file, one hook and one
20
+ report.
21
+ <!-- /guardrails-family -->
22
+
23
+ ## Why
24
+
25
+ Run all three and you have three inits, three config files, three output
26
+ shapes, and three pre-commit hooks fighting over one file. That is the
27
+ friction this repository removes, and that is all it removes:
28
+
29
+ - **one policy file**, `.guardrails.yaml`, keyed by the role each gate
30
+ fills rather than by the product filling it;
31
+ - **one init**, which writes that file and a single pre-commit hook running
32
+ every enabled gate whose stage is `commit`, which by default is every gate
33
+ but the intent one;
34
+ - **one report**, as text for a terminal or as a single SARIF 2.1.0 log
35
+ with one run per gate.
36
+
37
+ **A clean run prints one line.** Most runs are clean, and the design
38
+ constraint on all of this is that the gates must not slow development down,
39
+ with ceremony rather than runtime named as the cost. A screenful of per-gate
40
+ detail on a commit that found nothing is that cost, paid on every commit, and
41
+ it is what makes a team switch a hook off.
42
+
43
+ ## Quickstart
44
+
45
+ Install the gates. Each of them is a working tool on its own, and none of
46
+ them needs this one:
47
+
48
+ ```
49
+ npm install -g @vaultcompass/dep-guard @vaultcompass/vault-guard @vaultcompass/intent-guard
50
+ ```
51
+
52
+ The umbrella is optional. Install it when running the three separately has
53
+ become the annoying part:
54
+
55
+ ```
56
+ npm install -g @vaultcompass/conductor
57
+ ```
58
+
59
+ From the repository root, look before you write:
60
+
61
+ ```
62
+ conductor init --dry-run
63
+ ```
64
+
65
+ That prints every file it would write or change and writes nothing. Then:
66
+
67
+ ```
68
+ conductor init
69
+ ```
70
+
71
+ which writes `.guardrails.yaml` with every gate listed and only the ones it
72
+ found switched on, plus one pre-commit hook running every enabled gate whose
73
+ stage is `commit`.
74
+
75
+ Commit something. A clean commit prints one line:
76
+
77
+ ```
78
+ conductor: clean, nothing blocked. 2 gate(s) ran: dependencies (dep-guard), secrets (vault-guard). Deferred to a later stage: intent (intent-guard) from stage ci. 1 note(s). Re-run with --verbose for the full report.
79
+ ```
80
+
81
+ A commit with a staged credential in it prints the full report and exits 1:
82
+
83
+ ```
84
+ conductor run: 2 gate(s), 1 finding(s)
85
+
86
+ dependencies dep-guard 0.2.1 exit 0 251ms via dep-guard on path
87
+ threshold medium suppressed 0 ignored 0
88
+
89
+ secrets vault-guard 1.4.6 exit 1 97ms via vault-guard on path
90
+ BLOCKING critical vault-guard/anthropic jest.config.mjs:27:32
91
+ Possible secret of type 'anthropic'
92
+ threshold medium suppressed 0 ignored not reported
93
+
94
+ deferred intent intent-guard did not run here; it runs from stage ci onwards
95
+
96
+ verdict: exit 1, 1 blocking finding(s) across 2 gate(s).
97
+ ```
98
+
99
+ Both gates there are the ones you installed a moment ago, running with their
100
+ own thresholds and their own baselines. The umbrella found nothing of its
101
+ own, because it looks for nothing of its own.
102
+
103
+ ## What it deliberately is not
104
+
105
+ It is not a fourth gate. It finds no bugs of its own and scans nothing.
106
+ Every finding about your code came from one of the three gates and is
107
+ labelled with which one. The only findings it adds are about the gates
108
+ themselves, and they are labelled `conductor`: a gate that is switched on
109
+ and could not run, and a gate whose output it could not read. Those exist
110
+ because a report that reads clean when nothing looked is the failure this
111
+ whole family exists to prevent.
112
+
113
+ It is not something you adopt before the gates are useful. Each gate keeps
114
+ its own config file, its own baseline, its own thresholds, and its own exit
115
+ codes. The umbrella never writes into any of them: it passes a policy to
116
+ each gate as command-line flags, which every one of the three already
117
+ treats as higher precedence than its own config. Delete this tool and every
118
+ gate still runs, with exactly the configuration it had, because nothing
119
+ here ever touched it.
120
+
121
+ It does not overrule a gate. A gate that says a commit is blocked blocks
122
+ the commit. The umbrella can add to that decision and never subtracts from
123
+ it.
124
+
125
+ ## The policy file
126
+
127
+ `.guardrails.yaml`, at the repository root. `conductor init` writes one with
128
+ every gate listed and only the ones it found switched on.
129
+
130
+ ```yaml
131
+ version: 1
132
+
133
+ gates:
134
+ dependencies:
135
+ product: dep-guard
136
+ enabled: true
137
+ stage: commit
138
+ enforce: true
139
+ options:
140
+ fail-on: high
141
+ secrets:
142
+ product: vault-guard
143
+ enabled: true
144
+ stage: commit
145
+ enforce: true
146
+ intent:
147
+ product: intent-guard
148
+ enabled: true
149
+ stage: ci
150
+ # It runs and reports in CI without failing the run. Flip it to
151
+ # true once a few pull requests show the signal is worth blocking on.
152
+ enforce: false
153
+ options:
154
+ require-frozen: false
155
+
156
+ report:
157
+ format: text
158
+ ```
159
+
160
+ **Gates are keyed by role**, not by product. `dependencies`, `secrets`,
161
+ `intent`. The `product` field says which binary fills that role today.
162
+
163
+ **`enabled`** defaults to true. A gate that is enabled and whose binary
164
+ cannot be found is a blocking finding of the umbrella's own
165
+ (`conductor/gate-missing`), never a silent skip.
166
+
167
+ **`stage`** says when a gate runs: `commit`, `push`, or `ci`. Stages are
168
+ **cumulative** in that order, so a gate runs at its own stage and at every
169
+ later one, and a run at `ci` runs everything that is enabled. The defaults
170
+ are `commit` for `dependencies` and `secrets` and `ci` for `intent`.
171
+
172
+ A gate held back by the stage filter is never silent. It is one line in the
173
+ text report naming the stage it is waiting for, and a `conductor/gate-deferred`
174
+ notification in the SARIF log's `conductor` run. Its binary is not even looked
175
+ for, so a gate installed only on the CI image does not fail a developer's
176
+ commit.
177
+
178
+ **`enforce`** defaults to true. A gate with `enforce: false` runs, reports,
179
+ and its findings appear in the text report and the SARIF log exactly as an
180
+ enforced gate's do. The only thing it cannot do is change the exit code: its
181
+ blocking findings do not raise it, and its failing to run at all does not
182
+ make the run exit 2. That is the adoption ramp, so a gate can be switched on
183
+ and read for a few weeks before it is allowed to refuse anybody's commit.
184
+ `init` writes it out for every gate, and starts the intent gate at `false`.
185
+
186
+ **`options`** is handed to that gate unchanged. Each key is one of that
187
+ gate's own long flags with the leading dashes stripped: `fail-on: high`
188
+ becomes `--fail-on high`, `online: true` becomes `--online`,
189
+ `require-frozen: false` becomes `--no-require-frozen`, and a list becomes
190
+ one flag per entry. The handful of flags the umbrella supplies itself (the
191
+ JSON format flag, `--staged`, and the intent gate's `--project`) are
192
+ rejected if you also set them, rather than being silently overridden.
193
+
194
+ **There is no shared severity threshold, on purpose.** One top-level
195
+ `failOn` would read as one decision and mean three different things, so
196
+ setting one is an error rather than a knob that half works. Each gate keeps
197
+ its own threshold in its own `options` block, spelled the way that gate
198
+ spells it.
199
+
200
+ **`command`** takes an absolute path and overrides binary resolution for
201
+ that gate, for pointing at a build that is not installed anywhere.
202
+
203
+ **`report.format`** is `text` or `sarif`, and `--format` overrides it.
204
+
205
+ ## Commands
206
+
207
+ `conductor init` writes the policy file and one pre-commit hook.
208
+
209
+ - `--dry-run` prints every file it would write or change and writes nothing.
210
+ - `--revert` removes exactly what a previous init wrote, and nothing else.
211
+ A file changed since init is reported and left alone.
212
+ - `--adopt` replaces one gate's own pre-commit hook with the umbrella hook.
213
+ Without it, init reports the collision and stops rather than stacking a
214
+ second invocation of a gate that is already hooked. A hook the umbrella
215
+ does not recognise is never replaced, with or without `--adopt`.
216
+ - `--force` acts on a file **conductor itself wrote** and that has changed
217
+ since: on its own it replaces a managed hook somebody has edited, and with
218
+ `--revert` it removes one, restoring an adopted hook if there was one. It
219
+ never overrides a foreign-hook or gate-hook refusal, with or without
220
+ `--adopt`: those hooks were never conductor's, and no flag here turns
221
+ somebody else's file into one this tool may overwrite.
222
+
223
+ `conductor run` runs every enabled gate and prints one report.
224
+
225
+ - `--staged` gates the git index against HEAD, which is what the hook does.
226
+ - `--format text|sarif`.
227
+ - `--stage commit|push|ci` runs the gates at that stopping point and every
228
+ earlier one. With no `--stage` at all, every enabled gate runs, whatever
229
+ its stage. An unknown value is a usage error and exits 2 rather than
230
+ quietly running everything or nothing: a typo in a CI file that runs every
231
+ gate and one that runs none both look like a passing build.
232
+ - `--base <ref>` measures the intent gate against what this branch changed
233
+ since `<ref>`, rather than against the index. See "Intent at a pull
234
+ request" below.
235
+ - `--spec <path>` names the spec the intent gate imports its contract from.
236
+ - `--output <path>` writes the report to a file instead of to stdout, for a
237
+ CI step that uploads it. One line still goes to stdout, because a job whose
238
+ only product is an uploaded artifact otherwise reads as a job that did
239
+ nothing. A path that cannot be written is exit 2, not a green run beside a
240
+ report nobody can read.
241
+ - `--verbose` prints the full per-gate report even when the run is clean.
242
+ Text output only; the SARIF log never changes shape with it.
243
+ - `--gate <role>`, repeatable. A gate the policy file enables and this flag
244
+ leaves out is named as excluded, on one line in the text report and as a
245
+ `conductor/gate-excluded` notification in the SARIF log's `conductor` run.
246
+ It never reaches the exit code.
247
+
248
+ ### Exit codes
249
+
250
+ - **0** every enabled gate ran and none blocked.
251
+ - **1** every enabled gate ran and at least one blocked.
252
+ - **2** an enabled gate could not run: its binary is missing, it exited with
253
+ its own could-not-run code, or it exited 1 with nothing parseable on
254
+ stdout, which is what a rejected config file looks like from two of the
255
+ three.
256
+
257
+ ## Intent at a pull request
258
+
259
+ The intent gate is the only one of the three with any ceremony: its native
260
+ flow wants a contract approved before the work starts, which is a per-task
261
+ human step. That step is exactly what a pull request cannot carry, so at the
262
+ `ci` stage the umbrella stands in for it.
263
+
264
+ **What it measures.** With `--base <ref>`, the changed-path set is what this
265
+ branch changed since it forked, from
266
+ `git diff --name-only --no-renames <base>...HEAD` in the repository root.
267
+
268
+ With no `--base`, `GITHUB_BASE_REF` is used as `origin/<value>` when it is
269
+ set, and the text report says so. With neither, the intent gate runs the way
270
+ it does at a commit: against the staged index, or the paths you name.
271
+
272
+ A git failure here is **fail-closed**: could-not-run, so exit 2 for an
273
+ enforced gate and a note for an unenforced one. There is deliberately no
274
+ fallback to an empty path set, because an empty path set is what a passing
275
+ gate looks like. In Actions this is almost always a shallow checkout, so
276
+ **`actions/checkout` needs `fetch-depth: 0`** for the merge base to exist.
277
+
278
+ **Where the contract comes from**, in order:
279
+
280
+ 1. `--spec <path>` on the umbrella's own command line. Typed just now, so it
281
+ outranks everything, and a path here that is not on disk is reported
282
+ rather than replaced: running a different contract than the one somebody
283
+ named is the wrong kindness.
284
+ 2. `<repo>/.conductor/intent-contract.yaml`, when it is **frozen**. The
285
+ native flow wins wherever a team has done it. Frozen is the test rather
286
+ than present: an unfrozen contract is a draft somebody left behind, and
287
+ running the gate against it fails every pull request on "not frozen by
288
+ user" without checking anything.
289
+ 3. The **first** `Spec: <path>` line in the pull request body, read from the
290
+ event payload at `GITHUB_EVENT_PATH`. A path here that is not on disk, or
291
+ one that leaves the repository, falls through to the next rule.
292
+ 4. A markdown file **directly under** `docs/superpowers/specs` whose name
293
+ relates to the branch. The branch slug is the branch name with its first
294
+ segment (`feat/`, `fix/`) removed; a filename is reduced by stripping a
295
+ `YYYY-MM-DD-` prefix and a trailing `-design`; the two are candidates when
296
+ either contains the other. Several candidates are ranked: a stem **equal**
297
+ to the slug first, then the **longest** stem, and only then the newest
298
+ name, which is a lexical tie-break, so **date every spec**.
299
+
300
+ **A branch with neither** is a third state beside deferred and could-not-run:
301
+ the gate is switched on, it ran, and it had nothing to check. It gets one
302
+ line in the text report and one `intent-guard/no-contract` notification
303
+ in the `conductor` run, and it **never** reaches the exit code, enforced or
304
+ not. A branch with no spec is a branch this gate has no opinion about, and
305
+ turning that into a failed build is how a gate gets switched off across a
306
+ repository.
307
+
308
+ **What blocks is unchanged.** Blocking stays where intent-guard puts it:
309
+ budget breaches block, subject to `enforce`. Drift on its own is reported and
310
+ not blocked, which is already intent-guard's own behaviour. The umbrella adds
311
+ no severity threshold of its own here either.
312
+
313
+ ## The Action
314
+
315
+ `action.yml` at the root is a composite action that runs the gates at the
316
+ `ci` stage and writes one SARIF log for the caller to upload.
317
+
318
+ It **installs nothing**, on purpose. It runs the conductor your repository
319
+ already depends on, so the version gating your pull requests is the one your
320
+ lockfile pins rather than whatever the registry serves that morning; instead
321
+ of installing, the action checks for `node_modules/.bin/conductor` and fails
322
+ with a sentence saying to add it as a devDependency. `--base` is passed only when the
323
+ `base-ref` input names one; left empty, the umbrella reads `GITHUB_BASE_REF`
324
+ itself and treats an empty value as "not a pull request", which is what a
325
+ push build wants.
326
+
327
+ ```yaml
328
+ name: guardrails
329
+ on: pull_request
330
+
331
+ jobs:
332
+ gates:
333
+ runs-on: ubuntu-latest
334
+ permissions:
335
+ contents: read
336
+ security-events: write
337
+ steps:
338
+ - uses: actions/checkout@v4
339
+ with:
340
+ # Required. Without it there is no merge base to diff against, and
341
+ # the intent gate fails closed rather than checking an empty set.
342
+ fetch-depth: 0
343
+ - uses: pnpm/action-setup@v4
344
+ - uses: actions/setup-node@v4
345
+ with:
346
+ node-version: 22
347
+ cache: pnpm
348
+ - run: pnpm install --frozen-lockfile
349
+ - id: conductor
350
+ uses: ./
351
+ with:
352
+ output: conductor.sarif
353
+ - uses: github/codeql-action/upload-sarif@v3
354
+ # Always: the log is most worth having on the run that failed.
355
+ if: always()
356
+ # The sarif path is published BEFORE the gates run, so on the exit 2
357
+ # cases that fail before anything is written (a policy error, an
358
+ # unknown stage, an unwritable output path) it names a file that was
359
+ # never created. Publishing early is the right trade for the common
360
+ # case, which is exit 1 with a real log; this step just has to
361
+ # tolerate the file being missing rather than failing the job a second
362
+ # time over it.
363
+ continue-on-error: true
364
+ with:
365
+ sarif_file: ${{ steps.conductor.outputs.sarif }}
366
+ ```
367
+
368
+ The `@v4` pins there are readable, not safe: a tag moves, so pinning by one
369
+ runs whatever its author pushes to it next. Pin every third-party action by
370
+ commit digest in a workflow you actually run, the way this repository's own
371
+ workflows do.
372
+
373
+ ## What is in and what is out
374
+
375
+ In: the policy file and its schema, `init` with dry-run, revert, and adopt,
376
+ `run` producing the combined text report and a combined SARIF log, the
377
+ composed exit code, per-gate `stage` and `enforce`, `run --stage`, the intent
378
+ gate at a pull request (`--base`, `--spec`, the imported contract, the
379
+ no-contract advisory), and the composite Action.
380
+
381
+ Out, deliberately: a unified baseline or ledger (each gate keeps its own, and
382
+ their fingerprints are not equally durable, so one shared file would expire
383
+ entries silently for one product and not another), an MCP registration,
384
+ running the gates concurrently, and any finding of the umbrella's own about
385
+ anybody's CODE. The findings it does raise are all about the gates
386
+ themselves: `conductor/gate-missing`, `conductor/gate-output-unparseable`
387
+ and `conductor/gate-failed`, plus the two diagnostics
388
+ `conductor/blocking-count-mismatch` and
389
+ `conductor/blocking-threshold-unknown`.
390
+
391
+ Also out: intent at the cohesion level, which is what a merge or a
392
+ promotion would want and which the audits do by hand today; and anything that
393
+ runs inside an agent session or on save, which intent-guard's own optional
394
+ session hooks already cover.
395
+
396
+ 0.2.0 is the first release, of a young tool rather than a finished one. The
397
+ gates are still the product; this is the convenience layer over them.
398
+
399
+ ## Design notes
400
+
401
+ The reasoning behind the decisions above lives in
402
+ [docs/design-notes.md](docs/design-notes.md): the digest ladder that lets a
403
+ re-install replace an older hook, how husky and lefthook are recognised and
404
+ why one of them is refused, what the hook says on each exit code, why a clean
405
+ report collapses to one line, the rule separating a SARIF notification from a
406
+ SARIF result, how the exit code is composed, and the mechanism behind the
407
+ intent gate at a pull request. Several of them were learned from running this
408
+ tool against real repositories rather than reasoned out in advance.
409
+
410
+ ## License
411
+
412
+ MIT, [Vault & Compass](https://vaultcompass.io)
package/dist/cli.d.ts ADDED
@@ -0,0 +1,3 @@
1
+ #!/usr/bin/env node
2
+ import { Command } from 'commander';
3
+ export declare function buildProgram(): Command;
package/dist/cli.js ADDED
@@ -0,0 +1,231 @@
1
+ #!/usr/bin/env node
2
+ // The umbrella's command-line entry point: two commands, "init" and "run".
3
+ //
4
+ // Nothing here decides anything. init.ts decides what to write, run.ts
5
+ // decides what to run, exit-codes.ts decides the exit code, and this file
6
+ // parses arguments and prints. That split is what lets every one of those
7
+ // decisions be tested without a subprocess.
8
+ import { Command, CommanderError } from 'commander';
9
+ import { execFileSync } from 'node:child_process';
10
+ import { readFileSync, realpathSync, writeFileSync } from 'node:fs';
11
+ import path from 'node:path';
12
+ import { fileURLToPath } from 'node:url';
13
+ import { EXIT_COULD_NOT_RUN } from './exit-codes.js';
14
+ import { applyInit, planInit, renderInitHuman, renderRevertHuman, revertInit, } from './init.js';
15
+ import { renderSarif } from './output-sarif.js';
16
+ import { renderText } from './output-text.js';
17
+ import { GATE_ROLES, GATE_STAGES, PolicyError, applyCliOverrides, loadPolicy } from './policy.js';
18
+ import { runAll } from './run.js';
19
+ const pkgPath = path.join(path.dirname(fileURLToPath(import.meta.url)), '..', 'package.json');
20
+ const pkg = JSON.parse(readFileSync(pkgPath, 'utf8'));
21
+ function repoRoot(cwd) {
22
+ // The policy file, the hook, and every child's working directory are all
23
+ // anchored at the working-tree root, so a run from a subdirectory behaves
24
+ // exactly like a run from the top.
25
+ try {
26
+ return execFileSync('git', ['rev-parse', '--show-toplevel'], {
27
+ cwd,
28
+ encoding: 'utf8',
29
+ stdio: ['ignore', 'pipe', 'ignore'],
30
+ }).trim();
31
+ }
32
+ catch {
33
+ return cwd;
34
+ }
35
+ }
36
+ function parseFormat(value) {
37
+ if (value !== 'text' && value !== 'sarif') {
38
+ throw new PolicyError(`--format must be "text" or "sarif", got "${value}".`);
39
+ }
40
+ return value;
41
+ }
42
+ /**
43
+ * An unknown stage is a usage error, never a silent full run.
44
+ *
45
+ * The dangerous failure here is the quiet one. A typo in a CI file that
46
+ * makes the job run every gate reads as a passing build with more coverage
47
+ * than it has, and a typo that makes it run none reads as a passing build
48
+ * with no coverage at all. Both look like success.
49
+ */
50
+ function parseStage(value) {
51
+ if (value === undefined) {
52
+ return undefined;
53
+ }
54
+ if (!GATE_STAGES.includes(value)) {
55
+ throw new PolicyError(`--stage must be one of ${GATE_STAGES.join(', ')}, got "${value}".`);
56
+ }
57
+ return value;
58
+ }
59
+ function parseRoles(values) {
60
+ if (values === undefined) {
61
+ return undefined;
62
+ }
63
+ for (const value of values) {
64
+ if (!GATE_ROLES.includes(value)) {
65
+ throw new PolicyError(`--gate must be one of ${GATE_ROLES.join(', ')}, got "${value}".`);
66
+ }
67
+ }
68
+ return values;
69
+ }
70
+ function fail(message) {
71
+ process.stderr.write(`${message}\n`);
72
+ return EXIT_COULD_NOT_RUN;
73
+ }
74
+ export function buildProgram() {
75
+ const program = new Command();
76
+ program
77
+ .name('conductor')
78
+ .description('One policy file, one hook, and one report over independently installed gates.')
79
+ .version(pkg.version)
80
+ // Without this, commander calls process.exit() itself on any usage
81
+ // problem, which makes the CLI untestable in-process and bypasses the
82
+ // exit-code vocabulary the rest of this tool uses.
83
+ .exitOverride();
84
+ program
85
+ .command('init')
86
+ .description('Write the policy file and one pre-commit hook that runs the commit-stage gates.')
87
+ .option('--dry-run', 'print every file that would be written or changed, and write nothing')
88
+ .option('--adopt', "replace a gate's own pre-commit hook with the umbrella hook")
89
+ .option('--revert', 'remove exactly what a previous init wrote')
90
+ .option('--force', 'act on a file that has changed since init wrote it: replace a managed hook somebody has edited, or with --revert remove one and restore any adopted hook')
91
+ .option('--json', 'print the result as JSON')
92
+ .exitOverride()
93
+ .action((options) => {
94
+ const cwd = process.cwd();
95
+ const shared = { cwd, pathValue: process.env.PATH ?? '' };
96
+ if (options.revert) {
97
+ const result = revertInit({ ...shared, force: Boolean(options.force) });
98
+ const rendered = `${renderRevertHuman(result)}\n`;
99
+ if (options.json) {
100
+ process.stdout.write(`${JSON.stringify(result)}\n`);
101
+ }
102
+ else if (result.ok) {
103
+ process.stdout.write(rendered);
104
+ }
105
+ else {
106
+ // A partial revert left something behind, so it is not success
107
+ // output. Writing it to stdout would let a script pipe it past a
108
+ // reader who needed to see it.
109
+ process.stderr.write(rendered);
110
+ }
111
+ process.exitCode = result.ok ? 0 : EXIT_COULD_NOT_RUN;
112
+ return;
113
+ }
114
+ const initOptions = {
115
+ ...shared,
116
+ ...(options.dryRun === undefined ? {} : { dryRun: options.dryRun }),
117
+ ...(options.adopt === undefined ? {} : { adopt: options.adopt }),
118
+ ...(options.force === undefined ? {} : { force: options.force }),
119
+ };
120
+ const result = applyInit(planInit(initOptions), initOptions);
121
+ if (options.json) {
122
+ process.stdout.write(`${JSON.stringify(result)}\n`);
123
+ }
124
+ else if (result.ok) {
125
+ process.stdout.write(`${renderInitHuman(result)}\n`);
126
+ }
127
+ else {
128
+ process.stderr.write(`${renderInitHuman(result)}\n`);
129
+ }
130
+ process.exitCode = result.ok ? 0 : EXIT_COULD_NOT_RUN;
131
+ });
132
+ program
133
+ .command('run')
134
+ .description('Run every enabled gate and print one combined report.')
135
+ .option('--staged', 'gate the git index against HEAD, the way the pre-commit hook does')
136
+ .option('--format <format>', 'output format: text or sarif')
137
+ .option('--stage <stage>', `which stopping point this run is: ${GATE_STAGES.join(', ')}. Stages are cumulative, so a gate runs at its own stage and every later one. Omit it to run every enabled gate.`)
138
+ .option('--base <ref>', 'measure the intent gate against what this branch changed since <ref>, rather than against the index. In Actions this defaults to origin/<GITHUB_BASE_REF> when it is set.')
139
+ .option('--output <path>', 'write the report to this file instead of to stdout, for a CI step that uploads it')
140
+ .option('--spec <path>', 'the spec the intent gate imports its contract from, outranking a Spec: line in the pull request body and the branch-name convention')
141
+ .option('--verbose', 'print the full per-gate report even when the run is clean. A clean run prints one summary line by default, because a pre-commit hook that prints a screenful on every commit is a hook a team switches off. Text output only; SARIF is unaffected.')
142
+ .option('--gate <role>', 'restrict the run to this role; repeatable', (value, previous = []) => [...previous, value])
143
+ .exitOverride()
144
+ .action((options) => {
145
+ const cwd = process.cwd();
146
+ const root = repoRoot(cwd);
147
+ try {
148
+ const policy = applyCliOverrides(loadPolicy(root), {
149
+ ...(parseRoles(options.gate) === undefined
150
+ ? {}
151
+ : { gates: parseRoles(options.gate) }),
152
+ });
153
+ const format = parseFormat(options.format ?? policy.report.format);
154
+ const stage = parseStage(options.stage);
155
+ const result = runAll(policy, {
156
+ repoRoot: root,
157
+ staged: Boolean(options.staged),
158
+ pathValue: process.env.PATH ?? '',
159
+ env: process.env,
160
+ ...(stage === undefined ? {} : { stage }),
161
+ ...(options.base === undefined ? {} : { base: options.base }),
162
+ ...(options.spec === undefined ? {} : { spec: options.spec }),
163
+ });
164
+ const rendered = format === 'sarif'
165
+ ? `${renderSarif(result, pkg.version)}\n`
166
+ : renderText(result, { verbose: Boolean(options.verbose) });
167
+ if (options.output === undefined) {
168
+ process.stdout.write(rendered);
169
+ }
170
+ else {
171
+ // A failure to write is the umbrella not carrying out what it was
172
+ // asked, so it takes the could-not-run code rather than the run's
173
+ // own. Reporting exit 0 next to a report nobody can read is the
174
+ // worst of the available answers: the upload step downstream would
175
+ // fail on a missing file with no explanation here.
176
+ writeFileSync(options.output, rendered);
177
+ // One line, so a CI job whose only product is an uploaded artifact
178
+ // does not read as a job that did nothing.
179
+ process.stdout.write(`conductor run: ${result.gates.length} gate(s), ${result.findings.length} finding(s); ` +
180
+ `${format} report written to ${options.output}\n`);
181
+ }
182
+ process.exitCode = result.exitCode;
183
+ }
184
+ catch (err) {
185
+ // One line, never a stack. runGate is total, so nothing from a gate
186
+ // reaches here; anything that does is the umbrella's own problem and
187
+ // still must not put a local filesystem path in front of a user who
188
+ // cannot act on it, or into a pre-commit hook's output.
189
+ process.exitCode = fail(err instanceof PolicyError
190
+ ? err.message
191
+ : `conductor: ${err instanceof Error ? err.message : String(err)}`);
192
+ }
193
+ });
194
+ return program;
195
+ }
196
+ async function main() {
197
+ try {
198
+ await buildProgram().parseAsync(process.argv);
199
+ }
200
+ catch (err) {
201
+ if (err instanceof CommanderError) {
202
+ // --help and --version already printed what they needed and carry
203
+ // exitCode 0. Everything else is a bad command line, which is the
204
+ // umbrella's "could not carry out what it was asked".
205
+ process.exitCode = err.exitCode === 0 ? 0 : EXIT_COULD_NOT_RUN;
206
+ return;
207
+ }
208
+ // The last backstop. Still one line, still no stack: an unhandled throw
209
+ // printing a stack into a pre-commit hook's output is how a local path
210
+ // ends up pasted into an issue.
211
+ process.exitCode = fail(`conductor: ${err instanceof Error ? err.message : String(err)}`);
212
+ }
213
+ }
214
+ // realpath both sides before comparing: on macOS the OS temp directory and
215
+ // other mount points resolve through a symlink, so import.meta.url reports
216
+ // the resolved path while process.argv[1] reports whatever the caller
217
+ // typed, and a naive comparison can silently skip main() entirely.
218
+ function isMainModule() {
219
+ if (process.argv[1] === undefined) {
220
+ return false;
221
+ }
222
+ try {
223
+ return realpathSync(fileURLToPath(import.meta.url)) === realpathSync(process.argv[1]);
224
+ }
225
+ catch {
226
+ return false;
227
+ }
228
+ }
229
+ if (isMainModule()) {
230
+ void main();
231
+ }