@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.
@@ -0,0 +1,315 @@
1
+ import { statSync } from 'node:fs';
2
+ import path from 'node:path';
3
+ import { MANIFEST_RELATIVE_PATH, readIfExists } from './init-manifest.js';
4
+ /** The one string that says "conductor init wrote this". */
5
+ export const MANAGED_HOOK_MARKER = 'guardrails-managed-hook: v1';
6
+ /**
7
+ * Markers each gate's own installer writes, so a collision is recognised
8
+ * rather than clobbered. Two of these are literal marker comments the other
9
+ * tools write on purpose; the third has no marker at all and is matched on
10
+ * the two strings its hook always contains, which is exactly how that
11
+ * tool's own installer recognises its own hook.
12
+ */
13
+ export const DEP_GUARD_HOOK_MARKER = 'dep-guard-managed-hook: v1';
14
+ export const INTENT_GUARD_HOOK_MARKER = 'conductor-managed-pre-commit';
15
+ /**
16
+ * The standalone config files simple-git-hooks reads, exactly as its own
17
+ * README lists them. yorkie has no equivalent: its config is the
18
+ * `gitHooks` key and nothing else.
19
+ */
20
+ const SIMPLE_GIT_HOOKS_CONFIG_FILES = [
21
+ '.simple-git-hooks.cjs',
22
+ '.simple-git-hooks.js',
23
+ '.simple-git-hooks.mjs',
24
+ '.simple-git-hooks.json',
25
+ 'simple-git-hooks.cjs',
26
+ 'simple-git-hooks.js',
27
+ 'simple-git-hooks.mjs',
28
+ 'simple-git-hooks.json',
29
+ ];
30
+ /**
31
+ * The `.husky` directory whose generated subdirectory git has been pointed
32
+ * at, or null when this is not that arrangement.
33
+ *
34
+ * The rule is STRUCTURAL and nothing else: the hooks directory is named
35
+ * `_`, and its parent is named `.husky`. Only husky creates that path, so
36
+ * the shape alone identifies it, and both halves are required.
37
+ *
38
+ * Two things are deliberately NOT part of the rule, each for a reason that
39
+ * cost a bug:
40
+ *
41
+ * - THE CONTENT of the pre-commit file git executes. The line that sources
42
+ * husky's shim appears in two completely different places:
43
+ *
44
+ * husky 9 core.hooksPath = .husky/_ .husky/_/pre-commit sources
45
+ * _/h and IS a dispatcher; the tracked hook is one up.
46
+ * husky 8 core.hooksPath = .husky .husky/pre-commit sources
47
+ * _/husky.sh as a PREAMBLE and IS the tracked hook already.
48
+ *
49
+ * Reading content therefore fired against husky 8's tracked hook, and
50
+ * "one directory up" then pointed at the parent of `.husky`, which is
51
+ * the repository root. Init wrote a hook there, never read the real one
52
+ * so never saw the gate hook in it, reported success, and left every
53
+ * commit ungated. The structural rule excludes husky 8 on its own,
54
+ * because there the hooks directory is `.husky` and not `_`.
55
+ *
56
+ * - THE PRESENCE OF THE SHIM (`h`, or husky 8's `husky.sh`). Requiring it
57
+ * looks like useful confirmation and quietly reintroduces the original
58
+ * trap. husky gitignores `.husky/_`, so `git clean -xdf` deletes the
59
+ * whole directory while `core.hooksPath=.husky/_` sits in `.git/config`
60
+ * and survives. In that state there is no shim, no dispatcher, and
61
+ * nothing whatever to confirm, so a shim requirement sends init down the
62
+ * ordinary path to write `.husky/_/pre-commit` -- which is exactly the
63
+ * file husky's next prepare step wipes. The shim is evidence that husky
64
+ * ran recently, not evidence about whose directory this is, so it is
65
+ * reported and never tested against.
66
+ *
67
+ * The tracked target is this `.husky` directory's own hook, never a
68
+ * computed parent of whatever directory git happens to point at.
69
+ */
70
+ export function huskyDirectoryFor(hooksDir) {
71
+ if (path.basename(hooksDir) !== '_') {
72
+ return null;
73
+ }
74
+ const huskyDir = path.dirname(hooksDir);
75
+ if (path.basename(huskyDir) !== '.husky') {
76
+ return null;
77
+ }
78
+ return huskyDir;
79
+ }
80
+ /** Whether husky's shim is in place, which is worth SAYING but never testing. */
81
+ export function huskyShimPresent(hooksDir) {
82
+ return isFile(path.join(hooksDir, 'h')) || isFile(path.join(hooksDir, 'husky.sh'));
83
+ }
84
+ /**
85
+ * What each of these two managers actually writes into the hook it
86
+ * generates, checked against a real install rather than against anybody's
87
+ * memory of one. The captured files are in tests/fixtures/hooks.
88
+ *
89
+ * lefthook is recognised by `call_lefthook`, the shell function its
90
+ * generated hook defines and then calls on the last line. Verified against
91
+ * lefthook 2.1.12 and 1.7.18, which both write it twice.
92
+ *
93
+ * `lefthook_version:` is a second alternative and IS NOT VERIFIED. Neither
94
+ * of those versions writes it, and the string does not appear anywhere in
95
+ * the 2.1.12 binary either, so it recognises nothing lefthook produces
96
+ * today. It stays because a spare alternative in an OR cannot cause a false
97
+ * negative and may still catch a much older install. What could not stay is
98
+ * the comment that used to be here, which called both halves the
99
+ * installer's own mark: a hand-written fixture in the suite carried the
100
+ * invented line, so the fixture and the code agreed with each other and
101
+ * neither had ever been held up against lefthook. Recognising lefthook on
102
+ * that string alone misclassifies both real hooks as native, which is how
103
+ * init ends up writing into a file lefthook regenerates.
104
+ *
105
+ * The pre-commit framework stamps its own URL, and that one is exact:
106
+ * verified against pre-commit 4.6.2, whose marker line is character for
107
+ * character the string below.
108
+ */
109
+ export function detectGeneratedHook(content) {
110
+ if (content.includes('call_lefthook') || content.includes('lefthook_version:')) {
111
+ return 'lefthook';
112
+ }
113
+ if (content.includes('File generated by pre-commit: https://pre-commit.com')) {
114
+ return 'precommit';
115
+ }
116
+ return null;
117
+ }
118
+ export function generatedHookGuidance(manager, relPath) {
119
+ const owner = manager === 'lefthook' ? 'lefthook' : 'the pre-commit framework';
120
+ const config = manager === 'lefthook' ? 'lefthook-local.yml' : '.pre-commit-config.yaml';
121
+ const stanza = manager === 'lefthook'
122
+ ? 'add "conductor:" under pre-commit.commands with "run: conductor run --staged"'
123
+ : 'add a local hook entry running "conductor run --staged" to its repos: list';
124
+ return (`${relPath} is generated by ${owner}, which rewrites it on every install, so anything ` +
125
+ `written there is lost without a word. Nothing was changed. To run the umbrella under ` +
126
+ `${owner}, ${stanza} in ${config}. Note that ${owner} owns the commit's exit code, so the ` +
127
+ "umbrella's 1 (a gate blocked) and 2 (a gate could not run) do not survive it.");
128
+ }
129
+ /**
130
+ * The manager that generated this hook, for the two whose hook text comes
131
+ * out of package.json. Checked against real installs, captured in
132
+ * tests/fixtures/hooks.
133
+ *
134
+ * simple-git-hooks is recognised by `SKIP_SIMPLE_GIT_HOOKS`, the opt-out
135
+ * variable its generated hook tests on its first line. Verified against
136
+ * 2.14.0 and 2.11.1.
137
+ *
138
+ * IT IS NOT IN EVERY VERSION, and that is the whole reason the package.json
139
+ * key below exists rather than being belt and braces. simple-git-hooks 2.8.0
140
+ * writes the shebang and the user's own command and nothing else: there is
141
+ * no string in that file belonging to simple-git-hooks, so no content rule
142
+ * can recognise it, at any price. A repository on that version is
143
+ * unrecognisable from its hook alone and would have had the umbrella hook
144
+ * written into a file the next install rewrites.
145
+ *
146
+ * yorkie is recognised by `yorkie/src/runner.js`, the script its generated
147
+ * hook invokes. Verified against 2.0.0, which writes it relative, and 1.0.2,
148
+ * which writes the same suffix under an absolute path, so the suffix is what
149
+ * both have in common. The `#yorkie ` version stamp on the second line is a
150
+ * second alternative and is present in both captures too; it is second
151
+ * because it is a comment, and a comment is the part of a generated file
152
+ * most likely to be reworded.
153
+ */
154
+ export function detectManagedHook(content) {
155
+ if (content.includes('SKIP_SIMPLE_GIT_HOOKS')) {
156
+ return 'simple-git-hooks';
157
+ }
158
+ if (content.includes('yorkie/src/runner.js') || content.includes('#yorkie ')) {
159
+ return 'yorkie';
160
+ }
161
+ return null;
162
+ }
163
+ export function declaredManagedHooks(root) {
164
+ // A standalone config file counts as a declaration on its own. Taken
165
+ // verbatim from simple-git-hooks' own README, which says the config may
166
+ // live in ".simple-git-hooks.cjs, .simple-git-hooks.js,
167
+ // .simple-git-hooks.mjs, .simple-git-hooks.json, or
168
+ // simple-git-hooks.{cjs,js,mjs,json}". It is an EXACT list rather than a
169
+ // prefix or extension test, so a simple-git-hooks.yaml or a
170
+ // simple-git-hooks.md is what it looks like -- somebody's notes -- and not
171
+ // a reason to refuse an install.
172
+ //
173
+ // This is the third signal and the only one that fires for the repository
174
+ // that has all the others against it: a standalone config plus an older
175
+ // simple-git-hooks, whose generated hook carries no marker at all.
176
+ // Checked BEFORE package.json, and the order is the same one
177
+ // simple-git-hooks resolves in: it reads package.json last, so whichever
178
+ // of these exists is the file that actually decides the hook.
179
+ const configFile = SIMPLE_GIT_HOOKS_CONFIG_FILES.find((file) => isFile(path.join(root, file)));
180
+ if (configFile !== undefined) {
181
+ return { manager: 'simple-git-hooks', detectedIn: { kind: 'config-file', file: configFile } };
182
+ }
183
+ const raw = readIfExists(path.join(root, 'package.json'));
184
+ if (raw === undefined) {
185
+ return null;
186
+ }
187
+ let parsed;
188
+ try {
189
+ parsed = JSON.parse(raw);
190
+ }
191
+ catch {
192
+ return null;
193
+ }
194
+ if (typeof parsed !== 'object' || parsed === null) {
195
+ return null;
196
+ }
197
+ const manifest = parsed;
198
+ if (isPlainObject(manifest['simple-git-hooks'])) {
199
+ return { manager: 'simple-git-hooks', detectedIn: { kind: 'package.json' } };
200
+ }
201
+ if (isPlainObject(manifest.gitHooks)) {
202
+ return { manager: 'yorkie', detectedIn: { kind: 'package.json' } };
203
+ }
204
+ return null;
205
+ }
206
+ function isPlainObject(value) {
207
+ return typeof value === 'object' && value !== null && !Array.isArray(value);
208
+ }
209
+ /**
210
+ * What init says when it finds one of those two, and why it says nothing
211
+ * else.
212
+ *
213
+ * The honest answer here is a refusal, not an offer. These managers have no
214
+ * tracked hook file to redirect into and no config file of their own to name:
215
+ * the only place the umbrella's command could go is a key in package.json,
216
+ * and init does not write package.json. That is not squeamishness. Init
217
+ * writes a hook, a policy file and a manifest, and the manifest is what
218
+ * makes --revert honest; an edit merged into somebody's package.json has no
219
+ * revert story that is not a guess about which of their later edits were
220
+ * theirs. So the guidance says exactly what to add and leaves the adding to
221
+ * the person whose file it is.
222
+ *
223
+ * The exit-code sentence differs between the two, and both halves are held
224
+ * against the captured fixtures rather than against anybody's memory:
225
+ * simple-git-hooks runs the entry as the last command of a plain `sh`
226
+ * script, so the umbrella's status is the hook's status, while yorkie wraps
227
+ * its runner in `|| { ...; exit 1; }` and turns every non-zero exit into 1.
228
+ */
229
+ export function managedHooksGuidance(manager, relPath, detectedIn) {
230
+ // WHERE THE ENTRY GOES IS WHERE THE DECLARATION ALREADY IS.
231
+ // simple-git-hooks reads package.json LAST, so while a standalone config
232
+ // file exists an entry added to package.json is precisely the one it
233
+ // ignores. Naming package.json there would send somebody to edit a file
234
+ // that will not be read, and leave them with the umbrella uninstalled and
235
+ // no error to explain it.
236
+ const home = detectedIn.kind === 'config-file' ? detectedIn.file : 'package.json';
237
+ const entry = detectedIn.kind === 'config-file'
238
+ ? `the "pre-commit" entry in ${detectedIn.file}`
239
+ : manager === 'simple-git-hooks'
240
+ ? 'the "pre-commit" entry under "simple-git-hooks" in package.json'
241
+ : 'the "pre-commit" entry under "gitHooks" in package.json';
242
+ const reinstall = manager === 'simple-git-hooks'
243
+ ? 're-run "npx simple-git-hooks"'
244
+ : 're-run the install (yorkie rewrites its hooks on postinstall)';
245
+ const exitCodes = manager === 'simple-git-hooks'
246
+ ? `${manager} runs that entry as the last command of the hook it generates, so the ` +
247
+ "umbrella's exit codes reach git unchanged: 1 means a gate blocked, 2 means a gate " +
248
+ 'could not run.'
249
+ : `${manager}'s generated hook turns every non-zero exit into 1, so the umbrella's 2 ` +
250
+ '(a gate could not run, and nothing was checked) reaches git as 1 (a gate blocked). ' +
251
+ 'Both still stop the commit.';
252
+ const lead = detectedIn.kind === 'hook'
253
+ ? `${relPath} was generated by ${manager} from its own declaration, and is rewritten on ` +
254
+ 'every install.'
255
+ : `${home} declares ${manager}, which generates ${relPath} from that declaration and ` +
256
+ 'rewrites it on every install.';
257
+ return (`${lead} A hook written there is gone after the next install while ` +
258
+ `${MANIFEST_RELATIVE_PATH} still records it as installed, so the repository would report a ` +
259
+ 'guardrail it no longer has. Nothing was changed, and --force does not override this: that ' +
260
+ `file was never conductor's to hold. To run the umbrella under ${manager}, set ${entry} ` +
261
+ 'to "conductor run --staged --stage commit" yourself, and ' +
262
+ `${reinstall}. If something is already in that entry, put the umbrella LAST, as its own ` +
263
+ 'command rather than chained behind && : a chain stops at the first failure, so an ' +
264
+ "umbrella in front of it hides the other command's verdict and one behind an && never " +
265
+ `runs at all once anything ahead of it fails. conductor does not edit ${home}, so it ` +
266
+ 'cannot do that for you; a later release may offer to. ' +
267
+ exitCodes);
268
+ }
269
+ export function detectGateHook(content) {
270
+ if (content.includes(DEP_GUARD_HOOK_MARKER)) {
271
+ return 'dep-guard';
272
+ }
273
+ // Deliberately still the pre-rename string: it is state already sitting
274
+ // in users' repositories, and the tool that writes it did not rename it
275
+ // either, precisely so an older hook stays recognisable.
276
+ if (content.includes(INTENT_GUARD_HOOK_MARKER)) {
277
+ return 'intent-guard';
278
+ }
279
+ if (content.includes('vault-guard') && content.includes('scan --staged')) {
280
+ return 'vault-guard';
281
+ }
282
+ return null;
283
+ }
284
+ /**
285
+ * Existence as a plain file, with no opinion about the executable bit.
286
+ * husky's shim is copied out of the package with whatever mode the tarball
287
+ * carried, and it is sourced rather than executed, so requiring +x here
288
+ * would make detection depend on something husky does not guarantee.
289
+ */
290
+ function isFile(file) {
291
+ try {
292
+ return statSync(file).isFile();
293
+ }
294
+ catch {
295
+ return false;
296
+ }
297
+ }
298
+ export function foreignGuidance(relPath) {
299
+ return (`${relPath} already exists and was not written by conductor init. Merge "conductor run --staged" ` +
300
+ 'into it yourself, or move it aside and re-run init. Init never replaces a hook it does not ' +
301
+ "recognise, because that hook is somebody's working setup.");
302
+ }
303
+ export function editedManagedGuidance(relPath) {
304
+ return (`${relPath} carries conductor's own marker but does not match the hook this version writes, ` +
305
+ 'and either does not match the one recorded in the manifest or there is no manifest to ' +
306
+ 'check against. Either way nothing on disk says these are the contents conductor left, so ' +
307
+ "nothing was changed: an edited hook is somebody's working setup, marker or not. Re-run " +
308
+ 'with --force to replace it anyway, or delete it by hand and re-run.');
309
+ }
310
+ export function gateHookGuidance(product, relPath) {
311
+ return (`${relPath} is ${product}'s own pre-commit hook. Adding the umbrella hook alongside it would ` +
312
+ `run ${product} twice and report its findings twice. Re-run with --adopt to replace it with ` +
313
+ 'the umbrella hook, which runs every enabled commit-stage gate including that one, or leave ' +
314
+ 'things as they are and do not run init here.');
315
+ }
@@ -0,0 +1,64 @@
1
+ import type { Product } from './policy.js';
2
+ export declare const MANIFEST_RELATIVE_PATH = ".guardrails/manifest.json";
3
+ export interface ManifestFile {
4
+ path: string;
5
+ sha256: string;
6
+ /**
7
+ * What this file is to the umbrella. Recorded rather than inferred from
8
+ * the path, because revert's whole decision turns on whether the HOOK
9
+ * survived, and sniffing that from a filename is a guess.
10
+ */
11
+ kind: 'hook' | 'policy';
12
+ }
13
+ export interface Manifest {
14
+ version: 1;
15
+ files: ManifestFile[];
16
+ adopted: {
17
+ path: string;
18
+ content: string;
19
+ product: Product;
20
+ } | null;
21
+ }
22
+ export declare function sha256(content: string): string;
23
+ /**
24
+ * Whether a path the manifest names is contained to the repository.
25
+ *
26
+ * The manifest is committed input, so a path in it is whatever a commit put
27
+ * there. Revert and apply run this over every path they would write to or
28
+ * delete before touching anything, and refuse the whole operation if any one
29
+ * of them is not contained.
30
+ *
31
+ * Two conditions, because a path can escape two ways. The resolved path,
32
+ * treated as plain strings, must be inside the root: this refuses an absolute
33
+ * path and one that climbs out with ../. And no component of the path may be a
34
+ * SYMLINK. A committed dangling symlink (its target does not exist) is the case
35
+ * that broke an earlier version of this: existsSync FOLLOWS the link, finds the
36
+ * missing target, and reports the link absent, so a walk that resolved only the
37
+ * deepest existing ancestor judged the link a plain not-yet-existing leaf and
38
+ * let writeFileSync and chmodSync, which DO follow the final link, land the
39
+ * write on the outside target. lstatSync does not follow, so it catches a
40
+ * symlink component even when its target is gone. init never writes through a
41
+ * symlink, so a symlink anywhere along the path means this is not a path init
42
+ * wrote, and it is refused whatever it points at.
43
+ *
44
+ * Paths here need not exist yet: an adopted hook is restored to a path revert
45
+ * has just removed, and a recorded file may be legitimately gone. The scan
46
+ * stops at the first component that does not exist, because nothing below a
47
+ * missing component exists either, so there is no symlink left to find. A
48
+ * relative candidate is taken against the repository root, which is how the
49
+ * real attack lands: a person running revert has cd'd into the checkout.
50
+ */
51
+ export declare function manifestPathInsideRepo(repoRoot: string, candidate: string): boolean;
52
+ export declare function readIfExists(file: string): string | undefined;
53
+ /**
54
+ * The manifest a previous init left, or null when there is none or it will
55
+ * not parse.
56
+ *
57
+ * An unreadable manifest is deliberately the same answer as a missing one:
58
+ * everything that consults it here is deciding whether a file on disk is
59
+ * one the umbrella wrote, and "the record is unreadable" is not evidence
60
+ * that it was.
61
+ */
62
+ export declare function readManifest(root: string): Manifest | null;
63
+ /** The hook digest a previous init recorded, or null when there is none. */
64
+ export declare function recordedHookSha(root: string): string | null;
@@ -0,0 +1,127 @@
1
+ import { createHash } from 'node:crypto';
2
+ import { existsSync, lstatSync, readFileSync, realpathSync } from 'node:fs';
3
+ import path from 'node:path';
4
+ export const MANIFEST_RELATIVE_PATH = '.guardrails/manifest.json';
5
+ export function sha256(content) {
6
+ return createHash('sha256').update(content).digest('hex');
7
+ }
8
+ /**
9
+ * Whether a path the manifest names is contained to the repository.
10
+ *
11
+ * The manifest is committed input, so a path in it is whatever a commit put
12
+ * there. Revert and apply run this over every path they would write to or
13
+ * delete before touching anything, and refuse the whole operation if any one
14
+ * of them is not contained.
15
+ *
16
+ * Two conditions, because a path can escape two ways. The resolved path,
17
+ * treated as plain strings, must be inside the root: this refuses an absolute
18
+ * path and one that climbs out with ../. And no component of the path may be a
19
+ * SYMLINK. A committed dangling symlink (its target does not exist) is the case
20
+ * that broke an earlier version of this: existsSync FOLLOWS the link, finds the
21
+ * missing target, and reports the link absent, so a walk that resolved only the
22
+ * deepest existing ancestor judged the link a plain not-yet-existing leaf and
23
+ * let writeFileSync and chmodSync, which DO follow the final link, land the
24
+ * write on the outside target. lstatSync does not follow, so it catches a
25
+ * symlink component even when its target is gone. init never writes through a
26
+ * symlink, so a symlink anywhere along the path means this is not a path init
27
+ * wrote, and it is refused whatever it points at.
28
+ *
29
+ * Paths here need not exist yet: an adopted hook is restored to a path revert
30
+ * has just removed, and a recorded file may be legitimately gone. The scan
31
+ * stops at the first component that does not exist, because nothing below a
32
+ * missing component exists either, so there is no symlink left to find. A
33
+ * relative candidate is taken against the repository root, which is how the
34
+ * real attack lands: a person running revert has cd'd into the checkout.
35
+ */
36
+ export function manifestPathInsideRepo(repoRoot, candidate) {
37
+ try {
38
+ const root = realpathSync(repoRoot);
39
+ const abs = path.resolve(root, candidate);
40
+ // Deepest ancestor of abs that exists on disk. realpathSync on the whole
41
+ // path throws when the leaf is not there, so resolve the part that exists
42
+ // and keep the rest as a tail. existsSync FOLLOWS symlinks, which is why a
43
+ // dangling symlink is not trusted here; the tail is scanned with lstatSync
44
+ // below.
45
+ let ancestor = abs;
46
+ while (!existsSync(ancestor)) {
47
+ const parent = path.dirname(ancestor);
48
+ if (parent === ancestor) {
49
+ break;
50
+ }
51
+ ancestor = parent;
52
+ }
53
+ const realAncestor = realpathSync(ancestor);
54
+ const tail = path.relative(ancestor, abs);
55
+ // Containment, on resolved paths so a macOS temp dir reached through
56
+ // /var -> /private/var does not read as an escape, and so an existing
57
+ // symlink directory that points outside is caught by its resolved target.
58
+ const resolved = tail === '' ? realAncestor : path.join(realAncestor, tail);
59
+ const inside = path.relative(root, resolved);
60
+ if (inside === '' ||
61
+ inside === '..' ||
62
+ inside.startsWith(`..${path.sep}`) ||
63
+ path.isAbsolute(inside)) {
64
+ return false;
65
+ }
66
+ // No component of the tail may be a symlink. lstatSync does not follow, so
67
+ // a committed DANGLING symlink is caught even though existsSync reported it
68
+ // absent: existsSync followed the link to its missing target, which let an
69
+ // earlier version treat the link as a plain not-yet-existing leaf and then
70
+ // let writeFileSync and chmodSync, which DO follow the final link, land the
71
+ // write on the outside target. init never writes through a symlink, so any
72
+ // symlink component means this is not a path init wrote. The scan starts at
73
+ // the resolved ancestor, whose own components are already real, and walks
74
+ // to the leaf, stopping at the first component that does not exist.
75
+ let current = realAncestor;
76
+ for (const segment of tail === '' ? [] : tail.split(path.sep)) {
77
+ current = path.join(current, segment);
78
+ let entry;
79
+ try {
80
+ entry = lstatSync(current);
81
+ }
82
+ catch {
83
+ break;
84
+ }
85
+ if (entry.isSymbolicLink()) {
86
+ return false;
87
+ }
88
+ }
89
+ return true;
90
+ }
91
+ catch {
92
+ return false;
93
+ }
94
+ }
95
+ export function readIfExists(file) {
96
+ try {
97
+ return readFileSync(file, 'utf8');
98
+ }
99
+ catch {
100
+ return undefined;
101
+ }
102
+ }
103
+ /**
104
+ * The manifest a previous init left, or null when there is none or it will
105
+ * not parse.
106
+ *
107
+ * An unreadable manifest is deliberately the same answer as a missing one:
108
+ * everything that consults it here is deciding whether a file on disk is
109
+ * one the umbrella wrote, and "the record is unreadable" is not evidence
110
+ * that it was.
111
+ */
112
+ export function readManifest(root) {
113
+ const raw = readIfExists(path.join(root, MANIFEST_RELATIVE_PATH));
114
+ if (raw === undefined) {
115
+ return null;
116
+ }
117
+ try {
118
+ return JSON.parse(raw);
119
+ }
120
+ catch {
121
+ return null;
122
+ }
123
+ }
124
+ /** The hook digest a previous init recorded, or null when there is none. */
125
+ export function recordedHookSha(root) {
126
+ return readManifest(root)?.files.find((file) => file.kind === 'hook')?.sha256 ?? null;
127
+ }
@@ -0,0 +1,12 @@
1
+ import { POLICY_FILE_NAME } from './policy.js';
2
+ import type { GateRole } from './policy.js';
3
+ export { POLICY_FILE_NAME };
4
+ /** Names of the gates whose binary resolves right now. */
5
+ export declare function detectGates(root: string, pathValue: string): Set<GateRole>;
6
+ /**
7
+ * The policy file, written by hand rather than serialised, because the
8
+ * comments are half the point: a first-run policy file that explains what
9
+ * each key is for is most of a first-run experience, and a YAML emitter
10
+ * cannot carry them.
11
+ */
12
+ export declare function renderPolicy(detected: Set<GateRole>): string;
@@ -0,0 +1,103 @@
1
+ import { statSync } from 'node:fs';
2
+ import path from 'node:path';
3
+ import { DEFAULT_STAGE_FOR_ROLE, GATE_ROLES, POLICY_FILE_NAME, PRODUCT_FOR_ROLE } from './policy.js';
4
+ import { CANDIDATES } from './resolve.js';
5
+ export { POLICY_FILE_NAME };
6
+ /** Names of the gates whose binary resolves right now. */
7
+ export function detectGates(root, pathValue) {
8
+ const found = new Set();
9
+ for (const role of GATE_ROLES) {
10
+ const product = PRODUCT_FOR_ROLE[role];
11
+ for (const candidate of CANDIDATES[product]) {
12
+ // Same order as resolve.ts, though only the answer matters here:
13
+ // detection asks whether a gate is installed at all, not which copy
14
+ // of it would run.
15
+ const local = isExecutable(path.join(root, 'node_modules', '.bin', candidate.name));
16
+ const onPath = pathValue
17
+ .split(path.delimiter)
18
+ .filter((dir) => dir.length > 0)
19
+ .some((dir) => isExecutable(path.join(dir, candidate.name)));
20
+ if (local || onPath) {
21
+ found.add(role);
22
+ break;
23
+ }
24
+ }
25
+ }
26
+ return found;
27
+ }
28
+ function isExecutable(file) {
29
+ try {
30
+ const stats = statSync(file);
31
+ return stats.isFile() && (stats.mode & 0o111) !== 0;
32
+ }
33
+ catch {
34
+ return false;
35
+ }
36
+ }
37
+ const ROLE_DESCRIPTION = {
38
+ dependencies: 'what comes in: hallucinated names, typosquats, tampered lockfile entries',
39
+ secrets: 'what goes out: credentials about to be committed',
40
+ intent: 'what was approved: drift from a frozen intent contract, and change budgets',
41
+ };
42
+ /**
43
+ * The policy file, written by hand rather than serialised, because the
44
+ * comments are half the point: a first-run policy file that explains what
45
+ * each key is for is most of a first-run experience, and a YAML emitter
46
+ * cannot carry them.
47
+ */
48
+ export function renderPolicy(detected) {
49
+ const lines = [
50
+ '# Guardrail policy. One file for every gate this repository runs.',
51
+ '#',
52
+ '# Gates are keyed by the ROLE they fill, and the product filling that role',
53
+ '# is one line inside it. Swapping or renaming a product is a one-line edit',
54
+ '# rather than a rename of the key your CI reads.',
55
+ '#',
56
+ '# There is deliberately no shared severity threshold. Each gate keeps its',
57
+ '# own, spelled the way that gate spells it, inside its own options block.',
58
+ '#',
59
+ '# stage says when a gate runs: commit, push, or ci. Stages are cumulative,',
60
+ '# so a gate runs at its own stage and at every later one, and a run at ci',
61
+ '# runs everything enabled. The values below are the defaults.',
62
+ '#',
63
+ '# enforce says whether a gate can change the exit code. A gate with',
64
+ '# enforce: false runs and reports exactly as an enforced one does and',
65
+ '# never fails the run, which is how a gate is adopted before anybody is',
66
+ '# ready to have it refuse a commit. It is written out below for every',
67
+ '# gate, for the same reason stage is: a default that lives only in the',
68
+ '# parser is a default nobody can find.',
69
+ 'version: 1',
70
+ '',
71
+ 'gates:',
72
+ ];
73
+ for (const role of GATE_ROLES) {
74
+ const product = PRODUCT_FOR_ROLE[role];
75
+ const enabled = detected.has(role);
76
+ lines.push(` # ${ROLE_DESCRIPTION[role]}`);
77
+ if (!enabled) {
78
+ lines.push(` # not found in node_modules/.bin or on PATH. Install ${product}, then set enabled: true.`);
79
+ }
80
+ lines.push(` ${role}:`);
81
+ lines.push(` product: ${product}`);
82
+ lines.push(` enabled: ${enabled ? 'true' : 'false'}`);
83
+ lines.push(` stage: ${DEFAULT_STAGE_FOR_ROLE[role]}`);
84
+ // The intent gate is the one with ceremony, and the ramp is what makes
85
+ // that ceremony adoptable: it reports for a few pull requests before it
86
+ // is allowed to refuse anybody's merge. Writing that here rather than
87
+ // describing it in a comment is the difference between a fresh init
88
+ // producing the ramp and three repositories being hand-edited into it.
89
+ if (role === 'intent') {
90
+ lines.push(' # It runs and reports in CI without failing the run. Flip it to');
91
+ lines.push(' # true once a few pull requests show the signal is worth blocking on.');
92
+ lines.push(' enforce: false');
93
+ }
94
+ else {
95
+ lines.push(' enforce: true');
96
+ }
97
+ lines.push(' # Handed to this gate unchanged. Keys are its own long flags,');
98
+ lines.push(' # without the leading dashes. Example: fail-on: high');
99
+ lines.push(' options: {}');
100
+ }
101
+ lines.push('', 'report:', ' format: text', '');
102
+ return lines.join('\n');
103
+ }