@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.
@@ -0,0 +1,354 @@
1
+ // Running one gate as a child process.
2
+ //
3
+ // Wrapper, not library: nothing here imports any gate's own package. That
4
+ // is what keeps the umbrella from taking three exact version pins and
5
+ // needing a release of its own every time one of the three ships, and it is
6
+ // what makes "this gate ran and exited N, output unparsed" an available
7
+ // outcome instead of a build error.
8
+ //
9
+ // The one non-obvious constraint, and it came from running the tools rather
10
+ // than from reading them: the CHILD'S WORKING DIRECTORY MUST BE THE
11
+ // REPOSITORY ROOT. vault-guard resolves both its config file and its
12
+ // baseline from process.cwd() rather than from the path argument, so a
13
+ // child spawned from anywhere else scans the right files with the wrong
14
+ // configuration and the wrong baseline, and says nothing about it.
15
+ // dep-guard resolves from its path argument and intent-guard from
16
+ // --project, so setting cwd correctly is the single approach that is right
17
+ // for all three.
18
+ import { spawnSync } from 'node:child_process';
19
+ import { NormalizeError } from './envelope.js';
20
+ import { normalizeDepGuard, normalizeFailedGate, normalizeIntentGuard, normalizeMisconfiguredGate, normalizeMissingGate, normalizeUnparseableGate, normalizeVaultGuard, } from './normalize.js';
21
+ import { renderOptionFlags } from './policy.js';
22
+ import { ResolveError, candidateNames, resolveGateBinary } from './resolve.js';
23
+ /**
24
+ * A gate that never got as far as being spawned.
25
+ *
26
+ * The preparation for the intent gate happens before any child process, and
27
+ * a failure there has to compose exactly like any other could-not-run: exit 2
28
+ * for an enforced gate and a note for an unenforced one. So it is expressed
29
+ * as an ordinary GateOutcome rather than as a fourth kind of thing the report
30
+ * would have to learn about.
31
+ */
32
+ export function preparationFailed(gate, detail) {
33
+ return {
34
+ role: gate.role,
35
+ product: gate.product,
36
+ stage: gate.stage,
37
+ enforce: gate.enforce,
38
+ productVersion: null,
39
+ argv: [],
40
+ binary: null,
41
+ exitCode: null,
42
+ durationMs: 0,
43
+ stderr: '',
44
+ couldNotRun: { reason: 'preparation-failed', detail },
45
+ findings: [normalizeFailedGate(gate.role, gate.product, detail)],
46
+ run: EMPTY_RUN,
47
+ diagnostics: [],
48
+ };
49
+ }
50
+ const EMPTY_RUN = {
51
+ failOn: null,
52
+ suppressed: 0,
53
+ ignored: 0,
54
+ diagnostics: [],
55
+ details: {},
56
+ };
57
+ /**
58
+ * The arguments the umbrella adds, per product.
59
+ *
60
+ * These are the reserved options the policy schema refuses to let a user
61
+ * set, and this is the only place they are written. The passthrough block
62
+ * goes last so a gate's own flags are visible at the end of the command
63
+ * line in the report, where they read as the user's own additions.
64
+ *
65
+ * Exported so a test can DERIVE the flags this writes and hold
66
+ * RESERVED_OPTIONS in policy.ts against them. The two lists are otherwise
67
+ * parallel and hand-maintained, and a flag added here and forgotten there
68
+ * would let a policy file write the same flag a second time, with the winner
69
+ * decided by that gate's own argument parser rather than by anything the
70
+ * user could read in their own policy file.
71
+ */
72
+ export function gateArgs(gate, staged, intent) {
73
+ const passthrough = renderOptionFlags(gate.options);
74
+ switch (gate.product) {
75
+ case 'dep-guard':
76
+ return [...(staged ? ['--staged'] : []), '--format', 'json', ...passthrough];
77
+ case 'vault-guard':
78
+ // No path argument: the CLI defaults it to "." and the umbrella runs
79
+ // with cwd at the repository root anyway. Passing one would also risk
80
+ // a passthrough value being read as the positional.
81
+ return [...(staged ? ['--staged'] : []), '-f', 'json', ...passthrough];
82
+ case 'intent-guard': {
83
+ if (intent === undefined) {
84
+ return ['--project', '.', ...(staged ? ['--staged'] : []), '--json', ...passthrough];
85
+ }
86
+ // A prepared run replaces --staged entirely rather than adding to it.
87
+ // The two path sources are ADDITIVE in intent-guard, so leaving
88
+ // --staged on would silently widen a pull request's change set with
89
+ // whatever happens to be in the index of the machine running it.
90
+ //
91
+ // --paths is passed even when the branch changed nothing, so the empty
92
+ // set is stated rather than left for the gate to fill in from the
93
+ // index.
94
+ return [
95
+ '--project',
96
+ intent.projectDir,
97
+ ...(intent.paths === null
98
+ ? staged
99
+ ? ['--staged']
100
+ : []
101
+ : ['--paths', intent.paths.join(',')]),
102
+ '--json',
103
+ ...passthrough,
104
+ ];
105
+ }
106
+ }
107
+ }
108
+ /**
109
+ * Asks a binary for its version.
110
+ *
111
+ * Never called for a binary the candidate table marks unsafe to ask: the
112
+ * per-command binaries ignore --version and run the gate instead, so a
113
+ * probe there would have side effects on the user's repository.
114
+ */
115
+ function probeVersion(binary, repoRoot, timeoutMs) {
116
+ if (binary.versionProbe === null) {
117
+ return null;
118
+ }
119
+ const probe = spawnSync(binary.versionProbe.command, binary.versionProbe.argv, {
120
+ cwd: repoRoot,
121
+ encoding: 'utf8',
122
+ timeout: timeoutMs,
123
+ });
124
+ if (probe.status !== 0 || typeof probe.stdout !== 'string') {
125
+ return null;
126
+ }
127
+ // All three print a bare version string. Take the first line and accept
128
+ // it only if it looks like one, so a future help banner does not end up
129
+ // in a SARIF driver's version field.
130
+ const first = probe.stdout.trim().split('\n')[0]?.trim() ?? '';
131
+ return /^v?\d+\.\d+\.\d+/.test(first) ? first.replace(/^v/, '') : null;
132
+ }
133
+ function normalizeFor(product, parsed, version) {
134
+ switch (product) {
135
+ case 'dep-guard':
136
+ return normalizeDepGuard(parsed, version);
137
+ case 'vault-guard':
138
+ return normalizeVaultGuard(parsed, version);
139
+ case 'intent-guard':
140
+ return normalizeIntentGuard(parsed, version);
141
+ }
142
+ }
143
+ /**
144
+ * An error's message, never its stack.
145
+ *
146
+ * A stack reaching the terminal puts a local filesystem path in front of a
147
+ * user who cannot act on any of it, and puts one into a report that gets
148
+ * uploaded. The message is the part that says what went wrong.
149
+ */
150
+ function messageOf(err) {
151
+ if (err instanceof Error) {
152
+ return err.message;
153
+ }
154
+ return String(err);
155
+ }
156
+ /**
157
+ * Runs one gate. TOTAL: this never throws.
158
+ *
159
+ * That is a contract, not a hope. The caller maps over the enabled gates in
160
+ * order, so an escaping error does not just lose this gate's report, it
161
+ * loses every gate after it, and it surfaces as a stack trace with exit 1,
162
+ * which the pre-commit hook reports as "a gate blocked". Everything that can
163
+ * go wrong here is a could-not-run for THIS gate, composing to exit 2, with
164
+ * a finding of the umbrella's own saying so.
165
+ */
166
+ export function runGate(gate, options) {
167
+ const progress = {
168
+ role: gate.role,
169
+ product: gate.product,
170
+ stage: gate.stage,
171
+ enforce: gate.enforce,
172
+ productVersion: null,
173
+ argv: [],
174
+ binary: null,
175
+ exitCode: null,
176
+ durationMs: 0,
177
+ stderr: '',
178
+ // Carried on every return path below, including the failures: which
179
+ // contract a gate WOULD have used is exactly as interesting when it could
180
+ // not run as when it could.
181
+ ...(options.intent === undefined
182
+ ? {}
183
+ : {
184
+ intent: {
185
+ contractSource: options.intent.contractSource,
186
+ baseRef: options.intent.baseRef,
187
+ },
188
+ }),
189
+ };
190
+ const started = Date.now();
191
+ try {
192
+ return runGateInner(gate, options, started, progress);
193
+ }
194
+ catch (err) {
195
+ // The backstop. Anything the paths below did not anticipate lands here
196
+ // rather than in the user's terminal.
197
+ const detail = messageOf(err);
198
+ return {
199
+ ...progress,
200
+ durationMs: Date.now() - started,
201
+ couldNotRun: { reason: 'unparseable-output', detail },
202
+ findings: [normalizeUnparseableGate(gate.role, gate.product, detail)],
203
+ run: EMPTY_RUN,
204
+ diagnostics: [],
205
+ };
206
+ }
207
+ }
208
+ function runGateInner(gate, options, started, progress) {
209
+ const timeoutMs = options.timeoutMs ?? 120_000;
210
+ const base = progress;
211
+ let binary;
212
+ try {
213
+ binary = resolveGateBinary(gate, options.repoRoot, options.pathValue);
214
+ }
215
+ catch (err) {
216
+ // A ResolveError is the expected shape here; anything else is still a
217
+ // problem with this gate rather than with the run, so it takes the same
218
+ // path instead of being rethrown into the caller's map.
219
+ const detail = err instanceof ResolveError ? err.message : messageOf(err);
220
+ return {
221
+ ...base,
222
+ durationMs: Date.now() - started,
223
+ couldNotRun: { reason: 'configured-command-missing', detail },
224
+ // Only reachable when the policy named a command, since that is the
225
+ // only thing resolution throws over. So the finding names that path
226
+ // and not the candidate list, which was never searched.
227
+ findings: [
228
+ gate.command === undefined
229
+ ? normalizeMissingGate(gate.role, gate.product, candidateNames(gate.product))
230
+ : normalizeMisconfiguredGate(gate.role, gate.product, gate.command, detail),
231
+ ],
232
+ run: EMPTY_RUN,
233
+ diagnostics: [],
234
+ };
235
+ }
236
+ if (binary === null) {
237
+ return {
238
+ ...base,
239
+ durationMs: Date.now() - started,
240
+ couldNotRun: {
241
+ reason: 'binary-missing',
242
+ // Named in resolution order, which is the repository's own copy
243
+ // first. Saying PATH first points a reader at the location this
244
+ // tool prefers second, which is the wrong place to install it.
245
+ detail: `no ${gate.product} binary in node_modules/.bin or on PATH`,
246
+ },
247
+ // A missing enabled gate is a finding of the umbrella's own, never a
248
+ // silent skip. Skipping is how a gate ends up switched on in the
249
+ // policy file and absent in reality for months.
250
+ findings: [normalizeMissingGate(gate.role, gate.product, candidateNames(gate.product))],
251
+ run: EMPTY_RUN,
252
+ diagnostics: [],
253
+ };
254
+ }
255
+ const version = probeVersion(binary, options.repoRoot, timeoutMs);
256
+ const argv = [...binary.argvPrefix, ...gateArgs(gate, options.staged, options.intent)];
257
+ const child = spawnSync(binary.command, argv, {
258
+ cwd: options.repoRoot,
259
+ encoding: 'utf8',
260
+ timeout: timeoutMs,
261
+ maxBuffer: 64 * 1024 * 1024,
262
+ });
263
+ const withRun = {
264
+ ...base,
265
+ productVersion: version,
266
+ argv,
267
+ binary,
268
+ durationMs: Date.now() - started,
269
+ stderr: child.stderr ?? '',
270
+ };
271
+ // Keep the backstop's view current, so an unexpected throw below still
272
+ // reports which binary ran and what it printed.
273
+ Object.assign(progress, withRun);
274
+ if (child.error !== undefined) {
275
+ return {
276
+ ...withRun,
277
+ exitCode: null,
278
+ couldNotRun: { reason: 'spawn-failed', detail: child.error.message },
279
+ findings: [normalizeFailedGate(gate.role, gate.product, child.error.message)],
280
+ run: EMPTY_RUN,
281
+ diagnostics: [],
282
+ };
283
+ }
284
+ const exitCode = child.status;
285
+ const stdout = child.stdout ?? '';
286
+ // dep-guard's 2 means "could not run the checks at all" and it prints no
287
+ // JSON. The other two have no such code, but a signal-killed child or a
288
+ // timeout lands here too, and none of those are a clean result.
289
+ if (exitCode === null || exitCode > 1) {
290
+ const detail = exitCode === null
291
+ ? 'the gate did not exit normally (killed, or timed out).'
292
+ : `the gate exited ${exitCode}, which it uses for "could not run".`;
293
+ return {
294
+ ...withRun,
295
+ exitCode,
296
+ couldNotRun: { reason: 'gate-error', detail },
297
+ findings: [normalizeFailedGate(gate.role, gate.product, detail)],
298
+ run: EMPTY_RUN,
299
+ diagnostics: [],
300
+ };
301
+ }
302
+ let parsed;
303
+ try {
304
+ parsed = JSON.parse(stdout);
305
+ }
306
+ catch {
307
+ // Exit 1 with unparseable stdout is what a rejected config looks like
308
+ // from two of the three products, and it is could-not-run rather than
309
+ // clean. Reporting it as a policy violation would tell the user their
310
+ // code is at fault when their config is.
311
+ const detail = `the gate exited ${exitCode} without valid JSON on stdout. ` +
312
+ 'A rejected config file looks exactly like this, and it is not a clean result.';
313
+ return {
314
+ ...withRun,
315
+ exitCode,
316
+ couldNotRun: { reason: 'unparseable-output', detail },
317
+ findings: [normalizeUnparseableGate(gate.role, gate.product, detail)],
318
+ run: EMPTY_RUN,
319
+ diagnostics: [],
320
+ };
321
+ }
322
+ try {
323
+ const normalized = normalizeFor(gate.product, parsed, version);
324
+ return {
325
+ ...withRun,
326
+ exitCode,
327
+ couldNotRun: null,
328
+ findings: normalized.findings,
329
+ run: normalized.run,
330
+ diagnostics: normalized.diagnostics,
331
+ };
332
+ }
333
+ catch (err) {
334
+ // Deliberately NOT narrowed to NormalizeError. That narrowing was the
335
+ // defect: a normalizer reading a property off a null element threw a
336
+ // TypeError, which is not a NormalizeError, so it escaped here, escaped
337
+ // the run, and reached the user as a stack trace with exit 1. The
338
+ // normalizers now validate every element they touch, and this catch is
339
+ // the second line of that defence rather than the only one.
340
+ //
341
+ // The gate ran and answered; the umbrella did not understand it. That is
342
+ // could-not-run for the umbrella's purposes, and the message says which
343
+ // side the problem is on so nobody debugs the wrong repository.
344
+ const detail = err instanceof NormalizeError ? err.message : messageOf(err);
345
+ return {
346
+ ...withRun,
347
+ exitCode,
348
+ couldNotRun: { reason: 'unparseable-output', detail },
349
+ findings: [normalizeUnparseableGate(gate.role, gate.product, detail)],
350
+ run: EMPTY_RUN,
351
+ diagnostics: [],
352
+ };
353
+ }
354
+ }
package/dist/init.d.ts ADDED
@@ -0,0 +1,138 @@
1
+ import { POLICY_FILE_NAME } from './policy.js';
2
+ import type { GateRole, Product } from './policy.js';
3
+ export { POLICY_FILE_NAME };
4
+ /** The one string that says "conductor init wrote this". */
5
+ export declare const MANAGED_HOOK_MARKER = "guardrails-managed-hook: v1";
6
+ export declare const MANIFEST_RELATIVE_PATH = ".guardrails/manifest.json";
7
+ /**
8
+ * Markers each gate's own installer writes, so a collision is recognised
9
+ * rather than clobbered. Two of these are literal marker comments the other
10
+ * tools write on purpose; the third has no marker at all and is matched on
11
+ * the two strings its hook always contains, which is exactly how that
12
+ * tool's own installer recognises its own hook.
13
+ */
14
+ export declare const DEP_GUARD_HOOK_MARKER = "dep-guard-managed-hook: v1";
15
+ export declare const INTENT_GUARD_HOOK_MARKER = "conductor-managed-pre-commit";
16
+ /**
17
+ * Hook managers whose installed pre-commit file is GENERATED rather than
18
+ * written by a human. Every one of these rewrites that file on install, so
19
+ * it is never the file the umbrella may write into.
20
+ *
21
+ * The same four names dep-guard's and vault-guard's inits use, so the
22
+ * family says one thing. The difference is that those take the manager as
23
+ * a flag, and this one detects it: the umbrella's whole job is to be run
24
+ * once in a repository somebody else already wired up.
25
+ */
26
+ export type HookManager = 'native' | 'husky' | 'lefthook' | 'precommit';
27
+ export type ConflictReason = 'not-a-git-repository' | 'foreign-hook' | 'gate-hook' | 'generated-hook' | 'hooks-path-outside-repository' | 'no-manifest' | 'changed-since-init' | 'write-failed';
28
+ export interface InitConflict {
29
+ path: string;
30
+ reason: ConflictReason;
31
+ guidance: string;
32
+ }
33
+ export interface InitAction {
34
+ kind: 'write' | 'skip' | 'remove' | 'restore';
35
+ path: string;
36
+ detail: string;
37
+ }
38
+ export interface AdoptedHook {
39
+ product: Product;
40
+ content: string;
41
+ }
42
+ export interface InitResult {
43
+ ok: boolean;
44
+ dryRun: boolean;
45
+ alreadyInstalled: boolean;
46
+ actions: InitAction[];
47
+ conflicts: InitConflict[];
48
+ /** Absolute path of the hook file, empty when there is nothing to write. */
49
+ hookPath: string;
50
+ /**
51
+ * Which hook manager owns this repository's pre-commit hook, as detected.
52
+ * `husky` means hookPath is the TRACKED file rather than the generated
53
+ * one git executes.
54
+ */
55
+ hookManager: HookManager;
56
+ repoRoot: string;
57
+ adoptedFrom: AdoptedHook | null;
58
+ /** Contents to write, keyed by absolute path. Empty on a dry run's apply. */
59
+ writes: Array<{
60
+ path: string;
61
+ content: string;
62
+ executable: boolean;
63
+ kind: 'hook' | 'policy';
64
+ }>;
65
+ /**
66
+ * Files already on disk in exactly the right state, which the manifest is
67
+ * nevertheless missing.
68
+ *
69
+ * Nothing is written for these: the bytes are correct already. They exist
70
+ * because the manifest is what makes --revert honest, and a file init put
71
+ * there but cannot prove it put there is one revert walks past. Recording
72
+ * the content that is already on disk is what turns "I found this" into
73
+ * "this is mine to remove".
74
+ */
75
+ records: Array<{
76
+ path: string;
77
+ content: string;
78
+ kind: 'hook' | 'policy';
79
+ }>;
80
+ }
81
+ export interface InitOptions {
82
+ cwd: string;
83
+ /** PATH used for gate detection. Injected so tests never depend on the machine. */
84
+ pathValue: string;
85
+ dryRun?: boolean;
86
+ /** Replace a per-gate hook with the umbrella's. Never replaces a foreign one. */
87
+ adopt?: boolean;
88
+ /**
89
+ * Act on a file that has changed since init wrote it: on init, replace a
90
+ * managed hook somebody has edited; on revert, remove one. Never touches a
91
+ * foreign or gate-owned hook, which have their own routes.
92
+ */
93
+ force?: boolean;
94
+ }
95
+ /**
96
+ * The policy file, written by hand rather than serialised, because the
97
+ * comments are half the point: a first-run policy file that explains what
98
+ * each key is for is most of a first-run experience, and a YAML emitter
99
+ * cannot carry them.
100
+ */
101
+ export declare function renderPolicy(detected: Set<GateRole>): string;
102
+ export declare function planInit(options: InitOptions): InitResult;
103
+ export declare function applyInit(plan: InitResult, options: InitOptions): InitResult;
104
+ export interface RevertResult {
105
+ ok: boolean;
106
+ actions: InitAction[];
107
+ conflicts: InitConflict[];
108
+ }
109
+ /**
110
+ * Removes exactly what init wrote, and nothing else.
111
+ *
112
+ * A file whose contents no longer match what the manifest recorded is left
113
+ * alone and reported, because that file is now the user's whatever it
114
+ * started as, and a revert that deletes edited work is a revert nobody runs
115
+ * twice. Three rules follow from that, and all three were bugs here first:
116
+ *
117
+ * 1. IF THE HOOK SURVIVES, NOTHING IS REMOVED. Removing the policy file
118
+ * while leaving an edited hook in place leaves that hook running the
119
+ * umbrella with nothing to read, so every commit afterwards is refused
120
+ * with exit 2 -- while revert reported success. The hook is the piece
121
+ * that depends on the rest, so it decides whether a revert can proceed
122
+ * at all.
123
+ *
124
+ * 2. THE MANIFEST OUTLIVES A PARTIAL REVERT. It is deleted only once it
125
+ * holds nothing, because it is the only record of what is left AND, after
126
+ * an --adopt, the only copy of the gate hook that was replaced. Deleting
127
+ * it while that content was still needed made the gate's own hook
128
+ * unrecoverable.
129
+ *
130
+ * 3. A PARTIAL REVERT IS NOT A SUCCESS. It returns ok: false, so the exit
131
+ * code is non-zero and a script does not read "some of it" as "all of it".
132
+ *
133
+ * `--force` removes a changed file anyway, restoring adopted content if
134
+ * there is any. It is the deliberate way out of every state above.
135
+ */
136
+ export declare function revertInit(options: InitOptions): RevertResult;
137
+ export declare function renderInitHuman(result: InitResult): string;
138
+ export declare function renderRevertHuman(result: RevertResult): string;