@vaultcompass/conductor 0.4.5 → 0.4.7

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.d.ts CHANGED
@@ -1,38 +1,10 @@
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' | 'simple-git-hooks' | 'yorkie';
27
- /**
28
- * The two managers whose pre-commit TEXT lives in package.json rather than
29
- * in a config file of their own or in the hook file.
30
- *
31
- * They are kept apart from lefthook and the pre-commit framework because
32
- * the refusal is different: there is no manager-owned config file to point
33
- * somebody at, only a key in the file conductor deliberately never writes.
34
- */
35
- export type ManagedHookManager = 'simple-git-hooks' | 'yorkie';
1
+ import type { Product } from './policy.js';
2
+ import { DEP_GUARD_HOOK_MARKER, INTENT_GUARD_HOOK_MARKER, MANAGED_HOOK_MARKER } from './init-hook-detect.js';
3
+ import type { HookManager, ManagedHookManager } from './init-hook-detect.js';
4
+ import { MANIFEST_RELATIVE_PATH } from './init-manifest.js';
5
+ import { POLICY_FILE_NAME, renderPolicy } from './init-policy.js';
6
+ export { MANAGED_HOOK_MARKER, MANIFEST_RELATIVE_PATH, DEP_GUARD_HOOK_MARKER, INTENT_GUARD_HOOK_MARKER, POLICY_FILE_NAME, renderPolicy, };
7
+ export type { HookManager, ManagedHookManager };
36
8
  export type ConflictReason = 'not-a-git-repository' | 'foreign-hook' | 'gate-hook' | 'generated-hook'
37
9
  /**
38
10
  * A manager whose hook text lives in package.json owns this file:
@@ -115,13 +87,6 @@ export interface InitOptions {
115
87
  */
116
88
  force?: boolean;
117
89
  }
118
- /**
119
- * The policy file, written by hand rather than serialised, because the
120
- * comments are half the point: a first-run policy file that explains what
121
- * each key is for is most of a first-run experience, and a YAML emitter
122
- * cannot carry them.
123
- */
124
- export declare function renderPolicy(detected: Set<GateRole>): string;
125
90
  export declare function planInit(options: InitOptions): InitResult;
126
91
  export declare function applyInit(plan: InitResult, options: InitOptions): InitResult;
127
92
  export interface RevertResult {
package/dist/init.js CHANGED
@@ -63,294 +63,13 @@
63
63
  // repositories in a dogfood run: both would have taken the umbrella hook
64
64
  // and lost it at the next install, with the manifest still recording it
65
65
  // as installed. See detectManagedHook and declaredManagedHooks.
66
- import { createHash } from 'node:crypto';
67
66
  import { execFileSync } from 'node:child_process';
68
- import { chmodSync, existsSync, lstatSync, mkdirSync, readFileSync, readdirSync, realpathSync, rmSync, rmdirSync, statSync, writeFileSync, } from 'node:fs';
67
+ import { chmodSync, existsSync, mkdirSync, readdirSync, realpathSync, rmSync, rmdirSync, statSync, writeFileSync, } from 'node:fs';
69
68
  import path from 'node:path';
70
- import { DEFAULT_STAGE_FOR_ROLE, GATE_ROLES, POLICY_FILE_NAME, PRODUCT_FOR_ROLE } from './policy.js';
71
- import { CANDIDATES } from './resolve.js';
72
- export { POLICY_FILE_NAME };
73
- /** The one string that says "conductor init wrote this". */
74
- export const MANAGED_HOOK_MARKER = 'guardrails-managed-hook: v1';
75
- export const MANIFEST_RELATIVE_PATH = '.guardrails/manifest.json';
76
- /**
77
- * Markers each gate's own installer writes, so a collision is recognised
78
- * rather than clobbered. Two of these are literal marker comments the other
79
- * tools write on purpose; the third has no marker at all and is matched on
80
- * the two strings its hook always contains, which is exactly how that
81
- * tool's own installer recognises its own hook.
82
- */
83
- export const DEP_GUARD_HOOK_MARKER = 'dep-guard-managed-hook: v1';
84
- export const INTENT_GUARD_HOOK_MARKER = 'conductor-managed-pre-commit';
85
- /**
86
- * The standalone config files simple-git-hooks reads, exactly as its own
87
- * README lists them. yorkie has no equivalent: its config is the
88
- * `gitHooks` key and nothing else.
89
- */
90
- const SIMPLE_GIT_HOOKS_CONFIG_FILES = [
91
- '.simple-git-hooks.cjs',
92
- '.simple-git-hooks.js',
93
- '.simple-git-hooks.mjs',
94
- '.simple-git-hooks.json',
95
- 'simple-git-hooks.cjs',
96
- 'simple-git-hooks.js',
97
- 'simple-git-hooks.mjs',
98
- 'simple-git-hooks.json',
99
- ];
100
- /**
101
- * The `.husky` directory whose generated subdirectory git has been pointed
102
- * at, or null when this is not that arrangement.
103
- *
104
- * The rule is STRUCTURAL and nothing else: the hooks directory is named
105
- * `_`, and its parent is named `.husky`. Only husky creates that path, so
106
- * the shape alone identifies it, and both halves are required.
107
- *
108
- * Two things are deliberately NOT part of the rule, each for a reason that
109
- * cost a bug:
110
- *
111
- * - THE CONTENT of the pre-commit file git executes. The line that sources
112
- * husky's shim appears in two completely different places:
113
- *
114
- * husky 9 core.hooksPath = .husky/_ .husky/_/pre-commit sources
115
- * _/h and IS a dispatcher; the tracked hook is one up.
116
- * husky 8 core.hooksPath = .husky .husky/pre-commit sources
117
- * _/husky.sh as a PREAMBLE and IS the tracked hook already.
118
- *
119
- * Reading content therefore fired against husky 8's tracked hook, and
120
- * "one directory up" then pointed at the parent of `.husky`, which is
121
- * the repository root. Init wrote a hook there, never read the real one
122
- * so never saw the gate hook in it, reported success, and left every
123
- * commit ungated. The structural rule excludes husky 8 on its own,
124
- * because there the hooks directory is `.husky` and not `_`.
125
- *
126
- * - THE PRESENCE OF THE SHIM (`h`, or husky 8's `husky.sh`). Requiring it
127
- * looks like useful confirmation and quietly reintroduces the original
128
- * trap. husky gitignores `.husky/_`, so `git clean -xdf` deletes the
129
- * whole directory while `core.hooksPath=.husky/_` sits in `.git/config`
130
- * and survives. In that state there is no shim, no dispatcher, and
131
- * nothing whatever to confirm, so a shim requirement sends init down the
132
- * ordinary path to write `.husky/_/pre-commit` -- which is exactly the
133
- * file husky's next prepare step wipes. The shim is evidence that husky
134
- * ran recently, not evidence about whose directory this is, so it is
135
- * reported and never tested against.
136
- *
137
- * The tracked target is this `.husky` directory's own hook, never a
138
- * computed parent of whatever directory git happens to point at.
139
- */
140
- function huskyDirectoryFor(hooksDir) {
141
- if (path.basename(hooksDir) !== '_') {
142
- return null;
143
- }
144
- const huskyDir = path.dirname(hooksDir);
145
- if (path.basename(huskyDir) !== '.husky') {
146
- return null;
147
- }
148
- return huskyDir;
149
- }
150
- /** Whether husky's shim is in place, which is worth SAYING but never testing. */
151
- function huskyShimPresent(hooksDir) {
152
- return isFile(path.join(hooksDir, 'h')) || isFile(path.join(hooksDir, 'husky.sh'));
153
- }
154
- /**
155
- * What each of these two managers actually writes into the hook it
156
- * generates, checked against a real install rather than against anybody's
157
- * memory of one. The captured files are in tests/fixtures/hooks.
158
- *
159
- * lefthook is recognised by `call_lefthook`, the shell function its
160
- * generated hook defines and then calls on the last line. Verified against
161
- * lefthook 2.1.12 and 1.7.18, which both write it twice.
162
- *
163
- * `lefthook_version:` is a second alternative and IS NOT VERIFIED. Neither
164
- * of those versions writes it, and the string does not appear anywhere in
165
- * the 2.1.12 binary either, so it recognises nothing lefthook produces
166
- * today. It stays because a spare alternative in an OR cannot cause a false
167
- * negative and may still catch a much older install. What could not stay is
168
- * the comment that used to be here, which called both halves the
169
- * installer's own mark: a hand-written fixture in the suite carried the
170
- * invented line, so the fixture and the code agreed with each other and
171
- * neither had ever been held up against lefthook. Recognising lefthook on
172
- * that string alone misclassifies both real hooks as native, which is how
173
- * init ends up writing into a file lefthook regenerates.
174
- *
175
- * The pre-commit framework stamps its own URL, and that one is exact:
176
- * verified against pre-commit 4.6.2, whose marker line is character for
177
- * character the string below.
178
- */
179
- function detectGeneratedHook(content) {
180
- if (content.includes('call_lefthook') || content.includes('lefthook_version:')) {
181
- return 'lefthook';
182
- }
183
- if (content.includes('File generated by pre-commit: https://pre-commit.com')) {
184
- return 'precommit';
185
- }
186
- return null;
187
- }
188
- function generatedHookGuidance(manager, relPath) {
189
- const owner = manager === 'lefthook' ? 'lefthook' : 'the pre-commit framework';
190
- const config = manager === 'lefthook' ? 'lefthook-local.yml' : '.pre-commit-config.yaml';
191
- const stanza = manager === 'lefthook'
192
- ? 'add "conductor:" under pre-commit.commands with "run: conductor run --staged"'
193
- : 'add a local hook entry running "conductor run --staged" to its repos: list';
194
- return (`${relPath} is generated by ${owner}, which rewrites it on every install, so anything ` +
195
- `written there is lost without a word. Nothing was changed. To run the umbrella under ` +
196
- `${owner}, ${stanza} in ${config}. Note that ${owner} owns the commit's exit code, so the ` +
197
- "umbrella's 1 (a gate blocked) and 2 (a gate could not run) do not survive it.");
198
- }
199
- /**
200
- * The manager that generated this hook, for the two whose hook text comes
201
- * out of package.json. Checked against real installs, captured in
202
- * tests/fixtures/hooks.
203
- *
204
- * simple-git-hooks is recognised by `SKIP_SIMPLE_GIT_HOOKS`, the opt-out
205
- * variable its generated hook tests on its first line. Verified against
206
- * 2.14.0 and 2.11.1.
207
- *
208
- * IT IS NOT IN EVERY VERSION, and that is the whole reason the package.json
209
- * key below exists rather than being belt and braces. simple-git-hooks 2.8.0
210
- * writes the shebang and the user's own command and nothing else: there is
211
- * no string in that file belonging to simple-git-hooks, so no content rule
212
- * can recognise it, at any price. A repository on that version is
213
- * unrecognisable from its hook alone and would have had the umbrella hook
214
- * written into a file the next install rewrites.
215
- *
216
- * yorkie is recognised by `yorkie/src/runner.js`, the script its generated
217
- * hook invokes. Verified against 2.0.0, which writes it relative, and 1.0.2,
218
- * which writes the same suffix under an absolute path, so the suffix is what
219
- * both have in common. The `#yorkie ` version stamp on the second line is a
220
- * second alternative and is present in both captures too; it is second
221
- * because it is a comment, and a comment is the part of a generated file
222
- * most likely to be reworded.
223
- */
224
- function detectManagedHook(content) {
225
- if (content.includes('SKIP_SIMPLE_GIT_HOOKS')) {
226
- return 'simple-git-hooks';
227
- }
228
- if (content.includes('yorkie/src/runner.js') || content.includes('#yorkie ')) {
229
- return 'yorkie';
230
- }
231
- return null;
232
- }
233
- function declaredManagedHooks(root) {
234
- // A standalone config file counts as a declaration on its own. Taken
235
- // verbatim from simple-git-hooks' own README, which says the config may
236
- // live in ".simple-git-hooks.cjs, .simple-git-hooks.js,
237
- // .simple-git-hooks.mjs, .simple-git-hooks.json, or
238
- // simple-git-hooks.{cjs,js,mjs,json}". It is an EXACT list rather than a
239
- // prefix or extension test, so a simple-git-hooks.yaml or a
240
- // simple-git-hooks.md is what it looks like -- somebody's notes -- and not
241
- // a reason to refuse an install.
242
- //
243
- // This is the third signal and the only one that fires for the repository
244
- // that has all the others against it: a standalone config plus an older
245
- // simple-git-hooks, whose generated hook carries no marker at all.
246
- // Checked BEFORE package.json, and the order is the same one
247
- // simple-git-hooks resolves in: it reads package.json last, so whichever
248
- // of these exists is the file that actually decides the hook.
249
- const configFile = SIMPLE_GIT_HOOKS_CONFIG_FILES.find((file) => isFile(path.join(root, file)));
250
- if (configFile !== undefined) {
251
- return { manager: 'simple-git-hooks', detectedIn: { kind: 'config-file', file: configFile } };
252
- }
253
- const raw = readIfExists(path.join(root, 'package.json'));
254
- if (raw === undefined) {
255
- return null;
256
- }
257
- let parsed;
258
- try {
259
- parsed = JSON.parse(raw);
260
- }
261
- catch {
262
- return null;
263
- }
264
- if (typeof parsed !== 'object' || parsed === null) {
265
- return null;
266
- }
267
- const manifest = parsed;
268
- if (isPlainObject(manifest['simple-git-hooks'])) {
269
- return { manager: 'simple-git-hooks', detectedIn: { kind: 'package.json' } };
270
- }
271
- if (isPlainObject(manifest.gitHooks)) {
272
- return { manager: 'yorkie', detectedIn: { kind: 'package.json' } };
273
- }
274
- return null;
275
- }
276
- function isPlainObject(value) {
277
- return typeof value === 'object' && value !== null && !Array.isArray(value);
278
- }
279
- /**
280
- * What init says when it finds one of those two, and why it says nothing
281
- * else.
282
- *
283
- * The honest answer here is a refusal, not an offer. These managers have no
284
- * tracked hook file to redirect into and no config file of their own to name:
285
- * the only place the umbrella's command could go is a key in package.json,
286
- * and init does not write package.json. That is not squeamishness. Init
287
- * writes a hook, a policy file and a manifest, and the manifest is what
288
- * makes --revert honest; an edit merged into somebody's package.json has no
289
- * revert story that is not a guess about which of their later edits were
290
- * theirs. So the guidance says exactly what to add and leaves the adding to
291
- * the person whose file it is.
292
- *
293
- * The exit-code sentence differs between the two, and both halves are held
294
- * against the captured fixtures rather than against anybody's memory:
295
- * simple-git-hooks runs the entry as the last command of a plain `sh`
296
- * script, so the umbrella's status is the hook's status, while yorkie wraps
297
- * its runner in `|| { ...; exit 1; }` and turns every non-zero exit into 1.
298
- */
299
- function managedHooksGuidance(manager, relPath, detectedIn) {
300
- // WHERE THE ENTRY GOES IS WHERE THE DECLARATION ALREADY IS.
301
- // simple-git-hooks reads package.json LAST, so while a standalone config
302
- // file exists an entry added to package.json is precisely the one it
303
- // ignores. Naming package.json there would send somebody to edit a file
304
- // that will not be read, and leave them with the umbrella uninstalled and
305
- // no error to explain it.
306
- const home = detectedIn.kind === 'config-file' ? detectedIn.file : 'package.json';
307
- const entry = detectedIn.kind === 'config-file'
308
- ? `the "pre-commit" entry in ${detectedIn.file}`
309
- : manager === 'simple-git-hooks'
310
- ? 'the "pre-commit" entry under "simple-git-hooks" in package.json'
311
- : 'the "pre-commit" entry under "gitHooks" in package.json';
312
- const reinstall = manager === 'simple-git-hooks'
313
- ? 're-run "npx simple-git-hooks"'
314
- : 're-run the install (yorkie rewrites its hooks on postinstall)';
315
- const exitCodes = manager === 'simple-git-hooks'
316
- ? `${manager} runs that entry as the last command of the hook it generates, so the ` +
317
- "umbrella's exit codes reach git unchanged: 1 means a gate blocked, 2 means a gate " +
318
- 'could not run.'
319
- : `${manager}'s generated hook turns every non-zero exit into 1, so the umbrella's 2 ` +
320
- '(a gate could not run, and nothing was checked) reaches git as 1 (a gate blocked). ' +
321
- 'Both still stop the commit.';
322
- const lead = detectedIn.kind === 'hook'
323
- ? `${relPath} was generated by ${manager} from its own declaration, and is rewritten on ` +
324
- 'every install.'
325
- : `${home} declares ${manager}, which generates ${relPath} from that declaration and ` +
326
- 'rewrites it on every install.';
327
- return (`${lead} A hook written there is gone after the next install while ` +
328
- `${MANIFEST_RELATIVE_PATH} still records it as installed, so the repository would report a ` +
329
- 'guardrail it no longer has. Nothing was changed, and --force does not override this: that ' +
330
- `file was never conductor's to hold. To run the umbrella under ${manager}, set ${entry} ` +
331
- 'to "conductor run --staged --stage commit" yourself, and ' +
332
- `${reinstall}. If something is already in that entry, put the umbrella LAST, as its own ` +
333
- 'command rather than chained behind && : a chain stops at the first failure, so an ' +
334
- "umbrella in front of it hides the other command's verdict and one behind an && never " +
335
- `runs at all once anything ahead of it fails. conductor does not edit ${home}, so it ` +
336
- 'cannot do that for you; a later release may offer to. ' +
337
- exitCodes);
338
- }
339
- function detectGateHook(content) {
340
- if (content.includes(DEP_GUARD_HOOK_MARKER)) {
341
- return 'dep-guard';
342
- }
343
- // Deliberately still the pre-rename string: it is state already sitting
344
- // in users' repositories, and the tool that writes it did not rename it
345
- // either, precisely so an older hook stays recognisable.
346
- if (content.includes(INTENT_GUARD_HOOK_MARKER)) {
347
- return 'intent-guard';
348
- }
349
- if (content.includes('vault-guard') && content.includes('scan --staged')) {
350
- return 'vault-guard';
351
- }
352
- return null;
353
- }
69
+ import { DEP_GUARD_HOOK_MARKER, INTENT_GUARD_HOOK_MARKER, MANAGED_HOOK_MARKER, declaredManagedHooks, detectGateHook, detectGeneratedHook, detectManagedHook, editedManagedGuidance, foreignGuidance, gateHookGuidance, generatedHookGuidance, huskyDirectoryFor, huskyShimPresent, managedHooksGuidance, } from './init-hook-detect.js';
70
+ import { MANIFEST_RELATIVE_PATH, manifestPathInsideRepo, readIfExists, readManifest, recordedHookSha, sha256, } from './init-manifest.js';
71
+ import { POLICY_FILE_NAME, detectGates, renderPolicy } from './init-policy.js';
72
+ export { MANAGED_HOOK_MARKER, MANIFEST_RELATIVE_PATH, DEP_GUARD_HOOK_MARKER, INTENT_GUARD_HOOK_MARKER, POLICY_FILE_NAME, renderPolicy, };
354
73
  const HOOK = `#!/bin/sh
355
74
  # Guardrail pre-commit hook. ${MANAGED_HOOK_MARKER}
356
75
  # Installed by "conductor init". Remove it with "conductor init --revert".
@@ -433,96 +152,6 @@ fi
433
152
  # run at all. Collapsing 2 into 1 would report findings never looked for.
434
153
  exit "$conductor_status"
435
154
  `;
436
- function sha256(content) {
437
- return createHash('sha256').update(content).digest('hex');
438
- }
439
- /**
440
- * Whether a path the manifest names is contained to the repository.
441
- *
442
- * The manifest is committed input, so a path in it is whatever a commit put
443
- * there. Revert and apply run this over every path they would write to or
444
- * delete before touching anything, and refuse the whole operation if any one
445
- * of them is not contained.
446
- *
447
- * Two conditions, because a path can escape two ways. The resolved path,
448
- * treated as plain strings, must be inside the root: this refuses an absolute
449
- * path and one that climbs out with ../. And no component of the path may be a
450
- * SYMLINK. A committed dangling symlink (its target does not exist) is the case
451
- * that broke an earlier version of this: existsSync FOLLOWS the link, finds the
452
- * missing target, and reports the link absent, so a walk that resolved only the
453
- * deepest existing ancestor judged the link a plain not-yet-existing leaf and
454
- * let writeFileSync and chmodSync, which DO follow the final link, land the
455
- * write on the outside target. lstatSync does not follow, so it catches a
456
- * symlink component even when its target is gone. init never writes through a
457
- * symlink, so a symlink anywhere along the path means this is not a path init
458
- * wrote, and it is refused whatever it points at.
459
- *
460
- * Paths here need not exist yet: an adopted hook is restored to a path revert
461
- * has just removed, and a recorded file may be legitimately gone. The scan
462
- * stops at the first component that does not exist, because nothing below a
463
- * missing component exists either, so there is no symlink left to find. A
464
- * relative candidate is taken against the repository root, which is how the
465
- * real attack lands: a person running revert has cd'd into the checkout.
466
- */
467
- function manifestPathInsideRepo(repoRoot, candidate) {
468
- try {
469
- const root = realpathSync(repoRoot);
470
- const abs = path.resolve(root, candidate);
471
- // Deepest ancestor of abs that exists on disk. realpathSync on the whole
472
- // path throws when the leaf is not there, so resolve the part that exists
473
- // and keep the rest as a tail. existsSync FOLLOWS symlinks, which is why a
474
- // dangling symlink is not trusted here; the tail is scanned with lstatSync
475
- // below.
476
- let ancestor = abs;
477
- while (!existsSync(ancestor)) {
478
- const parent = path.dirname(ancestor);
479
- if (parent === ancestor) {
480
- break;
481
- }
482
- ancestor = parent;
483
- }
484
- const realAncestor = realpathSync(ancestor);
485
- const tail = path.relative(ancestor, abs);
486
- // Containment, on resolved paths so a macOS temp dir reached through
487
- // /var -> /private/var does not read as an escape, and so an existing
488
- // symlink directory that points outside is caught by its resolved target.
489
- const resolved = tail === '' ? realAncestor : path.join(realAncestor, tail);
490
- const inside = path.relative(root, resolved);
491
- if (inside === '' ||
492
- inside === '..' ||
493
- inside.startsWith(`..${path.sep}`) ||
494
- path.isAbsolute(inside)) {
495
- return false;
496
- }
497
- // No component of the tail may be a symlink. lstatSync does not follow, so
498
- // a committed DANGLING symlink is caught even though existsSync reported it
499
- // absent: existsSync followed the link to its missing target, which let an
500
- // earlier version treat the link as a plain not-yet-existing leaf and then
501
- // let writeFileSync and chmodSync, which DO follow the final link, land the
502
- // write on the outside target. init never writes through a symlink, so any
503
- // symlink component means this is not a path init wrote. The scan starts at
504
- // the resolved ancestor, whose own components are already real, and walks
505
- // to the leaf, stopping at the first component that does not exist.
506
- let current = realAncestor;
507
- for (const segment of tail === '' ? [] : tail.split(path.sep)) {
508
- current = path.join(current, segment);
509
- let entry;
510
- try {
511
- entry = lstatSync(current);
512
- }
513
- catch {
514
- break;
515
- }
516
- if (entry.isSymbolicLink()) {
517
- return false;
518
- }
519
- }
520
- return true;
521
- }
522
- catch {
523
- return false;
524
- }
525
- }
526
155
  function gitOutput(cwd, args) {
527
156
  try {
528
157
  return execFileSync('git', args, {
@@ -587,169 +216,6 @@ function samePath(left, right) {
587
216
  };
588
217
  return real(left) === real(right);
589
218
  }
590
- function readIfExists(file) {
591
- try {
592
- return readFileSync(file, 'utf8');
593
- }
594
- catch {
595
- return undefined;
596
- }
597
- }
598
- /**
599
- * The manifest a previous init left, or null when there is none or it will
600
- * not parse.
601
- *
602
- * An unreadable manifest is deliberately the same answer as a missing one:
603
- * everything that consults it here is deciding whether a file on disk is
604
- * one the umbrella wrote, and "the record is unreadable" is not evidence
605
- * that it was.
606
- */
607
- function readManifest(root) {
608
- const raw = readIfExists(path.join(root, MANIFEST_RELATIVE_PATH));
609
- if (raw === undefined) {
610
- return null;
611
- }
612
- try {
613
- return JSON.parse(raw);
614
- }
615
- catch {
616
- return null;
617
- }
618
- }
619
- /** The hook digest a previous init recorded, or null when there is none. */
620
- function recordedHookSha(root) {
621
- return readManifest(root)?.files.find((file) => file.kind === 'hook')?.sha256 ?? null;
622
- }
623
- /** Names of the gates whose binary resolves right now. */
624
- function detectGates(root, pathValue) {
625
- const found = new Set();
626
- for (const role of GATE_ROLES) {
627
- const product = PRODUCT_FOR_ROLE[role];
628
- for (const candidate of CANDIDATES[product]) {
629
- // Same order as resolve.ts, though only the answer matters here:
630
- // detection asks whether a gate is installed at all, not which copy
631
- // of it would run.
632
- const local = isExecutable(path.join(root, 'node_modules', '.bin', candidate.name));
633
- const onPath = pathValue
634
- .split(path.delimiter)
635
- .filter((dir) => dir.length > 0)
636
- .some((dir) => isExecutable(path.join(dir, candidate.name)));
637
- if (local || onPath) {
638
- found.add(role);
639
- break;
640
- }
641
- }
642
- }
643
- return found;
644
- }
645
- function isExecutable(file) {
646
- try {
647
- const stats = statSync(file);
648
- return stats.isFile() && (stats.mode & 0o111) !== 0;
649
- }
650
- catch {
651
- return false;
652
- }
653
- }
654
- /**
655
- * Existence as a plain file, with no opinion about the executable bit.
656
- * husky's shim is copied out of the package with whatever mode the tarball
657
- * carried, and it is sourced rather than executed, so requiring +x here
658
- * would make detection depend on something husky does not guarantee.
659
- */
660
- function isFile(file) {
661
- try {
662
- return statSync(file).isFile();
663
- }
664
- catch {
665
- return false;
666
- }
667
- }
668
- const ROLE_DESCRIPTION = {
669
- dependencies: 'what comes in: hallucinated names, typosquats, tampered lockfile entries',
670
- secrets: 'what goes out: credentials about to be committed',
671
- intent: 'what was approved: drift from a frozen intent contract, and change budgets',
672
- };
673
- /**
674
- * The policy file, written by hand rather than serialised, because the
675
- * comments are half the point: a first-run policy file that explains what
676
- * each key is for is most of a first-run experience, and a YAML emitter
677
- * cannot carry them.
678
- */
679
- export function renderPolicy(detected) {
680
- const lines = [
681
- '# Guardrail policy. One file for every gate this repository runs.',
682
- '#',
683
- '# Gates are keyed by the ROLE they fill, and the product filling that role',
684
- '# is one line inside it. Swapping or renaming a product is a one-line edit',
685
- '# rather than a rename of the key your CI reads.',
686
- '#',
687
- '# There is deliberately no shared severity threshold. Each gate keeps its',
688
- '# own, spelled the way that gate spells it, inside its own options block.',
689
- '#',
690
- '# stage says when a gate runs: commit, push, or ci. Stages are cumulative,',
691
- '# so a gate runs at its own stage and at every later one, and a run at ci',
692
- '# runs everything enabled. The values below are the defaults.',
693
- '#',
694
- '# enforce says whether a gate can change the exit code. A gate with',
695
- '# enforce: false runs and reports exactly as an enforced one does and',
696
- '# never fails the run, which is how a gate is adopted before anybody is',
697
- '# ready to have it refuse a commit. It is written out below for every',
698
- '# gate, for the same reason stage is: a default that lives only in the',
699
- '# parser is a default nobody can find.',
700
- 'version: 1',
701
- '',
702
- 'gates:',
703
- ];
704
- for (const role of GATE_ROLES) {
705
- const product = PRODUCT_FOR_ROLE[role];
706
- const enabled = detected.has(role);
707
- lines.push(` # ${ROLE_DESCRIPTION[role]}`);
708
- if (!enabled) {
709
- lines.push(` # not found in node_modules/.bin or on PATH. Install ${product}, then set enabled: true.`);
710
- }
711
- lines.push(` ${role}:`);
712
- lines.push(` product: ${product}`);
713
- lines.push(` enabled: ${enabled ? 'true' : 'false'}`);
714
- lines.push(` stage: ${DEFAULT_STAGE_FOR_ROLE[role]}`);
715
- // The intent gate is the one with ceremony, and the ramp is what makes
716
- // that ceremony adoptable: it reports for a few pull requests before it
717
- // is allowed to refuse anybody's merge. Writing that here rather than
718
- // describing it in a comment is the difference between a fresh init
719
- // producing the ramp and three repositories being hand-edited into it.
720
- if (role === 'intent') {
721
- lines.push(' # It runs and reports in CI without failing the run. Flip it to');
722
- lines.push(' # true once a few pull requests show the signal is worth blocking on.');
723
- lines.push(' enforce: false');
724
- }
725
- else {
726
- lines.push(' enforce: true');
727
- }
728
- lines.push(' # Handed to this gate unchanged. Keys are its own long flags,');
729
- lines.push(' # without the leading dashes. Example: fail-on: high');
730
- lines.push(' options: {}');
731
- }
732
- lines.push('', 'report:', ' format: text', '');
733
- return lines.join('\n');
734
- }
735
- function foreignGuidance(relPath) {
736
- return (`${relPath} already exists and was not written by conductor init. Merge "conductor run --staged" ` +
737
- 'into it yourself, or move it aside and re-run init. Init never replaces a hook it does not ' +
738
- "recognise, because that hook is somebody's working setup.");
739
- }
740
- function editedManagedGuidance(relPath) {
741
- return (`${relPath} carries conductor's own marker but does not match the hook this version writes, ` +
742
- 'and either does not match the one recorded in the manifest or there is no manifest to ' +
743
- 'check against. Either way nothing on disk says these are the contents conductor left, so ' +
744
- "nothing was changed: an edited hook is somebody's working setup, marker or not. Re-run " +
745
- 'with --force to replace it anyway, or delete it by hand and re-run.');
746
- }
747
- function gateHookGuidance(product, relPath) {
748
- return (`${relPath} is ${product}'s own pre-commit hook. Adding the umbrella hook alongside it would ` +
749
- `run ${product} twice and report its findings twice. Re-run with --adopt to replace it with ` +
750
- 'the umbrella hook, which runs every enabled commit-stage gate including that one, or leave ' +
751
- 'things as they are and do not run init here.');
752
- }
753
219
  export function planInit(options) {
754
220
  const dryRun = Boolean(options.dryRun);
755
221
  const actions = [];
@@ -1374,6 +840,18 @@ export function renderInitHuman(result) {
1374
840
  const verb = action.kind === 'skip' ? 'skip' : result.dryRun ? 'would write' : 'wrote';
1375
841
  lines.push(` ${verb} ${action.path} (${action.detail})`);
1376
842
  }
843
+ // Two different answers, and saying only the second one is wrong about the
844
+ // hook this command just wrote. The pre-commit hook runs `conductor run
845
+ // --staged --stage commit` with no --trust-base, and policyForRun reads the
846
+ // working tree when trustBase is undefined, so the hook honours this file on
847
+ // the very next commit. A pull request is the opposite: it is judged by the
848
+ // base branch's own copy, never by the one it is proposing, so the first
849
+ // pull request after adoption is inert and reports could-not-run. Said once,
850
+ // here, at the point of use, rather than left for somebody to discover from
851
+ // a could-not-run comment on their first pull request.
852
+ lines.push(`Note: the pre-commit hook uses ${POLICY_FILE_NAME} from your working tree right away. ` +
853
+ 'On a pull request conductor reads it from the base branch instead, so pull requests ' +
854
+ 'report could-not-run until this file is merged there.');
1377
855
  return lines.join('\n');
1378
856
  }
1379
857
  export function renderRevertHuman(result) {