@vaultcompass/conductor 0.8.1 → 0.10.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/git.d.ts CHANGED
@@ -15,7 +15,22 @@ export declare function useGitProgram(program: string): void;
15
15
  /** Runs one git command in `cwd`, reading stdout as UTF-8. Never throws. */
16
16
  export declare function runGit(cwd: string, args: readonly string[], options?: {
17
17
  maxBuffer?: number;
18
+ input?: string;
18
19
  }): GitResult;
20
+ /**
21
+ * Runs one git command in `cwd` and keeps stdout as BYTES. For a blob that is
22
+ * copied out byte for byte (the osv gate's base copies): decoding it as UTF-8
23
+ * would rewrite a file with invalid bytes before anything read it. Same
24
+ * program, same environment and same never-throws contract as runGit.
25
+ */
26
+ export declare function runGitBytes(cwd: string, args: readonly string[], options?: {
27
+ maxBuffer?: number;
28
+ }): {
29
+ status: number | null;
30
+ stdout: Buffer;
31
+ stderr: string;
32
+ error: Error | undefined;
33
+ };
19
34
  /**
20
35
  * A PATH with every entry that would resolve against the working directory
21
36
  * removed: an empty entry (which means the current directory) and a relative
package/dist/git.js CHANGED
@@ -38,6 +38,7 @@ export function runGit(cwd, args, options = {}) {
38
38
  encoding: 'utf8',
39
39
  maxBuffer: options.maxBuffer ?? 32 * 1024 * 1024,
40
40
  env: { ...process.env, GIT_NO_REPLACE_OBJECTS: '1' },
41
+ ...(options.input === undefined ? {} : { input: options.input }),
41
42
  });
42
43
  return {
43
44
  status: child.status,
@@ -46,6 +47,25 @@ export function runGit(cwd, args, options = {}) {
46
47
  error: child.error,
47
48
  };
48
49
  }
50
+ /**
51
+ * Runs one git command in `cwd` and keeps stdout as BYTES. For a blob that is
52
+ * copied out byte for byte (the osv gate's base copies): decoding it as UTF-8
53
+ * would rewrite a file with invalid bytes before anything read it. Same
54
+ * program, same environment and same never-throws contract as runGit.
55
+ */
56
+ export function runGitBytes(cwd, args, options = {}) {
57
+ const child = spawnSync(gitProgram, [...args], {
58
+ cwd,
59
+ maxBuffer: options.maxBuffer ?? 64 * 1024 * 1024,
60
+ env: { ...process.env, GIT_NO_REPLACE_OBJECTS: '1' },
61
+ });
62
+ return {
63
+ status: child.status,
64
+ stdout: Buffer.isBuffer(child.stdout) ? child.stdout : Buffer.alloc(0),
65
+ stderr: Buffer.isBuffer(child.stderr) ? child.stderr.toString('utf8') : '',
66
+ error: child.error,
67
+ };
68
+ }
49
69
  /**
50
70
  * A PATH with every entry that would resolve against the working directory
51
71
  * removed: an empty entry (which means the current directory) and a relative
@@ -168,6 +168,7 @@ export interface ManagedDeclaration {
168
168
  detectedIn: ManagedDetection;
169
169
  }
170
170
  export declare function declaredManagedHooks(root: string): ManagedDeclaration | null;
171
+ export declare function declaredHusky(root: string): string | null;
171
172
  /**
172
173
  * What init says when it finds one of those two, and why it says nothing
173
174
  * else.
@@ -203,6 +203,51 @@ export function declaredManagedHooks(root) {
203
203
  }
204
204
  return null;
205
205
  }
206
+ /**
207
+ * Where this repository's package.json declares husky, or null: a husky
208
+ * dependency or devDependency, or a prepare script that runs husky. The
209
+ * signal that exists on a fresh clone, before husky's own install has set
210
+ * core.hooksPath. Unreadable or unparseable is the same as undeclared, as for
211
+ * declaredManagedHooks above.
212
+ */
213
+ /**
214
+ * husky as a COMMAND in a script: at the start or after a shell separator
215
+ * (&&, ||, ;, |), optionally behind a package runner, and followed by an
216
+ * argument or the end. So "husky", "husky install", "is-ci || husky" and
217
+ * "npx husky" match, and "no-husky" or "echo skip husky" do not.
218
+ */
219
+ const HUSKY_COMMAND = /(?:^|&&|\|\||;|\|)\s*(?:(?:npx|pnpx|bunx)\s+|(?:pnpm|yarn|npm)\s+(?:exec\s+)?)?husky(?:\s|$)/;
220
+ export function declaredHusky(root) {
221
+ const raw = readIfExists(path.join(root, 'package.json'));
222
+ if (raw === undefined) {
223
+ return null;
224
+ }
225
+ let parsed;
226
+ try {
227
+ parsed = JSON.parse(raw);
228
+ }
229
+ catch {
230
+ return null;
231
+ }
232
+ if (!isPlainObject(parsed)) {
233
+ return null;
234
+ }
235
+ const manifest = parsed;
236
+ for (const key of ['devDependencies', 'dependencies']) {
237
+ const deps = manifest[key];
238
+ if (isPlainObject(deps) && deps.husky !== undefined) {
239
+ return `package.json (${key})`;
240
+ }
241
+ }
242
+ const scripts = manifest.scripts;
243
+ if (isPlainObject(scripts)) {
244
+ const prepare = scripts.prepare;
245
+ if (typeof prepare === 'string' && HUSKY_COMMAND.test(prepare)) {
246
+ return 'package.json (the prepare script)';
247
+ }
248
+ }
249
+ return null;
250
+ }
206
251
  function isPlainObject(value) {
207
252
  return typeof value === 'object' && value !== null && !Array.isArray(value);
208
253
  }
@@ -3,6 +3,7 @@ import path from 'node:path';
3
3
  import { NATIVE_CONTRACT_PATH } from './intent-prepare.js';
4
4
  import { DEFAULT_STAGE_FOR_ROLE, GATE_ROLES, POLICY_FILE_NAME, PRODUCT_FOR_ROLE } from './policy.js';
5
5
  import { installName } from './normalize.js';
6
+ import { profileFor } from './products.js';
6
7
  import { CANDIDATES } from './resolve.js';
7
8
  export { POLICY_FILE_NAME };
8
9
  /** Names of the gates whose binary resolves right now. */
@@ -102,6 +103,14 @@ export function renderPolicy(detected, frozenContractPath) {
102
103
  lines.push(` ${role}:`);
103
104
  lines.push(` product: ${product}`);
104
105
  lines.push(` enabled: ${enabled ? 'true' : 'false'}`);
106
+ // An external tool is enabled only because THIS machine has it, and
107
+ // nothing installs it anywhere else: say so where the next reader of the
108
+ // file will look, not only in init's own output, which nobody re-reads.
109
+ if (enabled && !profileFor(product).managed) {
110
+ lines.push(` # Enabled because ${product} was found on the machine that ran init. CI must`);
111
+ lines.push(` # install ${product} itself (conductor does not); without it this gate`);
112
+ lines.push(' # reports conductor/gate-missing and the run exits 2.');
113
+ }
105
114
  lines.push(` stage: ${DEFAULT_STAGE_FOR_ROLE[role]}`);
106
115
  // The intent gate is the one with ceremony, and the ramp is what makes
107
116
  // that ceremony adoptable: with no frozen contract yet, it reports for a
@@ -112,6 +121,7 @@ export function renderPolicy(detected, frozenContractPath) {
112
121
  // ramp is already climbed and enforcing from the start is what stops a
113
122
  // frozen contract's protected paths from producing findings that never
114
123
  // fail the check (issue #57).
124
+ let unfrozenIntent = false;
115
125
  if (role === 'intent') {
116
126
  if (frozenContractPath !== null) {
117
127
  lines.push(` # A frozen contract already exists at ${frozenContractPath}, so this gate`);
@@ -119,6 +129,7 @@ export function renderPolicy(detected, frozenContractPath) {
119
129
  lines.push(' enforce: true');
120
130
  }
121
131
  else {
132
+ unfrozenIntent = true;
122
133
  lines.push(` # No frozen contract yet (${NATIVE_CONTRACT_PATH}), so this gate runs`);
123
134
  lines.push(' # and reports without failing the run. Once a contract is frozen,');
124
135
  lines.push(' # set this to true by hand: conductor init never rewrites this file');
@@ -129,9 +140,47 @@ export function renderPolicy(detected, frozenContractPath) {
129
140
  else {
130
141
  lines.push(' enforce: true');
131
142
  }
143
+ // Only the vulnerabilities gate compares a pull request with its base.
144
+ // Written as report for a fresh repository, so an existing backlog does
145
+ // not block every pull request from the first one; a parser default of
146
+ // block keeps every policy written before the key existed as strict as
147
+ // it was.
148
+ if (role === 'vulnerabilities') {
149
+ lines.push(' # On a pull request, findings already on the base branch are reported');
150
+ lines.push(' # and do not block; only advisories the pull request introduces do.');
151
+ lines.push(' # Set present-on-base: block to block on every known vulnerability.');
152
+ lines.push(' present-on-base: report');
153
+ }
132
154
  lines.push(' # Handed to this gate unchanged. Keys are its own long flags,');
133
- lines.push(' # without the leading dashes. Example: fail-on: high');
134
- lines.push(' options: {}');
155
+ lines.push(' # without the leading dashes.');
156
+ if (role === 'secrets-history') {
157
+ lines.push(' # gitleaks has no severity floor. Tune its rules in .gitleaks.toml and');
158
+ lines.push(' # accept an old finding in .gitleaksignore, not here.');
159
+ // No timeout-seconds line: an absent key is the default, and writing
160
+ // 600 would freeze today's default into every new policy.
161
+ lines.push(' # A full-history scan can outlive the 600 s default on a large repository.');
162
+ lines.push(' # Set timeout-seconds beside enforce to change it; see the README.');
163
+ }
164
+ else if (role === 'vulnerabilities') {
165
+ lines.push(' # osv-scanner has no severity floor. Tune what it reports in');
166
+ lines.push(' # osv-scanner.toml, not here.');
167
+ }
168
+ else if (role === 'intent') {
169
+ lines.push(' # require-frozen: false lets the gate run and not block when no contract exists.');
170
+ }
171
+ else {
172
+ lines.push(' # Example: fail-on: high');
173
+ }
174
+ if (unfrozenIntent) {
175
+ // intent-guard blocks on a missing contract when require-frozen is true,
176
+ // its default. Without this key a full run prints a BLOCKING critical
177
+ // finding for the very state the unenforced ramp above exists for.
178
+ lines.push(' options:');
179
+ lines.push(' require-frozen: false');
180
+ }
181
+ else {
182
+ lines.push(' options: {}');
183
+ }
135
184
  }
136
185
  lines.push('', 'report:', ' format: text', '');
137
186
  return lines.join('\n');
package/dist/init.d.ts CHANGED
@@ -91,6 +91,12 @@ export interface InitResult {
91
91
  content: string;
92
92
  kind: 'hook' | 'policy';
93
93
  }>;
94
+ /**
95
+ * The .gitignore that GITIGNORE_LINE is appended to on apply, when the
96
+ * manifest is not already ignored and appending is safe. Absent otherwise.
97
+ * Never in the manifest: --revert does not touch .gitignore.
98
+ */
99
+ gitignoreAppend?: string;
94
100
  }
95
101
  export interface InitOptions {
96
102
  cwd: string;
@@ -117,6 +123,8 @@ export interface InitOptions {
117
123
  force?: boolean;
118
124
  }
119
125
  export declare function planInit(options: InitOptions): InitResult;
126
+ /** The line init adds to .gitignore for the per-machine manifest. */
127
+ export declare const GITIGNORE_LINE = ".guardrails/";
120
128
  export declare function applyInit(plan: InitResult, options: InitOptions): InitResult;
121
129
  export interface RevertResult {
122
130
  ok: boolean;
package/dist/init.js CHANGED
@@ -64,14 +64,14 @@
64
64
  // repositories in a dogfood run: both would have taken the umbrella hook
65
65
  // and lost it at the next install, with the manifest still recording it
66
66
  // as installed. See detectManagedHook and declaredManagedHooks.
67
- import { execFileSync } from 'node:child_process';
68
- import { chmodSync, closeSync, constants as fsConstants, existsSync, mkdirSync, openSync, readdirSync, realpathSync, rmSync, rmdirSync, statSync, writeFileSync, writeSync, } from 'node:fs';
67
+ import { execFileSync, spawnSync } from 'node:child_process';
68
+ import { chmodSync, closeSync, constants as fsConstants, existsSync, lstatSync, mkdirSync, openSync, readdirSync, realpathSync, rmSync, rmdirSync, statSync, writeFileSync, writeSync, } from 'node:fs';
69
69
  import path from 'node:path';
70
- 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 { DEP_GUARD_HOOK_MARKER, INTENT_GUARD_HOOK_MARKER, MANAGED_HOOK_MARKER, declaredHusky, declaredManagedHooks, detectGateHook, detectGeneratedHook, detectManagedHook, editedManagedGuidance, foreignGuidance, gateHookGuidance, generatedHookGuidance, huskyDirectoryFor, huskyShimPresent, managedHooksGuidance, } from './init-hook-detect.js';
71
71
  import { MANIFEST_RELATIVE_PATH, manifestPathInsideRepo, readIfExists, readManifest, recordedHookSha, sha256, } from './init-manifest.js';
72
72
  import { POLICY_FILE_NAME, detectGates, renderPolicy } from './init-policy.js';
73
73
  import { frozenNativeContractPath } from './intent-prepare.js';
74
- import { GATE_ROLES, PRODUCT_FOR_ROLE } from './policy.js';
74
+ import { GATE_ROLES, PRODUCT_FOR_ROLE, parsePolicy } from './policy.js';
75
75
  import { profileFor } from './products.js';
76
76
  export { MANAGED_HOOK_MARKER, MANIFEST_RELATIVE_PATH, DEP_GUARD_HOOK_MARKER, INTENT_GUARD_HOOK_MARKER, POLICY_FILE_NAME, renderPolicy, };
77
77
  const HOOK = `#!/bin/sh
@@ -178,6 +178,11 @@ function gitOutput(cwd, args) {
178
178
  function repoRootOf(cwd) {
179
179
  return gitOutput(cwd, ['rev-parse', '--show-toplevel']);
180
180
  }
181
+ /** Whether git tracks anything under .husky/ at the repository root. */
182
+ function trackedHuskyDirectory(cwd) {
183
+ const listed = gitOutput(cwd, ['ls-files', '--full-name', '--', ':/.husky']);
184
+ return listed !== null && listed.length > 0;
185
+ }
181
186
  function effectiveHooksDir(cwd, root) {
182
187
  const gitDir = gitOutput(cwd, ['rev-parse', '--git-dir']);
183
188
  const hooksPath = gitOutput(cwd, ['config', '--get', 'core.hooksPath']) ?? '';
@@ -186,7 +191,7 @@ function effectiveHooksDir(cwd, root) {
186
191
  // somewhere else entirely, so this one resolves against gitDir.
187
192
  const defaultDir = path.join(path.resolve(cwd, gitDir ?? '.git'), 'hooks');
188
193
  if (hooksPath.length === 0) {
189
- return { dir: defaultDir, outside: false, isDefault: true };
194
+ return { dir: defaultDir, outside: false, isDefault: true, configured: false };
190
195
  }
191
196
  // A RELATIVE core.hooksPath resolves against the WORKING-TREE ROOT.
192
197
  // Verified by experiment rather than by reading the documentation that
@@ -194,7 +199,7 @@ function effectiveHooksDir(cwd, root) {
194
199
  const dir = path.isAbsolute(hooksPath) ? hooksPath : path.join(root, hooksPath);
195
200
  const relative = path.relative(root, dir);
196
201
  const outside = relative.startsWith('..') || path.isAbsolute(relative);
197
- return { dir, outside, isDefault: samePath(dir, defaultDir) };
202
+ return { dir, outside, isDefault: samePath(dir, defaultDir), configured: true };
198
203
  }
199
204
  /**
200
205
  * Whether two paths name the same directory.
@@ -300,9 +305,11 @@ export function planInit(options) {
300
305
  // executes (on husky 8 that file IS the tracked hook), and never
301
306
  // conditional on husky's shim being present (a clean deletes it, and the
302
307
  // repository is still husky's).
303
- const huskyDir = huskyDirectoryFor(hooks.dir);
304
- const husky = huskyDir !== null;
305
- if (!husky) {
308
+ let huskyDir = huskyDirectoryFor(hooks.dir);
309
+ // Where husky was recognised from when core.hooksPath does not say so yet:
310
+ // a fresh clone of a husky repository, before its install has run.
311
+ let huskyDeclaredIn = null;
312
+ if (huskyDir === null) {
306
313
  const rel = path.relative(root, executedHookPath).split(path.sep).join('/');
307
314
  if (executedHook !== undefined) {
308
315
  const generatedBy = detectGeneratedHook(executedHook);
@@ -348,7 +355,25 @@ export function planInit(options) {
348
355
  hookManager: managedBy.manager,
349
356
  };
350
357
  }
358
+ // HUSKY ON A FRESH CLONE. core.hooksPath is set by husky's own install
359
+ // (its prepare script), so a clone that has not run it yet looks native,
360
+ // and a hook written to .git/hooks then goes dark the moment the install
361
+ // points git at .husky/_. The declaration is the signal that exists
362
+ // before the install: husky in package.json, or a tracked .husky/
363
+ // directory. Same rule as simple-git-hooks above, the declaration counts
364
+ // on its own, but the answer differs: husky HAS a tracked hook file, and
365
+ // that file is what both husky 8 and husky 9 end up running, so init
366
+ // writes there and says the install still has to run, rather than
367
+ // refusing. Only where git runs .git/hooks: a hooks directory somebody
368
+ // configured is their decision, not a fresh clone.
369
+ if (!hooks.configured) {
370
+ huskyDeclaredIn = declaredHusky(root) ?? (trackedHuskyDirectory(options.cwd) ? 'a tracked .husky/ directory' : null);
371
+ if (huskyDeclaredIn !== null) {
372
+ huskyDir = path.join(root, '.husky');
373
+ }
374
+ }
351
375
  }
376
+ const husky = huskyDir !== null;
352
377
  const hookManager = husky ? 'husky' : 'native';
353
378
  const hookPath = huskyDir === null ? executedHookPath : path.join(huskyDir, 'pre-commit');
354
379
  const relHook = path.relative(root, hookPath).split(path.sep).join('/');
@@ -427,7 +452,16 @@ export function planInit(options) {
427
452
  else if (existingHook !== undefined && existingHook.trim().length > 0) {
428
453
  const gateProduct = detectGateHook(existingHook);
429
454
  if (gateProduct === null) {
430
- conflicts.push({ path: relHook, reason: 'foreign-hook', guidance: foreignGuidance(relHook) });
455
+ conflicts.push({
456
+ path: relHook,
457
+ reason: 'foreign-hook',
458
+ guidance: foreignGuidance(relHook) +
459
+ // On a fresh husky clone the tracked hook is not run by anything yet.
460
+ (huskyDeclaredIn === null
461
+ ? ''
462
+ : ' Note that husky is not installed in this clone (core.hooksPath is not set), so that hook ' +
463
+ "does not run at all until the install (husky's prepare script) has run."),
464
+ });
431
465
  return { ...base, repoRoot: root, hookPath, hookManager };
432
466
  }
433
467
  if (!options.adopt) {
@@ -456,14 +490,18 @@ export function planInit(options) {
456
490
  // the one core.hooksPath points at. The shim's state is reported
457
491
  // here, where it informs, rather than tested in the rule, where it
458
492
  // would send a cleaned repository back into the trap.
459
- detail: husky
460
- ? `${created}: husky runs ${path
461
- .relative(root, executedHookPath)
462
- .split(path.sep)
463
- .join('/')}, which execs this tracked file${huskyShimPresent(hooks.dir)
464
- ? ''
465
- : ' (husky is not installed right now: its generated directory is empty or gone, and the next install restores it)'}`
466
- : created,
493
+ detail: huskyDeclaredIn !== null
494
+ ? `${created}: husky is declared in ${huskyDeclaredIn} but has not been installed in this ` +
495
+ 'clone (core.hooksPath is not set), so git runs nothing from here yet. Run your install ' +
496
+ "(husky's prepare script) and husky will run this tracked file; .git/hooks would be bypassed then"
497
+ : husky
498
+ ? `${created}: husky runs ${path
499
+ .relative(root, executedHookPath)
500
+ .split(path.sep)
501
+ .join('/')}, which execs this tracked file${huskyShimPresent(hooks.dir)
502
+ ? ''
503
+ : ' (husky is not installed right now: its generated directory is empty or gone, and the next install restores it)'}`
504
+ : created,
467
505
  });
468
506
  writes.push({ path: hookPath, content: HOOK, executable: true, kind: 'hook' });
469
507
  }
@@ -498,9 +536,11 @@ function finishPlan(options, root, policyPath, base, actions, writes, records, h
498
536
  const external = GATE_ROLES.filter((role) => detected.has(role) && !profileFor(PRODUCT_FOR_ROLE[role]).managed).map((role) => `${role} (${PRODUCT_FOR_ROLE[role]})`);
499
537
  if (external.length > 0) {
500
538
  const one = external.length === 1;
501
- notes.push(`Note: ${external.join(' and ')} ${one ? 'is' : 'are'} enabled because ` +
539
+ notes.push(`WARNING: ${external.join(' and ')} ${one ? 'is' : 'are'} enabled only because ` +
502
540
  `${one ? 'its tool was' : 'their tools were'} found on this machine's PATH; your CI ` +
503
- `workflow must install ${one ? 'it' : 'them'} too, conductor does not.`);
541
+ `workflow must install ${one ? 'it' : 'them'} too, conductor does not. A teammate or a CI ` +
542
+ `job without ${one ? 'it' : 'them'} gets conductor/gate-missing and exit 2; set enabled: ` +
543
+ `false in ${POLICY_FILE_NAME} if that is not wanted.`);
504
544
  }
505
545
  }
506
546
  else {
@@ -511,6 +551,7 @@ function finishPlan(options, root, policyPath, base, actions, writes, records, h
511
551
  path: POLICY_FILE_NAME,
512
552
  detail: 'already present, left exactly as it is',
513
553
  });
554
+ notes.push(...missingRoleNotes(existingPolicy));
514
555
  }
515
556
  // A record with nothing to write is still work: the manifest has to be
516
557
  // rebuilt, so this is not an "already installed, nothing to do" run.
@@ -518,10 +559,27 @@ function finishPlan(options, root, policyPath, base, actions, writes, records, h
518
559
  if (!alreadyInstalled) {
519
560
  actions.push({ kind: 'write', path: MANIFEST_RELATIVE_PATH, detail: 'record what init wrote' });
520
561
  }
562
+ // The manifest names absolute paths on this machine, so it is never meant
563
+ // to be committed. Appended to .gitignore when that can be done without
564
+ // touching a single existing line; otherwise the line to add is printed.
565
+ const ignore = alreadyInstalled ? null : planGitignore(root);
566
+ if (ignore !== null && ignore.kind === 'append') {
567
+ actions.push({
568
+ kind: 'write',
569
+ path: '.gitignore',
570
+ detail: `append "${GITIGNORE_LINE}" (the per-machine manifest); no other line is changed, and --revert leaves it`,
571
+ });
572
+ }
573
+ else if (ignore !== null) {
574
+ notes.push(`Note: ${MANIFEST_RELATIVE_PATH} is not ignored by git and init did not change .gitignore ` +
575
+ `(${ignore.why}). Add the line "${GITIGNORE_LINE}" to it yourself: the manifest records ` +
576
+ 'paths on this machine and is not meant to be committed.');
577
+ }
521
578
  return {
522
579
  ...base,
523
580
  ok: true,
524
581
  alreadyInstalled,
582
+ ...(ignore !== null && ignore.kind === 'append' ? { gitignoreAppend: ignore.path } : {}),
525
583
  hookPath: hook.hookPath,
526
584
  hookManager: hook.hookManager,
527
585
  repoRoot: root,
@@ -531,6 +589,89 @@ function finishPlan(options, root, policyPath, base, actions, writes, records, h
531
589
  notes,
532
590
  };
533
591
  }
592
+ /** The line init adds to .gitignore for the per-machine manifest. */
593
+ export const GITIGNORE_LINE = '.guardrails/';
594
+ /**
595
+ * Whether init can append GITIGNORE_LINE to .gitignore, or why not, or null
596
+ * when git already ignores the manifest (by any rule, in any ignore file).
597
+ *
598
+ * APPEND ONLY. Init never rewrites a file it did not write: the line goes at
599
+ * the end of an existing .gitignore, after a newline if the file lacks a
600
+ * final one, or into a new .gitignore. A .gitignore that is a symbolic link,
601
+ * not a regular file, or resolves outside the repository is left alone and
602
+ * the line is printed instead. Not recorded in the manifest, so --revert
603
+ * never removes or rewrites .gitignore.
604
+ */
605
+ function planGitignore(root) {
606
+ const probe = spawnSync('git', ['check-ignore', '-q', '--no-index', MANIFEST_RELATIVE_PATH], {
607
+ cwd: root,
608
+ stdio: 'ignore',
609
+ });
610
+ if (probe.status === 0) {
611
+ return null;
612
+ }
613
+ if (probe.status !== 1) {
614
+ return { kind: 'print', why: 'git could not say whether it is already ignored' };
615
+ }
616
+ const target = path.join(root, '.gitignore');
617
+ let info;
618
+ try {
619
+ info = lstatSync(target);
620
+ }
621
+ catch (err) {
622
+ if (err.code === 'ENOENT') {
623
+ return { kind: 'append', path: target };
624
+ }
625
+ return { kind: 'print', why: '.gitignore could not be read' };
626
+ }
627
+ if (info.isSymbolicLink()) {
628
+ return { kind: 'print', why: '.gitignore is a symbolic link' };
629
+ }
630
+ if (!info.isFile()) {
631
+ return { kind: 'print', why: '.gitignore is not a regular file' };
632
+ }
633
+ return { kind: 'append', path: target };
634
+ }
635
+ /** Appends the line without following a link swapped in after planning. */
636
+ function appendGitignore(target) {
637
+ const existing = readIfExists(target);
638
+ const lead = existing !== undefined && existing.length > 0 && !existing.endsWith('\n') ? '\n' : '';
639
+ const noFollow = fsConstants.O_NOFOLLOW ?? 0;
640
+ const fd = openSync(target, fsConstants.O_WRONLY | fsConstants.O_CREAT | fsConstants.O_APPEND | noFollow, 0o666);
641
+ try {
642
+ writeSync(fd, `${lead}${GITIGNORE_LINE}\n`);
643
+ }
644
+ finally {
645
+ closeSync(fd);
646
+ }
647
+ }
648
+ /**
649
+ * On an existing policy file, the roles it has no entry for, with the two
650
+ * lines that add each. The file itself is never touched; this only says what
651
+ * a newer conductor knows about that an older init did not write.
652
+ */
653
+ function missingRoleNotes(text) {
654
+ let policy;
655
+ try {
656
+ policy = parsePolicy(text, POLICY_FILE_NAME);
657
+ }
658
+ catch {
659
+ return [
660
+ `Note: ${POLICY_FILE_NAME} does not parse, so init could not list the gate roles it lacks. ` +
661
+ '"conductor run" says why.',
662
+ ];
663
+ }
664
+ const missing = GATE_ROLES.filter((role) => policy.gates[role] === undefined);
665
+ if (missing.length === 0) {
666
+ return [];
667
+ }
668
+ return [
669
+ `Note: ${POLICY_FILE_NAME} has no entry for ${missing.length} gate role(s): ${missing.join(', ')}. ` +
670
+ 'To add one, put its two lines under "gates:" (a role listed is enabled unless it also says ' +
671
+ 'enabled: false):',
672
+ ...missing.flatMap((role) => [` ${role}:`, ` product: ${PRODUCT_FOR_ROLE[role]}`]),
673
+ ];
674
+ }
534
675
  /**
535
676
  * The whole plan when --hook was not given: no hook is detected, no hook
536
677
  * manager is consulted, and no hook conflict can block the policy file from
@@ -658,6 +799,11 @@ export function applyInit(plan, options) {
658
799
  const manifestPath = path.join(plan.repoRoot, MANIFEST_RELATIVE_PATH);
659
800
  mkdirSync(path.dirname(manifestPath), { recursive: true });
660
801
  writeManifestFile(manifestPath, `${JSON.stringify(manifest, null, 2)}\n`);
802
+ // Last, and contained like every other write: a .gitignore resolving
803
+ // outside the repository is never appended to.
804
+ if (plan.gitignoreAppend !== undefined && manifestPathInsideRepo(plan.repoRoot, plan.gitignoreAppend)) {
805
+ appendGitignore(plan.gitignoreAppend);
806
+ }
661
807
  }
662
808
  catch (err) {
663
809
  return {
@@ -120,6 +120,17 @@ export type IntentPrepareResult = {
120
120
  kind: 'failed';
121
121
  step: PrepareStep;
122
122
  detail: string;
123
+ }
124
+ /**
125
+ * A preparation spawn was stopped at the intent gate's time limit (spawn
126
+ * error ETIMEDOUT, checked before the status). Not `failed`: the caller
127
+ * reports it as the timed-out could-not-run reason.
128
+ */
129
+ | {
130
+ kind: 'timed-out';
131
+ step: 'import-spec' | 'freeze';
132
+ elapsedMs: number;
133
+ signal: string | null;
123
134
  };
124
135
  export interface IntentPrepareOptions {
125
136
  repoRoot: string;
@@ -133,7 +144,13 @@ export interface IntentPrepareOptions {
133
144
  * it when no --base and no GITHUB_BASE_REF names another base.
134
145
  */
135
146
  trustBase?: string;
136
- timeoutMs?: number;
147
+ /**
148
+ * The intent gate's resolved time limit (`resolveTimeLimit` in
149
+ * src/gate-runner.ts), given in full to each preparation spawn. REQUIRED,
150
+ * with no fallback here, so the type checker holds the preparation to the
151
+ * one resolver.
152
+ */
153
+ timeoutMs: number;
137
154
  /**
138
155
  * The directory the per-run temporary project is created under.
139
156
  *
@@ -274,6 +274,7 @@ function subcommand(binary, name) {
274
274
  return { command: binary.command, argv: [...prefix.slice(0, -1), name] };
275
275
  }
276
276
  function run(command, argv, cwd, timeoutMs) {
277
+ const started = Date.now();
277
278
  const child = spawnSync(command, argv, {
278
279
  cwd,
279
280
  encoding: 'utf8',
@@ -285,8 +286,17 @@ function run(command, argv, cwd, timeoutMs) {
285
286
  stdout: child.stdout ?? '',
286
287
  stderr: child.stderr ?? '',
287
288
  errorMessage: child.error === undefined ? null : child.error.message,
289
+ errorCode: child.error === undefined ? null : (child.error.code ?? null),
290
+ signal: child.signal ?? null,
291
+ elapsedMs: Date.now() - started,
288
292
  };
289
293
  }
294
+ /** A preparation spawn stopped at the limit, as a result; null for any other outcome. */
295
+ function timedOutStep(result, step) {
296
+ return result.errorCode === 'ETIMEDOUT'
297
+ ? { kind: 'timed-out', step, elapsedMs: result.elapsedMs, signal: result.signal }
298
+ : null;
299
+ }
290
300
  /**
291
301
  * Everything the child complained with, trimmed and capped.
292
302
  *
@@ -403,8 +413,7 @@ export function prepareIntent(options) {
403
413
  * so the change set and the chain cannot differ between them.
404
414
  */
405
415
  function finishPreparation(options, source, importInput, proposals, note) {
406
- const { repoRoot, env } = options;
407
- const timeoutMs = options.timeoutMs ?? 120_000;
416
+ const { repoRoot, env, timeoutMs } = options;
408
417
  const resolvedBase = resolveBaseRefInRepo(repoRoot, {
409
418
  ...(options.base === undefined ? {} : { base: options.base }),
410
419
  ...(options.trustBase === undefined ? {} : { trustBase: options.trustBase }),
@@ -510,6 +519,13 @@ function finishPreparation(options, source, importInput, proposals, note) {
510
519
  ...(source.plan === null ? [] : ['--plan', path.join(readRoot, source.plan)]),
511
520
  '--dry-run',
512
521
  ], readRoot, timeoutMs);
522
+ // The time limit first, before the status, as in the runner: a stopped
523
+ // child's status is not an answer.
524
+ const importStopped = timedOutStep(importResult, 'import-spec');
525
+ if (importStopped !== null) {
526
+ discard();
527
+ return importStopped;
528
+ }
513
529
  if (importResult.errorMessage !== null) {
514
530
  discard();
515
531
  return { kind: 'failed', step: 'import-spec', detail: importResult.errorMessage };
@@ -588,6 +604,11 @@ function finishPreparation(options, source, importInput, proposals, note) {
588
604
  '--yes',
589
605
  '--json',
590
606
  ], readRoot, timeoutMs);
607
+ const freezeStopped = timedOutStep(freezeResult, 'freeze');
608
+ if (freezeStopped !== null) {
609
+ cleanup();
610
+ return freezeStopped;
611
+ }
591
612
  if (freezeResult.errorMessage !== null || freezeResult.status !== 0) {
592
613
  cleanup();
593
614
  return {