@gate-forge/cli 0.7.1 → 0.9.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 (296) hide show
  1. package/README.md +91 -704
  2. package/dist/adapter-audit.d.ts +208 -0
  3. package/dist/adapter-audit.d.ts.map +1 -0
  4. package/dist/adapter-audit.js +579 -0
  5. package/dist/adapter-audit.js.map +1 -0
  6. package/dist/adapter-scaffold.d.ts +91 -0
  7. package/dist/adapter-scaffold.d.ts.map +1 -0
  8. package/dist/adapter-scaffold.js +474 -0
  9. package/dist/adapter-scaffold.js.map +1 -0
  10. package/dist/adopted-baseline.d.ts +10 -0
  11. package/dist/adopted-baseline.d.ts.map +1 -1
  12. package/dist/adopted-baseline.js +18 -1
  13. package/dist/adopted-baseline.js.map +1 -1
  14. package/dist/args.d.ts +15 -0
  15. package/dist/args.d.ts.map +1 -1
  16. package/dist/args.js +61 -2
  17. package/dist/args.js.map +1 -1
  18. package/dist/behavior-setup.d.ts +239 -0
  19. package/dist/behavior-setup.d.ts.map +1 -0
  20. package/dist/behavior-setup.js +751 -0
  21. package/dist/behavior-setup.js.map +1 -0
  22. package/dist/broker.d.ts.map +1 -1
  23. package/dist/broker.js +28 -2
  24. package/dist/broker.js.map +1 -1
  25. package/dist/cache-exclusions.d.ts +45 -0
  26. package/dist/cache-exclusions.d.ts.map +1 -0
  27. package/dist/cache-exclusions.js +205 -0
  28. package/dist/cache-exclusions.js.map +1 -0
  29. package/dist/candidate-tree.d.ts +86 -14
  30. package/dist/candidate-tree.d.ts.map +1 -1
  31. package/dist/candidate-tree.js +236 -62
  32. package/dist/candidate-tree.js.map +1 -1
  33. package/dist/ci-witnessed-template.d.ts +43 -0
  34. package/dist/ci-witnessed-template.d.ts.map +1 -0
  35. package/dist/ci-witnessed-template.js +283 -0
  36. package/dist/ci-witnessed-template.js.map +1 -0
  37. package/dist/cli.d.ts +1 -1
  38. package/dist/cli.d.ts.map +1 -1
  39. package/dist/cli.js +31 -4
  40. package/dist/cli.js.map +1 -1
  41. package/dist/commands/adapters.d.ts +15 -0
  42. package/dist/commands/adapters.d.ts.map +1 -0
  43. package/dist/commands/adapters.js +355 -0
  44. package/dist/commands/adapters.js.map +1 -0
  45. package/dist/commands/adopt.d.ts +7 -0
  46. package/dist/commands/adopt.d.ts.map +1 -1
  47. package/dist/commands/adopt.js +44 -2
  48. package/dist/commands/adopt.js.map +1 -1
  49. package/dist/commands/baseline.d.ts.map +1 -1
  50. package/dist/commands/baseline.js +42 -1
  51. package/dist/commands/baseline.js.map +1 -1
  52. package/dist/commands/blocking.d.ts +105 -2
  53. package/dist/commands/blocking.d.ts.map +1 -1
  54. package/dist/commands/blocking.js +395 -53
  55. package/dist/commands/blocking.js.map +1 -1
  56. package/dist/commands/check.d.ts +36 -0
  57. package/dist/commands/check.d.ts.map +1 -1
  58. package/dist/commands/check.js +1068 -64
  59. package/dist/commands/check.js.map +1 -1
  60. package/dist/commands/classify.d.ts +2 -1
  61. package/dist/commands/classify.d.ts.map +1 -1
  62. package/dist/commands/classify.js +188 -5
  63. package/dist/commands/classify.js.map +1 -1
  64. package/dist/commands/enforce.d.ts +4 -4
  65. package/dist/commands/enforce.d.ts.map +1 -1
  66. package/dist/commands/enforce.js +41 -9
  67. package/dist/commands/enforce.js.map +1 -1
  68. package/dist/commands/enforcement.d.ts +13 -1
  69. package/dist/commands/enforcement.d.ts.map +1 -1
  70. package/dist/commands/enforcement.js +880 -33
  71. package/dist/commands/enforcement.js.map +1 -1
  72. package/dist/commands/explain.d.ts +1 -1
  73. package/dist/commands/explain.d.ts.map +1 -1
  74. package/dist/commands/explain.js +162 -3
  75. package/dist/commands/explain.js.map +1 -1
  76. package/dist/commands/history.d.ts +12 -0
  77. package/dist/commands/history.d.ts.map +1 -0
  78. package/dist/commands/history.js +45 -0
  79. package/dist/commands/history.js.map +1 -0
  80. package/dist/commands/init-presets.d.ts +155 -0
  81. package/dist/commands/init-presets.d.ts.map +1 -0
  82. package/dist/commands/init-presets.js +203 -0
  83. package/dist/commands/init-presets.js.map +1 -0
  84. package/dist/commands/init.d.ts +7 -12
  85. package/dist/commands/init.d.ts.map +1 -1
  86. package/dist/commands/init.js +987 -99
  87. package/dist/commands/init.js.map +1 -1
  88. package/dist/commands/keys.d.ts.map +1 -1
  89. package/dist/commands/keys.js +29 -13
  90. package/dist/commands/keys.js.map +1 -1
  91. package/dist/commands/next.d.ts.map +1 -1
  92. package/dist/commands/next.js +846 -19
  93. package/dist/commands/next.js.map +1 -1
  94. package/dist/commands/pre-commit.d.ts +25 -0
  95. package/dist/commands/pre-commit.d.ts.map +1 -1
  96. package/dist/commands/pre-commit.js +91 -6
  97. package/dist/commands/pre-commit.js.map +1 -1
  98. package/dist/commands/quarantine.d.ts +16 -0
  99. package/dist/commands/quarantine.d.ts.map +1 -0
  100. package/dist/commands/quarantine.js +213 -0
  101. package/dist/commands/quarantine.js.map +1 -0
  102. package/dist/commands/run.d.ts +39 -0
  103. package/dist/commands/run.d.ts.map +1 -0
  104. package/dist/commands/run.js +196 -0
  105. package/dist/commands/run.js.map +1 -0
  106. package/dist/commands/test-gates.d.ts +284 -2
  107. package/dist/commands/test-gates.d.ts.map +1 -1
  108. package/dist/commands/test-gates.js +3620 -187
  109. package/dist/commands/test-gates.js.map +1 -1
  110. package/dist/commands/tests.d.ts +1 -1
  111. package/dist/commands/tests.d.ts.map +1 -1
  112. package/dist/commands/tests.js +264 -29
  113. package/dist/commands/tests.js.map +1 -1
  114. package/dist/docs-exclusions.d.ts.map +1 -1
  115. package/dist/docs-exclusions.js +18 -3
  116. package/dist/docs-exclusions.js.map +1 -1
  117. package/dist/endpoint-compiler.d.ts.map +1 -1
  118. package/dist/endpoint-compiler.js +78 -9
  119. package/dist/endpoint-compiler.js.map +1 -1
  120. package/dist/engine-browser.d.ts +183 -0
  121. package/dist/engine-browser.d.ts.map +1 -0
  122. package/dist/engine-browser.js +381 -0
  123. package/dist/engine-browser.js.map +1 -0
  124. package/dist/engine-identity.d.ts +100 -0
  125. package/dist/engine-identity.d.ts.map +1 -0
  126. package/dist/engine-identity.js +182 -0
  127. package/dist/engine-identity.js.map +1 -0
  128. package/dist/evaluate.d.ts +105 -1
  129. package/dist/evaluate.d.ts.map +1 -1
  130. package/dist/evaluate.js +149 -18
  131. package/dist/evaluate.js.map +1 -1
  132. package/dist/execution.d.ts +253 -9
  133. package/dist/execution.d.ts.map +1 -1
  134. package/dist/execution.js +309 -12
  135. package/dist/execution.js.map +1 -1
  136. package/dist/gateforge-owned.d.ts +78 -0
  137. package/dist/gateforge-owned.d.ts.map +1 -0
  138. package/dist/gateforge-owned.js +254 -0
  139. package/dist/gateforge-owned.js.map +1 -0
  140. package/dist/git-hooks.d.ts +35 -0
  141. package/dist/git-hooks.d.ts.map +1 -1
  142. package/dist/git-hooks.js +140 -1
  143. package/dist/git-hooks.js.map +1 -1
  144. package/dist/git-ignored.d.ts +27 -0
  145. package/dist/git-ignored.d.ts.map +1 -0
  146. package/dist/git-ignored.js +102 -0
  147. package/dist/git-ignored.js.map +1 -0
  148. package/dist/git-objects.d.ts +60 -0
  149. package/dist/git-objects.d.ts.map +1 -0
  150. package/dist/git-objects.js +152 -0
  151. package/dist/git-objects.js.map +1 -0
  152. package/dist/glob.d.ts +33 -14
  153. package/dist/glob.d.ts.map +1 -1
  154. package/dist/glob.js +96 -5
  155. package/dist/glob.js.map +1 -1
  156. package/dist/history.d.ts +52 -0
  157. package/dist/history.d.ts.map +1 -0
  158. package/dist/history.js +116 -0
  159. package/dist/history.js.map +1 -0
  160. package/dist/host-load.d.ts +49 -0
  161. package/dist/host-load.d.ts.map +1 -0
  162. package/dist/host-load.js +78 -0
  163. package/dist/host-load.js.map +1 -0
  164. package/dist/index.d.ts +4 -1
  165. package/dist/index.d.ts.map +1 -1
  166. package/dist/index.js +2 -1
  167. package/dist/index.js.map +1 -1
  168. package/dist/input-snapshot.d.ts +63 -9
  169. package/dist/input-snapshot.d.ts.map +1 -1
  170. package/dist/input-snapshot.js +195 -17
  171. package/dist/input-snapshot.js.map +1 -1
  172. package/dist/io.d.ts +49 -0
  173. package/dist/io.d.ts.map +1 -1
  174. package/dist/io.js +22 -0
  175. package/dist/io.js.map +1 -1
  176. package/dist/mapping.d.ts +84 -1
  177. package/dist/mapping.d.ts.map +1 -1
  178. package/dist/mapping.js +276 -5
  179. package/dist/mapping.js.map +1 -1
  180. package/dist/native-freeze.d.ts +217 -0
  181. package/dist/native-freeze.d.ts.map +1 -0
  182. package/dist/native-freeze.js +332 -0
  183. package/dist/native-freeze.js.map +1 -0
  184. package/dist/pipeline.d.ts +67 -1
  185. package/dist/pipeline.d.ts.map +1 -1
  186. package/dist/pipeline.js +164 -6
  187. package/dist/pipeline.js.map +1 -1
  188. package/dist/planes-inference.d.ts +12 -5
  189. package/dist/planes-inference.d.ts.map +1 -1
  190. package/dist/planes-inference.js +13 -15
  191. package/dist/planes-inference.js.map +1 -1
  192. package/dist/playwright-browsers.d.ts +210 -0
  193. package/dist/playwright-browsers.d.ts.map +1 -0
  194. package/dist/playwright-browsers.js +364 -0
  195. package/dist/playwright-browsers.js.map +1 -0
  196. package/dist/plugins.d.ts +15 -5
  197. package/dist/plugins.d.ts.map +1 -1
  198. package/dist/plugins.js +59 -9
  199. package/dist/plugins.js.map +1 -1
  200. package/dist/progress.d.ts +148 -0
  201. package/dist/progress.d.ts.map +1 -0
  202. package/dist/progress.js +263 -0
  203. package/dist/progress.js.map +1 -0
  204. package/dist/providers.d.ts +26 -1
  205. package/dist/providers.d.ts.map +1 -1
  206. package/dist/providers.js +39 -0
  207. package/dist/providers.js.map +1 -1
  208. package/dist/receipts.d.ts +1 -0
  209. package/dist/receipts.d.ts.map +1 -1
  210. package/dist/receipts.js +35 -7
  211. package/dist/receipts.js.map +1 -1
  212. package/dist/repo-scan.d.ts +15 -1
  213. package/dist/repo-scan.d.ts.map +1 -1
  214. package/dist/repo-scan.js +329 -34
  215. package/dist/repo-scan.js.map +1 -1
  216. package/dist/reseal-chain.d.ts +184 -0
  217. package/dist/reseal-chain.d.ts.map +1 -0
  218. package/dist/reseal-chain.js +735 -0
  219. package/dist/reseal-chain.js.map +1 -0
  220. package/dist/reseal-evidence.d.ts +241 -0
  221. package/dist/reseal-evidence.d.ts.map +1 -0
  222. package/dist/reseal-evidence.js +319 -0
  223. package/dist/reseal-evidence.js.map +1 -0
  224. package/dist/reseal.d.ts +181 -0
  225. package/dist/reseal.d.ts.map +1 -0
  226. package/dist/reseal.js +1620 -0
  227. package/dist/reseal.js.map +1 -0
  228. package/dist/response-field-guidance.d.ts +82 -0
  229. package/dist/response-field-guidance.d.ts.map +1 -0
  230. package/dist/response-field-guidance.js +184 -0
  231. package/dist/response-field-guidance.js.map +1 -0
  232. package/dist/route-plane-proposals.d.ts +100 -0
  233. package/dist/route-plane-proposals.d.ts.map +1 -0
  234. package/dist/route-plane-proposals.js +213 -0
  235. package/dist/route-plane-proposals.js.map +1 -0
  236. package/dist/run-cache.d.ts +260 -0
  237. package/dist/run-cache.d.ts.map +1 -0
  238. package/dist/run-cache.js +771 -0
  239. package/dist/run-cache.js.map +1 -0
  240. package/dist/run-preflight.d.ts +77 -0
  241. package/dist/run-preflight.d.ts.map +1 -0
  242. package/dist/run-preflight.js +774 -0
  243. package/dist/run-preflight.js.map +1 -0
  244. package/dist/run-recipe.d.ts +107 -0
  245. package/dist/run-recipe.d.ts.map +1 -0
  246. package/dist/run-recipe.js +295 -0
  247. package/dist/run-recipe.js.map +1 -0
  248. package/dist/run-reliability.d.ts +126 -0
  249. package/dist/run-reliability.d.ts.map +1 -0
  250. package/dist/run-reliability.js +221 -0
  251. package/dist/run-reliability.js.map +1 -0
  252. package/dist/runtime.d.ts +15 -0
  253. package/dist/runtime.d.ts.map +1 -1
  254. package/dist/runtime.js +11 -1
  255. package/dist/runtime.js.map +1 -1
  256. package/dist/scope.d.ts +20 -0
  257. package/dist/scope.d.ts.map +1 -1
  258. package/dist/scope.js +26 -5
  259. package/dist/scope.js.map +1 -1
  260. package/dist/secret-guard.d.ts +36 -0
  261. package/dist/secret-guard.d.ts.map +1 -0
  262. package/dist/secret-guard.js +63 -0
  263. package/dist/secret-guard.js.map +1 -0
  264. package/dist/singleton-guidance.d.ts +82 -0
  265. package/dist/singleton-guidance.d.ts.map +1 -0
  266. package/dist/singleton-guidance.js +138 -0
  267. package/dist/singleton-guidance.js.map +1 -0
  268. package/dist/staged-candidate.d.ts +17 -0
  269. package/dist/staged-candidate.d.ts.map +1 -1
  270. package/dist/staged-candidate.js +50 -0
  271. package/dist/staged-candidate.js.map +1 -1
  272. package/dist/state-artifacts.d.ts +70 -0
  273. package/dist/state-artifacts.d.ts.map +1 -0
  274. package/dist/state-artifacts.js +215 -0
  275. package/dist/state-artifacts.js.map +1 -0
  276. package/dist/state.d.ts +170 -2
  277. package/dist/state.d.ts.map +1 -1
  278. package/dist/state.js +248 -8
  279. package/dist/state.js.map +1 -1
  280. package/dist/unmatched-routes.d.ts +60 -0
  281. package/dist/unmatched-routes.d.ts.map +1 -0
  282. package/dist/unmatched-routes.js +131 -0
  283. package/dist/unmatched-routes.js.map +1 -0
  284. package/dist/verifier-keys.d.ts +33 -2
  285. package/dist/verifier-keys.d.ts.map +1 -1
  286. package/dist/verifier-keys.js +95 -9
  287. package/dist/verifier-keys.js.map +1 -1
  288. package/guides/CONNECT-YOUR-PROJECT.md +425 -0
  289. package/guides/QUICKSTART.md +306 -26
  290. package/guides/REFERENCE.md +1710 -0
  291. package/guides/RUNNER-NEUTRAL-EVIDENCE.md +199 -0
  292. package/guides/TEST-ENVIRONMENT.md +1044 -6
  293. package/guides/UPGRADE-0.6-to-0.7.md +3 -3
  294. package/guides/UPGRADE-0.7-to-0.8.md +114 -0
  295. package/guides/UPGRADE-0.8-to-0.9.md +104 -0
  296. package/package.json +10 -9
@@ -19,23 +19,31 @@
19
19
  * external broker is reported `warn`/`not configured` unless an
20
20
  * operator-provided probe says otherwise.
21
21
  */
22
- import { accessSync, constants as fsConstants, existsSync, readFileSync, readdirSync } from 'node:fs';
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
24
  import { spawnSync } from 'node:child_process';
24
- import { homedir } from 'node:os';
25
- import { join, resolve } from 'node:path';
25
+ import { homedir, tmpdir } from 'node:os';
26
+ import { dirname, join, relative, resolve, sep } from 'node:path';
26
27
  import { BehaviorPolicySchema } from '@gate-forge/core';
27
28
  import { parse as parseYaml } from 'yaml';
28
- import { allCapabilities, canonicalJson, policyWeakenedCandidate, } from '@gate-forge/core';
29
+ import { auditAdapters } from '../adapter-audit.js';
30
+ import { allCapabilities, canonicalJson, policyWeakenedCandidate, resolveStrictnessMode, } from '@gate-forge/core';
29
31
  import { parseArgs } from '../args.js';
30
32
  import { trustedPolicyDigestForConfig } from '../execution.js';
31
33
  import { UsageError } from '../errors.js';
32
34
  import { writeLine } from '../io.js';
33
- import { TEST_MAP_RELATIVE } from '../mapping.js';
34
- import { inspectCommitHook } from '../git-hooks.js';
35
+ import { findRunnerConfigPath, TEST_MAP_RELATIVE } from '../mapping.js';
36
+ import { inspectCommitHook, isFrameworkManagedHookBody } from '../git-hooks.js';
35
37
  import { loadConfigAt, rejectUnknownFlags } from './common.js';
36
38
  import { resolveStateDir } from '../state.js';
39
+ import { resolveVerifierKeyring } from '../verifier-keys.js';
37
40
  import { describeApprovedPolicyResolution, resolveApprovedPolicyDigest } from '../trusted-policy.js';
38
- export const ENFORCEMENT_USAGE = 'usage: gateforge enforcement doctor [--json]';
41
+ import { engineIdentity, engineInstallProvenance, enginePackageRoot, engineSourceLine, } from '../engine-identity.js';
42
+ import { buildRunPreflight, findRunnerManifest, firstFailingCheck } from '../run-preflight.js';
43
+ import { findPlaywrightConfig } from '@gate-forge/pack-playwright';
44
+ import { browserBuildSummary, browserLaunchSummary, defaultBrowsersPath, inspectBrowserBuilds, unlaunchableBuilds, } from '../playwright-browsers.js';
45
+ import { engineBrowserRequirement, engineBrowserSummary, inspectEngineBrowserBuilds, resolveEngineBrowserInstall, } from '../engine-browser.js';
46
+ export const ENFORCEMENT_USAGE = 'usage: gateforge enforcement doctor [--json] [--strict-preflight]';
39
47
  /**
40
48
  * Runs `git` with NUL/UTF-8 output; null on any failure (a doctor check
41
49
  * reports the failure class, it never throws).
@@ -47,38 +55,298 @@ function probe(cwd, env, args) {
47
55
  return (result.stdout ?? '').trim();
48
56
  }
49
57
  /**
50
- * Cheap playwright readiness probe: package resolvable in the repo's
51
- * node_modules and a nonempty browser registry (default cache or
52
- * PLAYWRIGHT_BROWSERS_PATH). Never launches anything.
58
+ * Hashes the files the input snapshot would see (tracked + untracked non-ignored).
59
+ *
60
+ * Args:
61
+ * root: isolated hook-check checkout (a Git repository).
62
+ * env: environment for the Git inventory call.
63
+ *
64
+ * Returns:
65
+ * Map<string, string>: relative file paths mapped to content or symlink digests.
66
+ */
67
+ function snapshotHookWorkspace(root, env) {
68
+ const files = new Map();
69
+ const listed = spawnSync('git', ['ls-files', '-z', '--cached', '--others', '--exclude-standard'], {
70
+ cwd: root,
71
+ env,
72
+ encoding: 'utf8',
73
+ maxBuffer: 64 * 1024 * 1024,
74
+ });
75
+ if (listed.error !== undefined || listed.status !== 0) {
76
+ throw new Error(`git inventory failed: ${(listed.stderr ?? listed.error?.message ?? '').trim()}`);
77
+ }
78
+ for (const path of listed.stdout.split('\0')) {
79
+ if (path === '')
80
+ continue;
81
+ const absolute = join(root, ...path.split('/'));
82
+ let stat;
83
+ try {
84
+ stat = lstatSync(absolute);
85
+ }
86
+ catch {
87
+ files.set(path, 'deleted');
88
+ continue;
89
+ }
90
+ if (stat.isSymbolicLink()) {
91
+ files.set(path, createHash('sha256').update(readlinkSync(absolute)).digest('hex'));
92
+ }
93
+ else if (stat.isFile()) {
94
+ files.set(path, createHash('sha256').update(readFileSync(absolute)).digest('hex'));
95
+ }
96
+ }
97
+ return files;
98
+ }
99
+ /**
100
+ * Runs configured pre-commit hooks twice in a disposable checkout and reports workspace writes.
101
+ *
102
+ * Args:
103
+ * cwd: owner repository whose hook configuration will be copied.
104
+ * env: caller environment used only to locate the hook runner.
105
+ *
106
+ * Returns:
107
+ * { status, detail }: advisory hook-mutation doctor result.
108
+ */
109
+ function precommitMutationCheck(cwd, env) {
110
+ const configPath = join(cwd, '.pre-commit-config.yaml');
111
+ if (!existsSync(configPath)) {
112
+ return { status: 'warn', detail: 'no .pre-commit-config.yaml; hook mutation behavior was not checked' };
113
+ }
114
+ let hookIds = [];
115
+ try {
116
+ const config = parseYaml(readFileSync(configPath, 'utf8'));
117
+ const repos = Array.isArray(config?.repos) ? config.repos : [];
118
+ hookIds = repos.flatMap((repo) => {
119
+ if (typeof repo !== 'object' || repo === null || !('hooks' in repo) || !Array.isArray(repo.hooks))
120
+ return [];
121
+ return repo.hooks.flatMap((hook) => typeof hook === 'object' && hook !== null && 'id' in hook && typeof hook.id === 'string'
122
+ ? [hook.id]
123
+ : []);
124
+ });
125
+ }
126
+ catch (error) {
127
+ return { status: 'warn', detail: `pre-commit configuration could not be parsed: ${error.message}` };
128
+ }
129
+ const scratchRoot = mkdtempSync(join(tmpdir(), 'gateforge-hook-doctor-'));
130
+ const checkout = join(scratchRoot, 'checkout');
131
+ const excluded = new Set(['.git', 'node_modules', 'dist', 'coverage', '.venv']);
132
+ // Hooks run with the invoking user's HOME/XDG so installed interpreters
133
+ // (e.g. uv-managed Pythons) and the existing pre-commit cache are found,
134
+ // exactly as on a real commit. Only the checkout is isolated.
135
+ const passthrough = ['PATH', 'HOME', 'LANG', 'PRE_COMMIT_HOME', 'XDG_CACHE_HOME', 'XDG_DATA_HOME', 'XDG_CONFIG_HOME'];
136
+ const safeEnv = {
137
+ TMPDIR: scratchRoot,
138
+ GIT_CONFIG_GLOBAL: '/dev/null',
139
+ GIT_CONFIG_NOSYSTEM: '1',
140
+ GIT_TERMINAL_PROMPT: '0',
141
+ };
142
+ for (const name of passthrough) {
143
+ const value = env[name] ?? process.env[name];
144
+ if (value !== undefined)
145
+ safeEnv[name] = value;
146
+ }
147
+ safeEnv['LANG'] ??= 'C.UTF-8';
148
+ try {
149
+ cpSync(cwd, checkout, {
150
+ recursive: true,
151
+ filter: (source) => {
152
+ const path = relative(cwd, source);
153
+ if (path === '')
154
+ return true;
155
+ if (path.split(sep).some((segment) => excluded.has(segment)))
156
+ return false;
157
+ try {
158
+ return !lstatSync(source).isSymbolicLink();
159
+ }
160
+ catch {
161
+ return false;
162
+ }
163
+ },
164
+ });
165
+ for (const args of [
166
+ ['init', '--quiet'],
167
+ ['add', '--all'],
168
+ ['-c', 'user.name=Gateforge Doctor', '-c', 'user.email=doctor@localhost', 'commit', '--quiet', '-m', 'hook doctor snapshot'],
169
+ ]) {
170
+ const initialized = spawnSync('git', args, { cwd: checkout, env: safeEnv, encoding: 'utf8' });
171
+ if (initialized.error !== undefined || initialized.status !== 0) {
172
+ return { status: 'warn', detail: `isolated hook checkout could not be prepared: ${(initialized.stderr ?? initialized.error?.message ?? '').trim()}` };
173
+ }
174
+ }
175
+ const mutations = new Set();
176
+ const failures = [];
177
+ for (let pass = 0; pass < 2; pass += 1) {
178
+ const before = snapshotHookWorkspace(checkout, safeEnv);
179
+ const result = spawnSync('pre-commit', ['run', '--all-files'], {
180
+ cwd: checkout,
181
+ env: safeEnv,
182
+ encoding: 'utf8',
183
+ timeout: 120_000,
184
+ maxBuffer: 5 * 1024 * 1024,
185
+ });
186
+ if (result.error?.code === 'ENOENT') {
187
+ return { status: 'warn', detail: 'pre-commit is unavailable; hook mutation behavior was not checked' };
188
+ }
189
+ const after = snapshotHookWorkspace(checkout, safeEnv);
190
+ for (const path of new Set([...before.keys(), ...after.keys()])) {
191
+ if (before.get(path) !== after.get(path))
192
+ mutations.add(path);
193
+ }
194
+ if (result.error !== undefined || result.status !== 0) {
195
+ failures.push(`run ${pass + 1}: ${lastLines(result.stderr || result.stdout || result.error?.message || `exit ${String(result.status)}`, 3)}`);
196
+ }
197
+ }
198
+ if (mutations.size > 0) {
199
+ // These are the REPOSITORY's own hooks, and the doctor runs
200
+ // before (or without) any Gateforge hook — so the advice has to
201
+ // be ordered the way the owner meets it: install the hook first,
202
+ // then give it the first position. Telling someone to reorder a
203
+ // hook they do not have yet is not actionable.
204
+ const recommendation = hookIds[0] === 'gateforge-check'
205
+ ? ''
206
+ : '; these are your repo\'s own hooks, not Gateforge\'s — run `gateforge init --blocking` ' +
207
+ '(or `gateforge enforce`) to install gateforge-check, then move its entry to the ' +
208
+ 'FIRST in .pre-commit-config.yaml, above these hooks, so a file-mutating hook cannot invalidate its receipt';
209
+ return {
210
+ status: 'warn',
211
+ detail: `pre-commit hooks modified workspace files on repeated runs: ${summarizePaths([...mutations].sort(), 5)}${recommendation}`,
212
+ };
213
+ }
214
+ if (failures.length > 0) {
215
+ return {
216
+ status: 'warn',
217
+ detail: `pre-commit hooks did not complete cleanly in an isolated copy (without ${[...excluded].filter((name) => name !== '.git').join(', ')}), ` +
218
+ `so file changes by hooks were not checked; hooks that need those folders fail there. ` +
219
+ `Run \`pre-commit run --all-files\` in the repository to see the full error. Last lines: ${failures.join('; ')}`,
220
+ };
221
+ }
222
+ return { status: 'ok', detail: 'pre-commit hooks ran twice without workspace file mutations' };
223
+ }
224
+ catch (error) {
225
+ return { status: 'warn', detail: `hook mutation behavior was not checked: ${error.message}` };
226
+ }
227
+ finally {
228
+ rmSync(scratchRoot, { recursive: true, force: true });
229
+ }
230
+ }
231
+ /**
232
+ * Keeps the last non-empty lines of a command's output for a one-line summary.
233
+ *
234
+ * Args:
235
+ * text: raw command output.
236
+ * count: number of trailing non-empty lines to keep.
237
+ *
238
+ * Returns:
239
+ * string: the kept lines joined with " | ".
240
+ */
241
+ function lastLines(text, count) {
242
+ return text
243
+ .split('\n')
244
+ .map((line) => line.trim())
245
+ .filter((line) => line !== '')
246
+ .slice(-count)
247
+ .join(' | ');
248
+ }
249
+ /**
250
+ * Lists the first few paths and counts the remainder.
251
+ *
252
+ * Args:
253
+ * paths: sorted relative paths.
254
+ * limit: maximum number of paths to name.
255
+ *
256
+ * Returns:
257
+ * string: e.g. "a, b, c and 4 more".
258
+ */
259
+ function summarizePaths(paths, limit) {
260
+ const named = paths.slice(0, limit).join(', ');
261
+ return paths.length > limit ? `${named} and ${String(paths.length - limit)} more` : named;
262
+ }
263
+ /**
264
+ * Finds repository files that could expose the active verifier key.
53
265
  *
54
266
  * Args:
55
267
  * cwd: repository root.
268
+ * env: key-source and Git environment.
56
269
  *
57
270
  * Returns:
58
- * {status, detail}: ok / warn (no browsers) / fail (no package).
271
+ * object: offending relative paths and a non-secret scan status.
59
272
  */
60
- function playwrightReadiness(cwd) {
61
- let packageJson = null;
62
- let cursor = resolve(cwd);
63
- // Walk up like Node resolution: the CLI may run from a workspace root.
64
- for (let depth = 0; depth < 6; depth += 1) {
65
- const candidate = join(cursor, 'node_modules', 'playwright', 'package.json');
66
- if (existsSync(candidate)) {
67
- packageJson = candidate;
68
- break;
273
+ function verifierKeyExposure(cwd, env) {
274
+ let activeKey;
275
+ let configured = false;
276
+ let scanError = false;
277
+ try {
278
+ activeKey = resolveVerifierKeyring(cwd, env, [resolveStateDir(cwd)])?.active.key;
279
+ configured = activeKey !== undefined;
280
+ }
281
+ catch {
282
+ scanError = true;
283
+ }
284
+ const listingArgs = [
285
+ ['ls-files', '--cached', '--others', '--exclude-standard', '-z'],
286
+ ['ls-files', '--others', '--ignored', '--exclude-standard', '-z'],
287
+ ];
288
+ const listedPaths = [];
289
+ for (const args of listingArgs) {
290
+ const listed = spawnSync('git', args, { cwd, env, encoding: 'utf8' });
291
+ if (listed.error !== undefined || listed.status !== 0) {
292
+ return { paths: [], configured, scanError: true };
293
+ }
294
+ listedPaths.push(...(listed.stdout ?? '').split('\0'));
295
+ }
296
+ const keyBytes = activeKey === undefined ? null : Buffer.from(activeKey, 'utf8');
297
+ const paths = [];
298
+ for (const relativePath of new Set(listedPaths)) {
299
+ if (relativePath.length === 0)
300
+ continue;
301
+ const absolutePath = resolve(cwd, relativePath);
302
+ try {
303
+ const stat = lstatSync(absolutePath);
304
+ if (!stat.isFile())
305
+ continue;
306
+ if (relativePath.split(/[\\/]/).at(-1) === 'verifier.key') {
307
+ paths.push(relativePath);
308
+ continue;
309
+ }
310
+ if (keyBytes === null || stat.size !== keyBytes.length)
311
+ continue;
312
+ if (readFileSync(absolutePath).equals(keyBytes))
313
+ paths.push(relativePath);
314
+ }
315
+ catch {
316
+ scanError = true;
69
317
  }
70
- const parent = resolve(cursor, '..');
71
- if (parent === cursor)
72
- break;
73
- cursor = parent;
74
318
  }
319
+ return { paths: [...new Set(paths)].sort(), configured, scanError };
320
+ }
321
+ /**
322
+ * Cheap playwright readiness probe: package resolvable where the
323
+ * supervised run resolves it (next to the Playwright config, then from
324
+ * the repo root upward) and the browser builds THAT runner pins present
325
+ * in the cache (default cache or PLAYWRIGHT_BROWSERS_PATH). Counting
326
+ * cache entries proves nothing: a cache holding another Playwright
327
+ * release's builds is nonempty and still fails every test with
328
+ * `Executable doesn't exist`. Never launches anything.
329
+ *
330
+ * Args:
331
+ * cwd: repository root.
332
+ * env: operator environment (PLAYWRIGHT_BROWSERS_PATH).
333
+ *
334
+ * Returns:
335
+ * {status, detail}: ok / warn (no browsers at all) / fail (no
336
+ * package, or a pinned build the run would launch is missing).
337
+ */
338
+ function playwrightReadiness(cwd, env) {
339
+ // The SAME resolution order the supervised run uses (see
340
+ // `runnerCheck`): `@playwright/test` first, so the browser builds
341
+ // checked are the ones the run will actually launch.
342
+ const packageJson = findRunnerManifest(cwd, 'playwright', ['@playwright/test', 'playwright']);
75
343
  if (packageJson === null) {
76
344
  return {
77
345
  status: 'fail',
78
346
  detail: 'playwright is not installed (no node_modules/playwright found from the repo root); the supervised E2E runner cannot execute',
79
347
  };
80
348
  }
81
- const browsersPath = process.env['PLAYWRIGHT_BROWSERS_PATH'] ?? join(homedir(), '.cache', 'ms-playwright');
349
+ const browsersPath = defaultBrowsersPath(env);
82
350
  let browsers = 'missing';
83
351
  try {
84
352
  const entries = readdirSafe(browsersPath);
@@ -93,7 +361,262 @@ function playwrightReadiness(cwd) {
93
361
  detail: `playwright installed; browsers NOT found under '${browsersPath}' — run \`npx playwright install\` before the supervised run`,
94
362
  };
95
363
  }
96
- return { status: 'ok', detail: `playwright installed; browsers ${browsers} under '${browsersPath}'` };
364
+ // The cache is nonempty; only the builds the RESOLVED runner pins say
365
+ // whether its tests can launch. A runner that ships no readable
366
+ // registry keeps the historical line (an unresolvable install never
367
+ // invents revisions).
368
+ const configDir = playwrightInstallCwd(cwd);
369
+ const readiness = inspectBrowserBuilds(packageJson, playwrightConfigText(cwd), env);
370
+ const builds = browserBuildSummary(readiness, configDir);
371
+ if (builds === '') {
372
+ return { status: 'ok', detail: `playwright installed; browsers ${browsers} under '${browsersPath}'` };
373
+ }
374
+ if (readiness.missing.length > 0) {
375
+ return { status: 'fail', detail: `playwright installed; ${builds}` };
376
+ }
377
+ // Installed is not startable: on a bare Linux image the dynamic
378
+ // loader fails before `main`, and the cause never reaches the report.
379
+ const launch = browserLaunchSummary(unlaunchableBuilds(readiness), configDir);
380
+ if (launch !== '') {
381
+ return { status: 'fail', detail: `playwright installed; ${launch}` };
382
+ }
383
+ return { status: 'ok', detail: `playwright installed; browsers ${browsers} under '${browsersPath}'; ${builds}` };
384
+ }
385
+ /**
386
+ * The directory a `npx playwright install` fix must run in: the one
387
+ * holding the Playwright config the supervised run resolves the runner
388
+ * from (a sub-project like `e2e/` owns its own install), else the
389
+ * repository root.
390
+ *
391
+ * Args:
392
+ * cwd: repository root.
393
+ *
394
+ * Returns:
395
+ * string: the absolute directory the install command runs in.
396
+ */
397
+ function playwrightInstallCwd(cwd) {
398
+ const config = findPlaywrightConfig(cwd);
399
+ return config === null ? resolve(cwd) : dirname(resolve(cwd, config));
400
+ }
401
+ /**
402
+ * Readiness of the ENGINE-OWNED browser — the Chromium
403
+ * `@gate-forge/pack-playwright` pins and `EngineBrowserManager` drives
404
+ * for every `engine-browser` case, `ui.action` and `visible.confirm`.
405
+ *
406
+ * This is a separate fact from the `runner` line on purpose. The runner
407
+ * line answers "can the CONSUMER's tests launch a browser"; this one
408
+ * answers "can the ENGINE drive its own". A consumer whose Playwright is
409
+ * a different release from the pack's pin makes those two answers
410
+ * disagree — the consumer's Chromium 1234 installed and correct, the
411
+ * engine's 1208 absent — and reporting only the first is what let a
412
+ * first witnessed run die in the witness on `Executable doesn't exist`
413
+ * after the runner line said `ok`.
414
+ *
415
+ * The line is additive and leaves `runner` unchanged. A Playwright runner
416
+ * conservatively requires the engine browser; other runners without an
417
+ * `engine-browser` behavior case report that it is not required.
418
+ *
419
+ * Args:
420
+ * cwd: repository root.
421
+ * config: the loaded repository config.
422
+ * env: operator environment (`PLAYWRIGHT_BROWSERS_PATH`).
423
+ *
424
+ * Returns:
425
+ * {status, detail}: fail when a required engine build is missing or
426
+ * cannot start, warn when the requirement exists but cannot be
427
+ * observed, ok otherwise.
428
+ */
429
+ function engineBrowserReadiness(cwd, config, env) {
430
+ const requirement = engineBrowserRequirement(cwd, config.runner, config.behaviorPolicy);
431
+ if (!requirement.required)
432
+ return { status: 'ok', detail: `engine browser not required — ${requirement.reason}` };
433
+ const resolution = resolveEngineBrowserInstall(cwd);
434
+ if (resolution.kind === 'not-installed') {
435
+ return {
436
+ status: 'warn',
437
+ detail: `${requirement.reason}, but @gate-forge/pack-playwright is not installed under this repository — ` +
438
+ 'the engine browser could not be inspected',
439
+ };
440
+ }
441
+ if (resolution.kind === 'no-pinned-playwright') {
442
+ return {
443
+ status: 'warn',
444
+ detail: `${requirement.reason}, but the installed @gate-forge/pack-playwright resolves no readable pinned ` +
445
+ 'playwright release — the engine browser could not be inspected',
446
+ };
447
+ }
448
+ const readiness = inspectEngineBrowserBuilds(resolution.install, env);
449
+ const summary = engineBrowserSummary(readiness);
450
+ if (readiness.missing.length > 0 || readiness.unlaunchable.length > 0) {
451
+ return { status: 'fail', detail: summary };
452
+ }
453
+ return { status: 'ok', detail: summary };
454
+ }
455
+ /**
456
+ * The resolved Playwright config's source ('' when the repository has
457
+ * none): the config names the browsers its projects launch.
458
+ *
459
+ * Args:
460
+ * cwd: repository root.
461
+ *
462
+ * Returns:
463
+ * string: the config text, or '' when there is no readable config.
464
+ */
465
+ function playwrightConfigText(cwd) {
466
+ const config = findPlaywrightConfig(cwd);
467
+ if (config === null)
468
+ return '';
469
+ try {
470
+ return readFileSync(resolve(cwd, config), 'utf8');
471
+ }
472
+ catch {
473
+ return '';
474
+ }
475
+ }
476
+ /**
477
+ * Runner readiness for the CONFIGURED runner (`runner:` in
478
+ * `.gateforge.yml`; absent = playwright). Playwright keeps its exact
479
+ * historical probe, id and detail — a repository without the key sees
480
+ * byte-identical output. A non-Playwright runner reports the two cheap
481
+ * facts the supervised run needs: its own declaration (a config file at
482
+ * the repository root for vitest/cypress, a configured suite for pytest)
483
+ * and a resolvable runner package/binary. Nothing is launched.
484
+ *
485
+ * Args:
486
+ * cwd: repository root.
487
+ * config: the loaded repository config.
488
+ * env: the process environment (PATH resolution for pytest).
489
+ *
490
+ * Returns:
491
+ * {status, detail}: ok when both facts hold, fail otherwise.
492
+ */
493
+ function runnerReadiness(cwd, config, env) {
494
+ if (config.runner === 'playwright')
495
+ return playwrightReadiness(cwd, env);
496
+ if (config.runner === 'pytest')
497
+ return pytestReadiness(cwd, config, env);
498
+ return nodeRunnerReadiness(cwd, config.runner);
499
+ }
500
+ /**
501
+ * Readiness for a node-based runner (vitest, cypress): its config file
502
+ * at the repository root plus its package resolvable like Node resolves
503
+ * it (the CLI may run from a workspace root).
504
+ *
505
+ * Args:
506
+ * cwd: repository root.
507
+ * runner: the configured runner name.
508
+ *
509
+ * Returns:
510
+ * {status, detail}: ok when the config file and the package resolve.
511
+ */
512
+ function nodeRunnerReadiness(cwd, runner) {
513
+ const configFile = findRunnerConfigPath(cwd, runner);
514
+ if (configFile === null) {
515
+ return {
516
+ status: 'fail',
517
+ detail: `${runner} is the configured runner but no ${runner} config file was found at the repository root ` +
518
+ `(expected ${runner}.config.* at the repository root); the supervised E2E runner cannot execute`,
519
+ };
520
+ }
521
+ if (findUpwardPackage(cwd, runner) === null) {
522
+ return {
523
+ status: 'fail',
524
+ detail: `${runner} is configured (${configFile}) but ${runner} is not installed ` +
525
+ `(no node_modules/${runner} found from the repo root); run \`npm install --save-dev ${runner}\` ` +
526
+ 'before the supervised run',
527
+ };
528
+ }
529
+ return {
530
+ status: 'ok',
531
+ detail: `${runner} configured (${configFile}) and installed; the supervised run can execute it`,
532
+ };
533
+ }
534
+ /**
535
+ * Readiness for pytest: the owner registers the suite explicitly (there
536
+ * is no config file to probe) and the `pytest` executable must resolve on
537
+ * PATH. Fail-open to `fail` — an unresolvable runner never runs.
538
+ *
539
+ * Args:
540
+ * cwd: repository root.
541
+ * config: the loaded repository config.
542
+ * env: the process environment (PATH resolution).
543
+ *
544
+ * Returns:
545
+ * {status, detail}: ok when a suite is configured and pytest resolves.
546
+ */
547
+ function pytestReadiness(cwd, config, env) {
548
+ const suites = (config.diagnostics?.suites ?? []).filter((suite) => suite.runner === 'pytest');
549
+ if (suites.length === 0) {
550
+ return {
551
+ status: 'fail',
552
+ detail: 'pytest is the configured runner but no pytest suite is configured in .gateforge.yml ' +
553
+ '(diagnostics.suites); the supervised E2E runner cannot execute',
554
+ };
555
+ }
556
+ const names = suites.map((suite) => suite.name).join(', ');
557
+ const binary = findOnPath(env['PATH'], 'pytest');
558
+ if (binary === null) {
559
+ return {
560
+ status: 'fail',
561
+ detail: `pytest suite(s) configured (${names}) but no pytest executable was found on PATH; ` +
562
+ 'install it (python -m pip install pytest) before the supervised run',
563
+ };
564
+ }
565
+ return {
566
+ status: 'ok',
567
+ detail: `pytest suite(s) configured (${names}) and pytest resolves at '${binary}'; the supervised run can execute it`,
568
+ };
569
+ }
570
+ /**
571
+ * Resolves `<package>/package.json` upward from the repository root the
572
+ * way Node resolution walks (the CLI may run from a workspace root).
573
+ *
574
+ * Args:
575
+ * cwd: repository root.
576
+ * packageName: the runner's npm package name.
577
+ *
578
+ * Returns:
579
+ * string | null: the absolute package.json path, or null.
580
+ */
581
+ function findUpwardPackage(cwd, packageName) {
582
+ let cursor = resolve(cwd);
583
+ for (let depth = 0; depth < 6; depth += 1) {
584
+ const candidate = join(cursor, 'node_modules', packageName, 'package.json');
585
+ if (existsSync(candidate))
586
+ return candidate;
587
+ const parent = resolve(cursor, '..');
588
+ if (parent === cursor)
589
+ break;
590
+ cursor = parent;
591
+ }
592
+ return null;
593
+ }
594
+ /**
595
+ * Resolves an executable on PATH without launching anything.
596
+ *
597
+ * Args:
598
+ * pathValue: the PATH environment value.
599
+ * command: the executable name.
600
+ *
601
+ * Returns:
602
+ * string | null: the absolute path of the first match, or null.
603
+ */
604
+ function findOnPath(pathValue, command) {
605
+ if (pathValue === undefined || pathValue.length === 0)
606
+ return null;
607
+ for (const entry of pathValue.split(sep)) {
608
+ if (entry.length === 0)
609
+ continue;
610
+ const candidate = join(entry, command);
611
+ try {
612
+ accessSync(candidate, fsConstants.X_OK);
613
+ return candidate;
614
+ }
615
+ catch {
616
+ // not executable here: keep scanning PATH
617
+ }
618
+ }
619
+ return null;
97
620
  }
98
621
  /** Safe directory listing (missing dir → empty). */
99
622
  function readdirSafe(dir) {
@@ -104,6 +627,171 @@ function readdirSafe(dir) {
104
627
  return [];
105
628
  }
106
629
  }
630
+ /**
631
+ * Whether a `.pre-commit-config.yaml` declares Gateforge's hook.
632
+ *
633
+ * Args:
634
+ * path: absolute path to `.pre-commit-config.yaml`.
635
+ *
636
+ * Returns:
637
+ * boolean: true when a hook with id `gateforge-check` is declared.
638
+ */
639
+ function declaresGateforgeCheck(path) {
640
+ if (!existsSync(path))
641
+ return false;
642
+ let parsed;
643
+ try {
644
+ parsed = parseYaml(readFileSync(path, 'utf8'));
645
+ }
646
+ catch {
647
+ return false;
648
+ }
649
+ // Parsed YAML is external input: every step narrows with `typeof` /
650
+ // `in` so a malformed config answers "not wired" instead of trusting a
651
+ // fabricated shape.
652
+ if (typeof parsed !== 'object' || parsed === null || !('repos' in parsed))
653
+ return false;
654
+ const repos = parsed.repos;
655
+ if (!Array.isArray(repos))
656
+ return false;
657
+ return repos.some((repo) => {
658
+ if (typeof repo !== 'object' || repo === null || !('hooks' in repo))
659
+ return false;
660
+ const hooks = repo.hooks;
661
+ if (!Array.isArray(hooks))
662
+ return false;
663
+ return hooks.some((hook) => typeof hook === 'object' && hook !== null && 'id' in hook && hook.id === 'gateforge-check');
664
+ });
665
+ }
666
+ /**
667
+ * Whether this repository's commit gate runs through a pre-commit
668
+ * FRAMEWORK.
669
+ *
670
+ * A framework regenerates `.git/hooks/pre-commit` from
671
+ * `.pre-commit-config.yaml` on every `pre-commit install`, so the file
672
+ * in `.git/hooks` carries the framework's signature and never a
673
+ * Gateforge marker. Reading only for our marker therefore reported
674
+ * "a non-gateforge pre-commit hook exists … gateforge did not touch it"
675
+ * about a repository where `init` had just wired the gate through the
676
+ * framework config — the two commands contradicted each other on the
677
+ * same file. Both halves must hold: the hook file is framework
678
+ * generated AND the framework config actually declares our hook.
679
+ *
680
+ * Args:
681
+ * cwd: repository root.
682
+ * hookPath: the resolved `.git/hooks/pre-commit` path, if any.
683
+ *
684
+ * Returns:
685
+ * boolean: true when the gate is wired through the framework.
686
+ */
687
+ function frameworkHookGateWired(cwd, hookPath) {
688
+ if (hookPath === null || !existsSync(hookPath))
689
+ return false;
690
+ if (!isFrameworkManagedHookBody(readFileSync(hookPath, 'utf8')))
691
+ return false;
692
+ return declaresGateforgeCheck(join(cwd, '.pre-commit-config.yaml'));
693
+ }
694
+ /**
695
+ * Detects generated CI wiring without treating a template as server-side
696
+ * protection.
697
+ *
698
+ * Args:
699
+ * cwd: repository root.
700
+ *
701
+ * Returns:
702
+ * boolean: true when a Gateforge template is present and included.
703
+ */
704
+ function hasWiredCi(cwd) {
705
+ const gitlabTemplate = join(cwd, '.gateforge', 'ci', 'gitlab-gateforge.yml');
706
+ const gitlabConfig = join(cwd, '.gitlab-ci.yml');
707
+ if (existsSync(gitlabTemplate) && existsSync(gitlabConfig)) {
708
+ return readFileSync(gitlabConfig, 'utf8').includes('.gateforge/ci/gitlab-gateforge.yml');
709
+ }
710
+ const githubTemplate = join(cwd, '.github', 'workflows', 'gateforge.yml');
711
+ return existsSync(githubTemplate) && readFileSync(githubTemplate, 'utf8').includes('# Generated by Gateforge');
712
+ }
713
+ /**
714
+ * Probes GitHub branch protection using the caller's existing read-only
715
+ * CLI authentication.
716
+ *
717
+ * Args:
718
+ * io: process context.
719
+ *
720
+ * Returns:
721
+ * {verified, detail}: verified required-check status or an honest warning.
722
+ */
723
+ function probeGitHubProtection(io) {
724
+ if ((io.env['GH_TOKEN'] ?? io.env['GITHUB_TOKEN'] ?? '').length === 0) {
725
+ return { verified: false, detail: 'server protection: not verified (no GitHub API token configured)' };
726
+ }
727
+ const repository = io.env['GITHUB_REPOSITORY'];
728
+ const branch = io.env['GITHUB_BASE_REF'] ?? io.env['CI_DEFAULT_BRANCH'];
729
+ if (repository === undefined || branch === undefined || repository.length === 0 || branch.length === 0) {
730
+ return { verified: false, detail: 'server protection: not verified (repository or protected branch is unknown)' };
731
+ }
732
+ const result = spawnSync('gh', ['api', `repos/${repository}/branches/${encodeURIComponent(branch)}/protection`], { cwd: io.cwd, env: io.env, encoding: 'utf8', stdio: ['ignore', 'pipe', 'ignore'] });
733
+ if (result.error !== undefined || result.status !== 0) {
734
+ return { verified: false, detail: 'server protection: not verified (GitHub branch-protection probe failed)' };
735
+ }
736
+ try {
737
+ const protection = JSON.parse(result.stdout ?? '');
738
+ const contexts = protection.required_status_checks?.contexts;
739
+ const required = Array.isArray(contexts) && contexts.some((context) => context === 'gateforge');
740
+ return required
741
+ ? { verified: true, detail: `server protection: verified required status check 'gateforge' on '${branch}'` }
742
+ : { verified: false, detail: `server protection: branch is not verified to require status check 'gateforge' on '${branch}'` };
743
+ }
744
+ catch {
745
+ return { verified: false, detail: 'server protection: not verified (GitHub returned an unreadable protection response)' };
746
+ }
747
+ }
748
+ /**
749
+ * Probes GitLab branch protection and require-success merge settings with
750
+ * read-only API requests.
751
+ *
752
+ * Args:
753
+ * io: process context.
754
+ *
755
+ * Returns:
756
+ * {verified, detail}: verified branch and pipeline requirements or warning.
757
+ */
758
+ function probeGitLabProtection(io) {
759
+ if ((io.env['GITLAB_TOKEN'] ?? io.env['GLAB_TOKEN'] ?? '').length === 0) {
760
+ return { verified: false, detail: 'server protection: not verified (no GitLab API token configured)' };
761
+ }
762
+ const project = io.env['CI_PROJECT_ID'];
763
+ const branch = io.env['CI_DEFAULT_BRANCH'];
764
+ if (project === undefined || !/^[0-9]+$/.test(project) || branch === undefined || branch.length === 0) {
765
+ return { verified: false, detail: 'server protection: not verified (project or protected branch is unknown)' };
766
+ }
767
+ const env = { ...io.env, GITLAB_TOKEN: io.env['GITLAB_TOKEN'] ?? io.env['GLAB_TOKEN'] };
768
+ const projectResult = spawnSync('glab', ['api', `projects/${project}`], {
769
+ cwd: io.cwd,
770
+ env,
771
+ encoding: 'utf8',
772
+ stdio: ['ignore', 'pipe', 'ignore'],
773
+ });
774
+ const branchResult = spawnSync('glab', ['api', `projects/${project}/protected_branches/${encodeURIComponent(branch)}`], { cwd: io.cwd, env, encoding: 'utf8', stdio: ['ignore', 'pipe', 'ignore'] });
775
+ if (projectResult.error !== undefined ||
776
+ projectResult.status !== 0 ||
777
+ branchResult.error !== undefined ||
778
+ branchResult.status !== 0) {
779
+ return { verified: false, detail: 'server protection: not verified (GitLab read-only protection probe failed)' };
780
+ }
781
+ try {
782
+ const projectSettings = JSON.parse(projectResult.stdout ?? '');
783
+ const protectedBranch = JSON.parse(branchResult.stdout ?? '');
784
+ const verified = projectSettings.only_allow_merge_if_pipeline_succeeds === true &&
785
+ protectedBranch.name === branch &&
786
+ protectedBranch.allow_force_push === false;
787
+ return verified
788
+ ? { verified: true, detail: `server protection: verified protected branch and required passing pipeline on '${branch}'` }
789
+ : { verified: false, detail: `server protection: branch '${branch}' is not verified to require a passing protected pipeline` };
790
+ }
791
+ catch {
792
+ return { verified: false, detail: 'server protection: not verified (GitLab returned an unreadable protection response)' };
793
+ }
794
+ }
107
795
  /**
108
796
  * Builds the doctor report (all checks, honest statuses).
109
797
  *
@@ -118,12 +806,17 @@ export async function buildDoctorReport(io) {
118
806
  // 0. Config (all later checks degrade honestly when it fails).
119
807
  let mode = 'standard';
120
808
  let strictE2E = false;
809
+ let strictnessMode = 'strict';
121
810
  let configOk = true;
811
+ // The managed-run preconditions are an independent, read-only
812
+ // section: they add no authority over the enforcement checks.
813
+ const run = await buildRunPreflight(io);
122
814
  let configDetail = 'no .gateforge.yml — gateforge is not initialized in this repository';
123
815
  try {
124
816
  const config = loadConfigAt(io.cwd);
125
817
  mode = config.enforcement?.mode ?? 'standard';
126
818
  strictE2E = config.enforcement?.strictE2E === true;
819
+ strictnessMode = resolveStrictnessMode(config);
127
820
  configOk = true;
128
821
  configDetail = `.gateforge.yml loaded (mode ${mode}, strictE2E ${String(strictE2E)})`;
129
822
  }
@@ -132,15 +825,95 @@ export async function buildDoctorReport(io) {
132
825
  configDetail = `.gateforge.yml could not be loaded: ${error.message.split('\n')[0] ?? 'unknown'}`;
133
826
  }
134
827
  checks.push({ id: 'config', status: configOk ? 'ok' : 'fail', detail: configDetail });
828
+ // Gate strictness: a softened gate is not
829
+ // a failure — it is an owner decision that must stay LOUD forever, so
830
+ // it is never `ok` while it is not strict.
831
+ checks.push({
832
+ id: 'strictness-mode',
833
+ status: strictnessMode === 'strict' ? 'ok' : 'warn',
834
+ detail: strictnessMode === 'strict'
835
+ ? `gate strictness: strict (the default; every unresolved obligation blocks)`
836
+ : `gate strictness: ${strictnessMode} — the gate does NOT block everything it finds; ` +
837
+ "in 'warn' it exits 0 with wouldBlock, in 'changed' it blocks only debt this change touches. " +
838
+ 'Set mode: strict (or remove the key) to restore full blocking.',
839
+ });
840
+ const keyExposure = verifierKeyExposure(io.cwd, io.env);
841
+ const keyExposureDetail = keyExposure.paths.length > 0
842
+ ? `verifier key material found in repository/state files: ${keyExposure.paths.join(', ')}; move it to the owner-only XDG key ring with \`gateforge key create\`, then remove the exposed copies`
843
+ : keyExposure.scanError
844
+ ? 'verifier-key safety scan could not verify every source; use an external owner-only key ring and inspect repository/state files'
845
+ : keyExposure.configured
846
+ ? 'active verifier key is external; no repository/state copy found'
847
+ : 'no active external verifier key configured; create one with `gateforge key create --confirm` before witnessed receipt verification';
848
+ checks.push({
849
+ id: 'verifier-key-location',
850
+ status: keyExposure.paths.length > 0 || keyExposure.scanError || !keyExposure.configured ? 'warn' : 'ok',
851
+ detail: keyExposureDetail,
852
+ });
135
853
  // 1. Hook presence + ACTIVATION (never reported as managed protection).
136
854
  const hook = inspectCommitHook(io.cwd, io.env);
855
+ // A framework-managed hook is WIRED, not foreign: the gate lives in
856
+ // `.pre-commit-config.yaml` and runs on every commit exactly like any
857
+ // other framework hook. Reporting it as a non-gateforge hook Gateforge
858
+ // "did not touch" contradicted what `init` had just said about the
859
+ // very same file.
860
+ const frameworkGate = frameworkHookGateWired(io.cwd, hook.hookPath);
137
861
  checks.push({
138
862
  id: 'hook',
139
- status: hook.verifyOk ? 'ok' : hook.marker ? 'fail' : 'warn',
140
- detail: hook.detail,
863
+ status: frameworkGate || hook.verifyOk ? 'ok' : hook.marker ? 'fail' : 'warn',
864
+ detail: frameworkGate
865
+ ? `the commit gate runs through the pre-commit framework: ${hook.hookPath} is framework-generated ` +
866
+ 'and .pre-commit-config.yaml declares gateforge-check, which runs on every commit — gateforge does not ' +
867
+ 'edit the generated hook file (a direct edit is wiped by the next framework install)'
868
+ : hook.detail,
869
+ });
870
+ const hookMutation = precommitMutationCheck(io.cwd, io.env);
871
+ checks.push({ id: 'hook-mutation', ...hookMutation });
872
+ const ciWired = hasWiredCi(io.cwd);
873
+ checks.push({
874
+ id: 'ci',
875
+ status: ciWired ? 'ok' : 'warn',
876
+ detail: ciWired ? 'a Gateforge CI template is present and included' : 'no wired Gateforge CI template was detected',
877
+ });
878
+ const githubWorkflow = join(io.cwd, '.github', 'workflows', 'gateforge.yml');
879
+ const gitlabTemplate = join(io.cwd, '.gateforge', 'ci', 'gitlab-gateforge.yml');
880
+ const protection = existsSync(githubWorkflow)
881
+ ? probeGitHubProtection(io)
882
+ : existsSync(gitlabTemplate)
883
+ ? probeGitLabProtection(io)
884
+ : { verified: false, detail: 'server protection: not verified (no supported read-only probe context)' };
885
+ checks.push({
886
+ id: 'server-protection',
887
+ status: protection.verified ? 'ok' : 'warn',
888
+ detail: protection.detail,
889
+ });
890
+ // 2. Runner readiness for the CONFIGURED runner (cheap probes only —
891
+ // nothing is launched; without a `runner:` key this is exactly the
892
+ // historical Playwright probe).
893
+ checks.push({
894
+ id: 'runner',
895
+ ...(configOk
896
+ ? runnerReadiness(io.cwd, loadConfigAt(io.cwd), io.env)
897
+ : {
898
+ status: 'fail',
899
+ detail: 'runner readiness was not checked: .gateforge.yml could not be loaded, so the configured runner is unknown',
900
+ }),
901
+ });
902
+ // 2b. The ENGINE-OWNED browser, when this repository actually
903
+ // declares engine-controlled browser evidence. The `runner` line
904
+ // above reports the CONSUMER's builds and stays exactly as it was:
905
+ // a consumer on a different Playwright release is precisely the
906
+ // case where the two answers disagree, so collapsing them would
907
+ // reproduce the false all-clear this line exists to end.
908
+ checks.push({
909
+ id: 'engine-browser',
910
+ ...(configOk
911
+ ? engineBrowserReadiness(io.cwd, loadConfigAt(io.cwd), io.env)
912
+ : {
913
+ status: 'warn',
914
+ detail: 'engine browser readiness was not checked: .gateforge.yml could not be loaded, so no engine-browser requirement is known',
915
+ }),
141
916
  });
142
- // 2. Runner readiness (cheap probes only — nothing is launched).
143
- checks.push({ id: 'runner', ...playwrightReadiness(io.cwd) });
144
917
  // 3. Observer capability (Phase 0 capability registry; witness probe
145
918
  // only when the caller wired GATEFORGE_WITNESS_URL).
146
919
  const capabilities = allCapabilities();
@@ -161,6 +934,31 @@ export async function buildDoctorReport(io) {
161
934
  observerDetail += '; no external witness configured (the supervised run spawns a loopback witness)';
162
935
  }
163
936
  checks.push({ id: 'observer', status: 'ok', detail: observerDetail });
937
+ // 3a. Evidence adapters: the connect-your-project half, as one line.
938
+ // Diagnostic only — a missing or invalid adapter is the gate's own
939
+ // business, and it already blocks there.
940
+ try {
941
+ const config = loadConfigAt(io.cwd);
942
+ const reports = await auditAdapters(join(io.cwd, config.adapters ?? '.gateforge/adapters'));
943
+ const invalid = reports.filter((report) => !report.ok);
944
+ checks.push({
945
+ id: 'adapters',
946
+ status: invalid.length === 0 ? 'ok' : 'warn',
947
+ detail: reports.length === 0
948
+ ? 'no evidence adapter yet — `gateforge adapters scaffold` writes a starting point per business resource'
949
+ : `${String(reports.length)} evidence adapter(s) in ${config.adapters ?? '.gateforge/adapters'}` +
950
+ (invalid.length === 0
951
+ ? '; all satisfy the contract'
952
+ : `; ${String(invalid.length)} invalid (${invalid.map((report) => report.name).join(', ')}) — the witness refuses to start`),
953
+ });
954
+ }
955
+ catch (error) {
956
+ checks.push({
957
+ id: 'adapters',
958
+ status: 'warn',
959
+ detail: `evidence adapters could not be audited: ${error.message.split('\n')[0] ?? 'unknown'}`,
960
+ });
961
+ }
164
962
  // 3b. Complete-behavior readiness (plan 2026-09-19 Phase 9 item 3):
165
963
  // when `behaviorPolicy` is configured the doctor reports the profile's
166
964
  // actual state — document presence, parseability, and whether endpoint
@@ -308,11 +1106,18 @@ export async function buildDoctorReport(io) {
308
1106
  '`--no-verify`, an alternate core.hooksPath, direct plumbing, or an unrelated clone bypass it (ADR 0005 D1)',
309
1107
  });
310
1108
  }
1109
+ // A framework-wired gate is an ACTIVE local hook, exactly like a
1110
+ // Gateforge-owned one: the check runs on every commit either way.
1111
+ const hookActive = hook.verifyOk || frameworkGate;
1112
+ const level = ciWired && protection.verified ? 3 : ciWired ? 2 : hookActive ? 1 : 0;
311
1113
  return {
312
1114
  mode,
313
1115
  strictE2E,
1116
+ engine: engineIdentity(),
1117
+ level,
314
1118
  checks: [...checks].sort((a, b) => (a.id < b.id ? -1 : a.id > b.id ? 1 : 0)),
315
1119
  ready: checks.every((check) => check.status !== 'fail'),
1120
+ run,
316
1121
  };
317
1122
  }
318
1123
  /**
@@ -336,17 +1141,59 @@ export async function enforcementCommand(io, argv) {
336
1141
  writeLine(io.stdout, ENFORCEMENT_USAGE);
337
1142
  return 0;
338
1143
  }
339
- rejectUnknownFlags(options, ['json', 'help'], ENFORCEMENT_USAGE);
1144
+ rejectUnknownFlags(options, ['json', 'help', 'strict-preflight'], ENFORCEMENT_USAGE);
340
1145
  const report = await buildDoctorReport(io);
341
1146
  if (options['json'] === true) {
342
1147
  writeLine(io.stdout, canonicalJson(report));
343
- return 0;
1148
+ return strictExit(io, report.run, options['strict-preflight'] === true, 'json');
344
1149
  }
1150
+ writeLine(io.stdout, `You are at level ${report.level}.`);
1151
+ writeLine(io.stdout, report.level === 3
1152
+ ? 'The protected branch requires the Gateforge status check.'
1153
+ : report.level === 2
1154
+ ? "To reach level 3, protect the branch and require the 'gateforge' status check."
1155
+ : report.level === 1
1156
+ ? 'To reach level 2, wire the generated Gateforge CI template into your provider.'
1157
+ : 'To reach level 1, run `gateforge init --blocking`.');
345
1158
  writeLine(io.stdout, `gateforge enforcement doctor (mode ${report.mode}, strictE2E ${String(report.strictE2E)})`);
1159
+ writeLine(io.stdout, engineSourceLine(report.engine, engineInstallProvenance(enginePackageRoot())));
1160
+ if (report.engine.unpublished)
1161
+ writeLine(io.stdout, 'unpublished engine: CI will not have this code');
346
1162
  for (const check of report.checks) {
347
1163
  writeLine(io.stdout, ` [${check.status.toUpperCase()}] ${check.id}: ${check.detail}`);
348
1164
  }
349
1165
  writeLine(io.stdout, `overall: ${report.ready ? 'ready (no failing checks)' : 'NOT ready (failing checks above)'} — diagnostic only; exit 0 either way`);
350
- return 0;
1166
+ writeLine(io.stdout, 'run preconditions (read-only; `gateforge run` consumes these)');
1167
+ for (const check of report.run.checks) {
1168
+ writeLine(io.stdout, ` [${check.status.toUpperCase()}] ${check.id}: ${check.detail}`);
1169
+ }
1170
+ writeLine(io.stdout, `run preconditions: ${report.run.ready ? 'ready' : 'NOT ready (failing preconditions above)'} — report-only; exit 0 unless --strict-preflight`);
1171
+ return strictExit(io, report.run, options['strict-preflight'] === true, 'text');
1172
+ }
1173
+ /**
1174
+ * Applies `--strict-preflight`: the default doctor is report-only and
1175
+ * exits 0 whenever it runs, so today's behavior is byte-identical;
1176
+ * with the flag the FIRST failing precondition ends the command with
1177
+ * exit 1 and names the fix on stderr.
1178
+ *
1179
+ * Args:
1180
+ * io: process context.
1181
+ * run: the managed-run preflight section.
1182
+ * strict: whether `--strict-preflight` was given.
1183
+ * format: the printed surface, for the diagnostic wording.
1184
+ *
1185
+ * Returns:
1186
+ * number: 1 at the first failing precondition under the flag, else 0.
1187
+ */
1188
+ function strictExit(io, run, strict, format) {
1189
+ if (!strict)
1190
+ return 0;
1191
+ const failure = firstFailingCheck(run);
1192
+ if (failure === null)
1193
+ return 0;
1194
+ writeLine(io.stderr, `run preconditions: [FAIL] ${failure.id}: ${failure.detail}`);
1195
+ if (format === 'json')
1196
+ writeLine(io.stderr, 'run preconditions: not ready (see the run section of the report above)');
1197
+ return 1;
351
1198
  }
352
1199
  //# sourceMappingURL=enforcement.js.map