@vaultcompass/conductor 0.2.1 → 0.2.3

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/README.md CHANGED
@@ -220,6 +220,22 @@ that gate, for pointing at a build that is not installed anywhere.
220
220
  `--adopt`: those hooks were never conductor's, and no flag here turns
221
221
  somebody else's file into one this tool may overwrite.
222
222
 
223
+ Init recognises the hook manager already wired into the repository. husky is
224
+ redirected to the tracked hook it maintains rather than the generated
225
+ dispatcher git runs. lefthook and the pre-commit framework are refused, with
226
+ the stanza to add to their own config file. simple-git-hooks and yorkie are
227
+ refused too, and recognised from the declaration as well as from the hook
228
+ file, because the declaration is there on a fresh clone where the generated
229
+ hook is not yet: the `simple-git-hooks` or `gitHooks` key in package.json, or
230
+ any of the standalone config files simple-git-hooks reads. Their hook text
231
+ lives in package.json, which conductor does not write, so the guidance names
232
+ the entry to add and `--force` does not override the refusal.
233
+
234
+ That refusal applies only where git actually runs `.git/hooks`. Both managers
235
+ write that directory and neither reads `core.hooksPath`, so a repository that
236
+ has pointed git somewhere else has taken their file out of play, and init
237
+ proceeds normally without mentioning them.
238
+
223
239
  `conductor run` runs every enabled gate and prints one report.
224
240
 
225
241
  - `--staged` gates the git index against HEAD, which is what the hook does.
@@ -281,14 +297,32 @@ gate looks like. In Actions this is almost always a shallow checkout, so
281
297
  outranks everything, and a path here that is not on disk is reported
282
298
  rather than replaced: running a different contract than the one somebody
283
299
  named is the wrong kindness.
284
- 2. `<repo>/.conductor/intent-contract.yaml`, when it is **frozen**. The
285
- native flow wins wherever a team has done it. Frozen is the test rather
286
- than present: an unfrozen contract is a draft somebody left behind, and
287
- running the gate against it fails every pull request on "not frozen by
288
- user" without checking anything.
300
+ 2. `<repo>/.intent-guard/intent-contract.yaml`, when it is **frozen**, and
301
+ `<repo>/.conductor/intent-contract.yaml` after it. The native flow wins
302
+ wherever a team has done it. Frozen is the test rather than present: an
303
+ unfrozen contract is a draft somebody left behind, and running the gate
304
+ against it fails every pull request on "not frozen by user" without
305
+ checking anything.
306
+
307
+ The second path is the directory intent-guard used before 1.3.0, which
308
+ renamed it because `.conductor` had become the name of a different product
309
+ in this family. Both are read, so a repository on either version is
310
+ checked rather than blocked, and a run that used the old one says so: one
311
+ line on the gate's contract line in the text report, and an
312
+ `intent-guard/legacy-state-dir` notification in the SARIF log. If the
313
+ repository holds **both** directories, the gate does not run and says so,
314
+ naming both: that is the state intent-guard itself refuses every command
315
+ in, so the umbrella refuses on exactly the gate's rule rather than a
316
+ softer one. A `.conductor` holding nothing intent-guard wrote belongs to
317
+ something else and is ignored.
289
318
  3. The **first** `Spec: <path>` line in the pull request body, read from the
290
319
  event payload at `GITHUB_EVENT_PATH`. A path here that is not on disk, or
291
320
  one that leaves the repository, falls through to the next rule.
321
+ `Spec: none` is a **waiver**: it says this pull request deliberately has
322
+ no spec, so rule 4 is not tried and the gate reports itself skipped with
323
+ `intent-guard/contract-waived` instead of `intent-guard/no-contract`. The
324
+ token is exact and lowercase, a frozen contract at rule 2 still wins over
325
+ it, and `--spec` at rule 1 still overrides it.
292
326
  4. A markdown file **directly under** `docs/superpowers/specs` whose name
293
327
  relates to the branch. The branch slug is the branch name with its first
294
328
  segment (`feat/`, `fix/`) removed; a filename is reduced by stripping a
@@ -303,7 +337,20 @@ line in the text report and one `intent-guard/no-contract` notification
303
337
  in the `conductor` run, and it **never** reaches the exit code, enforced or
304
338
  not. A branch with no spec is a branch this gate has no opinion about, and
305
339
  turning that into a failed build is how a gate gets switched off across a
306
- repository.
340
+ repository. A waived pull request lands in the same state and is reported
341
+ under its own `intent-guard/contract-waived` id, with its own wording on the
342
+ skipped line, in the verdict and on the one-line summary of a clean run, so a
343
+ reader can tell "nobody has written one" from "somebody decided against one"
344
+ wherever they meet it.
345
+
346
+ **A waiver is a decision, recorded by whoever wrote the pull request body,
347
+ and that includes a contributor from a fork.** On the ordinary path, where a
348
+ repository has no frozen contract of its own, `Spec: none` means the intent
349
+ gate does not run at all on that pull request, and budget breaches are the
350
+ thing this gate blocks on. The one thing a waiver cannot override is a frozen
351
+ native contract, under either of the two paths above, which is checked first:
352
+ a repository that wants the gate to be non-waivable freezes a native contract
353
+ and keeps it committed.
307
354
 
308
355
  **What blocks is unchanged.** Blocking stays where intent-guard puts it:
309
356
  budget breaches block, subject to `enforce`. Drift on its own is reported and
@@ -370,6 +417,51 @@ runs whatever its author pushes to it next. Pin every third-party action by
370
417
  commit digest in a workflow you actually run, the way this repository's own
371
418
  workflows do.
372
419
 
420
+ ### The report as a pull request comment
421
+
422
+ The SARIF upload produces no alerts on a private repository without GitHub
423
+ Code Security, which is why that step carries `continue-on-error`. A comment
424
+ is free there. Add `pull-requests: write` to the job's `permissions` and this
425
+ step after the gates. It **runs the gates a second time**, because the Action
426
+ writes SARIF and nothing else, so the job costs roughly twice the gate time;
427
+ `--verbose` because a clean run otherwise collapses to one line.
428
+
429
+ ```yaml
430
+ - name: Comment the report on the pull request
431
+ # always: the report is most worth reading on the run that failed,
432
+ # and the gates step has already failed the job by then.
433
+ if: always()
434
+ continue-on-error: true
435
+ env:
436
+ GH_TOKEN: ${{ github.token }}
437
+ PR: ${{ github.event.pull_request.number }}
438
+ # || true: a blocking finding is a non-zero exit, and that verdict
439
+ # belongs to the gates step rather than to this one.
440
+ run: |
441
+ node_modules/.bin/conductor run --stage ci --format text --verbose --output conductor.txt || true
442
+ gh pr comment "$PR" --body-file conductor.txt
443
+ ```
444
+
445
+ **Mirror whatever you gave the Action**, or the two runs can report different
446
+ contracts. The step above matches the example, which passes neither
447
+ `base-ref` nor `spec`, so both runs read `GITHUB_BASE_REF` and the `Spec:`
448
+ line out of the job environment themselves and land on the same contract. If
449
+ you set either input on the gates step, pass the same values here as `--base`
450
+ and `--spec`; if you do not, the comment is a report of a contract source the
451
+ uploaded log never used.
452
+
453
+ **On a pull request from a fork the token is read-only**, so `gh pr comment`
454
+ fails, `continue-on-error` swallows the failure, and no comment appears on
455
+ exactly the pull requests a reviewer knows least about. Nothing here fixes
456
+ that: `pull_request_target` runs with a writable token and the base
457
+ repository's own workflow, which is a different security decision to take on
458
+ purpose rather than a flag to add.
459
+
460
+ This is a substitute for code-scanning alerts, not the same thing. A comment
461
+ is one snapshot of one run: no per-finding state, nothing to dismiss, no
462
+ history between runs, and a new comment every time rather than an alert that
463
+ closes when the finding goes away.
464
+
373
465
  ## What is in and what is out
374
466
 
375
467
  In: the policy file and its schema, `init` with dry-run, revert, and adopt,
package/dist/cli.js CHANGED
@@ -18,10 +18,27 @@ import { GATE_ROLES, GATE_STAGES, PolicyError, applyCliOverrides, loadPolicy } f
18
18
  import { runAll } from './run.js';
19
19
  const pkgPath = path.join(path.dirname(fileURLToPath(import.meta.url)), '..', 'package.json');
20
20
  const pkg = JSON.parse(readFileSync(pkgPath, 'utf8'));
21
+ /**
22
+ * The working-tree root, or a thrown one-line diagnosis of why there is none.
23
+ *
24
+ * The policy file, the hook, and every child's working directory are all
25
+ * anchored at the working-tree root, so a run from a subdirectory behaves
26
+ * exactly like a run from the top.
27
+ *
28
+ * This used to catch everything and return the working directory. Two quite
29
+ * different failures hid in that: git is not on PATH, and this directory is
30
+ * not inside a repository. Both then produced "no .guardrails.yaml here, run
31
+ * conductor init" from a subdirectory of a repository that has one, which is
32
+ * a confident answer to a question nobody asked. The generated hook has
33
+ * always named a missing git in its own words (src/init.ts), for the same
34
+ * reason.
35
+ *
36
+ * Errors rather than a fallback root, because the alternative is silently
37
+ * gating a commit against the wrong tree. `run`'s own catch turns these into
38
+ * one line on stderr with no stack and the could-not-run exit code, so
39
+ * nothing here has to know about either.
40
+ */
21
41
  function repoRoot(cwd) {
22
- // The policy file, the hook, and every child's working directory are all
23
- // anchored at the working-tree root, so a run from a subdirectory behaves
24
- // exactly like a run from the top.
25
42
  try {
26
43
  return execFileSync('git', ['rev-parse', '--show-toplevel'], {
27
44
  cwd,
@@ -29,8 +46,22 @@ function repoRoot(cwd) {
29
46
  stdio: ['ignore', 'pipe', 'ignore'],
30
47
  }).trim();
31
48
  }
32
- catch {
33
- return cwd;
49
+ catch (err) {
50
+ if (err.code === 'ENOENT') {
51
+ throw new Error('git is not on PATH, so the repository root could not be found. Install git, or ' +
52
+ 'run conductor from a shell that has it.');
53
+ }
54
+ if (typeof err.status === 'number') {
55
+ // git ran and refused. The directory is named because it is the one
56
+ // thing the reader has to check, and it is the directory they typed
57
+ // the command in rather than anything internal to this tool.
58
+ throw new Error(`not a git repository: ${cwd}. conductor anchors every gate at the working-tree ` +
59
+ 'root, so run it inside a checkout.');
60
+ }
61
+ // git is there and never got as far as an exit code: a permissions
62
+ // problem, or a machine out of processes. Neither of the two sentences
63
+ // above would be true, so this says what actually happened.
64
+ throw new Error(`git could not be run to find the repository root: ${err.message}`);
34
65
  }
35
66
  }
36
67
  function parseFormat(value) {
@@ -143,8 +174,11 @@ export function buildProgram() {
143
174
  .exitOverride()
144
175
  .action((options) => {
145
176
  const cwd = process.cwd();
146
- const root = repoRoot(cwd);
147
177
  try {
178
+ // Inside the try, because repoRoot now reports rather than guesses,
179
+ // and the catch below is what turns any of its three sentences into
180
+ // one line on stderr and the could-not-run exit code.
181
+ const root = repoRoot(cwd);
148
182
  const policy = applyCliOverrides(loadPolicy(root), {
149
183
  ...(parseRoles(options.gate) === undefined
150
184
  ? {}
@@ -186,6 +220,15 @@ export function buildProgram() {
186
220
  // reaches here; anything that does is the umbrella's own problem and
187
221
  // still must not put a local filesystem path in front of a user who
188
222
  // cannot act on it, or into a pre-commit hook's output.
223
+ //
224
+ // The working directory in repoRoot's "not a git repository" sentence
225
+ // is the deliberate exception, and it is the shape of the rule rather
226
+ // than a hole in it: the user typed the command in that directory, it
227
+ // is the one thing they have to check, and a message that withheld it
228
+ // would be telling somebody their directory is wrong without saying
229
+ // which one. What the rule is really about is a path this tool knows
230
+ // and the reader does not, in a stack frame or a message they cannot
231
+ // act on.
189
232
  process.exitCode = fail(err instanceof PolicyError
190
233
  ? err.message
191
234
  : `conductor: ${err instanceof Error ? err.message : String(err)}`);
@@ -199,7 +199,12 @@ export function runGate(gate, options) {
199
199
  ...progress,
200
200
  durationMs: Date.now() - started,
201
201
  couldNotRun: { reason: 'unparseable-output', detail },
202
- findings: [normalizeUnparseableGate(gate.role, gate.product, detail)],
202
+ // progress.stderr, because the comment on progress promises exactly
203
+ // this: it is kept current so an unexpected throw still reports which
204
+ // binary ran and what it printed. Leaving it off here made that
205
+ // promise false for the finding, which is the only part of it a
206
+ // published log ever sees.
207
+ findings: [normalizeUnparseableGate(gate.role, gate.product, detail, progress.stderr)],
203
208
  run: EMPTY_RUN,
204
209
  diagnostics: [],
205
210
  };
@@ -276,7 +281,9 @@ function runGateInner(gate, options, started, progress) {
276
281
  ...withRun,
277
282
  exitCode: null,
278
283
  couldNotRun: { reason: 'spawn-failed', detail: child.error.message },
279
- findings: [normalizeFailedGate(gate.role, gate.product, child.error.message)],
284
+ findings: [
285
+ normalizeFailedGate(gate.role, gate.product, child.error.message, withRun.stderr),
286
+ ],
280
287
  run: EMPTY_RUN,
281
288
  diagnostics: [],
282
289
  };
@@ -294,7 +301,11 @@ function runGateInner(gate, options, started, progress) {
294
301
  ...withRun,
295
302
  exitCode,
296
303
  couldNotRun: { reason: 'gate-error', detail },
297
- findings: [normalizeFailedGate(gate.role, gate.product, detail)],
304
+ // The child's own stderr goes with it. The text report prints it from
305
+ // the outcome, but a gate that could not run gets no SARIF run of its
306
+ // own, so this finding is the only place a published log can say what
307
+ // the gate actually complained about.
308
+ findings: [normalizeFailedGate(gate.role, gate.product, detail, withRun.stderr)],
298
309
  run: EMPTY_RUN,
299
310
  diagnostics: [],
300
311
  };
@@ -314,7 +325,7 @@ function runGateInner(gate, options, started, progress) {
314
325
  ...withRun,
315
326
  exitCode,
316
327
  couldNotRun: { reason: 'unparseable-output', detail },
317
- findings: [normalizeUnparseableGate(gate.role, gate.product, detail)],
328
+ findings: [normalizeUnparseableGate(gate.role, gate.product, detail, withRun.stderr)],
318
329
  run: EMPTY_RUN,
319
330
  diagnostics: [],
320
331
  };
@@ -346,7 +357,7 @@ function runGateInner(gate, options, started, progress) {
346
357
  ...withRun,
347
358
  exitCode,
348
359
  couldNotRun: { reason: 'unparseable-output', detail },
349
- findings: [normalizeUnparseableGate(gate.role, gate.product, detail)],
360
+ findings: [normalizeUnparseableGate(gate.role, gate.product, detail, withRun.stderr)],
350
361
  run: EMPTY_RUN,
351
362
  diagnostics: [],
352
363
  };
package/dist/init.d.ts CHANGED
@@ -23,8 +23,24 @@ export declare const INTENT_GUARD_HOOK_MARKER = "conductor-managed-pre-commit";
23
23
  * a flag, and this one detects it: the umbrella's whole job is to be run
24
24
  * once in a repository somebody else already wired up.
25
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' | 'manifest-unreadable' | 'changed-since-init' | 'write-failed';
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';
36
+ export type ConflictReason = 'not-a-git-repository' | 'foreign-hook' | 'gate-hook' | 'generated-hook'
37
+ /**
38
+ * A manager whose hook text lives in package.json owns this file:
39
+ * simple-git-hooks or yorkie. Distinct from generated-hook because the
40
+ * remedy is different -- there is no config file of the manager's own to
41
+ * point at, only a key in package.json that conductor will not write.
42
+ */
43
+ | 'managed-hooks' | 'hooks-path-outside-repository' | 'no-manifest' | 'manifest-unreadable' | 'changed-since-init' | 'write-failed';
28
44
  export interface InitConflict {
29
45
  path: string;
30
46
  reason: ConflictReason;
package/dist/init.js CHANGED
@@ -50,9 +50,22 @@
50
50
  // points init at the repository root, and the second fails exactly
51
51
  // after a `git clean -xdf` has removed the gitignored generated
52
52
  // directory, which is the state this whole property exists to survive.
53
+ //
54
+ // 6. A MANAGER WHOSE HOOK TEXT LIVES IN package.json IS REFUSED, AND THE
55
+ // DECLARATION IS THE SIGNAL. simple-git-hooks and yorkie generate
56
+ // .git/hooks/pre-commit from a key in package.json and rewrite it on
57
+ // every install, and neither has a tracked file to write instead. What
58
+ // makes them different from lefthook is that the declaration is there
59
+ // BEFORE the manager has ever run: a fresh clone has no generated hook
60
+ // to read, and that is exactly the state somebody runs init in. So the
61
+ // package.json key is checked as well as the file, and either one alone
62
+ // is enough. Found by running this tool against two of the eight public
63
+ // repositories in a dogfood run: both would have taken the umbrella hook
64
+ // and lost it at the next install, with the manifest still recording it
65
+ // as installed. See detectManagedHook and declaredManagedHooks.
53
66
  import { createHash } from 'node:crypto';
54
67
  import { execFileSync } from 'node:child_process';
55
- import { chmodSync, existsSync, mkdirSync, readFileSync, rmSync, rmdirSync, statSync, writeFileSync, } from 'node:fs';
68
+ import { chmodSync, existsSync, mkdirSync, readFileSync, realpathSync, rmSync, rmdirSync, statSync, writeFileSync, } from 'node:fs';
56
69
  import path from 'node:path';
57
70
  import { DEFAULT_STAGE_FOR_ROLE, GATE_ROLES, POLICY_FILE_NAME, PRODUCT_FOR_ROLE } from './policy.js';
58
71
  import { CANDIDATES } from './resolve.js';
@@ -69,6 +82,21 @@ export const MANIFEST_RELATIVE_PATH = '.guardrails/manifest.json';
69
82
  */
70
83
  export const DEP_GUARD_HOOK_MARKER = 'dep-guard-managed-hook: v1';
71
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
+ ];
72
100
  /**
73
101
  * The `.husky` directory whose generated subdirectory git has been pointed
74
102
  * at, or null when this is not that arrangement.
@@ -168,6 +196,146 @@ function generatedHookGuidance(manager, relPath) {
168
196
  `${owner}, ${stanza} in ${config}. Note that ${owner} owns the commit's exit code, so the ` +
169
197
  "umbrella's 1 (a gate blocked) and 2 (a gate could not run) do not survive it.");
170
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
+ }
171
339
  function detectGateHook(content) {
172
340
  if (content.includes(DEP_GUARD_HOOK_MARKER)) {
173
341
  return 'dep-guard';
@@ -293,11 +461,12 @@ function repoRootOf(cwd) {
293
461
  function effectiveHooksDir(cwd, root) {
294
462
  const gitDir = gitOutput(cwd, ['rev-parse', '--git-dir']);
295
463
  const hooksPath = gitOutput(cwd, ['config', '--get', 'core.hooksPath']) ?? '';
464
+ // With no core.hooksPath, hooks live in the git DIRECTORY, which is not
465
+ // the working-tree root: for a linked worktree or a submodule it is
466
+ // somewhere else entirely, so this one resolves against gitDir.
467
+ const defaultDir = path.join(path.resolve(cwd, gitDir ?? '.git'), 'hooks');
296
468
  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 };
469
+ return { dir: defaultDir, outside: false, isDefault: true };
301
470
  }
302
471
  // A RELATIVE core.hooksPath resolves against the WORKING-TREE ROOT.
303
472
  // Verified by experiment rather than by reading the documentation that
@@ -305,7 +474,31 @@ function effectiveHooksDir(cwd, root) {
305
474
  const dir = path.isAbsolute(hooksPath) ? hooksPath : path.join(root, hooksPath);
306
475
  const relative = path.relative(root, dir);
307
476
  const outside = relative.startsWith('..') || path.isAbsolute(relative);
308
- return { dir, outside };
477
+ return { dir, outside, isDefault: samePath(dir, defaultDir) };
478
+ }
479
+ /**
480
+ * Whether two paths name the same directory.
481
+ *
482
+ * Through `realpath`, not string comparison, because the two sides arrive by
483
+ * different routes: the default is built from the working directory the
484
+ * caller passed in, and a configured `core.hooksPath` resolves against the
485
+ * root git reported, which git has already resolved. On macOS the system
486
+ * temporary directory is a symlink, so those two spell the same directory
487
+ * two ways and a string compare answers "different" for a repository git
488
+ * treats as one place. Falls back to the resolved strings when a path does
489
+ * not exist yet, which is the ordinary case for a hooks directory init is
490
+ * about to create.
491
+ */
492
+ function samePath(left, right) {
493
+ const real = (candidate) => {
494
+ try {
495
+ return realpathSync(candidate);
496
+ }
497
+ catch {
498
+ return path.resolve(candidate);
499
+ }
500
+ };
501
+ return real(left) === real(right);
309
502
  }
310
503
  function readIfExists(file) {
311
504
  try {
@@ -524,16 +717,51 @@ export function planInit(options) {
524
717
  // repository is still husky's).
525
718
  const huskyDir = huskyDirectoryFor(hooks.dir);
526
719
  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('/');
720
+ if (!husky) {
721
+ const rel = path.relative(root, executedHookPath).split(path.sep).join('/');
722
+ if (executedHook !== undefined) {
723
+ const generatedBy = detectGeneratedHook(executedHook);
724
+ if (generatedBy !== null) {
725
+ conflicts.push({
726
+ path: rel,
727
+ reason: 'generated-hook',
728
+ guidance: generatedHookGuidance(generatedBy, rel),
729
+ });
730
+ return { ...base, repoRoot: root, hookPath: executedHookPath, hookManager: generatedBy };
731
+ }
732
+ }
733
+ // The installed file first, then the declaration. The file says what is
734
+ // there now; the declaration says what the next install will put there,
735
+ // and on a fresh clone it is the only one of the two that exists. Either
736
+ // alone is enough, and the refusal is the same either way: only the
737
+ // opening sentence of the guidance changes, so a reader is told which of
738
+ // the two was actually seen.
739
+ //
740
+ // This is checked only on the native path, and only where git actually
741
+ // runs .git/hooks. BOTH conditions are about the same fact: these two
742
+ // managers write .git/hooks/pre-commit directly and neither one reads
743
+ // core.hooksPath. Under husky, and under any other configured hooks
744
+ // directory, the file they rewrite is not the file git runs, so the
745
+ // umbrella's hook is in no danger from them and a refusal would name a
746
+ // file the manager never touches while blocking an install that is
747
+ // perfectly safe.
748
+ const fromHook = executedHook === undefined ? null : detectManagedHook(executedHook);
749
+ const declared = fromHook === null
750
+ ? declaredManagedHooks(root)
751
+ : { manager: fromHook, detectedIn: { kind: 'hook' } };
752
+ const managedBy = hooks.isDefault ? declared : null;
753
+ if (managedBy !== null) {
531
754
  conflicts.push({
532
755
  path: rel,
533
- reason: 'generated-hook',
534
- guidance: generatedHookGuidance(generatedBy, rel),
756
+ reason: 'managed-hooks',
757
+ guidance: managedHooksGuidance(managedBy.manager, rel, managedBy.detectedIn),
535
758
  });
536
- return { ...base, repoRoot: root, hookPath: executedHookPath, hookManager: generatedBy };
759
+ return {
760
+ ...base,
761
+ repoRoot: root,
762
+ hookPath: executedHookPath,
763
+ hookManager: managedBy.manager,
764
+ };
537
765
  }
538
766
  }
539
767
  const hookManager = husky ? 'husky' : 'native';