@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
@@ -18,30 +18,40 @@
18
18
  import { existsSync, mkdirSync, readFileSync, renameSync, unlinkSync, writeFileSync } from 'node:fs';
19
19
  import { randomUUID } from 'node:crypto';
20
20
  import { createInterface } from 'node:readline/promises';
21
- import { join } from 'node:path';
22
- import { parse as parseYaml } from 'yaml';
21
+ import { isAbsolute, join } from 'node:path';
22
+ import { parse as parseYaml, parseDocument, isSeq as isYamlSeq, isMap as isYamlMap } from 'yaml';
23
23
  import { ClassificationPolicySchema, PolicyFileSchema, loadConfig, parseConfig, serializeBaseline, strictCapabilityGaps, } from '@gate-forge/core';
24
24
  import { DEFAULT_PLANES_CONFIG, PLANES_CONFIG_PATH, createSqlalchemyDetector, parsePlanesConfigText, PACK_VERSION as PACK_SQLALCHEMY_VERSION, } from '@gate-forge/pack-sqlalchemy';
25
+ import { collectRoutePlaneFacts, proposeRouteFolderPlanes, } from '../route-plane-proposals.js';
25
26
  import { PACK_VERSION as PACK_FASTAPI_VERSION } from '@gate-forge/pack-fastapi';
26
27
  import { PACK_VERSION as PACK_HTTP_VERSION } from '@gate-forge/pack-http';
27
28
  import { PACK_VERSION as PACK_TASK_VERSION } from '@gate-forge/pack-task';
29
+ import { renderAlembicOptIn } from '@gate-forge/pack-alembic';
28
30
  import { parseArgs, stringFlag } from '../args.js';
29
- import { writeLine } from '../io.js';
31
+ import { recordInitPath, writeLine } from '../io.js';
30
32
  import { UsageError } from '../errors.js';
31
33
  import { languageDefaultPlugins, recommendPlugins, renderScanBlock, scanRepo } from '../repo-scan.js';
32
34
  import { rejectUnknownFlags } from './common.js';
33
- import { expandIncludePaths } from '../glob.js';
35
+ import { expandScanPaths } from '../glob.js';
36
+ import { gitIgnoredPaths } from '../git-ignored.js';
34
37
  import { inferPlanesConfig } from '../planes-inference.js';
35
- import { hasGateforgeMarker, installCommitHook, writeStandaloneGateScript } from '../git-hooks.js';
36
- import { appendPreCommitHook, ensureHookScript, engineRootFromInvocation, writeGitlabCiTemplate as writeSharedGitlabCiTemplate, } from './blocking.js';
38
+ import { hasGateforgeMarker, installCommitHook, installPrePushHook, writeStandaloneGateScript } from '../git-hooks.js';
39
+ import { appendPreCommitHook, ensureHookScript, engineRootFromInvocation, detectCiProvider, writeGitlabCiTemplate as writeSharedGitlabCiTemplate, writeServerProtectionInstructions, } from './blocking.js';
37
40
  import { trustedPolicyDigestForConfig } from '../execution.js';
38
41
  import { DOCS_EXCLUSIONS_GUARANTEE, DOCS_EXCLUSIONS_PATH, loadDocsExclusions, renderDocsExclusions, validateRequestedDocsFolders, } from '../docs-exclusions.js';
39
- export const INIT_USAGE = '[--no-scan] [--proof overlay|observe] [--blocking] [--pre-commit] [--mode changed|staged] ' +
40
- '[--witnessed staged|full] [--ci] [--no-ci] [--docs-exclude <folder,...> [--confirm-doc-exclusions]] ' +
41
- '[--strict-e2e] [--planes] [--behavior]';
42
+ import { CACHE_EXCLUSIONS_GUARANTEE, CACHE_EXCLUSIONS_PATH, loadCacheExclusions, renderCacheExclusions, validateRequestedCacheFiles, } from '../cache-exclusions.js';
43
+ import { DEFAULT_STATE_DIR } from '../state.js';
44
+ import { CHOOSE_ANOTHER_GOAL_ADVICE, INIT_PRESETS, isInitPresetName, parseGoalAnswer, renderGoalQuestion, renderPresetTable, renderPresetSummary, } from './init-presets.js';
45
+ import { BEHAVIOR_NAMESPACES, behaviorPackEvidence, behaviorSkeletonExamples, detectBehaviorPacks, parseBehaviorPacks, } from '../behavior-setup.js';
46
+ export const INIT_USAGE = '[--preset light|normal|strict] [--explain-presets] [--no-scan] [--proof overlay|observe] ' +
47
+ '[--blocking] [--no-blocking] [--pre-commit] [--no-pre-commit] [--mode changed|staged] ' +
48
+ '[--witnessed staged|full] [--ci] [--no-ci] ' +
49
+ '[--docs-exclude <folder,...> [--docs-exclude-file <path>] [--confirm-doc-exclusions]] [--cache-exclude <file,...> ' +
50
+ '[--confirm-cache-exclusions]] [--strict-e2e] [--planes] [--no-planes] ' +
51
+ '[--behavior] [--no-behavior] [--behavior-packs <pack,...>] [--unmatched-routes block|warn]';
42
52
  /** Template for the complete-behavior owner document (plan §4.1). */
43
53
  export const BEHAVIOR_TEMPLATE = `\
44
- # Complete-behavior owner document (plan §4.1).
54
+ # Complete-behavior owner document.
45
55
  # Presence of this file enables the complete-behavior profile: every
46
56
  # discovered endpoint must have an approved declaration (cases or an
47
57
  # owner disposition). There is no warnOnly or silent fallback.
@@ -83,16 +93,20 @@ const BUNDLED_PLUGIN_VERSIONS = Object.freeze({
83
93
  });
84
94
  /**
85
95
  * The bundled plugin ids init may write (the four trusted detector
86
- * packs). `gateforge.pack-task` carries no semantic verifier, so it is
87
- * opt-in only via `--plugins` — never recommended, never defaulted.
96
+ * packs). `gateforge.pack-task` is opt-in only via `--plugins` — never
97
+ * recommended, never defaulted — because the `task:*` contracts it
98
+ * discovers are gradable ONLY once the owner configures a
99
+ * `queueObserver` (the engine's own queue read); without one every one
100
+ * of them stays `VERIFIER_UNSUPPORTED`/fail-closed.
88
101
  */
89
102
  const KNOWN_BUNDLED_PLUGIN_IDS = new Set(Object.keys(BUNDLED_PLUGIN_MODULES));
90
103
  /**
91
104
  * Selects the bundled detectors required by the generated coverage and
92
105
  * trusted-entry-point rules for the requested source languages.
93
- * `gateforge.pack-task` is NEVER included: it has no semantic verifier
94
- * (every contract grades VERIFIER_UNSUPPORTED), so it is opt-in only
95
- * via `--plugins`.
106
+ * `gateforge.pack-task` is NEVER included: it is opt-in only via
107
+ * `--plugins`, because its contracts grade only with a configured
108
+ * `queueObserver` and a generated default would promise coverage the
109
+ * repository cannot produce.
96
110
  *
97
111
  * Args:
98
112
  * languages (readonly string[]): Languages selected by `gateforge init`.
@@ -109,6 +123,63 @@ function pluginsTemplate(pluginIds) {
109
123
  .map((id) => ` - id: ${id}\n version: '${BUNDLED_PLUGIN_VERSIONS[id]}'\n transport: in-process\n module: '${BUNDLED_PLUGIN_MODULES[id]}'`)
110
124
  .join('\n');
111
125
  }
126
+ /**
127
+ * Adds the requested bundled detectors to an existing `.gateforge.yml`
128
+ * without touching anything else in the owner's file.
129
+ *
130
+ * The merge is ADDITIVE: an id already present keeps its owner's entry
131
+ * (version pin, transport, module) byte for byte, an id that is absent
132
+ * is appended with the bundled module/version, and no entry is ever
133
+ * removed — `--plugins` chooses what to ADD, and the plugin list is the
134
+ * one config section the product's own tip tells a user to change.
135
+ * Everything outside the `plugins:` sequence (keys, comments, the
136
+ * owner's own edits) is preserved exactly.
137
+ *
138
+ * Args:
139
+ * existingText: the current `.gateforge.yml` contents.
140
+ * pluginIds: the bundled detector ids to ensure are present.
141
+ *
142
+ * Returns:
143
+ * string | null: the merged document, or null when every requested id
144
+ * is already present (nothing to write).
145
+ *
146
+ * Throws:
147
+ * UsageError: the merged document would not satisfy the pinned
148
+ * config schema (a broken merge must fail here, not at the next run).
149
+ */
150
+ function mergePluginsIntoConfig(existingText, pluginIds) {
151
+ const document = parseDocument(existingText);
152
+ const pluginsNode = document.get('plugins');
153
+ if (!isYamlSeq(pluginsNode)) {
154
+ throw new UsageError('init --plugins: the existing .gateforge.yml has no `plugins:` list to add to; ' +
155
+ 'add the entry by hand (one block per detector: `id`, `version`, `transport`, `module`)');
156
+ }
157
+ const present = new Set();
158
+ for (const item of pluginsNode.items) {
159
+ // A `plugins:` entry is a YAML mapping node, not a plain object.
160
+ if (!isYamlMap(item))
161
+ continue;
162
+ const id = item.get('id');
163
+ if (typeof id === 'string')
164
+ present.add(id);
165
+ }
166
+ const missing = pluginIds.filter((id) => !present.has(id));
167
+ if (missing.length === 0)
168
+ return null;
169
+ for (const id of missing) {
170
+ pluginsNode.add({
171
+ id,
172
+ version: BUNDLED_PLUGIN_VERSIONS[id],
173
+ transport: 'in-process',
174
+ module: BUNDLED_PLUGIN_MODULES[id],
175
+ });
176
+ }
177
+ const merged = document.toString();
178
+ // Self-check against the pinned schema BEFORE writing (the same
179
+ // contract the fresh-config path keeps).
180
+ parseConfig(parseYaml(merged), { file: '.gateforge.yml' });
181
+ return merged;
182
+ }
112
183
  /**
113
184
  * Selects source-only include globs so AST detectors do not parse
114
185
  * dependencies, caches, lockfiles, or arbitrary repository assets.
@@ -132,27 +203,21 @@ function sourceIncludePatterns(languages) {
132
203
  return patterns.length > 0 ? patterns : ['**/*'];
133
204
  }
134
205
  /**
135
- * The starter policies document (plan phase 5): the gradable
136
- * `persistence:*` namespace for automatically classified resources.
137
- * UI-semantic `crud:*` stays opt-in and visibly fail-closed until a
138
- * trusted UI observer exists (ADR 0003 §3).
206
+ * The starter policies preserve available persistence evidence and use
207
+ * only transport-level proof for consumed HTTP endpoints.
139
208
  */
140
209
  /**
141
- * Opt-in transport-only endpoint policy (plan §8 / D1): proves only that
210
+ * Transport-only endpoint policy example (plan §8 / D1): proves only that
142
211
  * the witness observed a matching HTTP exchange in the bound run. Test
143
212
  * attribution is suite-claimed — it does not prove which browser, UI
144
- * action, or test produced the exchange. Selecting this document
145
- * changes the guarantee: it is a SEPARATE opt-in policy, never an
146
- * automatic migration of the default frontend requirement, baselines,
147
- * or waivers.
213
+ * action, or test produced the exchange.
148
214
  */
149
215
  export const TRANSPORT_ONLY_POLICY_EXAMPLE = `\
150
- # Transport-only endpoint policy (plan §8 / D1, explicit opt-in).
216
+ # Transport-only endpoint policy.
151
217
  # Each obligation proves only that the witness observed a matching HTTP
152
218
  # exchange in the bound run ("witness observed an HTTP exchange");
153
219
  # test attribution is suite-claimed ("suite-claimed"), never proven
154
- # browser-issued by an independent channel. Selecting this policy narrows the
155
- # guarantee relative to the default frontend requirement below.
220
+ # browser-issued by an independent channel.
156
221
  schemaVersion: 1
157
222
  policies:
158
223
  - id: frontend-consumed-endpoints-transport-only
@@ -170,10 +235,17 @@ export const POLICIES_TEMPLATE = `\
170
235
  # and are graded on the witness's own engine-side observation.
171
236
  # UI-semantic crud:* contracts intentionally fail closed (no
172
237
  # witness-controlled UI observation channel exists yet) — add them only
173
- # deliberately. Endpoint proof stays transport-only and opt-in
174
- # (TRANSPORT_ONLY_POLICY_EXAMPLE below): 'http:frontend-request-observed'
175
- # has no independent browser/test observation channel, so it is NEVER a
176
- # starter requirement.
238
+ # deliberately. Consumed HTTP endpoints use transport-only proof;
239
+ # 'http:frontend-request-observed' has no independent browser/test channel
240
+ # and is never included in a new-install starter.
241
+ #
242
+ # A route no UI calls owes nothing below, so a NEW endpoint with no test is
243
+ # invisible until it is consumed. To make every discovered route owe the
244
+ # observation contracts (only NEW debt blocks; run 'gateforge adopt' to
245
+ # forgive what already exists), uncomment the options section below:
246
+ #
247
+ # options:
248
+ # 'http.endpoint.requireObservation': all
177
249
  schemaVersion: 1
178
250
  policies:
179
251
  # Capability-scoped endpoint policies (workflow/validation/...) may be added
@@ -187,6 +259,13 @@ policies:
187
259
  - persistence:read
188
260
  - persistence:update
189
261
  - persistence:delete
262
+ - id: frontend-consumed-endpoints-transport-only
263
+ when:
264
+ kind: http.endpoint
265
+ consumed: true
266
+ require:
267
+ - http:request-observed
268
+ - http:response-status-ok
190
269
  `;
191
270
  /**
192
271
  * The classification policy (plan phase 5, ADR 0003 D4/D5): scan roots
@@ -204,8 +283,8 @@ policies:
204
283
  * Task-scoped rules (the `linkage.task` coverage rule and the worker
205
284
  * entry-point detector binding) are emitted ONLY when `pack-task` is in
206
285
  * the selected plugin set: a coverage rule or detector binding naming an
207
- * unconfigured detector fails every run closed, and task is opt-in
208
- * (no semantic verifier).
286
+ * unconfigured detector fails every run closed, and task is opt-in —
287
+ * its contracts grade only with a configured `queueObserver`.
209
288
  */
210
289
  function classificationPolicyTemplate(languages, pluginIds) {
211
290
  const selected = new Set(pluginIds);
@@ -277,17 +356,60 @@ volatileFields:
277
356
  - created_at
278
357
  `;
279
358
  }
359
+ /**
360
+ * The runner names the repository scan can detect, in the order the scan
361
+ * reports its signals. `playwright` is the frozen default: it is never
362
+ * written into a new config.
363
+ */
364
+ const DETECTABLE_RUNNERS = ['playwright', 'vitest', 'cypress', 'pytest'];
280
365
  /** Builds the `.gateforge.yml` document for the requested languages. */
281
- function configTemplate(languages, pluginIds, options = {}) {
282
- const enforcementBlock = options.strictE2E === true
366
+ function configTemplate(languages, pluginIds,
367
+ /** `strictnessMode` writes the owner-owned `mode:` key; undefined writes NO key, which is today's byte-identical config. */
368
+ options = {}) {
369
+ const enforcementBlock = options.enforcement === true
283
370
  ? `# Enforcement: standard mode combines the local hook with a mandatory
284
371
  # trusted server check. strictE2E makes waived/baselined in-scope E2E
285
372
  # obligations NOT proof (they block with ENFORCEMENT_UNTRUSTED).
286
373
  enforcement:
287
374
  mode: standard
288
- strictE2E: true
375
+ strictE2E: ${String(options.strictE2E === true)}
376
+ receiptStage: pre-push
289
377
  `
290
378
  : '';
379
+ // The owner-owned strictness key. Only written when a preset named it:
380
+ // without a preset the config stays byte-identical to today's, and an
381
+ // ABSENT key means `strict` (the frozen behavior).
382
+ const strictnessBlock = options.strictnessMode === undefined
383
+ ? ''
384
+ : `# How hard the gate blocks: strict = block everything, changed = block
385
+ # only the debt this change touches, warn = report everything and block
386
+ # nothing. This softens the GATE, never the evidence.
387
+ mode: ${options.strictnessMode}
388
+ `;
389
+ // The owner-owned runner key: only written when the scan detected a
390
+ // single non-Playwright runner. An absent key means `playwright`, the
391
+ // frozen default, so an existing/ambiguous setup is byte-identical.
392
+ const runnerBlock = options.runner === undefined
393
+ ? ''
394
+ : `# The test runner the supervised gate drives. Playwright is the default when
395
+ # this key is absent; the scan detected another runner in this repository.
396
+ runner: ${options.runner}
397
+ `;
398
+ const historyBlock = options.historyRetentionDays === undefined
399
+ ? ''
400
+ : `history:\n retentionDays: ${String(options.historyRetentionDays)}\n`;
401
+ // The owner-owned unmatched-route grading. Only written when the owner
402
+ // answered (the terminal question, the flag, or the non-interactive
403
+ // `warn`); an existing config that said nothing keeps saying nothing,
404
+ // and the `check`/`next` banner keeps asking.
405
+ const endpointsBlock = options.unmatchedRoutes === undefined
406
+ ? ''
407
+ : `# Routes whose name matches no discovered resource (ENDPOINT_RESOURCE_CANDIDATE_UNMATCHED).
408
+ # 'warn' reports them as advisories with a banner; 'block' makes them
409
+ # blocking entries like any other finding. Absent means 'warn'.
410
+ endpoints:
411
+ unmatchedRoutes: ${options.unmatchedRoutes}
412
+ `;
291
413
  return `\
292
414
  # gateforge project configuration (schemaVersion 1)
293
415
  schemaVersion: 1
@@ -308,6 +430,15 @@ ${sourceIncludePatterns(languages).map((pattern) => ` - '${pattern}'`).join
308
430
  - '**/.mypy_cache/**'
309
431
  - '**/dist/**'
310
432
  - '**/build/**'
433
+ # Hidden dot-folders (agent tooling like .claude/ or .cursor/,
434
+ # editor/tool caches, leftover merge or working folders) hold
435
+ # tooling and debris, never application code. The rule is generic
436
+ # -- it keys on the dot prefix at any depth -- so any hidden folder
437
+ # is skipped, whatever it is called. .gateforge is the ONE
438
+ # exception and is deliberately NOT matched here: Gateforge's own
439
+ # configuration stays in scope.
440
+ - '**/.(!(gateforge))/**'
441
+ - '.!(gateforge)/**'
311
442
  # Detector plugins. Bundled detectors are preconfigured for the selected
312
443
  # languages and are loaded from their trusted package entry points.
313
444
  plugins:
@@ -323,7 +454,7 @@ witness:
323
454
  maxDurationSeconds: 5
324
455
  clock:
325
456
  mode: system
326
- ${enforcementBlock}\
457
+ ${endpointsBlock}${runnerBlock}${historyBlock}${strictnessBlock}${enforcementBlock}\
327
458
  `;
328
459
  }
329
460
  /**
@@ -374,7 +505,12 @@ You are gated by Gateforge. Work one blocking item at a time.
374
505
  2. Read the single \`next:\` block: \`cause\`, \`why\`, and exactly one \`do:\` line.
375
506
  3. Do the single \`do:\` line. Stop. Re-run \`gateforge next\`.
376
507
 
377
- \`next\` prints ONE action — never a dump. Mapping is intent, not proof.
508
+
509
+ ## Setup guides
510
+
511
+ - Environment rules: \`node_modules/@gate-forge/cli/guides/TEST-ENVIRONMENT.md\`.
512
+ - Quickstart: \`node_modules/@gate-forge/cli/guides/QUICKSTART.md\`.
513
+ (both ship with the installed CLI package)
378
514
 
379
515
  ## Proof lives in the overlay
380
516
 
@@ -417,8 +553,10 @@ with a surface map — they do NOT rewrite existing journeys.
417
553
  - New proof tests go here: \`tests/e2e/gateforge/<resource>.<op>.spec.js\`.
418
554
  - Do not rewrite existing \`tests/e2e/**\` journeys into \`evidence.ui\`.
419
555
  - Do not use \`gateforge tests mark\` as proof: mappings are intent, not proof.
420
- - Fixture shape: \`example/e2e/accounts-crud-journey.spec.js\` in the
421
- gateforge monorepo and the \`@gate-forge/pack-playwright\` README.
556
+ - Fixture shape: \`node_modules/@gate-forge/pack-playwright/examples/overlay-proof.spec.js\`
557
+ (a complete, runnable proof test shipped with the pack you installed —
558
+ copy it here and change the surface). Journey-writing rules:
559
+ \`node_modules/@gate-forge/pack-playwright/README.md\`.
422
560
  `;
423
561
  /**
424
562
  * The Observe proof checklist init prints (never writes) for
@@ -436,6 +574,23 @@ const OBSERVE_CHECKLIST = `observe proof checklist (existing suite through the w
436
574
  4. Run \`gateforge test-gates --changed\`, then \`gateforge check --require-e2e\`.
437
575
  Honest scope: proves persistence (the server stored what the proxied
438
576
  request sent), not "the engine typed the form".`;
577
+ /**
578
+ * The adoption block init prints on the FIRST init of a repository that
579
+ * already has code. Such a repository is not green on day one: the very
580
+ * next commit sees everything discovery found as existing debt. Without
581
+ * this block the owner meets that as a wall of findings with no name
582
+ * for the sanctioned way through it — `gateforge adopt` — which is why
583
+ * the command had to be discovered from a source file instead of from
584
+ * `init`.
585
+ *
586
+ * Everything here is exactly what `adopt` does: the recorded set, its
587
+ * shrink-only standing, and the one case where an adopted E2E
588
+ * obligation still blocks.
589
+ */
590
+ const ADOPT_ADVICE = `this repository already had code, so \`gateforge check\` reports what discovery finds today, and today\'s findings block the first commit:
591
+ gateforge adopt — records today\'s blocking findings as forgiven debt, in a baseline plus a dated, count-annotated receipt, then wires the blocking gate.
592
+ it is shrink-only from here: it never forgives new work. Resolve debt and run \`gateforge baseline update\` to shrink the recorded set; new unproven work keeps blocking.
593
+ with strictE2E enabled, an adopted E2E obligation still blocks with ENFORCEMENT_UNTRUSTED as soon as a change touches it — baselined is not proof.`;
439
594
  /**
440
595
  * Asks (TTY only) whether init should write the recommended setup.
441
596
  * Flags win: `--accept-recommended` forces yes, `--plugins` (an explicit
@@ -446,7 +601,7 @@ async function resolveRecommended(io, options) {
446
601
  if (options['accept-recommended'] === true)
447
602
  return true;
448
603
  if (!process.stdin.isTTY) {
449
- writeLine(io.stdout, 'tip: re-run with --plugins <comma,list> to change detectors');
604
+ writeLine(io.stdout, 'tip: re-run with --plugins <comma,list> to add detectors (entries already in .gateforge.yml are kept; nothing else in the file changes)');
450
605
  return true;
451
606
  }
452
607
  const rl = createInterface({ input: process.stdin, output: process.stdout });
@@ -458,6 +613,70 @@ async function resolveRecommended(io, options) {
458
613
  rl.close();
459
614
  }
460
615
  }
616
+ /**
617
+ * Resolves the goal `init` should set up. Three paths, in order:
618
+ *
619
+ * 1. `--preset light|normal|strict` — an agent or CI run picks the goal
620
+ * explicitly.
621
+ * 2. A real terminal — ONE question ("What should Gateforge do for
622
+ * you?") with three choices, each explained in one line.
623
+ * 3. No terminal and no `--preset` — light only, stated ONCE on the
624
+ * line that also names `--preset <light|normal|strict>`. Gateforge
625
+ * never guesses normal or strict for someone who is not there:
626
+ * guessing strict blocks a team, guessing normal pretends a gate
627
+ * nobody asked for.
628
+ *
629
+ * A run that already carries explicit enforcement flags (`--blocking`,
630
+ * `--strict-e2e`, …) has chosen for itself: no preset is applied and the
631
+ * generated config keeps today's exact bytes.
632
+ *
633
+ * Args:
634
+ * io: process context (prompt + informational output).
635
+ * options: parsed init flags.
636
+ * enforcementFlagGiven (boolean): true when an enforcement flag was
637
+ * passed and therefore wins over any preset.
638
+ *
639
+ * Returns:
640
+ * Promise<{ name: InitPresetName; settings: InitPresetSettings;
641
+ * autoChosen?: boolean } | null>: the applied goal (with
642
+ * `autoChosen` when no human chose it), or null when the run kept
643
+ * today's behavior.
644
+ */
645
+ async function resolveGoal(io, options, enforcementFlagGiven, configExisted) {
646
+ const explicit = options['preset'];
647
+ if (explicit !== undefined && isInitPresetName(explicit)) {
648
+ if (!enforcementFlagGiven)
649
+ return { name: explicit, settings: INIT_PRESETS[explicit] };
650
+ writeLine(io.stdout, `note: --preset ${explicit} is ignored because an enforcement flag decides the wiring; the preset's meaning: ${INIT_PRESETS[explicit].explanation}`);
651
+ return null;
652
+ }
653
+ if (enforcementFlagGiven)
654
+ return null;
655
+ const interactive = process.stdin.isTTY === true && process.stdout.isTTY === true;
656
+ if (!interactive) {
657
+ // ONE line: which goal this run applied, and the flag that changes
658
+ // it. The closing summary used to state the same choice a second
659
+ // time, twenty lines later, in different words.
660
+ writeLine(io.stdout, configExisted
661
+ ? 'no terminal: keeping your existing .gateforge.yml — its `mode:` still decides how hard the gate blocks (the light goal wrote nothing here); ' +
662
+ CHOOSE_ANOTHER_GOAL_ADVICE
663
+ : `no terminal: writing the light preset (report everything, block nothing) — ${CHOOSE_ANOTHER_GOAL_ADVICE}`);
664
+ return { name: 'light', settings: INIT_PRESETS.light, autoChosen: true };
665
+ }
666
+ writeLine(io.stdout, renderGoalQuestion());
667
+ const rl = createInterface({ input: process.stdin, output: process.stdout });
668
+ let name;
669
+ try {
670
+ name = parseGoalAnswer(await rl.question(' '));
671
+ }
672
+ catch (error) {
673
+ throw new UsageError(error instanceof Error ? error.message : String(error));
674
+ }
675
+ finally {
676
+ rl.close();
677
+ }
678
+ return { name, settings: INIT_PRESETS[name] };
679
+ }
461
680
  /**
462
681
  * Asks (TTY only) whether gateforge should be a blocking gate. Flags win:
463
682
  * --blocking forces yes, --no-blocking forces no, and non-interactive
@@ -481,6 +700,149 @@ async function resolveBlocking(io, options) {
481
700
  rl.close();
482
701
  }
483
702
  }
703
+ /** Asks how long to retain supervised run history in a new interactive setup.
704
+ *
705
+ * Args:
706
+ * io: process context used for the prompt and informational output.
707
+ *
708
+ * Returns:
709
+ * Promise<number | 'off' | undefined>: selected retention; undefined leaves the feature off.
710
+ */
711
+ async function resolveHistoryRetention(io) {
712
+ if (!process.stdin.isTTY || !process.stdout.isTTY)
713
+ return undefined;
714
+ const rl = createInterface({ input: process.stdin, output: process.stdout });
715
+ try {
716
+ const answer = (await rl.question('Keep supervised run history? [14 days/off] (default 14): ')).trim().toLowerCase();
717
+ if (answer === '')
718
+ return 14;
719
+ if (answer === 'off')
720
+ return 'off';
721
+ const days = Number(answer);
722
+ if (Number.isInteger(days) && days >= 1 && days <= 90)
723
+ return days;
724
+ throw new UsageError("init: history retention must be an integer from 1 to 90, or 'off'");
725
+ }
726
+ finally {
727
+ rl.close();
728
+ }
729
+ }
730
+ /**
731
+ * Resolves how a NEW repository grades unmatched by-id routes (0.9.0,
732
+ * owner decision D7).
733
+ *
734
+ * Flags win, then the terminal question, then `warn`. A non-interactive
735
+ * run (an agent, a CI job, a test) writes `warn` and prints the exact
736
+ * setting to choose `block` — it never blocks a repository the owner
737
+ * never asked to gate on. A repository that ALREADY has a
738
+ * `.gateforge.yml` is left untouched: an existing config that has said
739
+ * nothing keeps saying nothing, and the banner keeps asking.
740
+ *
741
+ * Args:
742
+ * io: process context (prompt + informational output).
743
+ * options: parsed init flags.
744
+ * configExisted: whether `.gateforge.yml` was already present.
745
+ *
746
+ * Returns:
747
+ * Promise<{ mode: 'block' | 'warn' | undefined; note: string | undefined }>:
748
+ * the answer to write (`undefined` writes no key) and the non-interactive
749
+ * line to print.
750
+ */
751
+ async function resolveUnmatchedRoutes(io, options, configExisted) {
752
+ const flagValue = stringFlag(options, 'unmatched-routes');
753
+ if (flagValue !== undefined) {
754
+ const mode = flagValue.trim().toLowerCase();
755
+ if (mode !== 'block' && mode !== 'warn') {
756
+ throw new UsageError("init: --unmatched-routes must be 'block' or 'warn'");
757
+ }
758
+ return { mode, note: undefined };
759
+ }
760
+ if (configExisted)
761
+ return { mode: undefined, note: undefined };
762
+ if (!process.stdin.isTTY || !process.stdout.isTTY) {
763
+ return {
764
+ mode: 'warn',
765
+ note: "note: routes whose name matches no table will be REPORTED, not blocking. " +
766
+ "set 'endpoints:\n unmatchedRoutes: block' in .gateforge.yml (or re-run with --unmatched-routes block) to block on them",
767
+ };
768
+ }
769
+ // The question is printed by the command (like the goal question), so it
770
+ // is in the run's own output and survives a non-interactive transcript;
771
+ // the readline prompt only takes the answer.
772
+ writeLine(io.stdout, 'Routes whose name matches no table: block commits, or warn only? [block/warn] (default warn)');
773
+ const rl = createInterface({ input: process.stdin, output: process.stdout });
774
+ try {
775
+ const answer = (await rl.question(' ')).trim().toLowerCase();
776
+ if (answer === '')
777
+ return { mode: 'warn', note: undefined };
778
+ if (answer !== 'block' && answer !== 'warn') {
779
+ throw new UsageError("init: unmatched-route grading must be 'block' or 'warn'");
780
+ }
781
+ return { mode: answer, note: undefined };
782
+ }
783
+ finally {
784
+ rl.close();
785
+ }
786
+ }
787
+ /**
788
+ * Resolves which behavior packs' cases `init` enables (plan 2026-09-30
789
+ * Phase 4). Flags win, then the terminal question, then nothing.
790
+ *
791
+ * A non-interactive run — an agent, a CI job, a test — NEVER enables a
792
+ * pack silently: it prints what it found and the exact flag that
793
+ * enables each pack, and returns none. `--no-behavior` prints nothing at
794
+ * all, so a repository that shows no behavior pack keeps `init`
795
+ * byte-identical.
796
+ *
797
+ * Args:
798
+ * io: process context (the question is asked on the real terminal).
799
+ * input: the detected packs and the owner's explicit flags.
800
+ *
801
+ * Returns:
802
+ * Promise<BehaviorNamespace[]>: the enabled namespaces, in print order.
803
+ */
804
+ async function resolveBehaviorPacks(io, input) {
805
+ if (input.disabled)
806
+ return [];
807
+ if (input.explicit.length > 0)
808
+ return [...input.explicit];
809
+ if (input.detectedPacks.length === 0)
810
+ return [];
811
+ if (input.enableAll)
812
+ return input.detectedPacks.map((pack) => pack.namespace);
813
+ if (!process.stdin.isTTY) {
814
+ writeLine(io.stdout, 'behavior packs detected in this repository (nothing is enabled without a flag):');
815
+ for (const pack of input.detectedPacks) {
816
+ writeLine(io.stdout, ` ${pack.namespace} — ${behaviorPackEvidence(pack)}`);
817
+ }
818
+ writeLine(io.stdout, 'enable their cases, then re-run init:');
819
+ for (const pack of input.detectedPacks) {
820
+ writeLine(io.stdout, ` gateforge init --behavior-packs ${pack.namespace}`);
821
+ }
822
+ if (input.detectedPacks.length > 1) {
823
+ const all = input.detectedPacks.map((pack) => pack.namespace).join(',');
824
+ writeLine(io.stdout, ` gateforge init --behavior-packs ${all}`);
825
+ }
826
+ return [];
827
+ }
828
+ const enabled = [];
829
+ const rl = createInterface({ input: process.stdin, output: process.stdout });
830
+ try {
831
+ writeLine(io.stdout, 'behavior packs detected in this repository — enable the cases for the ones this app really has:');
832
+ for (const pack of input.detectedPacks) {
833
+ writeLine(io.stdout, ` ${pack.namespace} — ${behaviorPackEvidence(pack)}`);
834
+ const answer = (await rl.question(`enable ${pack.namespace} behavior cases? [y/N] `))
835
+ .trim()
836
+ .toLowerCase();
837
+ if (answer === 'y' || answer === 'yes')
838
+ enabled.push(pack.namespace);
839
+ }
840
+ }
841
+ finally {
842
+ rl.close();
843
+ }
844
+ return BEHAVIOR_NAMESPACES.filter((namespace) => enabled.includes(namespace));
845
+ }
484
846
  /**
485
847
  * Asks (TTY only) whether init should propose `.gateforge/planes.json`
486
848
  * from the discovered model directories. Flags win: --planes forces
@@ -507,28 +869,67 @@ async function resolvePlanes(io, options) {
507
869
  rl.close();
508
870
  }
509
871
  }
872
+ /**
873
+ * Reads an owner-supplied folder list file: ONE folder per line, blank
874
+ * lines and `#` comments ignored. The comma list stays supported; this
875
+ * is the same declaration in a form that survives a long repository
876
+ * (typing or pasting dozens of folder names into one prompt wraps
877
+ * unreadably, and `paste -sd,` is not discoverable).
878
+ *
879
+ * Args:
880
+ * cwd: absolute repository root the relative path resolves against.
881
+ * filePath: the value given to `--docs-exclude-file`.
882
+ *
883
+ * Returns:
884
+ * string[]: the folders named by the file, in file order.
885
+ *
886
+ * Throws:
887
+ * UsageError: the file is missing or unreadable (never guessed at).
888
+ */
889
+ function readFolderListFile(cwd, filePath) {
890
+ const absolute = isAbsolute(filePath) ? filePath : join(cwd, filePath);
891
+ let text;
892
+ try {
893
+ text = readFileSync(absolute, 'utf8');
894
+ }
895
+ catch (error) {
896
+ throw new UsageError(`init: cannot read --docs-exclude-file '${filePath}': ${error instanceof Error ? error.message : String(error)}`);
897
+ }
898
+ return text
899
+ .split('\n')
900
+ .map((line) => line.split('#')[0]?.trim() ?? '')
901
+ .filter((line) => line.length > 0);
902
+ }
510
903
  /** Resolves the init owner's explicit documentation-folder declaration. */
511
904
  async function resolveDocsExclusionsForInit(io, options, config) {
512
905
  const current = loadDocsExclusions(io.cwd, config);
513
906
  const requestedValue = stringFlag(options, 'docs-exclude');
907
+ const fileValue = stringFlag(options, 'docs-exclude-file');
514
908
  const confirmUpdate = options['confirm-doc-exclusions'] === true;
515
909
  if (typeof options['confirm-doc-exclusions'] !== 'boolean' && options['confirm-doc-exclusions'] !== undefined) {
516
910
  throw new UsageError("init: '--confirm-doc-exclusions' must be a boolean flag");
517
911
  }
518
- if (requestedValue !== undefined) {
519
- const requested = requestedValue.trim() === ''
520
- ? []
521
- : validateRequestedDocsFolders(io.cwd, requestedValue.split(',').map((folder) => folder.trim()).filter((folder) => folder.length > 0), config);
912
+ if (requestedValue !== undefined || fileValue !== undefined) {
913
+ // Both flags are the SAME declaration in two spellings, so they
914
+ // combine into one ordered, deduplicated list instead of one
915
+ // silently winning over the other.
916
+ const declared = [
917
+ ...(requestedValue === undefined || requestedValue.trim() === ''
918
+ ? []
919
+ : requestedValue.split(',').map((folder) => folder.trim()).filter((folder) => folder.length > 0)),
920
+ ...(fileValue === undefined ? [] : readFolderListFile(io.cwd, fileValue)),
921
+ ];
922
+ const requested = [...new Set(declared)];
522
923
  if (current.length > 0 && JSON.stringify(requested) !== JSON.stringify(current) && !confirmUpdate) {
523
924
  throw new UsageError(`init: changing ${DOCS_EXCLUSIONS_PATH} needs explicit owner review; repeat with --confirm-doc-exclusions`);
524
925
  }
525
926
  if (current.length === 0 && requested.length === 0 && confirmUpdate) {
526
927
  throw new UsageError('init: --confirm-doc-exclusions requires a non-empty --docs-exclude update');
527
928
  }
528
- return { folders: requested, changed: JSON.stringify(requested) !== JSON.stringify(current) };
929
+ return { folders: validateRequestedDocsFolders(io.cwd, requested, config), changed: JSON.stringify(requested) !== JSON.stringify(current) };
529
930
  }
530
931
  if (confirmUpdate) {
531
- throw new UsageError('init: --confirm-doc-exclusions requires --docs-exclude');
932
+ throw new UsageError('init: --confirm-doc-exclusions requires --docs-exclude or --docs-exclude-file');
532
933
  }
533
934
  if (current.length > 0)
534
935
  return { folders: current, changed: false };
@@ -536,7 +937,8 @@ async function resolveDocsExclusionsForInit(io, options, config) {
536
937
  const rl = createInterface({ input: process.stdin, output: process.stdout });
537
938
  try {
538
939
  const answer = await rl.question('Owner assertion: enter documentation-only folders to exclude from evidence identity, or leave blank for none. ' +
539
- 'Gateforge cannot prove that app/tests do not read these files. Folders (comma-separated): ');
940
+ 'Gateforge cannot prove that app/tests do not read these files. Folders (comma-separated; for a long list ' +
941
+ 'write them one per line to a file and pass --docs-exclude-file <path>): ');
540
942
  const raw = answer.trim();
541
943
  const folders = raw.length === 0
542
944
  ? []
@@ -547,18 +949,135 @@ async function resolveDocsExclusionsForInit(io, options, config) {
547
949
  rl.close();
548
950
  }
549
951
  }
550
- writeLine(io.stdout, 'tip: non-interactive init keeps full evidence identity; use --docs-exclude <folder,...> to opt in');
952
+ writeLine(io.stdout, 'tip: non-interactive init keeps full evidence identity; use --docs-exclude <folder,...> (or --docs-exclude-file <path>, one folder per line) to opt in');
551
953
  return { folders: [], changed: false };
552
954
  }
955
+ /**
956
+ * Resolves the init owner's explicit Python bytecode exclusion list.
957
+ *
958
+ * Args:
959
+ * io: process context.
960
+ * options: parsed init flags.
961
+ * config: validated Gateforge configuration.
962
+ *
963
+ * Returns:
964
+ * object: validated files and whether the declaration must be written.
965
+ *
966
+ * Throws:
967
+ * UsageError: invalid flags or an unconfirmed owner-list change.
968
+ */
969
+ function resolveCacheExclusionsForInit(io, options, config) {
970
+ const current = loadCacheExclusions(io.cwd, config);
971
+ const declarationExists = existsSync(join(io.cwd, ...CACHE_EXCLUSIONS_PATH.split('/')));
972
+ const requestedValue = stringFlag(options, 'cache-exclude');
973
+ const confirmUpdate = options['confirm-cache-exclusions'] === true;
974
+ if (typeof options['confirm-cache-exclusions'] !== 'boolean' &&
975
+ options['confirm-cache-exclusions'] !== undefined) {
976
+ throw new UsageError("init: '--confirm-cache-exclusions' must be a boolean flag");
977
+ }
978
+ if (requestedValue === undefined) {
979
+ if (confirmUpdate)
980
+ throw new UsageError('init: --confirm-cache-exclusions requires --cache-exclude');
981
+ return { files: current, changed: false };
982
+ }
983
+ const requested = requestedValue.trim() === ''
984
+ ? []
985
+ : validateRequestedCacheFiles(io.cwd, requestedValue.split(',').map((file) => file.trim()).filter((file) => file.length > 0), config);
986
+ const changed = JSON.stringify(requested) !== JSON.stringify(current);
987
+ if (declarationExists && changed && !confirmUpdate) {
988
+ throw new UsageError(`init: changing ${CACHE_EXCLUSIONS_PATH} needs explicit owner review; repeat with --confirm-cache-exclusions`);
989
+ }
990
+ if (declarationExists && !changed && confirmUpdate) {
991
+ throw new UsageError('init: --confirm-cache-exclusions requires a changed --cache-exclude list');
992
+ }
993
+ return { files: requested, changed };
994
+ }
995
+ /**
996
+ * Asks the owner ONE plane question per ROUTE folder that still has
997
+ * unresolved endpoints (owner decision D1: ask, never infer).
998
+ *
999
+ * The linked model's plane is shown as a HINT and is never applied: an
1000
+ * `accounts` route can serve master data, so the owner answers for the
1001
+ * ROUTES. `proposeRouteFolderPlaneRules` already withholds the hint when
1002
+ * the linked models disagree or are themselves unresolved, so a hint
1003
+ * here always means "these routes serve a model whose plane IS this".
1004
+ *
1005
+ * A non-interactive run proposes nothing and writes nothing: it prints
1006
+ * the folders and the runnable `gateforge classify plane` shape for each,
1007
+ * with the plane and the reason LEFT AS PLACEHOLDERS — printing a concrete
1008
+ * plane would be inferring it for the owner, which is exactly what D1
1009
+ * forbids, and an agent that copies the line would apply a wrong plane to
1010
+ * a folder whose models init inferred as `master`.
1011
+ *
1012
+ * Args:
1013
+ * cwd: absolute repository root.
1014
+ * io: process context.
1015
+ *
1016
+ * Returns:
1017
+ * Promise<PlaneConfigRule[]>: the rules the owner answered for.
1018
+ */
1019
+ async function askRouteFolderPlanes(cwd, io) {
1020
+ let proposals;
1021
+ try {
1022
+ proposals = proposeRouteFolderPlanes(await collectRoutePlaneFacts(cwd));
1023
+ }
1024
+ catch (cause) {
1025
+ writeLine(io.stdout, `warning: route plane discovery failed (${cause instanceof Error ? cause.message : String(cause)}); ` +
1026
+ 'answer the route folders with `gateforge classify plane <folder> <tenant|master|global> --reason "<why>" --confirm` — init continues');
1027
+ return [];
1028
+ }
1029
+ if (proposals.length === 0)
1030
+ return [];
1031
+ const planes = new Set(['tenant', 'master', 'global']);
1032
+ const answers = [];
1033
+ if (process.stdin.isTTY !== true || process.stdout.isTTY !== true) {
1034
+ writeLine(io.stdout, `route folders with no answered plane (${proposals.length}) — one owner answer each, ` +
1035
+ 'never inferred from the linked model:');
1036
+ for (const proposal of proposals) {
1037
+ writeLine(io.stdout, ` ${proposal.folder} (${proposal.routeCount} route(s)` +
1038
+ `${proposal.hintPlane === null ? '' : `, linked model(s) ${proposal.linkedModels.join(', ')} answer to ${proposal.hintPlane} — a hint only`})`);
1039
+ writeLine(io.stdout, ` gateforge classify plane ${proposal.folder} <tenant|master|global> --reason '<why the ROUTES in this folder serve that data>' --confirm`);
1040
+ }
1041
+ return answers;
1042
+ }
1043
+ const rl = createInterface({ input: process.stdin, output: process.stdout });
1044
+ try {
1045
+ writeLine(io.stdout, 'route folders whose plane is still unanswered — one answer per folder, asked because ' +
1046
+ 'a route linked to a model can still serve different data:');
1047
+ for (const proposal of proposals) {
1048
+ const hint = proposal.hintPlane === null
1049
+ ? ''
1050
+ : ` — hint only: the linked model(s) ${proposal.linkedModels.join(', ')} answer to ${proposal.hintPlane}; ` +
1051
+ 'a route can serve other data, so this is your answer to make';
1052
+ const answer = (await rl.question(`plane for '${proposal.folder}' (${proposal.routeCount} route(s)) — tenant/master/global, blank to skip${hint}: `))
1053
+ .trim()
1054
+ .toLowerCase();
1055
+ if (!planes.has(answer)) {
1056
+ if (answer !== '')
1057
+ writeLine(io.stdout, ` skipped '${proposal.folder}': '${answer}' is not a plane`);
1058
+ continue;
1059
+ }
1060
+ answers.push({
1061
+ match: `${proposal.folder}/**`,
1062
+ plane: answer,
1063
+ reason: `answered for the route folder '${proposal.folder}' during gateforge init; review before relying on this`,
1064
+ });
1065
+ }
1066
+ }
1067
+ finally {
1068
+ rl.close();
1069
+ }
1070
+ return answers;
1071
+ }
553
1072
  /**
554
1073
  * Runs discovery over the repo's own include/exclude config, infers a
555
- * planes proposal from the discovered table directories, self-checks
556
- * the draft against the runtime's strict parser, and writes
557
- * `.gateforge/planes.json` — only when absent (never overwrites a
558
- * reviewed document). Inference failure is surfaced as a visible
559
- * warning, never silently skipped, but does not abort the scaffold.
1074
+ * planes proposal from the discovered table directories, adds the owner's
1075
+ * answered ROUTE-folder rules, self-checks the draft against the runtime's
1076
+ * strict parser, and writes `.gateforge/planes.json` — only when absent
1077
+ * (never overwrites a reviewed document). Inference failure is surfaced as a
1078
+ * visible warning, never silently skipped, but does not abort the scaffold.
560
1079
  */
561
- async function proposePlanesConfig(cwd, io) {
1080
+ async function proposePlanesConfig(cwd, io, routeRules = []) {
562
1081
  const planesPath = join(cwd, PLANES_CONFIG_PATH);
563
1082
  if (existsSync(planesPath)) {
564
1083
  writeLine(io.stdout, `exists, leaving untouched: ${planesPath}`);
@@ -568,7 +1087,10 @@ async function proposePlanesConfig(cwd, io) {
568
1087
  try {
569
1088
  const config = loadConfig(join(cwd, '.gateforge.yml'));
570
1089
  const expandErrors = [];
571
- const paths = expandIncludePaths(config.project.paths.include, config.project.paths.exclude, cwd, expandErrors);
1090
+ // The same DETECTOR-INPUT scope the pipeline scans: a gitignored
1091
+ // tree (a built report bundle, a local cache) holds no table the
1092
+ // planes proposal should infer from.
1093
+ const paths = expandScanPaths(config.project.paths.include, config.project.paths.exclude, cwd, gitIgnoredPaths(cwd), expandErrors);
572
1094
  // The planes config plays no role in inference (only table SOURCE
573
1095
  // paths matter), so the detector runs with the default no-mapping
574
1096
  // rule — immune to whatever a previous run wrote.
@@ -587,16 +1109,97 @@ async function proposePlanesConfig(cwd, io) {
587
1109
  if (inference.skippedTestTables > 0) {
588
1110
  writeLine(io.stdout, `note: ${inference.skippedTestTables} table(s) under test directories were excluded from plane inference (fixtures are not business surface)`);
589
1111
  }
590
- if (inference.config === null) {
591
- writeLine(io.stdout, `tip: ${inference.note ?? 'nothing to propose'}`);
592
- return;
593
- }
594
- const serialized = `${JSON.stringify(inference.config, null, 2)}\n`;
1112
+ // A reviewed file with zero rules is a real answer, not a failure:
1113
+ // it declares no plane, which is exactly what the classifier already
1114
+ // assumes while the file is absent. Writing it anyway is what makes
1115
+ // `gateforge init --planes` the runnable prerequisite the
1116
+ // `gateforge next` guidance prints for an unresolved route.
1117
+ // The owner's ROUTE-folder answers join the inferred model rules in the
1118
+ // one file init writes: both are reviewed proposals, and splitting them
1119
+ // across two writes would make the second overwrite the first.
1120
+ const combined = [...(inference.config?.rules ?? []), ...routeRules];
1121
+ const serialized = `${JSON.stringify(combined.length === 0 ? { rules: [] } : { rules: combined }, null, 2)}\n`;
595
1122
  // Self-check the draft against the runtime's strict reader contract
596
1123
  // BEFORE writing (a broken proposal must fail here, not at the next run).
597
1124
  parsePlanesConfigText(serialized, planesPath);
598
1125
  writeFileSync(planesPath, serialized, 'utf8');
599
- writeLine(io.stdout, `created: ${planesPath} (${inference.config.rules.length} rule(s) inferred from model directories — review the reasons before the next gateforge run)`);
1126
+ if (inference.config === null) {
1127
+ writeLine(io.stdout, `created: ${planesPath} (no rule could be inferred — ${inference.note ?? 'nothing to propose'}; ` +
1128
+ 'the file declares no plane, so every table still blocks until you add a reviewed rule)');
1129
+ return;
1130
+ }
1131
+ writeLine(io.stdout, `created: ${planesPath} (${combined.length} rule(s) — ${inference.config?.rules.length ?? 0} inferred from model directories, ` +
1132
+ `${routeRules.length} answered for route folders — review the reasons before the next gateforge run)`);
1133
+ }
1134
+ /**
1135
+ * The engine-owned state directories that must never be committed.
1136
+ *
1137
+ * `.gateforge/test-gates/` holds everything a supervised run caches and
1138
+ * seals: the test catalog, plugin caches, receipts, records, spool and
1139
+ * history. The engine writes it on every `check`/`test-gates`/`next`,
1140
+ * so after `init` the very next `git add -A` staged it — and then the
1141
+ * gate, quite correctly, reported the engine's own cache as unmapped
1142
+ * product changes. Nothing else under `.gateforge/` is engine state:
1143
+ * policies, adapters, waivers, baselines, hooks and the CI template are
1144
+ * owner-reviewed files that MUST be committed.
1145
+ */
1146
+ const ENGINE_STATE_IGNORE_ENTRIES = [`${DEFAULT_STATE_DIR}/`];
1147
+ /**
1148
+ * Whether a `.gitignore` already covers one engine-state entry.
1149
+ *
1150
+ * Comparison is line-wise and tolerant of the forms a human writes
1151
+ * (leading `/`, a trailing `/`, surrounding spaces, a comment) so a
1152
+ * repeated `init` never appends the same rule twice.
1153
+ *
1154
+ * Args:
1155
+ * text: the current `.gitignore` contents (empty when absent).
1156
+ * entry: the repo-relative directory to ignore.
1157
+ *
1158
+ * Returns:
1159
+ * boolean: true when the file already ignores that path.
1160
+ */
1161
+ function ignoresEngineState(text, entry) {
1162
+ const wanted = entry.replace(/\/+$/, '');
1163
+ return text.split('\n').some((line) => {
1164
+ const trimmed = line.trim().replace(/^\/+|\/+$/g, '');
1165
+ return trimmed === wanted || trimmed === `${wanted}/**`;
1166
+ });
1167
+ }
1168
+ /**
1169
+ * Adds the engine-owned state directories to the repository's
1170
+ * `.gitignore`, creating the file when absent and appending when
1171
+ * present. The owner's own lines are preserved byte for byte and a
1172
+ * second run reports "already ignored" instead of appending again.
1173
+ *
1174
+ * Args:
1175
+ * io: process context.
1176
+ * cwd: absolute repository root.
1177
+ *
1178
+ * Returns:
1179
+ * void.
1180
+ */
1181
+ function ignoreEngineState(io, cwd) {
1182
+ const path = join(cwd, '.gitignore');
1183
+ const existed = existsSync(path);
1184
+ const existing = existed ? readFileSync(path, 'utf8') : '';
1185
+ const missing = ENGINE_STATE_IGNORE_ENTRIES.filter((entry) => !ignoresEngineState(existing, entry));
1186
+ if (missing.length === 0) {
1187
+ if (existed) {
1188
+ recordInitPath(io, cwd, path, 'preserved');
1189
+ writeLine(io.stdout, `exists, leaving untouched: ${path} (gateforge engine state already ignored)`);
1190
+ }
1191
+ return;
1192
+ }
1193
+ const block = [
1194
+ '# Gateforge engine state — never committed (regenerated by every run).',
1195
+ ...missing,
1196
+ '',
1197
+ ].join('\n');
1198
+ const prefix = existing.length === 0 || existing.endsWith('\n') ? existing : `${existing}\n`;
1199
+ writeFileSync(path, `${prefix}${block}`, 'utf8');
1200
+ recordInitPath(io, cwd, path, existed ? 'modified' : 'created');
1201
+ writeLine(io.stdout, `${existed ? 'updated' : 'created'}: ${path} (gateforge engine state ignored: ${missing.join(', ')} — ` +
1202
+ 'without this, `git add -A` stages the run cache and the gate blocks on its own files)');
600
1203
  }
601
1204
  /**
602
1205
  * Runs `gateforge init` in the io cwd.
@@ -609,12 +1212,18 @@ async function proposePlanesConfig(cwd, io) {
609
1212
  * number: exit code (0).
610
1213
  */
611
1214
  export async function initCommand(io, argv) {
1215
+ // The ledger every writer below fills: the closing summary names only
1216
+ // what THIS run created or kept, so it can never offer to delete the
1217
+ // owner's pre-existing config, baselines, waivers, hooks or CI file.
1218
+ io.initPaths ??= { created: [], modified: [], preserved: [] };
612
1219
  const { options } = parseArgs(argv);
613
1220
  if (options['help'] === true) {
614
1221
  writeLine(io.stdout, INIT_USAGE);
615
1222
  return 0;
616
1223
  }
617
1224
  rejectUnknownFlags(options, [
1225
+ 'preset',
1226
+ 'explain-presets',
618
1227
  'languages',
619
1228
  'plugins',
620
1229
  'accept-recommended',
@@ -632,10 +1241,30 @@ export async function initCommand(io, argv) {
632
1241
  'planes',
633
1242
  'no-planes',
634
1243
  'behavior',
1244
+ 'unmatched-routes',
1245
+ 'no-behavior',
1246
+ 'behavior-packs',
635
1247
  'docs-exclude',
1248
+ 'docs-exclude-file',
636
1249
  'confirm-doc-exclusions',
1250
+ 'cache-exclude',
1251
+ 'confirm-cache-exclusions',
637
1252
  'help',
638
1253
  ], INIT_USAGE);
1254
+ // --explain-presets prints the ONE mapping table and exits: it must
1255
+ // never scan, prompt or write, so an agent can read what a preset
1256
+ // means before choosing one.
1257
+ if (options['explain-presets'] === true) {
1258
+ writeLine(io.stdout, renderPresetTable());
1259
+ return 0;
1260
+ }
1261
+ if (typeof options['explain-presets'] !== 'boolean' && options['explain-presets'] !== undefined) {
1262
+ throw new UsageError("flag '--explain-presets' must be a boolean flag");
1263
+ }
1264
+ const presetValue = options['preset'];
1265
+ if (presetValue !== undefined && !isInitPresetName(presetValue)) {
1266
+ throw new UsageError(`flag '--preset' must be 'light', 'normal' or 'strict' (got '${String(presetValue)}')`);
1267
+ }
639
1268
  // --proof validation BEFORE any writes: the selected proof path
640
1269
  // (overlay default, observe reuses the existing suite).
641
1270
  const proofValue = options['proof'];
@@ -683,10 +1312,24 @@ export async function initCommand(io, argv) {
683
1312
  if (explicitLanguages !== null && explicitLanguages.length === 0) {
684
1313
  throw new UsageError(`flag '--languages' requires at least one language`);
685
1314
  }
686
- const strictE2E = options['strict-e2e'] === true;
687
1315
  if (typeof options['strict-e2e'] !== 'boolean' && options['strict-e2e'] !== undefined) {
688
- throw new UsageError(`flag '--strict-e2e' must be a boolean flag`);
1316
+ throw new UsageError("flag '--strict-e2e' must be a boolean flag");
689
1317
  }
1318
+ // Goal resolution (plan Phase 1/2): --preset wins, then the one goal
1319
+ // question in a terminal, then light with a loud note. A run that
1320
+ // already carries explicit enforcement flags has chosen for itself, so
1321
+ // no preset is applied and today's byte-identical behavior is kept.
1322
+ const enforcementFlagGiven = options['blocking'] === true ||
1323
+ options['no-blocking'] === true ||
1324
+ options['pre-commit'] === true ||
1325
+ options['no-pre-commit'] === true ||
1326
+ options['witnessed'] !== undefined ||
1327
+ options['mode'] !== undefined ||
1328
+ options['ci'] === true ||
1329
+ options['no-ci'] === true ||
1330
+ options['strict-e2e'] === true;
1331
+ const goal = await resolveGoal(io, options, enforcementFlagGiven, existsSync(join(io.cwd, '.gateforge.yml')));
1332
+ const strictE2E = goal !== null ? goal.settings.strictE2E : options['strict-e2e'] === true;
690
1333
  // Strict-setup preflight (plan Phase 0 item 4): BEFORE anything is
691
1334
  // written — a strict setup demanding an unavailable proof channel
692
1335
  // stays visibly incomplete instead of shipping a false green. The
@@ -696,15 +1339,30 @@ export async function initCommand(io, argv) {
696
1339
  preflightStrictSetup(POLICIES_TEMPLATE);
697
1340
  }
698
1341
  // Scan + recommend + choose (Phase 1 item 1): heuristics inform the
699
- // install; nothing extra is silently enabled. --no-scan skips the
700
- // filesystem walk and falls back to the language-derived set.
1342
+ // install; nothing extra is silently enabled. `--no-scan` skips the
1343
+ // filesystem walk and falls back to the language-derived set (and
1344
+ // claims nothing about how much code is there); `--languages` skips
1345
+ // only the language DERIVATION — the signals and the number of files
1346
+ // the walk really saw are still true.
701
1347
  const noScan = options['no-scan'] === true;
702
- const scan = noScan || explicitLanguages !== null
703
- ? {
704
- languages: explicitLanguages ?? ['python'],
705
- signals: noScan ? [] : scanRepo(io.cwd).signals,
706
- }
707
- : scanRepo(io.cwd);
1348
+ const walked = noScan ? null : scanRepo(io.cwd);
1349
+ const scan = walked === null
1350
+ ? { languages: explicitLanguages ?? ['python'], signals: [], reasons: undefined, files: 0 }
1351
+ : explicitLanguages === null
1352
+ ? walked
1353
+ : { ...walked, languages: explicitLanguages };
1354
+ // Which runner the scan saw. The `runner:` key is owner-owned, so it
1355
+ // is written ONLY when exactly one non-Playwright runner was detected:
1356
+ // Playwright stays the frozen default, and an ambiguous repository
1357
+ // (Playwright + something else, or several others) keeps today's
1358
+ // behavior plus one plain line naming the choice it left to the owner.
1359
+ const detectedRunners = DETECTABLE_RUNNERS.filter((runner) => scan.signals.includes(runner));
1360
+ const otherRunners = detectedRunners.filter((runner) => runner !== 'playwright');
1361
+ const detectedRunner = detectedRunners.includes('playwright') || otherRunners.length !== 1 ? undefined : otherRunners[0];
1362
+ if (otherRunners.length > 0 && detectedRunner === undefined) {
1363
+ writeLine(io.stdout, `note: other test runners detected (${otherRunners.join(', ')}); the new config keeps the default runner — ` +
1364
+ "set `runner: <playwright|pytest|vitest|cypress>` in .gateforge.yml to pick one");
1365
+ }
708
1366
  const recommended = explicitPlugins ?? recommendPlugins(scan);
709
1367
  writeLine(io.stdout, renderScanBlock(scan, recommended, proofMode));
710
1368
  // Flags win: an explicit --plugins choice skips the prompt entirely.
@@ -713,9 +1371,41 @@ export async function initCommand(io, argv) {
713
1371
  return 0;
714
1372
  }
715
1373
  const cwd = io.cwd;
1374
+ // Which CI provider this repository ALREADY used, captured BEFORE any
1375
+ // CI file is written by this run: a repository that shows no provider
1376
+ // at all gets both sets of instructions, and after wiring
1377
+ // `.gitlab-ci.yml` always exists — the question would then be answered
1378
+ // by us rather than read from the repository.
1379
+ const ciProviderBeforeWiring = detectCiProvider(cwd);
1380
+ // Whether `.gateforge.yml` was already there BEFORE this run: the
1381
+ // preset summary must tell the truth about what changed.
1382
+ const existedConfigAtStart = existsSync(join(io.cwd, '.gateforge.yml'));
1383
+ const historyRetentionDays = existsSync(join(cwd, '.gateforge.yml')) ? undefined : await resolveHistoryRetention(io);
1384
+ // How a NEW repository grades unmatched by-id routes (0.9.0, owner
1385
+ // decision D7). Asked once, in a terminal; `warn` and the exact key to
1386
+ // choose `block` on a non-interactive run; an existing config is left
1387
+ // alone and keeps the `check`/`next` banner asking.
1388
+ const unmatchedRoutes = await resolveUnmatchedRoutes(io, options, existedConfigAtStart);
1389
+ if (unmatchedRoutes.note !== undefined)
1390
+ writeLine(io.stdout, unmatchedRoutes.note);
716
1391
  const languages = scan.languages;
717
1392
  const pluginIds = recommended;
718
- const generatedDraftConfig = () => parseConfig(parseYaml(configTemplate(languages, pluginIds, { strictE2E })), { file: '.gateforge.yml' });
1393
+ const configOptions = {
1394
+ strictE2E,
1395
+ enforcement: strictE2E ||
1396
+ options['blocking'] === true ||
1397
+ options['pre-commit'] === true ||
1398
+ (options['witnessed'] === 'staged' || options['witnessed'] === 'full'),
1399
+ historyRetentionDays,
1400
+ // A preset names the owner-owned strictness key; without one the key
1401
+ // stays absent, which means `strict` (today's frozen behavior).
1402
+ strictnessMode: goal?.settings.strictnessMode,
1403
+ // The scanned runner, when it is unambiguous and not Playwright.
1404
+ runner: detectedRunner,
1405
+ // The owner's answer for unmatched by-id routes; undefined writes no key.
1406
+ unmatchedRoutes: unmatchedRoutes.mode,
1407
+ };
1408
+ const generatedDraftConfig = () => parseConfig(parseYaml(configTemplate(languages, pluginIds, configOptions)), { file: '.gateforge.yml' });
719
1409
  let draftConfig;
720
1410
  if (existsSync(join(cwd, '.gateforge.yml'))) {
721
1411
  try {
@@ -723,8 +1413,11 @@ export async function initCommand(io, argv) {
723
1413
  }
724
1414
  catch (error) {
725
1415
  const docsChoiceRequested = stringFlag(options, 'docs-exclude') !== undefined;
1416
+ const cacheChoiceRequested = stringFlag(options, 'cache-exclude') !== undefined;
726
1417
  if (docsChoiceRequested ||
1418
+ cacheChoiceRequested ||
727
1419
  existsSync(join(cwd, ...DOCS_EXCLUSIONS_PATH.split('/'))) ||
1420
+ existsSync(join(cwd, ...CACHE_EXCLUSIONS_PATH.split('/'))) ||
728
1421
  (process.stdin.isTTY === true && process.stdout.isTTY === true)) {
729
1422
  throw error;
730
1423
  }
@@ -735,6 +1428,7 @@ export async function initCommand(io, argv) {
735
1428
  draftConfig = generatedDraftConfig();
736
1429
  }
737
1430
  const docsExclusionChoice = await resolveDocsExclusionsForInit(io, options, draftConfig);
1431
+ const cacheExclusionChoice = resolveCacheExclusionsForInit(io, options, draftConfig);
738
1432
  const gateforgeDir = join(cwd, '.gateforge');
739
1433
  const targets = [
740
1434
  {
@@ -744,8 +1438,8 @@ export async function initCommand(io, argv) {
744
1438
  // Self-check the template against the pinned schema before
745
1439
  // writing anything (a broken template must fail here, not in
746
1440
  // every later command).
747
- parseConfig(parseYaml(configTemplate(languages, pluginIds, { strictE2E })), { file: '.gateforge.yml' });
748
- writeFileSync(join(cwd, '.gateforge.yml'), configTemplate(languages, pluginIds, { strictE2E }), 'utf8');
1441
+ parseConfig(parseYaml(configTemplate(languages, pluginIds, configOptions)), { file: '.gateforge.yml' });
1442
+ writeFileSync(join(cwd, '.gateforge.yml'), configTemplate(languages, pluginIds, configOptions), 'utf8');
749
1443
  },
750
1444
  },
751
1445
  {
@@ -789,10 +1483,27 @@ export async function initCommand(io, argv) {
789
1483
  ]
790
1484
  : []),
791
1485
  ];
1486
+ /**
1487
+ * Queues one scaffold file, keyed by path. Two steps of the same run
1488
+ * can want the SAME file with different content (the config and the
1489
+ * config-with-behaviorPolicy); pushing both made the second entry
1490
+ * report "exists, leaving untouched" about a file the same run had
1491
+ * just created, and silently dropped the richer content. The later
1492
+ * entry wins, in the later entry's position, so exactly one line per
1493
+ * file is ever printed and the fullest content is what lands.
1494
+ */
1495
+ const pushTarget = (target) => {
1496
+ const existing = targets.findIndex((candidate) => candidate.path === target.path);
1497
+ if (existing === -1) {
1498
+ targets.push(target);
1499
+ return;
1500
+ }
1501
+ targets[existing] = target;
1502
+ };
792
1503
  if (docsExclusionChoice.changed) {
793
1504
  const exclusionPath = join(cwd, ...DOCS_EXCLUSIONS_PATH.split('/'));
794
1505
  const exclusionText = renderDocsExclusions(docsExclusionChoice.folders);
795
- targets.push({
1506
+ pushTarget({
796
1507
  path: exclusionPath,
797
1508
  label: 'owner-declared documentation exclusions',
798
1509
  write: () => {
@@ -809,35 +1520,102 @@ export async function initCommand(io, argv) {
809
1520
  },
810
1521
  });
811
1522
  }
1523
+ if (cacheExclusionChoice.changed) {
1524
+ const exclusionPath = join(cwd, ...CACHE_EXCLUSIONS_PATH.split('/'));
1525
+ const exclusionText = renderCacheExclusions(cacheExclusionChoice.files);
1526
+ pushTarget({
1527
+ path: exclusionPath,
1528
+ label: 'owner-declared Python bytecode exclusions',
1529
+ write: () => {
1530
+ const temporaryPath = join(gateforgeDir, `.cache-exclusions-${randomUUID()}.tmp`);
1531
+ try {
1532
+ writeFileSync(temporaryPath, exclusionText, { flag: 'wx', encoding: 'utf8' });
1533
+ renameSync(temporaryPath, exclusionPath);
1534
+ }
1535
+ catch (error) {
1536
+ if (existsSync(temporaryPath))
1537
+ unlinkSync(temporaryPath);
1538
+ throw error;
1539
+ }
1540
+ },
1541
+ });
1542
+ }
812
1543
  mkdirSync(join(gateforgeDir, 'adapters'), { recursive: true });
813
1544
  mkdirSync(join(gateforgeDir, 'waivers'), { recursive: true });
814
1545
  mkdirSync(join(gateforgeDir, 'baselines'), { recursive: true });
815
- // Behavior-profile setup (plan 2026-09-19 §4.11): `--behavior` scaffolds
816
- // .gateforge/behavior.yml (scaffold only — never real approval) and
817
- // wires `behaviorPolicy` into a NEW .gateforge.yml; an existing config
818
- // is left untouched with an instruction to add the key manually.
819
- // `--no-behavior` skips; default (flag absent) skips.
820
- const behaviorFlag = options['behavior'] === true;
1546
+ // Behavior-case setup (plan 2026-09-19 §4.11, Phase 4 of
1547
+ // 2026-09-25): `--behavior` scaffolds .gateforge/behavior.yml
1548
+ // (scaffold only — never real approval) and wires `behaviorPolicy`
1549
+ // into a NEW .gateforge.yml; an existing config is left untouched with
1550
+ // the exact line to add. `--behavior-packs <pack,...>` enables the
1551
+ // named packs' example cases; `--no-behavior` skips.
1552
+ //
1553
+ // Detection decides what init OFFERS, never what it enables: flags
1554
+ // win, then the terminal question, then nothing. A non-interactive
1555
+ // (agent/CI) run prints the exact flag for each pack it found and
1556
+ // enables none of them.
821
1557
  const noBehavior = options['no-behavior'] === true;
822
- const wantBehavior = behaviorFlag && !noBehavior;
1558
+ const behaviorFlag = options['behavior'] === true;
1559
+ const packsValue = options['behavior-packs'];
1560
+ if (typeof packsValue === 'boolean' || Array.isArray(packsValue)) {
1561
+ throw new UsageError("flag '--behavior-packs' may only be given once");
1562
+ }
1563
+ if (typeof packsValue !== 'string' && packsValue !== undefined) {
1564
+ throw new UsageError("flag '--behavior-packs' must be a comma-separated list of pack names");
1565
+ }
1566
+ let requestedNamespaces = [];
1567
+ if (packsValue !== undefined) {
1568
+ try {
1569
+ requestedNamespaces = parseBehaviorPacks(packsValue);
1570
+ }
1571
+ catch (cause) {
1572
+ throw new UsageError(`flag '--behavior-packs': ${cause instanceof Error ? cause.message : String(cause)}`);
1573
+ }
1574
+ if (requestedNamespaces.length === 0) {
1575
+ throw new UsageError("flag '--behavior-packs' requires at least one pack name");
1576
+ }
1577
+ }
1578
+ // The `task` pack is offered ONLY when the owner's config declares a
1579
+ // `queueObserver`: without the engine's own queue read every `task:*`
1580
+ // case fails closed, so recommending it would print a flag whose cases
1581
+ // can never be satisfied. Absent the block the offer is byte-identical
1582
+ // to a repository that has no background work at all.
1583
+ const detectedPacks = noScan || noBehavior
1584
+ ? []
1585
+ : detectBehaviorPacks(cwd, draftConfig.queueObserver !== undefined);
1586
+ const enabledNamespaces = await resolveBehaviorPacks(io, {
1587
+ detectedPacks,
1588
+ explicit: requestedNamespaces,
1589
+ enableAll: behaviorFlag && requestedNamespaces.length === 0,
1590
+ disabled: noBehavior,
1591
+ });
1592
+ const wantBehavior = enabledNamespaces.length > 0 || (behaviorFlag && !noBehavior);
823
1593
  if (wantBehavior) {
824
1594
  const behaviorPath = join(gateforgeDir, 'behavior.yml');
1595
+ const enabledPacks = detectedPacks.filter((pack) => enabledNamespaces.includes(pack.namespace));
1596
+ const template = `${BEHAVIOR_TEMPLATE}${behaviorSkeletonExamples(enabledPacks)}`;
825
1597
  if (existsSync(behaviorPath)) {
826
1598
  writeLine(io.stdout, `exists, leaving untouched: ${behaviorPath}`);
1599
+ for (const pack of enabledPacks) {
1600
+ writeLine(io.stdout, ` the ${pack.namespace} example case for this repository — add it under 'endpoints:' in ${behaviorPath}:`);
1601
+ for (const line of behaviorSkeletonExamples([pack]).split('\n').slice(1)) {
1602
+ writeLine(io.stdout, ` ${line}`);
1603
+ }
1604
+ }
827
1605
  }
828
1606
  else {
829
- targets.push({
1607
+ pushTarget({
830
1608
  path: behaviorPath,
831
1609
  label: 'complete-behavior document (SCAFFOLD — not approval)',
832
- write: () => writeFileSync(behaviorPath, BEHAVIOR_TEMPLATE, 'utf8'),
1610
+ write: () => writeFileSync(behaviorPath, template, 'utf8'),
833
1611
  });
834
1612
  }
835
1613
  if (!existsSync(join(cwd, '.gateforge.yml'))) {
836
- targets.push({
1614
+ pushTarget({
837
1615
  path: join(cwd, '.gateforge.yml'),
838
1616
  label: 'config (with behaviorPolicy)',
839
1617
  write: () => {
840
- const text = configTemplate(languages, pluginIds, { strictE2E });
1618
+ const text = configTemplate(languages, pluginIds, configOptions);
841
1619
  const withBehavior = text.replace(/^policies:/m, 'behaviorPolicy: .gateforge/behavior.yml\npolicies:');
842
1620
  parseConfig(parseYaml(withBehavior), { file: '.gateforge.yml' });
843
1621
  writeFileSync(join(cwd, '.gateforge.yml'), withBehavior, 'utf8');
@@ -845,22 +1623,54 @@ export async function initCommand(io, argv) {
845
1623
  });
846
1624
  }
847
1625
  else {
848
- writeLine(io.stdout, 'note: existing .gateforge.yml left untouched — add `behaviorPolicy: .gateforge/behavior.yml` to enable the profile');
1626
+ writeLine(io.stdout, 'note: existing .gateforge.yml left untouched — add this line to it to enable the profile:');
1627
+ writeLine(io.stdout, ' behaviorPolicy: .gateforge/behavior.yml');
1628
+ }
1629
+ }
1630
+ // An EXPLICIT `--plugins` on an initialized repository ADDS the
1631
+ // requested detectors to the owner's config instead of being ignored.
1632
+ // The merge is additive (an existing entry keeps the owner's version
1633
+ // pin; nothing is removed) and touches only the `plugins:` list, so
1634
+ // the product's own tip — "re-run with --plugins … to change
1635
+ // detectors" — is finally true. Every other key, comment, and edit in
1636
+ // the file is preserved byte for byte, and the schema is checked
1637
+ // before anything is written.
1638
+ if (explicitPlugins !== null && existsSync(join(cwd, '.gateforge.yml'))) {
1639
+ const configPath = join(cwd, '.gateforge.yml');
1640
+ const merged = mergePluginsIntoConfig(readFileSync(configPath, 'utf8'), explicitPlugins);
1641
+ if (merged === null) {
1642
+ writeLine(io.stdout, `${explicitPlugins.join(', ')} already configured in ${configPath}; leaving it untouched`);
1643
+ }
1644
+ else {
1645
+ writeFileSync(configPath, merged, 'utf8');
1646
+ const added = loadConfig(configPath).plugins
1647
+ .map((plugin) => plugin.id)
1648
+ .filter((id) => explicitPlugins.includes(id));
1649
+ recordInitPath(io, cwd, configPath, 'modified');
1650
+ writeLine(io.stdout, `updated: ${configPath} (added detector(s): ${added.join(', ')} — every other key left as it was)`);
849
1651
  }
850
1652
  }
851
1653
  for (const target of targets) {
852
1654
  if (existsSync(target.path)) {
853
- if (target.label === 'owner-declared documentation exclusions' && docsExclusionChoice.changed) {
1655
+ if ((target.label === 'owner-declared documentation exclusions' && docsExclusionChoice.changed) ||
1656
+ (target.label === 'owner-declared Python bytecode exclusions' && cacheExclusionChoice.changed)) {
854
1657
  target.write();
1658
+ recordInitPath(io, cwd, target.path, 'modified');
855
1659
  writeLine(io.stdout, `updated: ${target.path}`);
856
1660
  continue;
857
1661
  }
1662
+ recordInitPath(io, cwd, target.path, 'preserved');
858
1663
  writeLine(io.stdout, `exists, leaving untouched: ${target.path}`);
859
1664
  continue;
860
1665
  }
861
1666
  target.write();
1667
+ recordInitPath(io, cwd, target.path, 'created');
862
1668
  writeLine(io.stdout, `created: ${target.path}`);
863
1669
  }
1670
+ // Engine-owned state is never a product change: without this the
1671
+ // first `git add -A` stages the run cache the gate just wrote, and the
1672
+ // gate then blocks on its own files.
1673
+ ignoreEngineState(io, cwd);
864
1674
  // Observe proof checklist (observe proof only): the work no scaffold
865
1675
  // can do — proxy wiring, adapter bindings, and kind declarations.
866
1676
  if (proofMode === 'observe') {
@@ -880,6 +1690,14 @@ export async function initCommand(io, argv) {
880
1690
  writeLine(io.stdout, `candidate policy digest to approve outside the repository: ${approvalDigest}`);
881
1691
  writeLine(io.stdout, 'set GATEFORGE_APPROVED_POLICY_DIGEST in a protected owner environment to this exact digest; without a matching pin, Gateforge refuses to use the exclusions');
882
1692
  }
1693
+ if (cacheExclusionChoice.files.length > 0) {
1694
+ const writtenConfig = loadConfig(join(cwd, '.gateforge.yml'));
1695
+ const approvalDigest = trustedPolicyDigestForConfig(cwd, writtenConfig);
1696
+ writeLine(io.stdout, `owner-declared Python bytecode files: ${cacheExclusionChoice.files.join(', ')}`);
1697
+ writeLine(io.stdout, `warning: ${CACHE_EXCLUSIONS_GUARANTEE}`);
1698
+ writeLine(io.stdout, `candidate policy digest to approve outside the repository: ${approvalDigest}`);
1699
+ writeLine(io.stdout, 'set GATEFORGE_APPROVED_POLICY_DIGEST in a protected owner environment to this exact digest; without a matching pin, Gateforge refuses to use the exclusions');
1700
+ }
883
1701
  // Plane-config proposal (flags win; TTY prompt fills the gap;
884
1702
  // non-interactive defaults to scaffold-only, like every granular step):
885
1703
  // --planes / --no-planes
@@ -887,9 +1705,20 @@ export async function initCommand(io, argv) {
887
1705
  // discovered tables live in — a review artifact with a reason on
888
1706
  // every rule, written only when absent, never silently applied
889
1707
  // (the next run reads it and the user reviews first).
890
- if (languages.includes('python')) {
1708
+ //
1709
+ // An EXPLICIT `--planes` is always honored: it is the runnable
1710
+ // prerequisite the `gateforge next` guidance prints for an unresolved
1711
+ // route, and a language gate would make that printed command a no-op
1712
+ // on exactly the repositories that need it. The proposal itself is
1713
+ // conservative — no discovered table means no inferred rule.
1714
+ const planesRequested = options['planes'] === true;
1715
+ if (planesRequested || languages.includes('python')) {
891
1716
  if (await resolvePlanes(io, options)) {
892
- await proposePlanesConfig(cwd, io);
1717
+ // The route folders are asked in the SAME flow, right before the
1718
+ // model folders are written, so both sets of answers land in one
1719
+ // reviewed `.gateforge/planes.json`.
1720
+ const routeRules = await askRouteFolderPlanes(cwd, io);
1721
+ await proposePlanesConfig(cwd, io, routeRules);
893
1722
  }
894
1723
  }
895
1724
  // Behavior-profile setup (plan 2026-09-19 §4.11): `--behavior` scaffolds
@@ -925,14 +1754,23 @@ export async function initCommand(io, argv) {
925
1754
  if (witnessedValue !== undefined && modeValue !== undefined) {
926
1755
  throw new UsageError("init: --witnessed selects the pre-commit execution mode and cannot be combined with '--mode'");
927
1756
  }
928
- const blocking = await resolveBlocking(io, options);
929
- const preCommit = options['pre-commit'] === true || blocking || witnessedValue !== undefined;
930
- const ci = options['ci'] === true || blocking;
1757
+ // The goal decides the wiring; explicit flags already short-circuited
1758
+ // goal resolution above, so nothing here can contradict a flag. When
1759
+ // there is no goal, today's granular behavior is unchanged.
1760
+ const blocking = goal !== null ? goal.settings.wiring === 'blocking' : await resolveBlocking(io, options);
1761
+ const preCommit = options['pre-commit'] === true ||
1762
+ blocking ||
1763
+ witnessedValue !== undefined ||
1764
+ (goal !== null && goal.settings.wiring === 'pre-commit');
1765
+ const ci = options['ci'] === true || blocking || (goal !== null && goal.settings.ci);
1766
+ const receiptStage = preCommit ? loadConfig(join(cwd, '.gateforge.yml')).enforcement?.receiptStage : undefined;
931
1767
  const mode = typeof modeValue === 'string'
932
1768
  ? modeValue
933
- : blocking
934
- ? 'staged'
935
- : 'changed';
1769
+ : goal !== null
1770
+ ? goal.settings.mode
1771
+ : blocking
1772
+ ? 'staged'
1773
+ : 'changed';
936
1774
  if (preCommit) {
937
1775
  const hookDir = join(gateforgeDir, 'hooks');
938
1776
  mkdirSync(hookDir, { recursive: true });
@@ -944,8 +1782,12 @@ export async function initCommand(io, argv) {
944
1782
  : witnessedValue === 'full'
945
1783
  ? ['pre-commit', '--scope', 'full']
946
1784
  : mode === 'staged'
947
- ? ['check', '--staged', '--require-e2e']
948
- : ['check', '--changed'];
1785
+ ? receiptStage === 'pre-push' || receiptStage === 'ci'
1786
+ ? ['check', '--staged']
1787
+ : ['check', '--staged', '--require-e2e']
1788
+ : receiptStage === 'pre-commit'
1789
+ ? ['check', '--changed', '--require-e2e']
1790
+ : ['check', '--changed'];
949
1791
  ensureHookScript(io, engineRootFromInvocation(), gateArgs);
950
1792
  // The ACTIVE hook (plan Phase 5 item 1): install into the resolved
951
1793
  // hooks directory AND verify activation — never merely write a
@@ -972,6 +1814,11 @@ export async function initCommand(io, argv) {
972
1814
  // integrates through the framework config instead (appendPreCommitHook
973
1815
  // below) — the hook block runs on every commit like any other.
974
1816
  const frameworkManaged = outcome.status === 'framework';
1817
+ // The undo list must name the hook this run installed and NOT name
1818
+ // one that was already there.
1819
+ if (outcome.hookPath !== null) {
1820
+ recordInitPath(io, cwd, outcome.hookPath, outcome.status === 'installed' ? 'created' : 'preserved');
1821
+ }
975
1822
  switch (outcome.status) {
976
1823
  case 'installed':
977
1824
  writeLine(io.stdout, `installed: ${outcome.detail}`);
@@ -998,8 +1845,49 @@ export async function initCommand(io, argv) {
998
1845
  'Honest limit: `git commit --no-verify` bypasses the local hook (ADR 0005 D1) — standard enforcement also requires the trusted server check.'
999
1846
  : `blocking gate wired: active pre-commit hook (${gateArgs.join(' ')}) + .gitlab-ci.yml include. ` +
1000
1847
  'Honest limit: `git commit --no-verify` bypasses the local hook (ADR 0005 D1) — standard enforcement also requires the trusted server check.');
1848
+ if (receiptStage === 'pre-push') {
1849
+ const pushHook = installPrePushHook(cwd, io.env);
1850
+ if (pushHook.status === 'conflict' || pushHook.status === 'incomplete') {
1851
+ throw new UsageError(`${pushHook.detail}\nRequired action:\n${pushHook.action}`);
1852
+ }
1853
+ if (pushHook.hookPath !== null) {
1854
+ recordInitPath(io, cwd, pushHook.hookPath, pushHook.status === 'installed' ? 'created' : 'preserved');
1855
+ }
1856
+ writeLine(io.stdout, `${pushHook.status}: ${pushHook.detail}`);
1857
+ }
1858
+ writeServerProtectionInstructions(io, ciProviderBeforeWiring);
1859
+ }
1860
+ // A preset can ask for the CI job without a local hook (`normal`):
1861
+ // the server check is then the only place the gate runs, which is a
1862
+ // real choice, not a fallback.
1863
+ if (ci && !preCommit) {
1864
+ writeSharedGitlabCiTemplate(io, 'strict');
1865
+ }
1866
+ // What the goal wrote, in plain words, plus the command that undoes it.
1867
+ if (goal !== null) {
1868
+ const ledger = io.initPaths;
1869
+ for (const line of renderPresetSummary(goal.name, {
1870
+ configExisted: existedConfigAtStart,
1871
+ autoChosen: goal.autoChosen === true,
1872
+ created: [...(ledger?.created ?? [])],
1873
+ modified: [...(ledger?.modified ?? [])],
1874
+ repoHasCommitHook: existsSync(join(cwd, '.git/hooks/pre-commit')),
1875
+ repoHasCi: existsSync(join(cwd, '.gitlab-ci.yml')) || existsSync(join(cwd, '.github/workflows/gateforge.yml')),
1876
+ })) {
1877
+ writeLine(io.stdout, line);
1878
+ }
1879
+ }
1880
+ // A repository that already had code before this run gets the
1881
+ // adoption path named HERE, where the owner is deciding what the
1882
+ // gate will do to them. `init` on a fresh project has no debt and
1883
+ // must not talk about adopting one.
1884
+ if (!existedConfigAtStart && scan.files > 0) {
1885
+ writeLine(io.stdout, ADOPT_ADVICE);
1001
1886
  }
1002
1887
  writeLine(io.stdout, 'skeleton ready: .gateforge/adapters, .gateforge/waivers, .gateforge/baselines');
1888
+ const alembicOptIn = renderAlembicOptIn(cwd);
1889
+ if (alembicOptIn !== null)
1890
+ writeLine(io.stdout, alembicOptIn);
1003
1891
  return 0;
1004
1892
  }
1005
1893
  //# sourceMappingURL=init.js.map