@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/init.js ADDED
@@ -0,0 +1,973 @@
1
+ // `conductor init`: one policy file, one pre-commit hook, one manifest.
2
+ //
3
+ // The manifest is what makes --revert honest. Without one, "undo the init"
4
+ // means guessing which files were the tool's, and a tool that guesses about
5
+ // deletion in somebody's repository has to be wrong only once.
6
+ //
7
+ // Four properties are the whole point, and three of them are bugs some tool
8
+ // in this family has actually shipped:
9
+ //
10
+ // 1. FAIL CLOSED. A missing umbrella binary blocks the commit. The
11
+ // tempting alternative, warning and letting the commit through so a
12
+ // teammate without the tool is not stuck, means the gate is silently
13
+ // absent exactly where it is most likely to be absent, and a guardrail
14
+ // that is off when the tool is missing is a guardrail an attacker turns
15
+ // off by making the tool missing.
16
+ //
17
+ // 2. PRESERVE THE EXIT CODE. 2 means a gate could not run; 1 means a gate
18
+ // blocked. A hook written the natural way, `if conductor run; then exit
19
+ // 0; fi; exit 1`, collapses 2 into 1 and reports findings that were
20
+ // never looked for.
21
+ //
22
+ // 3. A RELATIVE core.hooksPath RESOLVES AGAINST THE WORKTREE ROOT, not
23
+ // against the .git directory. A sibling tool resolved it against the
24
+ // .git directory and the test that covered the case asserted the same
25
+ // wrong location, so the two agreed with each other and neither was
26
+ // checked against git. The test here drives a real commit instead.
27
+ //
28
+ // 4. NEVER STACK A SECOND HOOK. If a gate already installed its own
29
+ // pre-commit hook, adding the umbrella's alongside it means that gate
30
+ // runs twice and its findings appear twice. Init reports the collision
31
+ // and stops, or replaces the gate's hook when told to adopt it.
32
+ //
33
+ // 5. NEVER WRITE INTO A HOOK MANAGER'S GENERATED DIRECTORY. Where git
34
+ // looks and where the hook a human maintains lives are not always the
35
+ // same file. husky 9 sets core.hooksPath to .husky/_, a generated and
36
+ // gitignored directory it rewrites on every install; the file git
37
+ // executes there is a dispatcher that execs the TRACKED hook one
38
+ // directory up. Reading the dispatcher reports the repository's real
39
+ // gate hook as foreign, so --adopt cannot adopt it, and writing the
40
+ // dispatcher puts the umbrella hook somewhere the next install deletes
41
+ // without a word. Found by running this tool against a real husky 9
42
+ // repository, which is the only way it could have been found: every
43
+ // fixture in the suite agreed with the code.
44
+ //
45
+ // The recognition rule is structural and nothing else: the hooks
46
+ // directory is named `_` and its parent is named `.husky`. Only husky
47
+ // creates that path. See huskyDirectoryFor for why neither the content
48
+ // of the executed file nor the presence of husky's shim is allowed to
49
+ // join the rule: the first fires against husky 8's tracked hook and
50
+ // points init at the repository root, and the second fails exactly
51
+ // after a `git clean -xdf` has removed the gitignored generated
52
+ // directory, which is the state this whole property exists to survive.
53
+ import { createHash } from 'node:crypto';
54
+ import { execFileSync } from 'node:child_process';
55
+ import { chmodSync, mkdirSync, readFileSync, rmSync, rmdirSync, statSync, writeFileSync, } from 'node:fs';
56
+ import path from 'node:path';
57
+ import { DEFAULT_STAGE_FOR_ROLE, GATE_ROLES, POLICY_FILE_NAME, PRODUCT_FOR_ROLE } from './policy.js';
58
+ import { CANDIDATES } from './resolve.js';
59
+ export { POLICY_FILE_NAME };
60
+ /** The one string that says "conductor init wrote this". */
61
+ export const MANAGED_HOOK_MARKER = 'guardrails-managed-hook: v1';
62
+ export const MANIFEST_RELATIVE_PATH = '.guardrails/manifest.json';
63
+ /**
64
+ * Markers each gate's own installer writes, so a collision is recognised
65
+ * rather than clobbered. Two of these are literal marker comments the other
66
+ * tools write on purpose; the third has no marker at all and is matched on
67
+ * the two strings its hook always contains, which is exactly how that
68
+ * tool's own installer recognises its own hook.
69
+ */
70
+ export const DEP_GUARD_HOOK_MARKER = 'dep-guard-managed-hook: v1';
71
+ export const INTENT_GUARD_HOOK_MARKER = 'conductor-managed-pre-commit';
72
+ /**
73
+ * The `.husky` directory whose generated subdirectory git has been pointed
74
+ * at, or null when this is not that arrangement.
75
+ *
76
+ * The rule is STRUCTURAL and nothing else: the hooks directory is named
77
+ * `_`, and its parent is named `.husky`. Only husky creates that path, so
78
+ * the shape alone identifies it, and both halves are required.
79
+ *
80
+ * Two things are deliberately NOT part of the rule, each for a reason that
81
+ * cost a bug:
82
+ *
83
+ * - THE CONTENT of the pre-commit file git executes. The line that sources
84
+ * husky's shim appears in two completely different places:
85
+ *
86
+ * husky 9 core.hooksPath = .husky/_ .husky/_/pre-commit sources
87
+ * _/h and IS a dispatcher; the tracked hook is one up.
88
+ * husky 8 core.hooksPath = .husky .husky/pre-commit sources
89
+ * _/husky.sh as a PREAMBLE and IS the tracked hook already.
90
+ *
91
+ * Reading content therefore fired against husky 8's tracked hook, and
92
+ * "one directory up" then pointed at the parent of `.husky`, which is
93
+ * the repository root. Init wrote a hook there, never read the real one
94
+ * so never saw the gate hook in it, reported success, and left every
95
+ * commit ungated. The structural rule excludes husky 8 on its own,
96
+ * because there the hooks directory is `.husky` and not `_`.
97
+ *
98
+ * - THE PRESENCE OF THE SHIM (`h`, or husky 8's `husky.sh`). Requiring it
99
+ * looks like useful confirmation and quietly reintroduces the original
100
+ * trap. husky gitignores `.husky/_`, so `git clean -xdf` deletes the
101
+ * whole directory while `core.hooksPath=.husky/_` sits in `.git/config`
102
+ * and survives. In that state there is no shim, no dispatcher, and
103
+ * nothing whatever to confirm, so a shim requirement sends init down the
104
+ * ordinary path to write `.husky/_/pre-commit` -- which is exactly the
105
+ * file husky's next prepare step wipes. The shim is evidence that husky
106
+ * ran recently, not evidence about whose directory this is, so it is
107
+ * reported and never tested against.
108
+ *
109
+ * The tracked target is this `.husky` directory's own hook, never a
110
+ * computed parent of whatever directory git happens to point at.
111
+ */
112
+ function huskyDirectoryFor(hooksDir) {
113
+ if (path.basename(hooksDir) !== '_') {
114
+ return null;
115
+ }
116
+ const huskyDir = path.dirname(hooksDir);
117
+ if (path.basename(huskyDir) !== '.husky') {
118
+ return null;
119
+ }
120
+ return huskyDir;
121
+ }
122
+ /** Whether husky's shim is in place, which is worth SAYING but never testing. */
123
+ function huskyShimPresent(hooksDir) {
124
+ return isFile(path.join(hooksDir, 'h')) || isFile(path.join(hooksDir, 'husky.sh'));
125
+ }
126
+ /**
127
+ * What each of these two managers actually writes into the hook it
128
+ * generates, checked against a real install rather than against anybody's
129
+ * memory of one. The captured files are in tests/fixtures/hooks.
130
+ *
131
+ * lefthook is recognised by `call_lefthook`, the shell function its
132
+ * generated hook defines and then calls on the last line. Verified against
133
+ * lefthook 2.1.12 and 1.7.18, which both write it twice.
134
+ *
135
+ * `lefthook_version:` is a second alternative and IS NOT VERIFIED. Neither
136
+ * of those versions writes it, and the string does not appear anywhere in
137
+ * the 2.1.12 binary either, so it recognises nothing lefthook produces
138
+ * today. It stays because a spare alternative in an OR cannot cause a false
139
+ * negative and may still catch a much older install. What could not stay is
140
+ * the comment that used to be here, which called both halves the
141
+ * installer's own mark: a hand-written fixture in the suite carried the
142
+ * invented line, so the fixture and the code agreed with each other and
143
+ * neither had ever been held up against lefthook. Recognising lefthook on
144
+ * that string alone misclassifies both real hooks as native, which is how
145
+ * init ends up writing into a file lefthook regenerates.
146
+ *
147
+ * The pre-commit framework stamps its own URL, and that one is exact:
148
+ * verified against pre-commit 4.6.2, whose marker line is character for
149
+ * character the string below.
150
+ */
151
+ function detectGeneratedHook(content) {
152
+ if (content.includes('call_lefthook') || content.includes('lefthook_version:')) {
153
+ return 'lefthook';
154
+ }
155
+ if (content.includes('File generated by pre-commit: https://pre-commit.com')) {
156
+ return 'precommit';
157
+ }
158
+ return null;
159
+ }
160
+ function generatedHookGuidance(manager, relPath) {
161
+ const owner = manager === 'lefthook' ? 'lefthook' : 'the pre-commit framework';
162
+ const config = manager === 'lefthook' ? 'lefthook-local.yml' : '.pre-commit-config.yaml';
163
+ const stanza = manager === 'lefthook'
164
+ ? 'add "conductor:" under pre-commit.commands with "run: conductor run --staged"'
165
+ : 'add a local hook entry running "conductor run --staged" to its repos: list';
166
+ return (`${relPath} is generated by ${owner}, which rewrites it on every install, so anything ` +
167
+ `written there is lost without a word. Nothing was changed. To run the umbrella under ` +
168
+ `${owner}, ${stanza} in ${config}. Note that ${owner} owns the commit's exit code, so the ` +
169
+ "umbrella's 1 (a gate blocked) and 2 (a gate could not run) do not survive it.");
170
+ }
171
+ function detectGateHook(content) {
172
+ if (content.includes(DEP_GUARD_HOOK_MARKER)) {
173
+ return 'dep-guard';
174
+ }
175
+ // Deliberately still the pre-rename string: it is state already sitting
176
+ // in users' repositories, and the tool that writes it did not rename it
177
+ // either, precisely so an older hook stays recognisable.
178
+ if (content.includes(INTENT_GUARD_HOOK_MARKER)) {
179
+ return 'intent-guard';
180
+ }
181
+ if (content.includes('vault-guard') && content.includes('scan --staged')) {
182
+ return 'vault-guard';
183
+ }
184
+ return null;
185
+ }
186
+ const HOOK = `#!/bin/sh
187
+ # Guardrail pre-commit hook. ${MANAGED_HOOK_MARKER}
188
+ # Installed by "conductor init". Remove it with "conductor init --revert".
189
+ #
190
+ # No "set -e" of its own, and written to survive somebody else's. Under
191
+ # "set -e" a shell exits at the failing command before its status can be
192
+ # captured, which keeps the exit code but loses the explanatory line, so a
193
+ # blocked commit prints nothing about why. husky's dispatcher runs this
194
+ # file as "sh -e", so every command allowed to fail is in a condition
195
+ # context rather than standing alone.
196
+ #
197
+ # "command -v" rather than "which": "which" is not in POSIX, is absent from
198
+ # some minimal images, and reports success in some shells for a builtin
199
+ # that is not an executable.
200
+
201
+ # A conductor installed only as a devDependency of this repository is not
202
+ # on PATH, and was invisible to its own hook until this line existed: every
203
+ # commit reported the umbrella missing and blocked, which is the right
204
+ # answer to the wrong question. The root comes from git rather than from
205
+ # the working directory: git runs a pre-commit hook from the top level
206
+ # today, but a hook invoked by hand or by another manager can start in a
207
+ # subdirectory, where a relative "node_modules/.bin" points at nothing.
208
+ conductor_no_git=0
209
+ if command -v git >/dev/null 2>&1; then
210
+ conductor_root=$(git rev-parse --show-toplevel 2>/dev/null) || conductor_root=""
211
+ if [ -n "$conductor_root" ] && [ -d "$conductor_root/node_modules/.bin" ]; then
212
+ PATH="$conductor_root/node_modules/.bin:$PATH"
213
+ export PATH
214
+ fi
215
+ else
216
+ # Without git the root cannot be found, so node_modules/.bin cannot be
217
+ # looked in, so a conductor installed only there is invisible. That is a
218
+ # different fact from "conductor is not installed", and saying the second
219
+ # one sends the reader off to reinstall a tool that may already be sitting
220
+ # in the repository.
221
+ conductor_no_git=1
222
+ fi
223
+
224
+ if ! command -v conductor >/dev/null 2>&1; then
225
+ if [ "$conductor_no_git" -eq 1 ]; then
226
+ echo "conductor: git is not on this hook's PATH, so the repository's node_modules/.bin could not be located and no conductor was found there or on PATH. This commit was NOT checked by any guardrail gate." >&2
227
+ else
228
+ echo "conductor: command not found, so this commit was NOT checked by any guardrail gate. Install the umbrella, or run 'conductor init --revert' to remove this hook." >&2
229
+ fi
230
+ exit 1
231
+ fi
232
+
233
+ # --stage commit, not every stage. A pre-commit hook IS the commit stopping
234
+ # point, and the gates are split across stopping points on ceremony rather
235
+ # than on runtime: the dependency and secret gates are silent until they
236
+ # find something, while the intent gate wants a contract approved before the
237
+ # work starts, which is a per-task human step and belongs at a pull request.
238
+ # Running everything here is what makes a team disable the hook.
239
+ conductor_status=0
240
+ conductor run --staged --stage commit || conductor_status=$?
241
+
242
+ # One message per exit code, not one message for both. The comment below
243
+ # says collapsing 2 into 1 would report findings never looked for, and a
244
+ # single human-readable line saying "commit blocked" for both did exactly
245
+ # that: exit 2 means a gate could not run, so nothing was checked, and
246
+ # calling that a blocked commit describes a decision nobody made.
247
+ #
248
+ # Neither line mentions a bypass flag. Every gate already has a recorded,
249
+ # reviewable, scoped escape: an allow entry, an ignore path, a baseline, or
250
+ # enforce: false in .guardrails.yaml. A bypass skips every gate invisibly,
251
+ # including the ones that would have caught something unrelated to the
252
+ # finding somebody disagreed with, and leaves no trace of the decision.
253
+ if [ "$conductor_status" -eq 1 ]; then
254
+ echo "conductor: a gate blocked this commit. Review the report above. If you disagree with a finding, record the decision where the next reader can see it: an allow entry, an ignore path, or a baseline in that gate's own configuration, or enforce: false for the gate in .guardrails.yaml." >&2
255
+ elif [ "$conductor_status" -ne 0 ]; then
256
+ # "If there is a report above" rather than "the report above". This branch
257
+ # also catches an umbrella that crashed or was not executable, and exit 127
258
+ # with no output at all is one of the shapes that reaches here. Sending
259
+ # somebody to read a report that was never printed makes them hunt for
260
+ # output rather than for the gate.
261
+ echo "conductor: a gate could not run, so NOTHING was checked and this commit was not verified by any gate. If there is a report above, it names the gate and says why. Fix that before committing." >&2
262
+ fi
263
+
264
+ # Passed straight through. 1 means a gate blocked; 2 means a gate could not
265
+ # run at all. Collapsing 2 into 1 would report findings never looked for.
266
+ exit "$conductor_status"
267
+ `;
268
+ function sha256(content) {
269
+ return createHash('sha256').update(content).digest('hex');
270
+ }
271
+ function gitOutput(cwd, args) {
272
+ try {
273
+ return execFileSync('git', args, {
274
+ cwd,
275
+ encoding: 'utf8',
276
+ stdio: ['ignore', 'pipe', 'ignore'],
277
+ }).trim();
278
+ }
279
+ catch {
280
+ return null;
281
+ }
282
+ }
283
+ /**
284
+ * The working-tree root, or null when cwd is not inside a repository.
285
+ *
286
+ * Asked of git rather than probed for a `.git` entry, so init works from a
287
+ * subdirectory and gets a worktree or a submodule right, where `.git` is a
288
+ * file rather than a directory.
289
+ */
290
+ function repoRootOf(cwd) {
291
+ return gitOutput(cwd, ['rev-parse', '--show-toplevel']);
292
+ }
293
+ function effectiveHooksDir(cwd, root) {
294
+ const gitDir = gitOutput(cwd, ['rev-parse', '--git-dir']);
295
+ const hooksPath = gitOutput(cwd, ['config', '--get', 'core.hooksPath']) ?? '';
296
+ if (hooksPath.length === 0) {
297
+ // With no core.hooksPath, hooks live in the git DIRECTORY, which is not
298
+ // the working-tree root: for a linked worktree or a submodule it is
299
+ // somewhere else entirely, so this one resolves against gitDir.
300
+ return { dir: path.join(path.resolve(cwd, gitDir ?? '.git'), 'hooks'), outside: false };
301
+ }
302
+ // A RELATIVE core.hooksPath resolves against the WORKING-TREE ROOT.
303
+ // Verified by experiment rather than by reading the documentation that
304
+ // was misread the first time this was written in a sibling tool.
305
+ const dir = path.isAbsolute(hooksPath) ? hooksPath : path.join(root, hooksPath);
306
+ const relative = path.relative(root, dir);
307
+ const outside = relative.startsWith('..') || path.isAbsolute(relative);
308
+ return { dir, outside };
309
+ }
310
+ function readIfExists(file) {
311
+ try {
312
+ return readFileSync(file, 'utf8');
313
+ }
314
+ catch {
315
+ return undefined;
316
+ }
317
+ }
318
+ /**
319
+ * The manifest a previous init left, or null when there is none or it will
320
+ * not parse.
321
+ *
322
+ * An unreadable manifest is deliberately the same answer as a missing one:
323
+ * everything that consults it here is deciding whether a file on disk is
324
+ * one the umbrella wrote, and "the record is unreadable" is not evidence
325
+ * that it was.
326
+ */
327
+ function readManifest(root) {
328
+ const raw = readIfExists(path.join(root, MANIFEST_RELATIVE_PATH));
329
+ if (raw === undefined) {
330
+ return null;
331
+ }
332
+ try {
333
+ return JSON.parse(raw);
334
+ }
335
+ catch {
336
+ return null;
337
+ }
338
+ }
339
+ /** The hook digest a previous init recorded, or null when there is none. */
340
+ function recordedHookSha(root) {
341
+ return readManifest(root)?.files.find((file) => file.kind === 'hook')?.sha256 ?? null;
342
+ }
343
+ /** Names of the gates whose binary resolves right now. */
344
+ function detectGates(root, pathValue) {
345
+ const found = new Set();
346
+ for (const role of GATE_ROLES) {
347
+ const product = PRODUCT_FOR_ROLE[role];
348
+ for (const candidate of CANDIDATES[product]) {
349
+ // Same order as resolve.ts, though only the answer matters here:
350
+ // detection asks whether a gate is installed at all, not which copy
351
+ // of it would run.
352
+ const local = isExecutable(path.join(root, 'node_modules', '.bin', candidate.name));
353
+ const onPath = pathValue
354
+ .split(path.delimiter)
355
+ .filter((dir) => dir.length > 0)
356
+ .some((dir) => isExecutable(path.join(dir, candidate.name)));
357
+ if (local || onPath) {
358
+ found.add(role);
359
+ break;
360
+ }
361
+ }
362
+ }
363
+ return found;
364
+ }
365
+ function isExecutable(file) {
366
+ try {
367
+ const stats = statSync(file);
368
+ return stats.isFile() && (stats.mode & 0o111) !== 0;
369
+ }
370
+ catch {
371
+ return false;
372
+ }
373
+ }
374
+ /**
375
+ * Existence as a plain file, with no opinion about the executable bit.
376
+ * husky's shim is copied out of the package with whatever mode the tarball
377
+ * carried, and it is sourced rather than executed, so requiring +x here
378
+ * would make detection depend on something husky does not guarantee.
379
+ */
380
+ function isFile(file) {
381
+ try {
382
+ return statSync(file).isFile();
383
+ }
384
+ catch {
385
+ return false;
386
+ }
387
+ }
388
+ const ROLE_DESCRIPTION = {
389
+ dependencies: 'what comes in: hallucinated names, typosquats, tampered lockfile entries',
390
+ secrets: 'what goes out: credentials about to be committed',
391
+ intent: 'what was approved: drift from a frozen intent contract, and change budgets',
392
+ };
393
+ /**
394
+ * The policy file, written by hand rather than serialised, because the
395
+ * comments are half the point: a first-run policy file that explains what
396
+ * each key is for is most of a first-run experience, and a YAML emitter
397
+ * cannot carry them.
398
+ */
399
+ export function renderPolicy(detected) {
400
+ const lines = [
401
+ '# Guardrail policy. One file for every gate this repository runs.',
402
+ '#',
403
+ '# Gates are keyed by the ROLE they fill, and the product filling that role',
404
+ '# is one line inside it. Swapping or renaming a product is a one-line edit',
405
+ '# rather than a rename of the key your CI reads.',
406
+ '#',
407
+ '# There is deliberately no shared severity threshold. Each gate keeps its',
408
+ '# own, spelled the way that gate spells it, inside its own options block.',
409
+ '#',
410
+ '# stage says when a gate runs: commit, push, or ci. Stages are cumulative,',
411
+ '# so a gate runs at its own stage and at every later one, and a run at ci',
412
+ '# runs everything enabled. The values below are the defaults.',
413
+ '#',
414
+ '# enforce says whether a gate can change the exit code. A gate with',
415
+ '# enforce: false runs and reports exactly as an enforced one does and',
416
+ '# never fails the run, which is how a gate is adopted before anybody is',
417
+ '# ready to have it refuse a commit. It is written out below for every',
418
+ '# gate, for the same reason stage is: a default that lives only in the',
419
+ '# parser is a default nobody can find.',
420
+ 'version: 1',
421
+ '',
422
+ 'gates:',
423
+ ];
424
+ for (const role of GATE_ROLES) {
425
+ const product = PRODUCT_FOR_ROLE[role];
426
+ const enabled = detected.has(role);
427
+ lines.push(` # ${ROLE_DESCRIPTION[role]}`);
428
+ if (!enabled) {
429
+ lines.push(` # not found in node_modules/.bin or on PATH. Install ${product}, then set enabled: true.`);
430
+ }
431
+ lines.push(` ${role}:`);
432
+ lines.push(` product: ${product}`);
433
+ lines.push(` enabled: ${enabled ? 'true' : 'false'}`);
434
+ lines.push(` stage: ${DEFAULT_STAGE_FOR_ROLE[role]}`);
435
+ // The intent gate is the one with ceremony, and the ramp is what makes
436
+ // that ceremony adoptable: it reports for a few pull requests before it
437
+ // is allowed to refuse anybody's merge. Writing that here rather than
438
+ // describing it in a comment is the difference between a fresh init
439
+ // producing the ramp and three repositories being hand-edited into it.
440
+ if (role === 'intent') {
441
+ lines.push(' # It runs and reports in CI without failing the run. Flip it to');
442
+ lines.push(' # true once a few pull requests show the signal is worth blocking on.');
443
+ lines.push(' enforce: false');
444
+ }
445
+ else {
446
+ lines.push(' enforce: true');
447
+ }
448
+ lines.push(' # Handed to this gate unchanged. Keys are its own long flags,');
449
+ lines.push(' # without the leading dashes. Example: fail-on: high');
450
+ lines.push(' options: {}');
451
+ }
452
+ lines.push('', 'report:', ' format: text', '');
453
+ return lines.join('\n');
454
+ }
455
+ function foreignGuidance(relPath) {
456
+ return (`${relPath} already exists and was not written by conductor init. Merge "conductor run --staged" ` +
457
+ 'into it yourself, or move it aside and re-run init. Init never replaces a hook it does not ' +
458
+ "recognise, because that hook is somebody's working setup.");
459
+ }
460
+ function editedManagedGuidance(relPath) {
461
+ return (`${relPath} carries conductor's own marker but does not match the hook this version writes, ` +
462
+ 'and either does not match the one recorded in the manifest or there is no manifest to ' +
463
+ 'check against. Either way nothing on disk says these are the contents conductor left, so ' +
464
+ "nothing was changed: an edited hook is somebody's working setup, marker or not. Re-run " +
465
+ 'with --force to replace it anyway, or delete it by hand and re-run.');
466
+ }
467
+ function gateHookGuidance(product, relPath) {
468
+ return (`${relPath} is ${product}'s own pre-commit hook. Adding the umbrella hook alongside it would ` +
469
+ `run ${product} twice and report its findings twice. Re-run with --adopt to replace it with ` +
470
+ 'the umbrella hook, which runs every enabled commit-stage gate including that one, or leave ' +
471
+ 'things as they are and do not run init here.');
472
+ }
473
+ export function planInit(options) {
474
+ const dryRun = Boolean(options.dryRun);
475
+ const actions = [];
476
+ const conflicts = [];
477
+ const writes = [];
478
+ const records = [];
479
+ const base = {
480
+ ok: false,
481
+ dryRun,
482
+ alreadyInstalled: false,
483
+ actions,
484
+ conflicts,
485
+ hookPath: '',
486
+ hookManager: 'native',
487
+ repoRoot: '',
488
+ adoptedFrom: null,
489
+ writes,
490
+ records,
491
+ };
492
+ const root = repoRootOf(options.cwd);
493
+ if (root === null) {
494
+ conflicts.push({
495
+ path: '.git',
496
+ reason: 'not-a-git-repository',
497
+ guidance: 'Run "git init" first: a pre-commit hook has nothing to attach to otherwise.',
498
+ });
499
+ return base;
500
+ }
501
+ const hooks = effectiveHooksDir(options.cwd, root);
502
+ if (hooks.outside) {
503
+ conflicts.push({
504
+ path: hooks.dir,
505
+ reason: 'hooks-path-outside-repository',
506
+ guidance: `core.hooksPath points at ${hooks.dir}, outside this repository. Writing there would ` +
507
+ 'install this repository hook on every repository on the machine. Set a repository-local ' +
508
+ 'core.hooksPath (git config core.hooksPath .git/hooks) and re-run init.',
509
+ });
510
+ return { ...base, repoRoot: root };
511
+ }
512
+ // What git executes. Under husky this is a generated dispatcher rather
513
+ // than the hook anybody maintains, so it decides the manager and then
514
+ // stops being the file this function is about.
515
+ const executedHookPath = path.join(hooks.dir, 'pre-commit');
516
+ const executedHook = readIfExists(executedHookPath);
517
+ // The redirect fires on husky's OWN generated directory, recognised by
518
+ // its shape alone. The tracked hook is then that .husky directory's own
519
+ // pre-commit, which is what husky's shim runs:
520
+ // `s=$(dirname "$(dirname "$0")")/$n`. Never a computed parent of an
521
+ // arbitrary hooks directory, never decided by the content of the file git
522
+ // executes (on husky 8 that file IS the tracked hook), and never
523
+ // conditional on husky's shim being present (a clean deletes it, and the
524
+ // repository is still husky's).
525
+ const huskyDir = huskyDirectoryFor(hooks.dir);
526
+ const husky = huskyDir !== null;
527
+ if (!husky && executedHook !== undefined) {
528
+ const generatedBy = detectGeneratedHook(executedHook);
529
+ if (generatedBy !== null) {
530
+ const rel = path.relative(root, executedHookPath).split(path.sep).join('/');
531
+ conflicts.push({
532
+ path: rel,
533
+ reason: 'generated-hook',
534
+ guidance: generatedHookGuidance(generatedBy, rel),
535
+ });
536
+ return { ...base, repoRoot: root, hookPath: executedHookPath, hookManager: generatedBy };
537
+ }
538
+ }
539
+ const hookManager = husky ? 'husky' : 'native';
540
+ const hookPath = huskyDir === null ? executedHookPath : path.join(huskyDir, 'pre-commit');
541
+ const relHook = path.relative(root, hookPath).split(path.sep).join('/');
542
+ const policyPath = path.join(root, POLICY_FILE_NAME);
543
+ const manifestPath = path.join(root, MANIFEST_RELATIVE_PATH);
544
+ // Under husky this is the TRACKED file, never the dispatcher: reading the
545
+ // dispatcher reported a real gate hook as foreign, which is exactly what
546
+ // made --adopt unable to adopt it.
547
+ const existingHook = readIfExists(hookPath);
548
+ let adoptedFrom = null;
549
+ if (existingHook !== undefined && existingHook.includes(MANAGED_HOOK_MARKER)) {
550
+ // The marker alone used to end the matter, and that was a bug with a
551
+ // long fuse. A hook an OLDER conductor wrote carries the same marker, so
552
+ // it was skipped for ever: it kept running that version's command line
553
+ // after the hook text changed, and it never entered the new manifest, so
554
+ // a later --revert walked past it and left it behind. What the marker
555
+ // actually settles is whose hook this is, not which version of it, so
556
+ // the digest has to decide the rest.
557
+ const installed = sha256(existingHook);
558
+ const recorded = recordedHookSha(root);
559
+ if (installed === sha256(HOOK)) {
560
+ // Nothing to WRITE for the hook. The policy file is still checked
561
+ // below, so a repository whose policy file was deleted can get it
562
+ // back, and the manifest gets the same treatment: a hook that is
563
+ // already exactly right but is missing from the manifest has to be
564
+ // recorded, or --revert has no record that the hook is the
565
+ // umbrella's, reports success, and leaves it running. A git clean, a
566
+ // deleted .guardrails directory and an install from before there were
567
+ // manifests all land in that state.
568
+ if (recorded === installed) {
569
+ actions.push({
570
+ kind: 'skip',
571
+ path: relHook,
572
+ detail: 'already installed by conductor init',
573
+ });
574
+ }
575
+ else {
576
+ actions.push({
577
+ kind: 'skip',
578
+ path: relHook,
579
+ detail: 'already installed, and recorded in the manifest, which had lost it',
580
+ });
581
+ records.push({ path: hookPath, content: existingHook, kind: 'hook' });
582
+ }
583
+ }
584
+ else if (installed === recorded) {
585
+ // On disk it is exactly what the manifest says a previous init wrote,
586
+ // so nobody has touched it since and it is the umbrella's to replace.
587
+ actions.push({
588
+ kind: 'write',
589
+ path: relHook,
590
+ detail: 'update: the installed hook is from an older conductor',
591
+ });
592
+ writes.push({ path: hookPath, content: HOOK, executable: true, kind: 'hook' });
593
+ }
594
+ else if (options.force) {
595
+ actions.push({
596
+ kind: 'write',
597
+ path: relHook,
598
+ detail: 'replace (--force, the managed hook had been edited)',
599
+ });
600
+ writes.push({ path: hookPath, content: HOOK, executable: true, kind: 'hook' });
601
+ }
602
+ else {
603
+ // It matches neither this version's hook nor the recorded one, which
604
+ // includes the case where there is no manifest to check against. The
605
+ // marker says it started as ours; the digest says it is not any more,
606
+ // and an edited hook is somebody's working setup whatever comment sits
607
+ // at the top of it.
608
+ conflicts.push({
609
+ path: relHook,
610
+ reason: 'changed-since-init',
611
+ guidance: editedManagedGuidance(relHook),
612
+ });
613
+ return { ...base, repoRoot: root, hookPath, hookManager };
614
+ }
615
+ }
616
+ else if (existingHook !== undefined && existingHook.trim().length > 0) {
617
+ const gateProduct = detectGateHook(existingHook);
618
+ if (gateProduct === null) {
619
+ conflicts.push({ path: relHook, reason: 'foreign-hook', guidance: foreignGuidance(relHook) });
620
+ return { ...base, repoRoot: root, hookPath, hookManager };
621
+ }
622
+ if (!options.adopt) {
623
+ conflicts.push({
624
+ path: relHook,
625
+ reason: 'gate-hook',
626
+ guidance: gateHookGuidance(gateProduct, relHook),
627
+ });
628
+ return { ...base, repoRoot: root, hookPath, hookManager };
629
+ }
630
+ adoptedFrom = { product: gateProduct, content: existingHook };
631
+ actions.push({
632
+ kind: 'write',
633
+ path: relHook,
634
+ detail: `adopt: replace ${gateProduct}'s own hook (restored by --revert)`,
635
+ });
636
+ writes.push({ path: hookPath, content: HOOK, executable: true, kind: 'hook' });
637
+ }
638
+ else {
639
+ const created = existingHook === undefined ? 'create' : 'replace an empty file';
640
+ actions.push({
641
+ kind: 'write',
642
+ path: relHook,
643
+ // Say the redirect out loud in --dry-run: somebody reading it in a
644
+ // husky repository is entitled to know why the path on screen is not
645
+ // the one core.hooksPath points at. The shim's state is reported
646
+ // here, where it informs, rather than tested in the rule, where it
647
+ // would send a cleaned repository back into the trap.
648
+ detail: husky
649
+ ? `${created}: husky runs ${path
650
+ .relative(root, executedHookPath)
651
+ .split(path.sep)
652
+ .join('/')}, which execs this tracked file${huskyShimPresent(hooks.dir)
653
+ ? ''
654
+ : ' (husky is not installed right now: its generated directory is empty or gone, and the next install restores it)'}`
655
+ : created,
656
+ });
657
+ writes.push({ path: hookPath, content: HOOK, executable: true, kind: 'hook' });
658
+ }
659
+ const existingPolicy = readIfExists(policyPath);
660
+ if (existingPolicy === undefined) {
661
+ writes.push({
662
+ path: policyPath,
663
+ content: renderPolicy(detectGates(root, options.pathValue)),
664
+ executable: false,
665
+ kind: 'policy',
666
+ });
667
+ actions.push({ kind: 'write', path: POLICY_FILE_NAME, detail: 'create' });
668
+ }
669
+ else {
670
+ // Never rewritten. The policy file is the one artifact a user edits by
671
+ // hand, and re-running init must not have an opinion about their edits.
672
+ actions.push({
673
+ kind: 'skip',
674
+ path: POLICY_FILE_NAME,
675
+ detail: 'already present, left exactly as it is',
676
+ });
677
+ }
678
+ // A record with nothing to write is still work: the manifest has to be
679
+ // rebuilt, so this is not an "already installed, nothing to do" run.
680
+ const alreadyInstalled = writes.length === 0 && records.length === 0;
681
+ if (!alreadyInstalled) {
682
+ actions.push({ kind: 'write', path: MANIFEST_RELATIVE_PATH, detail: 'record what init wrote' });
683
+ }
684
+ return {
685
+ ...base,
686
+ ok: true,
687
+ alreadyInstalled,
688
+ hookPath,
689
+ hookManager,
690
+ repoRoot: root,
691
+ adoptedFrom,
692
+ writes,
693
+ records,
694
+ };
695
+ }
696
+ export function applyInit(plan, options) {
697
+ if (!plan.ok || plan.dryRun || plan.alreadyInstalled) {
698
+ return plan;
699
+ }
700
+ // What a previous init recorded. An upgrade rewrites the hook and nothing
701
+ // else, so a manifest built purely from this run's writes would forget the
702
+ // policy file it wrote last time, and would forget the gate hook --adopt
703
+ // replaced -- and the manifest is the only copy of that hook anywhere, so
704
+ // forgetting it makes the gate's own hook unrestorable.
705
+ const previous = readManifest(plan.repoRoot);
706
+ const manifest = {
707
+ version: 1,
708
+ files: [],
709
+ adopted: plan.adoptedFrom === null
710
+ ? (previous?.adopted ?? null)
711
+ : {
712
+ path: plan.hookPath,
713
+ content: plan.adoptedFrom.content,
714
+ product: plan.adoptedFrom.product,
715
+ },
716
+ };
717
+ try {
718
+ for (const write of plan.writes) {
719
+ mkdirSync(path.dirname(write.path), { recursive: true });
720
+ writeFileSync(write.path, write.content, 'utf8');
721
+ if (write.executable) {
722
+ // Set after the write rather than through the write's mode option:
723
+ // an existing file keeps its own mode when written through, and git
724
+ // will not run a hook it cannot execute. A hook that silently never
725
+ // runs is indistinguishable from no gate at all.
726
+ chmodSync(write.path, (statSync(write.path).mode & 0o777) | 0o755);
727
+ }
728
+ manifest.files.push({ path: write.path, sha256: sha256(write.content), kind: write.kind });
729
+ }
730
+ // Files already correct on disk that the manifest had lost. Nothing is
731
+ // written for these; the entry is the whole point.
732
+ for (const record of plan.records) {
733
+ manifest.files.push({
734
+ path: record.path,
735
+ sha256: sha256(record.content),
736
+ kind: record.kind,
737
+ });
738
+ }
739
+ // Everything a previous init recorded and this one did not rewrite. The
740
+ // fresh entries come first so the newly written digests are what a
741
+ // reader sees at the top of the file.
742
+ const rewritten = new Set([
743
+ ...plan.writes.map((write) => write.path),
744
+ ...plan.records.map((record) => record.path),
745
+ ]);
746
+ for (const file of previous?.files ?? []) {
747
+ if (!rewritten.has(file.path)) {
748
+ manifest.files.push(file);
749
+ }
750
+ }
751
+ const manifestPath = path.join(plan.repoRoot, MANIFEST_RELATIVE_PATH);
752
+ mkdirSync(path.dirname(manifestPath), { recursive: true });
753
+ writeFileSync(manifestPath, `${JSON.stringify(manifest, null, 2)}\n`, 'utf8');
754
+ }
755
+ catch (err) {
756
+ return {
757
+ ...plan,
758
+ ok: false,
759
+ conflicts: [
760
+ ...plan.conflicts,
761
+ {
762
+ path: plan.repoRoot,
763
+ reason: 'write-failed',
764
+ guidance: `Could not finish writing: ${err.message}`,
765
+ },
766
+ ],
767
+ };
768
+ }
769
+ void options;
770
+ return plan;
771
+ }
772
+ /**
773
+ * Removes exactly what init wrote, and nothing else.
774
+ *
775
+ * A file whose contents no longer match what the manifest recorded is left
776
+ * alone and reported, because that file is now the user's whatever it
777
+ * started as, and a revert that deletes edited work is a revert nobody runs
778
+ * twice. Three rules follow from that, and all three were bugs here first:
779
+ *
780
+ * 1. IF THE HOOK SURVIVES, NOTHING IS REMOVED. Removing the policy file
781
+ * while leaving an edited hook in place leaves that hook running the
782
+ * umbrella with nothing to read, so every commit afterwards is refused
783
+ * with exit 2 -- while revert reported success. The hook is the piece
784
+ * that depends on the rest, so it decides whether a revert can proceed
785
+ * at all.
786
+ *
787
+ * 2. THE MANIFEST OUTLIVES A PARTIAL REVERT. It is deleted only once it
788
+ * holds nothing, because it is the only record of what is left AND, after
789
+ * an --adopt, the only copy of the gate hook that was replaced. Deleting
790
+ * it while that content was still needed made the gate's own hook
791
+ * unrecoverable.
792
+ *
793
+ * 3. A PARTIAL REVERT IS NOT A SUCCESS. It returns ok: false, so the exit
794
+ * code is non-zero and a script does not read "some of it" as "all of it".
795
+ *
796
+ * `--force` removes a changed file anyway, restoring adopted content if
797
+ * there is any. It is the deliberate way out of every state above.
798
+ */
799
+ export function revertInit(options) {
800
+ const actions = [];
801
+ const conflicts = [];
802
+ const force = Boolean(options.force);
803
+ const root = repoRootOf(options.cwd);
804
+ if (root === null) {
805
+ conflicts.push({
806
+ path: '.git',
807
+ reason: 'not-a-git-repository',
808
+ guidance: 'Nothing to revert: this is not a git repository.',
809
+ });
810
+ return { ok: false, actions, conflicts };
811
+ }
812
+ const manifestPath = path.join(root, MANIFEST_RELATIVE_PATH);
813
+ const raw = readIfExists(manifestPath);
814
+ if (raw === undefined) {
815
+ conflicts.push({
816
+ path: MANIFEST_RELATIVE_PATH,
817
+ reason: 'no-manifest',
818
+ guidance: `No ${MANIFEST_RELATIVE_PATH}, so there is no record of what init wrote. Nothing was ` +
819
+ "removed: guessing which files were ours is how a revert deletes somebody's work.",
820
+ });
821
+ return { ok: false, actions, conflicts };
822
+ }
823
+ const manifest = JSON.parse(raw);
824
+ const relative = (file) => path.relative(root, file).split(path.sep).join('/');
825
+ const planned = manifest.files.map((file) => {
826
+ const current = readIfExists(file.path);
827
+ const state = current === undefined ? 'gone' : sha256(current) === file.sha256 ? 'match' : 'changed';
828
+ return { file, state };
829
+ });
830
+ const blockedHook = planned.find((entry) => entry.file.kind === 'hook' && entry.state === 'changed');
831
+ if (blockedHook !== undefined && !force) {
832
+ const rel = relative(blockedHook.file.path);
833
+ conflicts.push({
834
+ path: rel,
835
+ reason: 'changed-since-init',
836
+ guidance: `${rel} has changed since init wrote it, so nothing was removed. Removing the policy ` +
837
+ 'file while this hook stays in place would leave it running the umbrella with nothing ' +
838
+ `to read, and every commit would be refused. Re-run with --force to remove ${rel} anyway ` +
839
+ '(any adopted hook is restored), or delete it by hand and re-run.',
840
+ });
841
+ for (const entry of planned) {
842
+ actions.push({
843
+ kind: 'skip',
844
+ path: relative(entry.file.path),
845
+ detail: entry.state === 'changed' ? 'changed since init, left alone' : 'left alone',
846
+ });
847
+ }
848
+ return { ok: false, actions, conflicts };
849
+ }
850
+ const remaining = [];
851
+ let hookRemoved = false;
852
+ for (const { file, state } of planned) {
853
+ const rel = relative(file.path);
854
+ if (state === 'gone') {
855
+ actions.push({ kind: 'skip', path: rel, detail: 'already gone' });
856
+ if (file.kind === 'hook') {
857
+ hookRemoved = true;
858
+ }
859
+ continue;
860
+ }
861
+ if (state === 'changed' && !force) {
862
+ actions.push({ kind: 'skip', path: rel, detail: 'changed since init, left alone' });
863
+ conflicts.push({
864
+ path: rel,
865
+ reason: 'changed-since-init',
866
+ guidance: `${rel} has changed since init wrote it and was left alone. Re-run with --force to remove it anyway.`,
867
+ });
868
+ remaining.push(file);
869
+ continue;
870
+ }
871
+ rmSync(file.path, { force: true });
872
+ actions.push({
873
+ kind: 'remove',
874
+ path: rel,
875
+ detail: state === 'changed' ? 'removed (--force, it had changed)' : 'removed',
876
+ });
877
+ if (file.kind === 'hook') {
878
+ hookRemoved = true;
879
+ }
880
+ }
881
+ // Only restore an adopted hook once the umbrella hook that replaced it is
882
+ // actually gone. Putting the old hook back next to a hook the user has
883
+ // since edited would give them two.
884
+ let adopted = manifest.adopted;
885
+ if (adopted !== null && hookRemoved) {
886
+ mkdirSync(path.dirname(adopted.path), { recursive: true });
887
+ writeFileSync(adopted.path, adopted.content, 'utf8');
888
+ chmodSync(adopted.path, 0o755);
889
+ actions.push({
890
+ kind: 'restore',
891
+ path: relative(adopted.path),
892
+ detail: `restored ${adopted.product}'s own hook`,
893
+ });
894
+ adopted = null;
895
+ }
896
+ if (remaining.length === 0 && adopted === null) {
897
+ rmSync(manifestPath, { force: true });
898
+ actions.push({ kind: 'remove', path: MANIFEST_RELATIVE_PATH, detail: 'removed' });
899
+ const manifestDir = path.dirname(MANIFEST_RELATIVE_PATH);
900
+ try {
901
+ // rmdirSync, not rmSync: rmSync on a directory without recursive: true
902
+ // throws before it removes anything, so this swallowed its own error
903
+ // every time and left an empty .guardrails behind after a revert that
904
+ // said it had removed everything. rmdirSync removes an empty directory
905
+ // and refuses a non-empty one, which is exactly the rule wanted here.
906
+ rmdirSync(path.dirname(manifestPath));
907
+ actions.push({ kind: 'remove', path: manifestDir, detail: 'removed, it was empty' });
908
+ }
909
+ catch {
910
+ // The directory holds something else, so it stays. Reported rather
911
+ // than passed over: a directory this tool created and then left
912
+ // behind, with nothing said about it, reads as something revert
913
+ // forgot rather than as something it decided.
914
+ actions.push({
915
+ kind: 'skip',
916
+ path: manifestDir,
917
+ detail: 'kept: it holds something else, which is not ours to remove',
918
+ });
919
+ }
920
+ return { ok: true, actions, conflicts };
921
+ }
922
+ // Something is left, so the manifest stays and keeps describing it.
923
+ writeFileSync(manifestPath, `${JSON.stringify({ ...manifest, files: remaining, adopted }, null, 2)}\n`, 'utf8');
924
+ actions.push({
925
+ kind: 'skip',
926
+ path: MANIFEST_RELATIVE_PATH,
927
+ detail: 'kept: it still records what was left behind',
928
+ });
929
+ return { ok: false, actions, conflicts };
930
+ }
931
+ export function renderInitHuman(result) {
932
+ const lines = [];
933
+ if (result.conflicts.length > 0) {
934
+ lines.push('conductor init: nothing was written.');
935
+ for (const conflict of result.conflicts) {
936
+ lines.push(` ${conflict.path} (${conflict.reason})`);
937
+ lines.push(` ${conflict.guidance}`);
938
+ }
939
+ return lines.join('\n');
940
+ }
941
+ if (result.alreadyInstalled) {
942
+ lines.push('conductor init: already installed; nothing to do.');
943
+ }
944
+ else {
945
+ lines.push(result.dryRun ? 'conductor init (dry run): would write' : 'conductor init: wrote');
946
+ }
947
+ for (const action of result.actions) {
948
+ const verb = action.kind === 'skip' ? 'skip' : result.dryRun ? 'would write' : 'wrote';
949
+ lines.push(` ${verb} ${action.path} (${action.detail})`);
950
+ }
951
+ return lines.join('\n');
952
+ }
953
+ export function renderRevertHuman(result) {
954
+ const removed = result.actions.filter((action) => action.kind === 'remove').length;
955
+ const lines = [
956
+ removed === 0
957
+ ? 'conductor init --revert: nothing was removed.'
958
+ : 'conductor init --revert: partly done, see below.',
959
+ ];
960
+ if (result.ok) {
961
+ lines[0] = 'conductor init --revert:';
962
+ }
963
+ for (const action of result.actions) {
964
+ lines.push(` ${action.kind} ${action.path} (${action.detail})`);
965
+ }
966
+ // The conflicts go LAST rather than first, so the thing the user has to
967
+ // act on is the last line on their terminal rather than scrolled off the
968
+ // top behind a list of what did work.
969
+ for (const conflict of result.conflicts) {
970
+ lines.push('', ` ${conflict.path} (${conflict.reason})`, ` ${conflict.guidance}`);
971
+ }
972
+ return lines.join('\n');
973
+ }