@gate-forge/cli 0.9.0 → 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.
Files changed (93) hide show
  1. package/README.md +12 -5
  2. package/dist/cache-exclusions.d.ts +20 -13
  3. package/dist/cache-exclusions.d.ts.map +1 -1
  4. package/dist/cache-exclusions.js +47 -33
  5. package/dist/cache-exclusions.js.map +1 -1
  6. package/dist/cli.d.ts +1 -1
  7. package/dist/cli.d.ts.map +1 -1
  8. package/dist/cli.js +11 -0
  9. package/dist/cli.js.map +1 -1
  10. package/dist/commands/adopt.d.ts +3 -2
  11. package/dist/commands/adopt.d.ts.map +1 -1
  12. package/dist/commands/adopt.js +38 -5
  13. package/dist/commands/adopt.js.map +1 -1
  14. package/dist/commands/blocking.d.ts +20 -1
  15. package/dist/commands/blocking.d.ts.map +1 -1
  16. package/dist/commands/blocking.js +105 -10
  17. package/dist/commands/blocking.js.map +1 -1
  18. package/dist/commands/check.d.ts +34 -0
  19. package/dist/commands/check.d.ts.map +1 -1
  20. package/dist/commands/check.js +93 -7
  21. package/dist/commands/check.js.map +1 -1
  22. package/dist/commands/classify.d.ts +1 -0
  23. package/dist/commands/classify.d.ts.map +1 -1
  24. package/dist/commands/classify.js +230 -14
  25. package/dist/commands/classify.js.map +1 -1
  26. package/dist/commands/common.d.ts +6 -1
  27. package/dist/commands/common.d.ts.map +1 -1
  28. package/dist/commands/common.js +8 -1
  29. package/dist/commands/common.js.map +1 -1
  30. package/dist/commands/enforcement.d.ts +9 -1
  31. package/dist/commands/enforcement.d.ts.map +1 -1
  32. package/dist/commands/enforcement.js +448 -13
  33. package/dist/commands/enforcement.js.map +1 -1
  34. package/dist/commands/init.d.ts +20 -0
  35. package/dist/commands/init.d.ts.map +1 -1
  36. package/dist/commands/init.js +296 -93
  37. package/dist/commands/init.js.map +1 -1
  38. package/dist/commands/migrate.d.ts +14 -0
  39. package/dist/commands/migrate.d.ts.map +1 -0
  40. package/dist/commands/migrate.js +177 -0
  41. package/dist/commands/migrate.js.map +1 -0
  42. package/dist/commands/next.d.ts.map +1 -1
  43. package/dist/commands/next.js +7 -2
  44. package/dist/commands/next.js.map +1 -1
  45. package/dist/commands/pre-commit.d.ts.map +1 -1
  46. package/dist/commands/pre-commit.js +62 -19
  47. package/dist/commands/pre-commit.js.map +1 -1
  48. package/dist/commands/tests.d.ts.map +1 -1
  49. package/dist/commands/tests.js +54 -24
  50. package/dist/commands/tests.js.map +1 -1
  51. package/dist/docs-exclusions.d.ts +32 -5
  52. package/dist/docs-exclusions.d.ts.map +1 -1
  53. package/dist/docs-exclusions.js +60 -26
  54. package/dist/docs-exclusions.js.map +1 -1
  55. package/dist/evidence-config-text.d.ts +57 -0
  56. package/dist/evidence-config-text.d.ts.map +1 -0
  57. package/dist/evidence-config-text.js +263 -0
  58. package/dist/evidence-config-text.js.map +1 -0
  59. package/dist/execution.d.ts +51 -8
  60. package/dist/execution.d.ts.map +1 -1
  61. package/dist/execution.js +61 -29
  62. package/dist/execution.js.map +1 -1
  63. package/dist/gateforge-owned.d.ts +30 -5
  64. package/dist/gateforge-owned.d.ts.map +1 -1
  65. package/dist/gateforge-owned.js +136 -18
  66. package/dist/gateforge-owned.js.map +1 -1
  67. package/dist/git-hooks.d.ts.map +1 -1
  68. package/dist/git-hooks.js +15 -0
  69. package/dist/git-hooks.js.map +1 -1
  70. package/dist/input-snapshot.d.ts.map +1 -1
  71. package/dist/input-snapshot.js +2 -6
  72. package/dist/input-snapshot.js.map +1 -1
  73. package/dist/legacy-exclusion-paths.d.ts +28 -0
  74. package/dist/legacy-exclusion-paths.d.ts.map +1 -0
  75. package/dist/legacy-exclusion-paths.js +48 -0
  76. package/dist/legacy-exclusion-paths.js.map +1 -0
  77. package/dist/providers.d.ts +54 -0
  78. package/dist/providers.d.ts.map +1 -1
  79. package/dist/providers.js +101 -0
  80. package/dist/providers.js.map +1 -1
  81. package/dist/staged-candidate.d.ts.map +1 -1
  82. package/dist/staged-candidate.js +2 -1
  83. package/dist/staged-candidate.js.map +1 -1
  84. package/dist/trusted-policy.d.ts.map +1 -1
  85. package/dist/trusted-policy.js +3 -2
  86. package/dist/trusted-policy.js.map +1 -1
  87. package/guides/CONNECT-YOUR-PROJECT.md +64 -0
  88. package/guides/QUICKSTART.md +68 -15
  89. package/guides/REFERENCE.md +229 -33
  90. package/guides/TEST-ENVIRONMENT.md +36 -0
  91. package/guides/UPGRADE-0.8-to-0.9.md +9 -1
  92. package/guides/UPGRADE-0.9-to-0.10.md +137 -0
  93. package/package.json +10 -10
@@ -20,30 +20,43 @@
20
20
  * operator-provided probe says otherwise.
21
21
  */
22
22
  import { createHash } from 'node:crypto';
23
- import { accessSync, constants as fsConstants, cpSync, existsSync, lstatSync, mkdirSync, mkdtempSync, readFileSync, readlinkSync, readdirSync, rmSync, } from 'node:fs';
23
+ import { accessSync, chmodSync, constants as fsConstants, cpSync, existsSync, lstatSync, mkdirSync, mkdtempSync, readFileSync, readlinkSync, readdirSync, rmSync, writeFileSync, } from 'node:fs';
24
24
  import { spawnSync } from 'node:child_process';
25
25
  import { homedir, tmpdir } from 'node:os';
26
- import { dirname, join, relative, resolve, sep } from 'node:path';
27
- import { BehaviorPolicySchema } from '@gate-forge/core';
26
+ import { dirname, isAbsolute, join, relative, resolve, sep } from 'node:path';
27
+ import { BehaviorPolicySchema, QUARANTINE_DIR, trustedPolicyDigest } from '@gate-forge/core';
28
28
  import { parse as parseYaml } from 'yaml';
29
29
  import { auditAdapters } from '../adapter-audit.js';
30
+ import { normalizeRepoModule } from '../input-snapshot.js';
30
31
  import { allCapabilities, canonicalJson, policyWeakenedCandidate, resolveStrictnessMode, } from '@gate-forge/core';
31
32
  import { parseArgs } from '../args.js';
32
- import { trustedPolicyDigestForConfig } from '../execution.js';
33
+ import { trustedPolicyDigestEntriesForConfig, trustedPolicyDigestForConfig, } from '../execution.js';
33
34
  import { UsageError } from '../errors.js';
34
35
  import { writeLine } from '../io.js';
35
36
  import { findRunnerConfigPath, TEST_MAP_RELATIVE } from '../mapping.js';
36
37
  import { inspectCommitHook, isFrameworkManagedHookBody } from '../git-hooks.js';
38
+ import { StagedCandidateBlockError, freezeStagedCandidate, materializeStagedCandidate, releaseStagedCandidate, } from '../staged-candidate.js';
37
39
  import { loadConfigAt, rejectUnknownFlags } from './common.js';
38
40
  import { resolveStateDir } from '../state.js';
39
41
  import { resolveVerifierKeyring } from '../verifier-keys.js';
40
- import { describeApprovedPolicyResolution, resolveApprovedPolicyDigest } from '../trusted-policy.js';
42
+ import { APPROVED_POLICY_DIGEST_ENV, TRUSTED_CONFIG_ENV, describeApprovedPolicyResolution, resolveApprovedPolicyDigest, } from '../trusted-policy.js';
41
43
  import { engineIdentity, engineInstallProvenance, enginePackageRoot, engineSourceLine, } from '../engine-identity.js';
42
44
  import { buildRunPreflight, findRunnerManifest, firstFailingCheck } from '../run-preflight.js';
43
- import { findPlaywrightConfig } from '@gate-forge/pack-playwright';
45
+ import { declaresNoNamedProject, findPlaywrightConfig, listNativePlaywrightTests, unnamedProjectConfigWarning, } from '@gate-forge/pack-playwright';
44
46
  import { browserBuildSummary, browserLaunchSummary, defaultBrowsersPath, inspectBrowserBuilds, unlaunchableBuilds, } from '../playwright-browsers.js';
45
47
  import { engineBrowserRequirement, engineBrowserSummary, inspectEngineBrowserBuilds, resolveEngineBrowserInstall, } from '../engine-browser.js';
46
- export const ENFORCEMENT_USAGE = 'usage: gateforge enforcement doctor [--json] [--strict-preflight]';
48
+ export const ENFORCEMENT_USAGE = 'usage: gateforge enforcement doctor [--json] [--strict-preflight]\n' +
49
+ ' gateforge enforcement pin --pin-file <path> [--confirm]';
50
+ /**
51
+ * The `enforcement pin` usage line. The flag is `--pin-file`, NOT
52
+ * `--env-file`: Node parses `--env-file <path>` (and
53
+ * `--env-file-if-exists <path>`) out of argv itself, even after the script
54
+ * path — it would read the file (exit 9 on a missing one) and never reach
55
+ * the CLI. A flag Node owns cannot carry the pin.
56
+ */
57
+ export const ENFORCEMENT_PIN_USAGE = 'usage: gateforge enforcement pin --pin-file <path> [--confirm]';
58
+ /** Matches an existing approved-policy digest assignment in any shell form. */
59
+ const PIN_ASSIGNMENT = /^\s*(?:export\s+)?GATEFORGE_APPROVED_POLICY_DIGEST\s*=/;
47
60
  /**
48
61
  * Runs `git` with NUL/UTF-8 output; null on any failure (a doctor check
49
62
  * reports the failure class, it never throws).
@@ -54,6 +67,157 @@ function probe(cwd, env, args) {
54
67
  return null;
55
68
  return (result.stdout ?? '').trim();
56
69
  }
70
+ /**
71
+ * The trusted policy inputs the commit gate digests — the same
72
+ * documents `trustedPolicyDigestForConfig` hashes: the config,
73
+ * the policy/classification/behavior/runtime documents, the
74
+ * owner exclusion declarations, the mapping sidecar, the
75
+ * adapters and waivers directories, the quarantine directory,
76
+ * and every repo-relative in-process plugin module. Directories
77
+ * are named whole: `git status` reports every changed file
78
+ * below them.
79
+ *
80
+ * Args:
81
+ * cwd: absolute repository root.
82
+ * config: the loaded gateforge config.
83
+ *
84
+ * Returns:
85
+ * string[]: deduplicated repo-relative posix paths.
86
+ */
87
+ function policyInputPaths(cwd, config) {
88
+ const paths = new Set([
89
+ '.gateforge.yml',
90
+ config.policies,
91
+ config.classificationPolicy,
92
+ TEST_MAP_RELATIVE,
93
+ config.adapters,
94
+ config.waivers,
95
+ QUARANTINE_DIR,
96
+ ]);
97
+ if (config.behaviorPolicy !== undefined)
98
+ paths.add(config.behaviorPolicy);
99
+ if (config.runtime !== undefined)
100
+ paths.add(config.runtime);
101
+ for (const plugin of config.plugins) {
102
+ const module = plugin.module;
103
+ if (typeof module !== 'string')
104
+ continue;
105
+ if (!module.startsWith('./') && !module.startsWith('../'))
106
+ continue;
107
+ const normalized = normalizeRepoModule(module);
108
+ if (normalized !== null)
109
+ paths.add(normalized);
110
+ }
111
+ return [...paths];
112
+ }
113
+ /**
114
+ * One `git status --porcelain` line → its path (a rename keeps
115
+ * the NEW name; the two status letters are dropped).
116
+ */
117
+ function porcelainPath(line) {
118
+ const rest = line.slice(2);
119
+ const arrow = rest.indexOf(' -> ');
120
+ return (arrow >= 0 ? rest.slice(0, arrow) : rest).trim();
121
+ }
122
+ /**
123
+ * Joins path names for a diagnostic line: at most five, then a count.
124
+ * One shape for every path list the enforcement surfaces print, so a
125
+ * long list never turns a one-line diagnosis into a wall of text.
126
+ */
127
+ function boundedList(paths) {
128
+ const shown = paths.slice(0, 5).join(', ');
129
+ return `${shown}${paths.length > 5 ? ` and ${String(paths.length - 5)} more` : ''}`;
130
+ }
131
+ /**
132
+ * The trusted policy inputs whose STAGED bytes differ from the working
133
+ * tree (staged≠HEAD edits, unstaged edits and untracked inputs). null
134
+ * when Git cannot answer (no usable inventory).
135
+ */
136
+ function unstagedPolicyInputs(io, config) {
137
+ const result = spawnSync('git', ['status', '--porcelain', '--untracked-files=all', '--', ...policyInputPaths(io.cwd, config)], { cwd: io.cwd, env: io.env, encoding: 'utf8' });
138
+ if (result.error !== undefined || result.status !== 0)
139
+ return null;
140
+ // The RAW stdout, not `probe`: it trims, which would eat the leading
141
+ // status column of the first line and hide an unstaged policy input.
142
+ return result.stdout
143
+ .split('\n')
144
+ .filter((line) => line.length > 1 && line[1] !== ' ')
145
+ .map((line) => porcelainPath(line));
146
+ }
147
+ /** One document's bytes at a revision, or null when it is absent there. */
148
+ function revisionBytes(cwd, env, revision, path) {
149
+ const result = spawnSync('git', ['show', `${revision}:${path}`], { cwd, env, encoding: 'utf8' });
150
+ if (result.error !== undefined || result.status !== 0)
151
+ return null;
152
+ return result.stdout ?? '';
153
+ }
154
+ /**
155
+ * Computes the trusted policy state of the STAGED candidate through the
156
+ * REAL staged path: the index is frozen, the frozen tree is materialized
157
+ * into an isolated scratch checkout, and the digest is computed from the
158
+ * entry list of THAT checkout — the same functions, over the same bytes,
159
+ * `check --staged` runs. Each entry is then compared with its HEAD
160
+ * revision (presence AND bytes) so the surfaces can NAME the inputs that
161
+ * moved; a whitespace-only edit counts, because it moves the digest too.
162
+ */
163
+ function stagedPolicyState(io) {
164
+ // Nothing staged means there is no candidate to digest: say so with a
165
+ // stable message (a scratch-directory path would make the report move
166
+ // between two runs of an unchanged repository).
167
+ const staged = probe(io.cwd, io.env, ['ls-files', '--stage', '-z']);
168
+ if (staged === null || staged.length === 0) {
169
+ throw new UsageError('the staged index is empty — stage the policy inputs (git add) to evaluate them');
170
+ }
171
+ const frozen = freezeStagedCandidate(io.cwd, io.env);
172
+ try {
173
+ const checkoutDir = materializeStagedCandidate(io.cwd, io.env, frozen);
174
+ const checkoutConfig = loadConfigAt(checkoutDir);
175
+ const entries = trustedPolicyDigestEntriesForConfig(checkoutDir, checkoutConfig);
176
+ const changedSinceHead = entries.flatMap((entry) => {
177
+ if (entry.path === null)
178
+ return [];
179
+ // An optional input that is absent in BOTH revisions is unchanged:
180
+ // compare presence first, bytes second (an absent entry hashes as
181
+ // empty bytes, exactly like an empty file would).
182
+ const stagedPresent = existsSync(join(checkoutDir, ...entry.path.split('/')));
183
+ const atHead = frozen.headSha === null ? null : revisionBytes(io.cwd, io.env, frozen.headSha, entry.path);
184
+ const unchanged = atHead === null ? !stagedPresent : stagedPresent && atHead === entry.bytes;
185
+ return unchanged ? [] : [entry.name];
186
+ });
187
+ return { digest: trustedPolicyDigest(entries), changedSinceHead, headSha: frozen.headSha };
188
+ }
189
+ finally {
190
+ releaseStagedCandidate(frozen);
191
+ }
192
+ }
193
+ /**
194
+ * Rewrites the approved-policy digest line of an env file: the first
195
+ * assignment is replaced, a duplicate assignment is dropped (two pins in
196
+ * one file would make it ambiguous), and the line is appended when the
197
+ * file has none. Every other line is preserved verbatim.
198
+ */
199
+ function pinnedEnvBody(body, line) {
200
+ const lines = body.split('\n');
201
+ if (lines.length > 0 && lines[lines.length - 1] === '')
202
+ lines.pop();
203
+ const kept = [];
204
+ let replaced = false;
205
+ for (const existing of lines) {
206
+ if (!PIN_ASSIGNMENT.test(existing)) {
207
+ kept.push(existing);
208
+ }
209
+ else if (!replaced) {
210
+ replaced = true;
211
+ kept.push(line);
212
+ }
213
+ }
214
+ if (!replaced) {
215
+ if (kept.length > 0)
216
+ kept.push('');
217
+ kept.push(line);
218
+ }
219
+ return `${kept.join('\n')}\n`;
220
+ }
57
221
  /**
58
222
  * Hashes the files the input snapshot would see (tracked + untracked non-ignored).
59
223
  *
@@ -792,6 +956,55 @@ function probeGitLabProtection(io) {
792
956
  return { verified: false, detail: 'server protection: not verified (GitLab returned an unreadable protection response)' };
793
957
  }
794
958
  }
959
+ /**
960
+ * The playwright config's project naming, as the native
961
+ * enumeration read it (the config is untrusted code — only
962
+ * the runner can say which projects it declares). Test-gates
963
+ * join catalog rows to planned projects by name, so a config
964
+ * that declares no named project breaks the join (R1-5).
965
+ *
966
+ * Args:
967
+ * cwd: absolute repo root.
968
+ *
969
+ * Returns:
970
+ * Promise<{ status, detail }>: the playwright-projects doctor result.
971
+ */
972
+ async function playwrightProjectNaming(cwd) {
973
+ let nativeList;
974
+ try {
975
+ nativeList = await listNativePlaywrightTests({ cwd });
976
+ }
977
+ catch (error) {
978
+ return {
979
+ status: 'warn',
980
+ detail: `playwright project naming could not be checked: ${error.message.split('\n')[0] ?? 'unknown'}`,
981
+ };
982
+ }
983
+ const configPath = findPlaywrightConfig(cwd);
984
+ const configLabel = configPath ?? '(unknown playwright config)';
985
+ if (nativeList.status === 'unavailable') {
986
+ return {
987
+ status: 'ok',
988
+ detail: 'no playwright config — not an error for non-playwright repos',
989
+ };
990
+ }
991
+ if (declaresNoNamedProject(nativeList.projectNames)) {
992
+ return { status: 'fail', detail: unnamedProjectConfigWarning(configLabel) };
993
+ }
994
+ if (nativeList.projectNames === undefined) {
995
+ return {
996
+ status: 'ok',
997
+ detail: `playwright config '${configLabel}' ran, but this playwright version reports no project names`,
998
+ };
999
+ }
1000
+ const named = nativeList.projectNames
1001
+ .filter((name) => name.length > 0)
1002
+ .sort();
1003
+ return {
1004
+ status: 'ok',
1005
+ detail: `playwright config '${configLabel}' declares named project(s): ${named.join(', ')}`,
1006
+ };
1007
+ }
795
1008
  /**
796
1009
  * Builds the doctor report (all checks, honest statuses).
797
1010
  *
@@ -858,14 +1071,25 @@ export async function buildDoctorReport(io) {
858
1071
  // "did not touch" contradicted what `init` had just said about the
859
1072
  // very same file.
860
1073
  const frameworkGate = frameworkHookGateWired(io.cwd, hook.hookPath);
1074
+ // R1-7: the framework config declares our hook, but no
1075
+ // framework-GENERATED hook exists in the hooks directory
1076
+ // yet — the commit gate is NOT active until the framework
1077
+ // installs its hook (`pre-commit install`), so the row
1078
+ // fails instead of all-clearing.
1079
+ const frameworkConfigPending = !frameworkGate &&
1080
+ !hook.verifyOk &&
1081
+ declaresGateforgeCheck(join(io.cwd, '.pre-commit-config.yaml'));
861
1082
  checks.push({
862
1083
  id: 'hook',
863
- status: frameworkGate || hook.verifyOk ? 'ok' : hook.marker ? 'fail' : 'warn',
1084
+ status: frameworkGate || hook.verifyOk ? 'ok' : frameworkConfigPending ? 'fail' : hook.marker ? 'fail' : 'warn',
864
1085
  detail: frameworkGate
865
1086
  ? `the commit gate runs through the pre-commit framework: ${hook.hookPath} is framework-generated ` +
866
1087
  'and .pre-commit-config.yaml declares gateforge-check, which runs on every commit — gateforge does not ' +
867
1088
  'edit the generated hook file (a direct edit is wiped by the next framework install)'
868
- : hook.detail,
1089
+ : frameworkConfigPending
1090
+ ? `the commit gate is NOT active: .pre-commit-config.yaml declares gateforge-check but no framework-generated ` +
1091
+ `hook exists in '${hook.hooksDir ?? 'the hooks directory'}' — run \`pre-commit install\` to activate the gate`
1092
+ : hook.detail,
869
1093
  });
870
1094
  const hookMutation = precommitMutationCheck(io.cwd, io.env);
871
1095
  checks.push({ id: 'hook-mutation', ...hookMutation });
@@ -914,6 +1138,11 @@ export async function buildDoctorReport(io) {
914
1138
  detail: 'engine browser readiness was not checked: .gateforge.yml could not be loaded, so no engine-browser requirement is known',
915
1139
  }),
916
1140
  });
1141
+ // 2c. The playwright config's project naming (R1-5): the
1142
+ // enumeration's own answer, so a config with no named
1143
+ // project — which breaks the per-project identity join
1144
+ // test-gates depend on — is a FAILING row with the fix.
1145
+ checks.push({ id: 'playwright-projects', ...(await playwrightProjectNaming(io.cwd)) });
917
1146
  // 3. Observer capability (Phase 0 capability registry; witness probe
918
1147
  // only when the caller wired GATEFORGE_WITNESS_URL).
919
1148
  const capabilities = allCapabilities();
@@ -1046,9 +1275,17 @@ export async function buildDoctorReport(io) {
1046
1275
  ? ' — MISMATCHES the candidate policy revision (strict gates will block)'
1047
1276
  : ' — matches the candidate policy revision';
1048
1277
  }
1278
+ // R1-13: the FULL 64-hex digest (never a prefix) — the owner
1279
+ // copies it into the protected pin verbatim. An absent or
1280
+ // mismatched pin gets the exact owner action line.
1281
+ const pinMatches = resolution.status === 'ok' && resolution.digest !== null && resolution.digest === digest;
1282
+ const pinAction = pinMatches
1283
+ ? ''
1284
+ : `\nowner: pin this revision with ${APPROVED_POLICY_DIGEST_ENV}=${digest} ` +
1285
+ `(protected env, CI variable, or ${TRUSTED_CONFIG_ENV} outside the repo)`;
1049
1286
  policyDetail =
1050
- `trusted policy digest present (${digest.slice(0, 12)}…); gateforge binary: ${binaryPath} (${binaryOrigin}); ` +
1051
- `${describeApprovedPolicyResolution(resolution)}${matchNote}`;
1287
+ `trusted policy digest present (${digest}); gateforge binary: ${binaryPath} (${binaryOrigin}); ` +
1288
+ `${describeApprovedPolicyResolution(resolution)}${matchNote}${pinAction}`;
1052
1289
  policyStatus = 'ok';
1053
1290
  }
1054
1291
  catch (error) {
@@ -1057,6 +1294,111 @@ export async function buildDoctorReport(io) {
1057
1294
  }
1058
1295
  }
1059
1296
  checks.push({ id: 'trusted-binary-policy', status: policyStatus, detail: policyDetail });
1297
+ // 4b. Staged policy inputs. The commit gate digests the STAGED
1298
+ // bytes of the trusted policy inputs while the digest printed
1299
+ // above is computed from the WORKING TREE — an unstaged edit or
1300
+ // an untracked policy input makes the value the owner pins
1301
+ // wrong without any warning, so the doctor compares the two
1302
+ // trees over exactly the digested inputs.
1303
+ let policyStagedStatus;
1304
+ let policyStagedDetail;
1305
+ if (!configOk) {
1306
+ policyStagedStatus = 'warn';
1307
+ policyStagedDetail = 'policy input staging state not evaluated (config failed to load)';
1308
+ }
1309
+ else {
1310
+ const changed = unstagedPolicyInputs(io, loadConfigAt(io.cwd));
1311
+ if (changed === null) {
1312
+ policyStagedStatus = 'warn';
1313
+ policyStagedDetail = 'policy input staging state unknown (no usable Git inventory)';
1314
+ }
1315
+ else if (changed.length === 0) {
1316
+ policyStagedStatus = 'ok';
1317
+ policyStagedDetail = 'policy inputs are fully staged';
1318
+ }
1319
+ else {
1320
+ policyStagedStatus = 'warn';
1321
+ policyStagedDetail =
1322
+ `policy inputs differ between the staged index and the working tree: ${boundedList(changed)} — ` +
1323
+ 'the commit gate digests the STAGED bytes; stage them (git add) before pinning the digest printed here';
1324
+ }
1325
+ }
1326
+ checks.push({ id: 'policy-inputs-staged', status: policyStagedStatus, detail: policyStagedDetail });
1327
+ // 4c/4d. WHICH inputs moved, and does the provisioned pin still match
1328
+ // what the commit gate will digest (plan 2026-10-04 W2): the pin is a
1329
+ // single aggregate hash, so a mismatch alone never said WHICH input
1330
+ // moved. Both rows read the same staged policy state — the entry list
1331
+ // the digest is computed from — so the named inputs and the digest
1332
+ // can never disagree.
1333
+ let stagedPolicy = null;
1334
+ let stagedPolicyError = '';
1335
+ try {
1336
+ stagedPolicy = stagedPolicyState(io);
1337
+ }
1338
+ catch (error) {
1339
+ stagedPolicyError = error.message.split('\n')[0] ?? 'unknown error';
1340
+ }
1341
+ let driftStatus;
1342
+ let driftDetail;
1343
+ if (stagedPolicy === null) {
1344
+ driftStatus = 'warn';
1345
+ driftDetail = `staged policy inputs not evaluated (${stagedPolicyError})`;
1346
+ }
1347
+ else if (stagedPolicy.changedSinceHead.length === 0) {
1348
+ driftStatus = 'ok';
1349
+ driftDetail = 'no trusted policy input changed since HEAD';
1350
+ }
1351
+ else if (stagedPolicy.headSha === null) {
1352
+ driftStatus = 'warn';
1353
+ driftDetail =
1354
+ `no HEAD commit yet — every policy input is new in this first commit: ${boundedList(stagedPolicy.changedSinceHead)} — ` +
1355
+ 're-pin once the revision is committed';
1356
+ }
1357
+ else {
1358
+ driftStatus = 'warn';
1359
+ driftDetail =
1360
+ `policy inputs changed since HEAD: ${boundedList(stagedPolicy.changedSinceHead)} — ` +
1361
+ 'the commit gate digests the STAGED bytes, so the approved digest has to be re-pinned for them ' +
1362
+ '(gateforge enforcement pin --pin-file <path> outside the repo)';
1363
+ }
1364
+ checks.push({ id: 'policy-inputs-vs-HEAD', status: driftStatus, detail: driftDetail });
1365
+ let approvedStatus;
1366
+ let approvedDetail;
1367
+ if (!configOk || stagedPolicy === null) {
1368
+ approvedStatus = 'warn';
1369
+ approvedDetail = 'approved policy digest not compared against the staged inputs (they are unavailable)';
1370
+ }
1371
+ else {
1372
+ const resolution = resolveApprovedPolicyDigest({
1373
+ env: io.env,
1374
+ candidateCwd: io.cwd,
1375
+ candidateConfig: loadConfigAt(io.cwd),
1376
+ });
1377
+ if (resolution.status !== 'ok') {
1378
+ approvedStatus = 'warn';
1379
+ approvedDetail = `approved policy digest: not usable — ${resolution.detail}`;
1380
+ }
1381
+ else if (resolution.digest === null) {
1382
+ approvedStatus = 'warn';
1383
+ approvedDetail =
1384
+ `approved policy digest: absent — provision it outside the candidate (${APPROVED_POLICY_DIGEST_ENV}, ` +
1385
+ 'or gateforge enforcement pin --pin-file <path>)';
1386
+ }
1387
+ else if (resolution.digest === stagedPolicy.digest) {
1388
+ approvedStatus = 'ok';
1389
+ approvedDetail = `approved policy digest: matches staged (${resolution.digest})`;
1390
+ }
1391
+ else {
1392
+ approvedStatus = 'warn';
1393
+ const cause = stagedPolicy.changedSinceHead.length === 0
1394
+ ? 'no policy input changed in the staged index — the pin predates an already committed policy change'
1395
+ : `changed inputs: ${boundedList(stagedPolicy.changedSinceHead)}`;
1396
+ approvedDetail =
1397
+ `approved policy digest: does NOT match staged (${cause}) — ` +
1398
+ 're-pin with gateforge enforcement pin --pin-file <path> outside the repo';
1399
+ }
1400
+ }
1401
+ checks.push({ id: 'approved-digest', status: approvedStatus, detail: approvedDetail });
1060
1402
  // 5. Snapshot mode (inventory availability decides evidence binding).
1061
1403
  const inventory = probe(io.cwd, io.env, ['ls-files', '--stage', '-z']);
1062
1404
  checks.push({
@@ -1134,8 +1476,15 @@ export async function buildDoctorReport(io) {
1134
1476
  export async function enforcementCommand(io, argv) {
1135
1477
  const { options, positionals } = parseArgs(argv);
1136
1478
  const sub = positionals[0];
1137
- if (sub === undefined || sub !== 'doctor') {
1138
- throw new UsageError(`unknown enforcement subcommand '${sub ?? '(none)'}' (only 'doctor' exists)`);
1479
+ if (sub === 'pin') {
1480
+ if (options['help'] === true) {
1481
+ writeLine(io.stdout, ENFORCEMENT_PIN_USAGE);
1482
+ return 0;
1483
+ }
1484
+ return enforcementPinCommand(io, options, positionals.slice(1));
1485
+ }
1486
+ if (sub !== 'doctor') {
1487
+ throw new UsageError(`unknown enforcement subcommand '${sub ?? '(none)'}' (only 'doctor' and 'pin' exist)`);
1139
1488
  }
1140
1489
  if (options['help'] === true) {
1141
1490
  writeLine(io.stdout, ENFORCEMENT_USAGE);
@@ -1170,6 +1519,92 @@ export async function enforcementCommand(io, argv) {
1170
1519
  writeLine(io.stdout, `run preconditions: ${report.run.ready ? 'ready' : 'NOT ready (failing preconditions above)'} — report-only; exit 0 unless --strict-preflight`);
1171
1520
  return strictExit(io, report.run, options['strict-preflight'] === true, 'text');
1172
1521
  }
1522
+ /**
1523
+ * Runs `gateforge enforcement pin --pin-file <path> [--confirm]`: writes
1524
+ * the approved policy digest of the STAGED candidate into an env file
1525
+ * OUTSIDE the repository. The digest is the one the commit gate computes
1526
+ * (`check --staged` over the same frozen index), so the pin can never
1527
+ * approve a revision the gate never digests. Preview by default;
1528
+ * `--confirm` replaces exactly the
1529
+ * `GATEFORGE_APPROVED_POLICY_DIGEST=<hex>` line, mode 0600, and never
1530
+ * writes anywhere inside the candidate — the trust property of the pin.
1531
+ *
1532
+ * Args:
1533
+ * io: process context (cwd = the user's repository).
1534
+ * options: parsed flags after `enforcement pin`.
1535
+ * positionals: anything after the subcommand (usage error when present).
1536
+ *
1537
+ * Returns:
1538
+ * Promise<number>: 0 when the pin was written (or previewed).
1539
+ *
1540
+ * Throws:
1541
+ * UsageError: on a missing/in-repo env file, a policy input that is not
1542
+ * fully staged, or an env file that is not a plain file.
1543
+ */
1544
+ async function enforcementPinCommand(io, options, positionals) {
1545
+ rejectUnknownFlags(options, ['pin-file', 'confirm'], ENFORCEMENT_PIN_USAGE);
1546
+ if (positionals.length > 0) {
1547
+ throw new UsageError(`enforcement pin: unexpected argument '${positionals[0] ?? ''}' (${ENFORCEMENT_PIN_USAGE})`);
1548
+ }
1549
+ const rawPinFile = options['pin-file'];
1550
+ if (typeof rawPinFile !== 'string' || rawPinFile.length === 0) {
1551
+ throw new UsageError(`enforcement pin: --pin-file <path> is required (${ENFORCEMENT_PIN_USAGE})`);
1552
+ }
1553
+ const envFile = resolve(io.cwd, rawPinFile);
1554
+ const repoRoot = resolve(probe(io.cwd, io.env, ['rev-parse', '--show-toplevel']) ?? io.cwd);
1555
+ const insideRepo = relative(repoRoot, envFile);
1556
+ if (insideRepo === '' || (!insideRepo.startsWith('..') && !isAbsolute(insideRepo))) {
1557
+ throw new UsageError(`enforcement pin: --pin-file '${rawPinFile}' is inside the repository; the approved policy digest must ` +
1558
+ 'live OUTSIDE the candidate (e.g. ~/.config/<repo>.gateforge.env) — a candidate-controlled file cannot approve policy');
1559
+ }
1560
+ // The pin approves the revision the commit gate digests: the STAGED
1561
+ // bytes. A policy input that is not fully staged would pin a revision
1562
+ // the gate never sees, so name the files instead of writing a wrong pin.
1563
+ const config = loadConfigAt(io.cwd);
1564
+ const unstaged = unstagedPolicyInputs(io, config);
1565
+ if (unstaged === null) {
1566
+ throw new UsageError('enforcement pin: the staged policy inputs could not be read (no usable Git inventory)');
1567
+ }
1568
+ if (unstaged.length > 0) {
1569
+ throw new UsageError(`enforcement pin: policy inputs differ between the staged index and the working tree: ${boundedList(unstaged)} — ` +
1570
+ 'the commit gate digests the STAGED bytes; stage them (git add) and re-run');
1571
+ }
1572
+ let staged;
1573
+ try {
1574
+ staged = stagedPolicyState(io);
1575
+ }
1576
+ catch (error) {
1577
+ const detail = error instanceof StagedCandidateBlockError ? error.message : error.message;
1578
+ throw new UsageError(`enforcement pin: the staged policy inputs could not be read: ${detail}`);
1579
+ }
1580
+ const line = `${APPROVED_POLICY_DIGEST_ENV}=${staged.digest}`;
1581
+ writeLine(io.stdout, `staged policy digest: ${staged.digest}`);
1582
+ writeLine(io.stdout, `env file: ${envFile}`);
1583
+ if (options['confirm'] !== true) {
1584
+ writeLine(io.stdout, `preview: ${line} (nothing written — re-run with --confirm)`);
1585
+ return 0;
1586
+ }
1587
+ if (existsSync(envFile)) {
1588
+ const stats = lstatSync(envFile);
1589
+ if (stats.isSymbolicLink()) {
1590
+ throw new UsageError(`enforcement pin: '${rawPinFile}' is a symlink; the pin must be a plain file outside the candidate (fail closed)`);
1591
+ }
1592
+ if (!stats.isFile()) {
1593
+ throw new UsageError(`enforcement pin: '${rawPinFile}' is not a regular file (fail closed)`);
1594
+ }
1595
+ }
1596
+ else {
1597
+ mkdirSync(dirname(envFile), { recursive: true, mode: 0o700 });
1598
+ }
1599
+ const body = existsSync(envFile) ? readFileSync(envFile, 'utf8') : '';
1600
+ writeFileSync(envFile, pinnedEnvBody(body, line), { mode: 0o600 });
1601
+ // `mode` applies only when the file is CREATED; an env file that
1602
+ // already exists keeps its old bits, and the pin must never be
1603
+ // world-readable. Force the mode on every write.
1604
+ chmodSync(envFile, 0o600);
1605
+ writeLine(io.stdout, `wrote ${line} to ${envFile} (mode 0600)`);
1606
+ return 0;
1607
+ }
1173
1608
  /**
1174
1609
  * Applies `--strict-preflight`: the default doctor is report-only and
1175
1610
  * exits 0 whenever it runs, so today's behavior is byte-identical;