@vaultcompass/conductor 0.8.0 → 0.8.1

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.js ADDED
@@ -0,0 +1,224 @@
1
+ // Every git command the umbrella runs itself, through one door.
2
+ //
3
+ // Three properties hold for each of them, and keeping the calls in one place
4
+ // is what lets that be said once rather than checked at a dozen call sites:
5
+ //
6
+ // - THE PROGRAM. On a pull-request run the caller pins git to one absolute
7
+ // path, outside the repository's work tree, before anything else runs
8
+ // (`pinGitOutside`), so every git call here runs that program and no
9
+ // other. Outside pull-request mode this is plain `git`, found the way a
10
+ // shell finds it.
11
+ //
12
+ // - REPLACE OBJECTS ARE IGNORED. GIT_NO_REPLACE_OBJECTS is set on every
13
+ // call, so every read here sees the commit's own objects.
14
+ //
15
+ // - NOTHING HERE DECIDES WHAT A FAILURE MEANS. The result carries the exit
16
+ // status and the error, and each caller keeps "git said there is nothing
17
+ // there" apart from "git could not answer", because the second is never
18
+ // a reason to treat a trusted file as absent.
19
+ import { spawnSync } from 'node:child_process';
20
+ import { accessSync, chmodSync, constants, existsSync, mkdtempSync, realpathSync, rmSync, statSync, symlinkSync, } from 'node:fs';
21
+ import path from 'node:path';
22
+ let gitProgram = 'git';
23
+ /** The program every git call in this process runs. */
24
+ export function currentGitProgram() {
25
+ return gitProgram;
26
+ }
27
+ /**
28
+ * Pins the git program for the rest of this process. The CLI calls it once
29
+ * on a pull-request run, with an absolute path; tests call it to reset.
30
+ */
31
+ export function useGitProgram(program) {
32
+ gitProgram = program;
33
+ }
34
+ /** Runs one git command in `cwd`, reading stdout as UTF-8. Never throws. */
35
+ export function runGit(cwd, args, options = {}) {
36
+ const child = spawnSync(gitProgram, [...args], {
37
+ cwd,
38
+ encoding: 'utf8',
39
+ maxBuffer: options.maxBuffer ?? 32 * 1024 * 1024,
40
+ env: { ...process.env, GIT_NO_REPLACE_OBJECTS: '1' },
41
+ });
42
+ return {
43
+ status: child.status,
44
+ stdout: typeof child.stdout === 'string' ? child.stdout : '',
45
+ stderr: typeof child.stderr === 'string' ? child.stderr : '',
46
+ error: child.error,
47
+ };
48
+ }
49
+ /**
50
+ * A PATH with every entry that would resolve against the working directory
51
+ * removed: an empty entry (which means the current directory) and a relative
52
+ * one. Returns the cleaned value and what was removed, in order.
53
+ *
54
+ * Used on a run with a trust base, where the working directory of nearly
55
+ * every child is the tree under judgment, so that every PATH lookup, for
56
+ * git, for node in a gate's "#!/usr/bin/env node" line, or for a gate,
57
+ * resolves against an absolute directory.
58
+ */
59
+ export function absolutePathEntries(pathValue) {
60
+ const kept = [];
61
+ const removed = [];
62
+ for (const entry of pathValue.split(path.delimiter)) {
63
+ if (entry !== '' && path.isAbsolute(entry)) {
64
+ kept.push(entry);
65
+ }
66
+ else {
67
+ removed.push(entry);
68
+ }
69
+ }
70
+ return { value: kept.join(path.delimiter), removed };
71
+ }
72
+ /** Whether `candidate` (already resolved) is `root` or under it. */
73
+ function isInside(root, candidate) {
74
+ const relative = path.relative(root, candidate);
75
+ return relative === '' || (!relative.startsWith('..') && !path.isAbsolute(relative));
76
+ }
77
+ function realOrNull(candidate) {
78
+ try {
79
+ return realpathSync(candidate);
80
+ }
81
+ catch {
82
+ return null;
83
+ }
84
+ }
85
+ /**
86
+ * The nearest directory at or above `start` holding a `.git` entry (the
87
+ * work tree a git run from `start` would find), resolved, or null. Found
88
+ * without running git, because it decides which git may be run.
89
+ */
90
+ export function workTreeAbove(start) {
91
+ let current = realOrNull(start);
92
+ while (current !== null) {
93
+ if (existsSync(path.join(current, '.git'))) {
94
+ return current;
95
+ }
96
+ const parent = path.dirname(current);
97
+ if (parent === current) {
98
+ return null;
99
+ }
100
+ current = parent;
101
+ }
102
+ return null;
103
+ }
104
+ /**
105
+ * The first git on `pathValue` whose real path (symlinks resolved) is
106
+ * outside every root in `excluded`, as that real path, or null when there
107
+ * is none. Only absolute PATH entries are considered.
108
+ */
109
+ export function gitOutside(pathValue, excluded) {
110
+ const roots = excluded.map((root) => realOrNull(root) ?? root);
111
+ for (const dir of pathValue.split(path.delimiter)) {
112
+ if (dir === '' || !path.isAbsolute(dir)) {
113
+ continue;
114
+ }
115
+ const real = realOrNull(path.join(dir, 'git'));
116
+ if (real === null) {
117
+ continue;
118
+ }
119
+ try {
120
+ if (!statSync(real).isFile()) {
121
+ continue;
122
+ }
123
+ accessSync(real, constants.X_OK);
124
+ }
125
+ catch {
126
+ continue;
127
+ }
128
+ if (roots.some((root) => isInside(root, real))) {
129
+ continue;
130
+ }
131
+ return real;
132
+ }
133
+ return null;
134
+ }
135
+ /**
136
+ * Pins every git call in this process to the first git on `pathValue` that
137
+ * is outside the given work trees, and returns it; null, with nothing
138
+ * pinned, when there is none. Called once on a pull-request run.
139
+ */
140
+ export function pinGitOutside(pathValue, excluded) {
141
+ const chosen = gitOutside(pathValue, excluded);
142
+ if (chosen !== null) {
143
+ useGitProgram(chosen);
144
+ }
145
+ return chosen;
146
+ }
147
+ /** Whether the pinned git program's real path is inside `root`. */
148
+ export function pinnedGitInside(root) {
149
+ const real = realOrNull(gitProgram);
150
+ const resolvedRoot = realOrNull(root) ?? root;
151
+ return real !== null && path.isAbsolute(gitProgram) && isInside(resolvedRoot, real);
152
+ }
153
+ /** Whether `candidate`'s real path is `root`'s real path or under it. */
154
+ export function realPathInside(root, candidate) {
155
+ const real = realOrNull(candidate) ?? candidate;
156
+ return isInside(realOrNull(root) ?? root, real);
157
+ }
158
+ /** The name every private git directory starts with, under the temp directory. */
159
+ export const GIT_SHIM_PREFIX = 'conductor-git-';
160
+ /**
161
+ * On a run with a trust base: creates the private directory that goes first
162
+ * on PATH for every child the run starts, so that a gate, or anything a gate
163
+ * starts, that looks git up by name runs the pinned `program` and never a git
164
+ * found in a PATH entry inside the tree being judged.
165
+ *
166
+ * The directory is a fresh mkdtemp directory under `tempRoot`, mode 0700,
167
+ * holding exactly one entry, `git`, a symbolic link to `program`, so no other
168
+ * lookup is shadowed. git finds its helpers through its own exec path, not
169
+ * through PATH, so a link is enough. Throws, with a sentence saying why and
170
+ * what to set, when `tempRoot` is inside one of `excluded` or the directory
171
+ * cannot be made; it never returns an unprotected result silently.
172
+ *
173
+ * On Windows it creates nothing and returns null: a symbolic link needs a
174
+ * privilege there, and a git.cmd wrapper is not found by a child that starts
175
+ * git without a shell. There the gates look git up through the cleaned PATH.
176
+ */
177
+ export function createGitShim(program, tempRoot, excluded, platform = process.platform) {
178
+ if (platform === 'win32') {
179
+ return null;
180
+ }
181
+ const realTemp = realOrNull(tempRoot) ?? tempRoot;
182
+ if (excluded.some((root) => realPathInside(root, realTemp))) {
183
+ throw new Error(tempInsideTreeMessage(tempRoot));
184
+ }
185
+ let dir;
186
+ try {
187
+ dir = mkdtempSync(path.join(realTemp, GIT_SHIM_PREFIX));
188
+ chmodSync(dir, 0o700);
189
+ symlinkSync(program, path.join(dir, 'git'));
190
+ return dir;
191
+ }
192
+ catch (err) {
193
+ if (dir !== undefined) {
194
+ removeGitShim(dir);
195
+ }
196
+ throw new Error('conductor could not create the private git directory it puts first on PATH for the ' +
197
+ `gates under the system temporary directory (${tempRoot}): ` +
198
+ `${err instanceof Error ? err.message : String(err)}. ${SHIM_REMEDY}`);
199
+ }
200
+ }
201
+ const SHIM_REMEDY = 'Set TMPDIR to a writable directory outside the repository. Nothing was checked.';
202
+ /** Why a run cannot go ahead when the temp directory is inside the tree. */
203
+ export function tempInsideTreeMessage(tempRoot) {
204
+ return (`the system temporary directory (${tempRoot}) is inside the repository being judged, ` +
205
+ 'and on a pull-request run conductor keeps the directory it puts first on PATH for ' +
206
+ `the gates outside that tree. ${SHIM_REMEDY}`);
207
+ }
208
+ /** Removes a directory createGitShim made. Never throws. */
209
+ export function removeGitShim(dir) {
210
+ try {
211
+ rmSync(dir, { recursive: true, force: true });
212
+ }
213
+ catch {
214
+ // Nothing left to remove, or not removable; the run's outcome stands.
215
+ }
216
+ }
217
+ /** git's first line of complaint, without a trailing full stop. */
218
+ export function gitComplaint(result) {
219
+ if (result.error !== undefined) {
220
+ return `git could not be run: ${result.error.message}`;
221
+ }
222
+ const line = (result.stderr.trim().split('\n')[0] ?? '').replace(/\.+$/, '');
223
+ return line === '' ? `git exited ${result.status ?? -1}` : line;
224
+ }
package/dist/init.js CHANGED
@@ -65,7 +65,7 @@
65
65
  // and lost it at the next install, with the manifest still recording it
66
66
  // as installed. See detectManagedHook and declaredManagedHooks.
67
67
  import { execFileSync } from 'node:child_process';
68
- import { chmodSync, existsSync, mkdirSync, readdirSync, realpathSync, rmSync, rmdirSync, statSync, writeFileSync, } from 'node:fs';
68
+ import { chmodSync, closeSync, constants as fsConstants, existsSync, mkdirSync, openSync, readdirSync, realpathSync, rmSync, rmdirSync, statSync, writeFileSync, writeSync, } from 'node:fs';
69
69
  import path from 'node:path';
70
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';
71
71
  import { MANIFEST_RELATIVE_PATH, manifestPathInsideRepo, readIfExists, readManifest, recordedHookSha, sha256, } from './init-manifest.js';
@@ -546,6 +546,31 @@ function finishPlanWithoutHook(options, root, policyPath, base, actions, writes,
546
546
  adoptedFrom: null,
547
547
  });
548
548
  }
549
+ /** The conflict for a manifest path that resolves outside the repository. */
550
+ function manifestOutsideConflict() {
551
+ return {
552
+ path: MANIFEST_RELATIVE_PATH,
553
+ reason: 'manifest-path-outside-repository',
554
+ guidance: `${MANIFEST_RELATIVE_PATH} resolves outside this repository (it, or .guardrails, is a ` +
555
+ 'symbolic link pointing out of the checkout), so nothing was written. Replace the link ' +
556
+ 'with a real directory or file inside the repository and re-run.',
557
+ };
558
+ }
559
+ /**
560
+ * Writes the manifest without following a symbolic link at its own path:
561
+ * O_NOFOLLOW where the platform has it, so a link swapped in after the
562
+ * containment check is refused by the kernel rather than followed.
563
+ */
564
+ function writeManifestFile(target, body) {
565
+ const noFollow = fsConstants.O_NOFOLLOW ?? 0;
566
+ const fd = openSync(target, fsConstants.O_WRONLY | fsConstants.O_CREAT | fsConstants.O_TRUNC | noFollow, 0o666);
567
+ try {
568
+ writeSync(fd, body);
569
+ }
570
+ finally {
571
+ closeSync(fd);
572
+ }
573
+ }
549
574
  export function applyInit(plan, options) {
550
575
  if (!plan.ok || plan.dryRun || plan.alreadyInstalled) {
551
576
  return plan;
@@ -572,6 +597,11 @@ export function applyInit(plan, options) {
572
597
  // but the adopted record is carried forward from the committed manifest, and
573
598
  // a write that lands outside the repository is a write apply should refuse
574
599
  // whatever produced the path.
600
+ // The manifest's own path first, and before any write at all, so the
601
+ // manifest is written inside the repository or nothing is written.
602
+ if (!manifestPathInsideRepo(plan.repoRoot, path.join(plan.repoRoot, MANIFEST_RELATIVE_PATH))) {
603
+ return { ...plan, ok: false, conflicts: [...plan.conflicts, manifestOutsideConflict()] };
604
+ }
575
605
  const escaping = [
576
606
  ...plan.writes.map((write) => write.path),
577
607
  ...(manifest.adopted === null ? [] : [manifest.adopted.path]),
@@ -627,7 +657,7 @@ export function applyInit(plan, options) {
627
657
  }
628
658
  const manifestPath = path.join(plan.repoRoot, MANIFEST_RELATIVE_PATH);
629
659
  mkdirSync(path.dirname(manifestPath), { recursive: true });
630
- writeFileSync(manifestPath, `${JSON.stringify(manifest, null, 2)}\n`, 'utf8');
660
+ writeManifestFile(manifestPath, `${JSON.stringify(manifest, null, 2)}\n`);
631
661
  }
632
662
  catch (err) {
633
663
  return {
@@ -693,6 +723,13 @@ export function revertInit(options) {
693
723
  return { ok: false, actions, conflicts, dryRun };
694
724
  }
695
725
  const manifestPath = path.join(root, MANIFEST_RELATIVE_PATH);
726
+ // The manifest itself is contained like every path it names: revert
727
+ // rewrites or removes it, and a symlinked .guardrails (or manifest) would
728
+ // land that write outside the repository.
729
+ if (!manifestPathInsideRepo(root, manifestPath)) {
730
+ conflicts.push(manifestOutsideConflict());
731
+ return { ok: false, actions, conflicts, dryRun };
732
+ }
696
733
  const raw = readIfExists(manifestPath);
697
734
  if (raw === undefined) {
698
735
  conflicts.push({
@@ -883,7 +920,7 @@ export function revertInit(options) {
883
920
  }
884
921
  // Something is left, so the manifest stays and keeps describing it.
885
922
  if (!dryRun) {
886
- writeFileSync(manifestPath, `${JSON.stringify({ ...manifest, files: remaining, adopted }, null, 2)}\n`, 'utf8');
923
+ writeManifestFile(manifestPath, `${JSON.stringify({ ...manifest, files: remaining, adopted }, null, 2)}\n`);
887
924
  }
888
925
  actions.push({
889
926
  kind: 'skip',
@@ -1,7 +1,7 @@
1
1
  export interface BaseResolution {
2
2
  ref: string;
3
3
  /** Which input named it, so the report can say. */
4
- source: 'flag' | 'github';
4
+ source: 'flag' | 'github' | 'trust-base';
5
5
  }
6
6
  export type ChangedPaths = {
7
7
  ok: true;
@@ -43,6 +43,8 @@ export type ResolvedBase = {
43
43
  * both in full. The private ref wins and is not compared against the
44
44
  * remote-tracking ref. If neither exists the spelled remote ref is returned and the
45
45
  * diff fails closed, naming fetch-depth: 0.
46
+ * - Otherwise, on a run with a trust base: the commit the trust base
47
+ * resolves to.
46
48
  * - Null outside a pull request.
47
49
  *
48
50
  * Nothing is deepened here: a depth-1 private ref has no merge base and the
@@ -50,6 +52,7 @@ export type ResolvedBase = {
50
52
  */
51
53
  export declare function resolveBaseRefInRepo(repoRoot: string, options: {
52
54
  base?: string;
55
+ trustBase?: string;
53
56
  env: NodeJS.ProcessEnv;
54
57
  }): ResolvedBase;
55
58
  /**
@@ -81,3 +84,34 @@ export declare function currentBranch(repoRoot: string, env: NodeJS.ProcessEnv):
81
84
  * git error, because an empty path set is indistinguishable from a clean run.
82
85
  */
83
86
  export declare function changedPathsSince(repoRoot: string, base: string): ChangedPaths;
87
+ /**
88
+ * Why this change set cannot be handed to intent-guard as one `--paths`
89
+ * value, or null when it can.
90
+ *
91
+ * Asked only where `--paths` is the channel: a contract imported from a spec
92
+ * (its project is a temporary directory with no repository, so the gate
93
+ * cannot read the change set from git itself) or an intent-guard older than
94
+ * the release whose own `--base` reads the change set from git. Where the
95
+ * gate reads git itself, none of this applies and the change is judged.
96
+ *
97
+ * - A comma: `--paths` is comma-joined, so a comma in a filename arrives as
98
+ * two paths, a phantom that can be reported as outside allowed_paths and a
99
+ * real path that quietly stops being measured against a protected one.
100
+ * - A backslash: intent-guard refuses an explicit path list entry with one.
101
+ * - Leading or trailing whitespace: it cannot survive the list intact.
102
+ * - EVERY path starting with "-": intent-guard reads a `--paths` value that
103
+ * starts with "-" as a missing value, and there is no `--paths=value` form
104
+ * (verified against intent-guard 1.8.0: it is an unknown option). One path
105
+ * starting with "-" is fine once another leads the list
106
+ * (`orderForPathsFlag`), so this is refused only when every path does.
107
+ *
108
+ * A space or any other byte inside a path passes through unchanged.
109
+ */
110
+ export declare function pathsFlagRefusal(paths: readonly string[]): string | null;
111
+ /**
112
+ * The change set in the order it is joined for `--paths`: unchanged, except
113
+ * that when the first path starts with "-" the first path that does not is
114
+ * moved to the front, so the joined value does not start with "-". Order
115
+ * carries no meaning to the gate.
116
+ */
117
+ export declare function orderForPathsFlag(paths: readonly string[]): string[];
@@ -7,16 +7,17 @@
7
7
  // branch after this branch forked to this branch, so somebody else's merge
8
8
  // breaches this pull request's change budget.
9
9
  //
10
- // The umbrella computes the path set ITSELF rather than handing intent-guard
11
- // its own `--base`, and that is a deliberate cost. The contract for a run may
12
- // live in a temporary directory (see intent-prepare.ts), and `--base` inside
13
- // the gate resolves git relative to `--project`, where there is no
14
- // repository. Computing the set here and passing `--paths` is the one
15
- // arrangement that works for both the native and the imported contract, and
16
- // the flags below are copied from intent-guard 1.2.1 so the two agree on what
17
- // "changed" means rather than agreeing by coincidence.
18
- import { spawnSync } from 'node:child_process';
19
- import { PRIVATE_TRUST_BASE_REF, exactRefObject, refuseAmbiguousRef } from './trust-base.js';
10
+ // The umbrella computes the path set ITSELF, and how it reaches the gate
11
+ // depends on the contract. An imported contract lives in a temporary
12
+ // directory (see intent-prepare.ts), where the gate's own `--base` would
13
+ // resolve git relative to a `--project` with no repository in it, so that
14
+ // gate is always handed `--paths`. A native contract on an intent-guard new
15
+ // enough to read the change set from git itself is handed the gate's own
16
+ // `--base` instead (`intentChangeChannel` in gate-runner.ts), and `--paths`
17
+ // otherwise. The flags below are copied from intent-guard so the two agree
18
+ // on what "changed" means rather than agreeing by coincidence.
19
+ import { runGit } from './git.js';
20
+ import { PRIVATE_TRUST_BASE_REF, exactRefLookup, exactRefObject, refuseAmbiguousRef, resolveRev, } from './trust-base.js';
20
21
  /**
21
22
  * The ref to diff against, or null for a run that is not a pull request.
22
23
  *
@@ -49,6 +50,8 @@ export function resolveBaseRef(options) {
49
50
  * both in full. The private ref wins and is not compared against the
50
51
  * remote-tracking ref. If neither exists the spelled remote ref is returned and the
51
52
  * diff fails closed, naming fetch-depth: 0.
53
+ * - Otherwise, on a run with a trust base: the commit the trust base
54
+ * resolves to.
52
55
  * - Null outside a pull request.
53
56
  *
54
57
  * Nothing is deepened here: a depth-1 private ref has no merge base and the
@@ -59,7 +62,7 @@ export function resolveBaseRefInRepo(repoRoot, options) {
59
62
  // A base that starts with a dash is an OPTION to git, not a ref:
60
63
  // "--output=/x" made "git diff --output=/x...HEAD" write that file and
61
64
  // print nothing, an empty change set the intent gate then judged as clean.
62
- // Refused here, and changedPathsSince passes --end-of-options as well.
65
+ // Refused here, and changedPathsSince refuses it again itself.
63
66
  if (options.base.startsWith('-')) {
64
67
  return {
65
68
  ok: false,
@@ -84,7 +87,25 @@ export function resolveBaseRefInRepo(repoRoot, options) {
84
87
  }
85
88
  const fromGithub = options.env.GITHUB_BASE_REF;
86
89
  if (fromGithub === undefined || fromGithub === '') {
87
- return { ok: true, base: null };
90
+ if (options.trustBase === undefined) {
91
+ return { ok: true, base: null };
92
+ }
93
+ // No other base was named, so the change set is measured from the trust
94
+ // base: the commit the rules were read from is the one the pull request
95
+ // is judged against. Handed on as the commit id it resolves to, read the
96
+ // same way the trust base itself was (resolveRev never sends a refs/
97
+ // name through git's name resolution).
98
+ const commit = resolveRev(repoRoot, options.trustBase, 'commit');
99
+ if (commit === null) {
100
+ return {
101
+ ok: false,
102
+ detail: `the trust base does not resolve to a commit: "${options.trustBase}" names no commit in ` +
103
+ 'this repository, so there is no base to measure the intent gate against and nothing ' +
104
+ 'was checked. Fix: pass a trust base that is a commit in this checkout (in CI, check out ' +
105
+ 'with fetch-depth: 0).',
106
+ };
107
+ }
108
+ return { ok: true, base: { ref: commit, source: 'trust-base' } };
88
109
  }
89
110
  const remoteRef = `refs/remotes/origin/${fromGithub}`;
90
111
  // The private ref is the authority when it exists; refs/remotes/origin/<base>
@@ -93,16 +114,28 @@ export function resolveBaseRefInRepo(repoRoot, options) {
93
114
  // refusal). It is the base only when the private ref is absent. Both are
94
115
  // read with show-ref (the EXACT ref, never git's name resolution, which
95
116
  // would take a tag of that name) and the base handed on is the commit id.
96
- const priv = exactRefObject(repoRoot, PRIVATE_TRUST_BASE_REF);
97
- const remote = exactRefObject(repoRoot, remoteRef);
117
+ // A private ref git could not read is a refusal, never taken for an absent
118
+ // one; the remote-tracking ref is used only when the private ref is absent.
119
+ const privLookup = exactRefLookup(repoRoot, PRIVATE_TRUST_BASE_REF);
120
+ if (privLookup.kind === 'error') {
121
+ return {
122
+ ok: false,
123
+ detail: `the base branch could not be read: ${privLookup.detail}, so there is no base to measure ` +
124
+ 'the intent gate against and nothing was checked. Fix: check that git can read the ' +
125
+ `repository and that the action's fetch of the base branch into ${PRIVATE_TRUST_BASE_REF} ` +
126
+ 'succeeded, then run again.',
127
+ };
128
+ }
129
+ const priv = privLookup.kind === 'ref' ? privLookup.oid : null;
130
+ const remote = priv === null ? exactRefObject(repoRoot, remoteRef) : null;
98
131
  const chosen = priv ?? remote;
99
132
  if (chosen === null) {
100
133
  return {
101
134
  ok: false,
102
- detail: `neither ${PRIVATE_TRUST_BASE_REF} (the composite action's fetch of the base branch) nor ` +
103
- `${remoteRef} exists in this repository, so there is no base to measure the intent gate ` +
104
- 'against. Nothing was checked. In CI, check out with fetch-depth: 0, or fetch the base ' +
105
- 'ref before the run.',
135
+ detail: `the base branch is not in this repository: neither ${PRIVATE_TRUST_BASE_REF} (the ` +
136
+ `composite action's fetch of the base branch) nor ${remoteRef} exists, so there is no base ` +
137
+ 'to measure the intent gate against and nothing was checked. Fix: in CI, check out with ' +
138
+ 'fetch-depth: 0, or fetch the base ref before the run.',
106
139
  };
107
140
  }
108
141
  return { ok: true, base: { ref: chosen, source: 'github' } };
@@ -120,11 +153,8 @@ export function currentBranch(repoRoot, env) {
120
153
  if (fromGithub !== undefined && fromGithub !== '') {
121
154
  return fromGithub;
122
155
  }
123
- const child = spawnSync('git', ['rev-parse', '--abbrev-ref', 'HEAD'], {
124
- cwd: repoRoot,
125
- encoding: 'utf8',
126
- });
127
- const value = (child.stdout ?? '').trim();
156
+ const child = runGit(repoRoot, ['rev-parse', '--abbrev-ref', 'HEAD']);
157
+ const value = child.stdout.trim();
128
158
  if (child.status !== 0 || value === '' || value === 'HEAD') {
129
159
  return null;
130
160
  }
@@ -150,7 +180,16 @@ export function currentBranch(repoRoot, env) {
150
180
  * git error, because an empty path set is indistinguishable from a clean run.
151
181
  */
152
182
  export function changedPathsSince(repoRoot, base) {
153
- const child = spawnSync('git', [
183
+ // Refused here, inside the function that calls git, so no caller can skip
184
+ // it: "--output=/x...HEAD" is an option to git diff, not a range.
185
+ if (base.startsWith('-')) {
186
+ return {
187
+ ok: false,
188
+ detail: `refusing "${base}" as the intent gate base: it starts with a dash, so git would read it ` +
189
+ 'as an option rather than a ref. Nothing was checked.',
190
+ };
191
+ }
192
+ const child = runGit(repoRoot, [
154
193
  '-c',
155
194
  'core.quotePath=false',
156
195
  'diff',
@@ -160,12 +199,14 @@ export function changedPathsSince(repoRoot, base) {
160
199
  // names no file and which intent-guard refuses outright (backslash).
161
200
  '-z',
162
201
  '--no-renames',
163
- // Everything after this is a revision, never an option, whatever the
164
- // caller-given base looks like (the second line of defence behind the
165
- // dash refusal in resolveBaseRefInRepo).
166
- '--end-of-options',
202
+ // A moved submodule pointer is a change, and is listed whatever
203
+ // .gitmodules or git config says about ignoring submodules: the command
204
+ // line value overrides both.
205
+ '--ignore-submodules=none',
167
206
  `${base}...HEAD`,
168
- ], { cwd: repoRoot, encoding: 'utf8' });
207
+ // Ends the revisions, so the range is always read as a range.
208
+ '--',
209
+ ], { maxBuffer: 64 * 1024 * 1024 });
169
210
  if (child.error !== undefined) {
170
211
  return { ok: false, detail: `git could not be run: ${child.error.message}` };
171
212
  }
@@ -173,57 +214,76 @@ export function changedPathsSince(repoRoot, base) {
173
214
  // git's own first line usually ends in a full stop, and this message
174
215
  // continues after it. Two in a row reads as a typo in a message somebody
175
216
  // is already reading because something went wrong.
176
- const stderr = ((child.stderr ?? '').trim().split('\n')[0] ?? '').replace(/\.+$/, '');
217
+ const stderr = (child.stderr.trim().split('\n')[0] ?? '').replace(/\.+$/, '');
177
218
  return {
178
219
  ok: false,
179
220
  detail: `git could not resolve "${base}...HEAD" (exit ${child.status ?? -1})` +
180
221
  `${stderr === '' ? '' : `: ${stderr}`}. ` +
181
- 'In Actions this is usually a shallow checkout with no merge base; ' +
182
- 'check out with fetch-depth: 0, or fetch the base ref before the run.',
222
+ 'In Actions this is usually a shallow checkout with no merge base. ' +
223
+ 'Fix: check out with fetch-depth: 0, or fetch the base ref before the run.',
183
224
  };
184
225
  }
185
226
  // Split on NUL and NOTHING else. Trimming each entry was corrupting a
186
227
  // filename with leading or trailing whitespace into a different filename,
187
228
  // which is worse than refusing it: the gate would then check a path that
188
229
  // does not exist and never check the one that changed.
189
- const paths = (child.stdout ?? '').split('\0').filter((line) => line.length > 0);
230
+ const paths = child.stdout.split('\0').filter((line) => line.length > 0);
231
+ return { ok: true, paths };
232
+ }
233
+ /**
234
+ * Why this change set cannot be handed to intent-guard as one `--paths`
235
+ * value, or null when it can.
236
+ *
237
+ * Asked only where `--paths` is the channel: a contract imported from a spec
238
+ * (its project is a temporary directory with no repository, so the gate
239
+ * cannot read the change set from git itself) or an intent-guard older than
240
+ * the release whose own `--base` reads the change set from git. Where the
241
+ * gate reads git itself, none of this applies and the change is judged.
242
+ *
243
+ * - A comma: `--paths` is comma-joined, so a comma in a filename arrives as
244
+ * two paths, a phantom that can be reported as outside allowed_paths and a
245
+ * real path that quietly stops being measured against a protected one.
246
+ * - A backslash: intent-guard refuses an explicit path list entry with one.
247
+ * - Leading or trailing whitespace: it cannot survive the list intact.
248
+ * - EVERY path starting with "-": intent-guard reads a `--paths` value that
249
+ * starts with "-" as a missing value, and there is no `--paths=value` form
250
+ * (verified against intent-guard 1.8.0: it is an unknown option). One path
251
+ * starting with "-" is fine once another leads the list
252
+ * (`orderForPathsFlag`), so this is refused only when every path does.
253
+ *
254
+ * A space or any other byte inside a path passes through unchanged.
255
+ */
256
+ export function pathsFlagRefusal(paths) {
190
257
  for (const entry of paths) {
191
- // Fail closed rather than hand over a path the encoding cannot carry.
192
- // `--paths` is comma-joined, which is the only shape intent-guard 1.2.1
193
- // accepts, so a comma in a filename arrives as two paths: a phantom that
194
- // can be reported as outside allowed_paths, and a real path that quietly
195
- // stops being measured against a protected one. It invents a breach and
196
- // hides one, and neither half is visible in the report.
197
258
  if (entry.includes(',')) {
198
- return {
199
- ok: false,
200
- detail: `the changed path "${entry}" contains a comma, and the intent gate takes its ` +
201
- 'path list comma-joined, so it cannot be passed without splitting into two paths. ' +
202
- 'Nothing was checked, rather than checking a path that does not exist.',
203
- };
259
+ return (`the changed path "${entry}" contains a comma, and intent-guard takes an explicit path ` +
260
+ 'list comma-joined, so it cannot be passed without splitting into two paths.');
204
261
  }
205
- // intent-guard refuses ANY explicit --paths entry containing a backslash
206
- // (skill/src/changed-paths.ts, explicitPathIssue: "it contains a
207
- // backslash"), and exits 2 with a message that names the flag rather than
208
- // the file. Said here instead, naming the file. A newline, tab or quote
209
- // inside a path is accepted by intent-guard (it splits on commas only) and
210
- // passes through intact.
211
262
  if (entry.includes('\\')) {
212
- return {
213
- ok: false,
214
- detail: `the changed path "${entry}" contains a backslash, and intent-guard refuses an explicit ` +
215
- 'path list entry with one (--paths), so it cannot judge this change. Nothing was ' +
216
- 'checked. Rename the file, or run the intent gate against the index instead.',
217
- };
263
+ return (`the changed path "${entry}" contains a backslash, and intent-guard refuses an explicit ` +
264
+ 'path list entry with one.');
218
265
  }
219
266
  if (entry !== entry.trim()) {
220
- return {
221
- ok: false,
222
- detail: `the changed path "${entry}" has leading or trailing whitespace, which cannot ` +
223
- 'survive the gate path list intact. Nothing was checked, rather than checking a ' +
224
- 'path that does not exist. A space inside a path is fine.',
225
- };
267
+ return (`the changed path "${entry}" has leading or trailing whitespace, which cannot survive ` +
268
+ 'the path list intact. A space inside a path is fine.');
226
269
  }
227
270
  }
228
- return { ok: true, paths };
271
+ if (paths.length > 0 && paths.every((entry) => entry.startsWith('-'))) {
272
+ return (`every changed path starts with "-" (the first is "${paths[0]}"), and intent-guard reads ` +
273
+ 'a path list that starts with "-" as a missing value.');
274
+ }
275
+ return null;
276
+ }
277
+ /**
278
+ * The change set in the order it is joined for `--paths`: unchanged, except
279
+ * that when the first path starts with "-" the first path that does not is
280
+ * moved to the front, so the joined value does not start with "-". Order
281
+ * carries no meaning to the gate.
282
+ */
283
+ export function orderForPathsFlag(paths) {
284
+ const lead = paths.findIndex((entry) => !entry.startsWith('-'));
285
+ if (paths.length === 0 || !paths[0].startsWith('-') || lead === -1) {
286
+ return [...paths];
287
+ }
288
+ return [paths[lead], ...paths.slice(0, lead), ...paths.slice(lead + 1)];
229
289
  }