@gate-forge/cli 0.7.0 → 0.8.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 (254) hide show
  1. package/README.md +511 -51
  2. package/dist/adapter-audit.d.ts +154 -0
  3. package/dist/adapter-audit.d.ts.map +1 -0
  4. package/dist/adapter-audit.js +531 -0
  5. package/dist/adapter-audit.js.map +1 -0
  6. package/dist/adapter-scaffold.d.ts +66 -0
  7. package/dist/adapter-scaffold.d.ts.map +1 -0
  8. package/dist/adapter-scaffold.js +353 -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 +59 -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 +738 -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 +284 -0
  44. package/dist/commands/adapters.js.map +1 -0
  45. package/dist/commands/adopt.d.ts.map +1 -1
  46. package/dist/commands/adopt.js +9 -1
  47. package/dist/commands/adopt.js.map +1 -1
  48. package/dist/commands/baseline.d.ts.map +1 -1
  49. package/dist/commands/baseline.js +42 -1
  50. package/dist/commands/baseline.js.map +1 -1
  51. package/dist/commands/blocking.d.ts +81 -2
  52. package/dist/commands/blocking.d.ts.map +1 -1
  53. package/dist/commands/blocking.js +336 -53
  54. package/dist/commands/blocking.js.map +1 -1
  55. package/dist/commands/check.d.ts +36 -0
  56. package/dist/commands/check.d.ts.map +1 -1
  57. package/dist/commands/check.js +1008 -62
  58. package/dist/commands/check.js.map +1 -1
  59. package/dist/commands/classify.d.ts +2 -1
  60. package/dist/commands/classify.d.ts.map +1 -1
  61. package/dist/commands/classify.js +143 -5
  62. package/dist/commands/classify.js.map +1 -1
  63. package/dist/commands/enforce.d.ts +4 -4
  64. package/dist/commands/enforce.d.ts.map +1 -1
  65. package/dist/commands/enforce.js +41 -9
  66. package/dist/commands/enforce.js.map +1 -1
  67. package/dist/commands/enforcement.d.ts +13 -1
  68. package/dist/commands/enforcement.d.ts.map +1 -1
  69. package/dist/commands/enforcement.js +800 -30
  70. package/dist/commands/enforcement.js.map +1 -1
  71. package/dist/commands/history.d.ts +12 -0
  72. package/dist/commands/history.d.ts.map +1 -0
  73. package/dist/commands/history.js +45 -0
  74. package/dist/commands/history.js.map +1 -0
  75. package/dist/commands/init-presets.d.ts +148 -0
  76. package/dist/commands/init-presets.d.ts.map +1 -0
  77. package/dist/commands/init-presets.js +194 -0
  78. package/dist/commands/init-presets.js.map +1 -0
  79. package/dist/commands/init.d.ts +7 -12
  80. package/dist/commands/init.d.ts.map +1 -1
  81. package/dist/commands/init.js +610 -69
  82. package/dist/commands/init.js.map +1 -1
  83. package/dist/commands/keys.d.ts.map +1 -1
  84. package/dist/commands/keys.js +29 -13
  85. package/dist/commands/keys.js.map +1 -1
  86. package/dist/commands/next.d.ts.map +1 -1
  87. package/dist/commands/next.js +744 -15
  88. package/dist/commands/next.js.map +1 -1
  89. package/dist/commands/pre-commit.d.ts +25 -0
  90. package/dist/commands/pre-commit.d.ts.map +1 -1
  91. package/dist/commands/pre-commit.js +91 -6
  92. package/dist/commands/pre-commit.js.map +1 -1
  93. package/dist/commands/quarantine.d.ts +16 -0
  94. package/dist/commands/quarantine.d.ts.map +1 -0
  95. package/dist/commands/quarantine.js +213 -0
  96. package/dist/commands/quarantine.js.map +1 -0
  97. package/dist/commands/run.d.ts +39 -0
  98. package/dist/commands/run.d.ts.map +1 -0
  99. package/dist/commands/run.js +196 -0
  100. package/dist/commands/run.js.map +1 -0
  101. package/dist/commands/test-gates.d.ts +284 -2
  102. package/dist/commands/test-gates.d.ts.map +1 -1
  103. package/dist/commands/test-gates.js +3619 -186
  104. package/dist/commands/test-gates.js.map +1 -1
  105. package/dist/commands/tests.d.ts +1 -1
  106. package/dist/commands/tests.d.ts.map +1 -1
  107. package/dist/commands/tests.js +225 -22
  108. package/dist/commands/tests.js.map +1 -1
  109. package/dist/endpoint-compiler.d.ts.map +1 -1
  110. package/dist/endpoint-compiler.js +29 -8
  111. package/dist/endpoint-compiler.js.map +1 -1
  112. package/dist/engine-browser.d.ts +183 -0
  113. package/dist/engine-browser.d.ts.map +1 -0
  114. package/dist/engine-browser.js +381 -0
  115. package/dist/engine-browser.js.map +1 -0
  116. package/dist/engine-identity.d.ts +100 -0
  117. package/dist/engine-identity.d.ts.map +1 -0
  118. package/dist/engine-identity.js +182 -0
  119. package/dist/engine-identity.js.map +1 -0
  120. package/dist/evaluate.d.ts +89 -0
  121. package/dist/evaluate.d.ts.map +1 -1
  122. package/dist/evaluate.js +137 -16
  123. package/dist/evaluate.js.map +1 -1
  124. package/dist/execution.d.ts +253 -9
  125. package/dist/execution.d.ts.map +1 -1
  126. package/dist/execution.js +309 -12
  127. package/dist/execution.js.map +1 -1
  128. package/dist/git-hooks.d.ts +17 -0
  129. package/dist/git-hooks.d.ts.map +1 -1
  130. package/dist/git-hooks.js +119 -0
  131. package/dist/git-hooks.js.map +1 -1
  132. package/dist/git-objects.d.ts +60 -0
  133. package/dist/git-objects.d.ts.map +1 -0
  134. package/dist/git-objects.js +152 -0
  135. package/dist/git-objects.js.map +1 -0
  136. package/dist/history.d.ts +52 -0
  137. package/dist/history.d.ts.map +1 -0
  138. package/dist/history.js +116 -0
  139. package/dist/history.js.map +1 -0
  140. package/dist/host-load.d.ts +49 -0
  141. package/dist/host-load.d.ts.map +1 -0
  142. package/dist/host-load.js +78 -0
  143. package/dist/host-load.js.map +1 -0
  144. package/dist/input-snapshot.d.ts +63 -9
  145. package/dist/input-snapshot.d.ts.map +1 -1
  146. package/dist/input-snapshot.js +195 -17
  147. package/dist/input-snapshot.js.map +1 -1
  148. package/dist/io.d.ts +36 -0
  149. package/dist/io.d.ts.map +1 -1
  150. package/dist/io.js +21 -0
  151. package/dist/io.js.map +1 -1
  152. package/dist/mapping.d.ts +84 -1
  153. package/dist/mapping.d.ts.map +1 -1
  154. package/dist/mapping.js +276 -5
  155. package/dist/mapping.js.map +1 -1
  156. package/dist/native-freeze.d.ts +217 -0
  157. package/dist/native-freeze.d.ts.map +1 -0
  158. package/dist/native-freeze.js +332 -0
  159. package/dist/native-freeze.js.map +1 -0
  160. package/dist/pipeline.d.ts +52 -1
  161. package/dist/pipeline.d.ts.map +1 -1
  162. package/dist/pipeline.js +141 -3
  163. package/dist/pipeline.js.map +1 -1
  164. package/dist/playwright-browsers.d.ts +210 -0
  165. package/dist/playwright-browsers.d.ts.map +1 -0
  166. package/dist/playwright-browsers.js +364 -0
  167. package/dist/playwright-browsers.js.map +1 -0
  168. package/dist/plugins.d.ts +15 -5
  169. package/dist/plugins.d.ts.map +1 -1
  170. package/dist/plugins.js +59 -9
  171. package/dist/plugins.js.map +1 -1
  172. package/dist/progress.d.ts +148 -0
  173. package/dist/progress.d.ts.map +1 -0
  174. package/dist/progress.js +263 -0
  175. package/dist/progress.js.map +1 -0
  176. package/dist/providers.d.ts +26 -1
  177. package/dist/providers.d.ts.map +1 -1
  178. package/dist/providers.js +39 -0
  179. package/dist/providers.js.map +1 -1
  180. package/dist/receipts.d.ts +1 -0
  181. package/dist/receipts.d.ts.map +1 -1
  182. package/dist/receipts.js +35 -7
  183. package/dist/receipts.js.map +1 -1
  184. package/dist/repo-scan.d.ts +8 -1
  185. package/dist/repo-scan.d.ts.map +1 -1
  186. package/dist/repo-scan.js +221 -27
  187. package/dist/repo-scan.js.map +1 -1
  188. package/dist/reseal-chain.d.ts +184 -0
  189. package/dist/reseal-chain.d.ts.map +1 -0
  190. package/dist/reseal-chain.js +735 -0
  191. package/dist/reseal-chain.js.map +1 -0
  192. package/dist/reseal-evidence.d.ts +241 -0
  193. package/dist/reseal-evidence.d.ts.map +1 -0
  194. package/dist/reseal-evidence.js +319 -0
  195. package/dist/reseal-evidence.js.map +1 -0
  196. package/dist/reseal.d.ts +181 -0
  197. package/dist/reseal.d.ts.map +1 -0
  198. package/dist/reseal.js +1620 -0
  199. package/dist/reseal.js.map +1 -0
  200. package/dist/response-field-guidance.d.ts +82 -0
  201. package/dist/response-field-guidance.d.ts.map +1 -0
  202. package/dist/response-field-guidance.js +184 -0
  203. package/dist/response-field-guidance.js.map +1 -0
  204. package/dist/run-cache.d.ts +260 -0
  205. package/dist/run-cache.d.ts.map +1 -0
  206. package/dist/run-cache.js +771 -0
  207. package/dist/run-cache.js.map +1 -0
  208. package/dist/run-preflight.d.ts +77 -0
  209. package/dist/run-preflight.d.ts.map +1 -0
  210. package/dist/run-preflight.js +774 -0
  211. package/dist/run-preflight.js.map +1 -0
  212. package/dist/run-recipe.d.ts +107 -0
  213. package/dist/run-recipe.d.ts.map +1 -0
  214. package/dist/run-recipe.js +295 -0
  215. package/dist/run-recipe.js.map +1 -0
  216. package/dist/run-reliability.d.ts +126 -0
  217. package/dist/run-reliability.d.ts.map +1 -0
  218. package/dist/run-reliability.js +221 -0
  219. package/dist/run-reliability.js.map +1 -0
  220. package/dist/runtime.d.ts +15 -0
  221. package/dist/runtime.d.ts.map +1 -1
  222. package/dist/runtime.js +11 -1
  223. package/dist/runtime.js.map +1 -1
  224. package/dist/secret-guard.d.ts +36 -0
  225. package/dist/secret-guard.d.ts.map +1 -0
  226. package/dist/secret-guard.js +63 -0
  227. package/dist/secret-guard.js.map +1 -0
  228. package/dist/singleton-guidance.d.ts +73 -0
  229. package/dist/singleton-guidance.d.ts.map +1 -0
  230. package/dist/singleton-guidance.js +118 -0
  231. package/dist/singleton-guidance.js.map +1 -0
  232. package/dist/staged-candidate.d.ts +17 -0
  233. package/dist/staged-candidate.d.ts.map +1 -1
  234. package/dist/staged-candidate.js +50 -0
  235. package/dist/staged-candidate.js.map +1 -1
  236. package/dist/state-artifacts.d.ts +70 -0
  237. package/dist/state-artifacts.d.ts.map +1 -0
  238. package/dist/state-artifacts.js +215 -0
  239. package/dist/state-artifacts.js.map +1 -0
  240. package/dist/state.d.ts +170 -2
  241. package/dist/state.d.ts.map +1 -1
  242. package/dist/state.js +248 -8
  243. package/dist/state.js.map +1 -1
  244. package/dist/verifier-keys.d.ts +33 -2
  245. package/dist/verifier-keys.d.ts.map +1 -1
  246. package/dist/verifier-keys.js +95 -9
  247. package/dist/verifier-keys.js.map +1 -1
  248. package/guides/CONNECT-YOUR-PROJECT.md +367 -0
  249. package/guides/QUICKSTART.md +404 -0
  250. package/guides/RUNNER-NEUTRAL-EVIDENCE.md +199 -0
  251. package/guides/TEST-ENVIRONMENT.md +1226 -0
  252. package/guides/UPGRADE-0.6-to-0.7.md +65 -0
  253. package/guides/UPGRADE-0.7-to-0.8.md +114 -0
  254. package/package.json +12 -10
@@ -8,23 +8,47 @@
8
8
  * prints the single highest-ranked item. Exit 0 when clean, 1 when a
9
9
  * next action exists, 2 on config/usage errors.
10
10
  */
11
- import { existsSync } from 'node:fs';
11
+ import { existsSync, readFileSync } from 'node:fs';
12
+ import { parse as parseYaml } from 'yaml';
12
13
  import { join } from 'node:path';
13
- import { BLOCKING_VERDICTS, CAUSE_NEXT_ACTIONS, } from '@gate-forge/core';
14
- import { discoverTestCatalog, findPlaywrightConfig, TestDiscoveryError, } from '@gate-forge/pack-playwright';
14
+ import { BLOCKING_VERDICTS, CAUSE_NEXT_ACTIONS, BEHAVIOR_CASE_DOMAIN, HTTP_ENDPOINT_RESOURCE_KIND, PolicyFileSchema, sha256Canonical, } from '@gate-forge/core';
15
+ import { ENDPOINT_SEMANTICS_UNRESOLVED, FASTAPI_PREFIX_UNRESOLVED, } from '@gate-forge/http-contract';
16
+ import { PLANES_CONFIG_PATH } from '@gate-forge/pack-sqlalchemy';
17
+ import { FASTAPI_SCAN_CONFIG_PATH } from '@gate-forge/pack-fastapi';
18
+ import { discoverTestCatalog, TestDiscoveryError, } from '@gate-forge/pack-playwright';
15
19
  import { parseArgs } from '../args.js';
16
20
  import { resolveAdoptedBaseline } from '../adopted-baseline.js';
17
21
  import { UsageError } from '../errors.js';
18
22
  import { writeLine } from '../io.js';
19
23
  import { evaluateRun } from '../evaluate.js';
20
- import { loadOptionalTestMap, mappedCoverageFrom, mappingBlocking, resolveRepositoryMappings, } from '../mapping.js';
21
- import { collectInputFiles, computeInputSnapshot, diffInputFiles, SnapshotUnavailableError, UnsupportedSnapshotError, } from '../input-snapshot.js';
24
+ import { findRunnerConfigPath, loadOptionalTestMap, mappedCoverageFrom, mappingBlocking, nativeInventoryBlocking, resolveRepositoryMappings, } from '../mapping.js';
25
+ import { collectInputFiles, computeInputSnapshot, diffInputFiles, symlinkNotices, SnapshotUnavailableError, UnsupportedSnapshotError, } from '../input-snapshot.js';
22
26
  import { runPipeline, sourcesByResourceId } from '../pipeline.js';
23
27
  import { resolveProvider } from '../providers.js';
24
28
  import { computeEvaluationScope, detectStagedWorkingTreeMismatches } from '../scope.js';
25
29
  import { httpRoutesView, resolveStateDir } from '../state.js';
30
+ import { engineGeneratedStateFileFilter } from '../state-artifacts.js';
26
31
  import { loadConfigAt, rejectUnknownFlags, VERIFIER_KEY_ENV } from './common.js';
32
+ import { loadCacheExclusions } from '../cache-exclusions.js';
33
+ import { singletonPerTenantGuidanceLines } from '../singleton-guidance.js';
34
+ import { buildEndpointDeclaration, loadBehaviorRecipes, renderProofSpec, renderTestMapEntries, } from '../behavior-setup.js';
35
+ import { ENDPOINT_CAPABILITIES, ENDPOINTS_CONFIG_PATH } from '../endpoint-config.js';
27
36
  export const NEXT_USAGE = 'usage: gateforge next [--changed] [--json]';
37
+ /**
38
+ * The causes that mean "this repository has no proof yet" rather than
39
+ * "this proof failed". A fresh repository owes all three at once, so the
40
+ * behavior setup is printed for any of them.
41
+ */
42
+ const SETUP_CAUSES = [
43
+ 'ENDPOINT_BEHAVIOR_MISSING',
44
+ 'TEST_INVENTORY_INCOMPLETE',
45
+ 'TEST_MAPPING_MISSING',
46
+ ];
47
+ const ENVIRONMENT_GUIDES = {
48
+ EVIDENCE_STALE: 'packages/cli/guides/TEST-ENVIRONMENT.md#keep-the-repository-unchanged-during-a-run',
49
+ ENFORCEMENT_UNTRUSTED: 'packages/cli/guides/TEST-ENVIRONMENT.md#run-containers-as-your-user',
50
+ RUN_INCOMPLETE: 'packages/cli/guides/TEST-ENVIRONMENT.md#register-the-same-tests-in-every-mode',
51
+ };
28
52
  /**
29
53
  * Ranks a cause per the plan §2 table: capability gaps first, mapping
30
54
  * intent last, everything else blocking after that.
@@ -35,7 +59,7 @@ function rankCause(cause, kind) {
35
59
  return 1;
36
60
  // Complete-behavior setup/declaration problems block before any
37
61
  // test-generation advice: an owner document gap is not something a
38
- // test can fix (plan §5 — rank configuration first).
62
+ // test can fix.
39
63
  case 'ENDPOINT_BEHAVIOR_MISSING':
40
64
  case 'BEHAVIOR_REFERENCE_STALE':
41
65
  case 'BEHAVIOR_CASE_UNMAPPED':
@@ -46,6 +70,15 @@ function rankCause(cause, kind) {
46
70
  case 'BEHAVIOR_UNEXPECTED_EFFECT':
47
71
  case 'ENFORCEMENT_BOUNDARY_UNVERIFIED':
48
72
  return 2;
73
+ case 'MIGRATION_MISSING':
74
+ case 'MIGRATION_LINEAGE_BROKEN':
75
+ case 'MIGRATION_DOWNGRADE_NOOP':
76
+ case 'MIGRATION_DRIFT':
77
+ case 'MIGRATION_ROUNDTRIP_FAILED':
78
+ case 'MIGRATION_DATA_LOST':
79
+ case 'MIGRATION_CONFLICT':
80
+ case 'MIGRATION_SCRATCH_UNSAFE':
81
+ return 2;
49
82
  case 'CRUD_COVERAGE_MISSING':
50
83
  return 3;
51
84
  case 'CHANGE_UNMAPPED':
@@ -59,6 +92,8 @@ function rankCause(cause, kind) {
59
92
  case 'TEST_NOT_EXECUTED':
60
93
  case 'TEST_FAILED':
61
94
  return 7;
95
+ case 'TEST_INVENTORY_INCOMPLETE':
96
+ return 0;
62
97
  case 'TEST_MAPPING_MISSING':
63
98
  case 'TEST_MAPPING_AMBIGUOUS':
64
99
  case 'TEST_MAPPING_STALE':
@@ -92,7 +127,12 @@ function rankBlockers(blocking, verdicts) {
92
127
  cause: cause ?? 'BLOCKING_FINDING',
93
128
  why: entry.detail,
94
129
  do: entry.nextAction ??
95
- (cause !== null ? CAUSE_NEXT_ACTIONS[cause] : 'Run `gateforge check` for the full report and resolve this blocker.'),
130
+ (cause !== null
131
+ ? CAUSE_NEXT_ACTIONS[cause]
132
+ : entry.resourceId !== null && entry.resourceId !== undefined
133
+ ? `gateforge explain ${entry.resourceId}`
134
+ : 'gateforge discover --json'),
135
+ kind: entry.kind,
96
136
  rank: rankCause(cause, entry.kind),
97
137
  });
98
138
  }
@@ -106,12 +146,585 @@ function rankBlockers(blocking, verdicts) {
106
146
  why: verdict.reason ?? `obligation '${verdict.obligation.id}' is ${verdict.verdict}`,
107
147
  do: verdict.nextAction ??
108
148
  (cause !== null ? CAUSE_NEXT_ACTIONS[cause] : CAUSE_NEXT_ACTIONS['EVIDENCE_NOT_COLLECTED']),
149
+ kind: 'verdict',
109
150
  rank: rankCause(cause, 'verdict'),
110
151
  });
111
152
  }
112
153
  candidates.sort((a, b) => (a.rank !== b.rank ? a.rank - b.rank : a.id < b.id ? -1 : a.id > b.id ? 1 : 0));
113
154
  return candidates;
114
155
  }
156
+ /**
157
+ * The state-changing command that clears ONE classifier block. A code
158
+ * with no entry here is never given an invented command.
159
+ */
160
+ const CLASSIFIER_BLOCK_ANSWERS = {
161
+ ADAPTER_MISSING: '`gateforge adapters scaffold` — run it, then review the adapter it writes for this resource',
162
+ DELETE_SEMANTICS_UNRESOLVED: "declare what the endpoint does in '.gateforge/endpoints.json' — 'crud-archive' or 'crud-delete' on a DELETE endpoint (an ENDPOINT_SEMANTICS_UNRESOLVED block prints the exact entry)",
163
+ PLANE_UNRESOLVED: "gateforge classify plane <file> <tenant|master|global> --reason '<why>' --confirm — or change the existing rule for that file in '.gateforge/planes.json'",
164
+ };
165
+ /**
166
+ * The answer for a resource the classifier blocked DEFINITIONALLY: it
167
+ * has no effective classification, so nothing on it can be graded.
168
+ *
169
+ * The block used to be exactly three lines ending in `do: gateforge
170
+ * classify --json` — a read-only dump that writes nothing, so the
171
+ * documented loop (run the printed command, run `next` again) printed
172
+ * the identical block forever, and nothing named the blocks that
173
+ * actually hold the resource. `gateforge explain <id>` shows them, so
174
+ * the id this block prints is the one that resolves.
175
+ *
176
+ * Args:
177
+ * candidate: the ranked next item.
178
+ * decisions: the run's classifier decisions.
179
+ *
180
+ * Returns:
181
+ * { do: string; lines: string[] }: the imperative action and the
182
+ * explanation, or `null` when this candidate is not such a block.
183
+ */
184
+ function classifierBlockGuidance(candidate, decisions) {
185
+ if (candidate.kind !== 'unclassified')
186
+ return null;
187
+ const decision = decisions.find((row) => row.name === candidate.id || row.resourceId === candidate.id);
188
+ const blocks = decision?.blocks ?? [];
189
+ if (blocks.length === 0)
190
+ return null;
191
+ const first = blocks[0];
192
+ const answer = CLASSIFIER_BLOCK_ANSWERS[first.code];
193
+ return {
194
+ do: answer ?? `read every block on this resource with \`gateforge explain ${shellQuote(candidate.id)}\``,
195
+ lines: [
196
+ 'about this block: the classifier refused this resource definitionally, so it carries no effective',
197
+ 'classification and nothing on it can be graded. `gateforge classify --json` only LISTS these blocks — it',
198
+ 'writes nothing, so running it and running `gateforge next` again prints this identical block. What closes',
199
+ 'each one:',
200
+ ...blocks.map((block) => ` [${block.code}] — ${CLASSIFIER_BLOCK_ANSWERS[block.code] ?? 'nothing in Gateforge closes this on your behalf; its evidence is below'}`),
201
+ `Read every block and the evidence behind it: gateforge explain ${shellQuote(candidate.id)}`,
202
+ ],
203
+ };
204
+ }
205
+ /**
206
+ * Quotes one shell argument so generated commands can be copied safely.
207
+ *
208
+ * Args:
209
+ * value: the argument text.
210
+ *
211
+ * Returns:
212
+ * string: a POSIX single-quoted argument.
213
+ */
214
+ function shellQuote(value) {
215
+ return `'${value.replace(/'/g, "'\\''")}'`;
216
+ }
217
+ /**
218
+ * Builds owner-directed advice for an endpoint with no resolved plane.
219
+ *
220
+ * Every printed command runs exactly as printed, and no line printed
221
+ * with it is something a user could paste into a shell by mistake: the
222
+ * prerequisite that creates the owner-reviewed planes file is printed
223
+ * FIRST (the plane command below it exits 2 without that file) and ONLY
224
+ * while that file is absent — repeating "run this once" on every route
225
+ * makes the sentence false for everyone but the first.
226
+ *
227
+ * Args:
228
+ * routeName: canonical method and path shown to the user.
229
+ * resourceName: detector identity used by the owner-only policy edit.
230
+ * source: router source file used by the plane writer.
231
+ * cwd: absolute repository root (the planes file is repo-relative).
232
+ *
233
+ * Returns:
234
+ * string[]: ordered question, runnable commands, and exact policy edit.
235
+ */
236
+ function unresolvedRouteGuidance(routeName, resourceName, source, cwd) {
237
+ const choices = ['tenant', 'master', 'global'];
238
+ const commands = choices.map((plane) => {
239
+ const reason = `Owner review confirms the ${plane} plane for ${routeName}.`;
240
+ return `gateforge classify plane ${shellQuote(source)} ${plane} --reason ${shellQuote(reason)} --confirm`;
241
+ });
242
+ const planesMissing = !existsSync(join(cwd, PLANES_CONFIG_PATH));
243
+ return [
244
+ // One plain line BEFORE the question: a new repo meets this
245
+ // question first, and no shipped document prepares anyone for it.
246
+ // It says what is being asked, why only the owner can answer it,
247
+ // and what each answer does next — so the question is answerable
248
+ // from the output alone.
249
+ 'about this question: this route has no data plane, so Gateforge cannot tell whether its records are ' +
250
+ 'per-tenant, shared master data, or global — that is an owner decision no detector can read from the ' +
251
+ 'code. Answer once, then run only the `classify plane` command for that answer (tenant / master / ' +
252
+ 'global), or, if the route is not used by real users, the internal rule printed at the end.',
253
+ `question: ${routeName} — is this route used by real users, and which data plane owns its records?`,
254
+ 'This edits a classification input; re-approve any approved policy pin before strict gates run.',
255
+ ...(planesMissing
256
+ ? [
257
+ `The plane command below needs the owner-reviewed '${PLANES_CONFIG_PATH}' first — run this once to create it:`,
258
+ 'gateforge init --planes',
259
+ ]
260
+ : []),
261
+ 'Then choose only the command for the boundary confirmed by the owner:',
262
+ ...commands,
263
+ 'Owner-only alternative: only if this route is genuinely internal, edit `.gateforge/classification-policy.yml` under `internalRules`:',
264
+ ' - match:',
265
+ ' resourceKind: http.endpoint',
266
+ ` resourceName: ${JSON.stringify(resourceName)}`,
267
+ ' reason: "<owner-written reason and evidence for treating this route as internal>"',
268
+ 'An internal rule is certificate-checked; it is not an override.',
269
+ ];
270
+ }
271
+ /**
272
+ * Builds the owner-authored capability declaration for an endpoint whose
273
+ * semantics no detector could prove, so the block that otherwise ends in
274
+ * a read-only `discover --json` dump becomes answerable from the output
275
+ * alone.
276
+ *
277
+ * The printed document IS the schema the compiler reads (see
278
+ * `endpoint-config.ts`): one rule, scoped to THIS endpoint by its exact
279
+ * method and canonical path, with the two owner-chosen fields marked and
280
+ * their allowed values named. Nothing else is invented — the selectors
281
+ * and the rule shape are the product's own, so a declaration copied out
282
+ * of this block parses and applies.
283
+ *
284
+ * Args:
285
+ * detail: the blocking entry's detail (the compiler's own sentence).
286
+ * graph: the run's resource graph (the endpoint identity comes from it).
287
+ *
288
+ * Returns:
289
+ * string[]: the explanation, the exact entry, and the verify command;
290
+ * an empty array when the detail is not an unresolved endpoint or the
291
+ * graph carries no matching identity.
292
+ */
293
+ function endpointSemanticsGuidance(detail, graph) {
294
+ if (!detail.startsWith(`${ENDPOINT_SEMANTICS_UNRESOLVED}:`))
295
+ return [];
296
+ const route = graph.resources.find((resource) => {
297
+ if (resource.kind !== HTTP_ENDPOINT_RESOURCE_KIND)
298
+ return false;
299
+ const identity = resource.attributes['identity'];
300
+ return typeof identity === 'string' && detail.includes(`endpoint '${identity}'`);
301
+ });
302
+ if (route === undefined)
303
+ return [];
304
+ const method = route.attributes['method'];
305
+ const canonicalPath = route.attributes['canonicalPath'];
306
+ if (typeof method !== 'string' || typeof canonicalPath !== 'string')
307
+ return [];
308
+ // A DELETE is asked one question (archive or really delete); every
309
+ // other verb is asked what the endpoint DOES at all.
310
+ const choices = method === 'DELETE'
311
+ ? [
312
+ "'crud-archive' (the record survives — the handler only sets an archived/deactivated state)",
313
+ "'crud-delete' (the record is really removed)",
314
+ ]
315
+ : [`one of: ${ENDPOINT_CAPABILITIES.join(', ')}`];
316
+ return [
317
+ `about this block: ${method} ${canonicalPath} is discovered, but nothing Gateforge can read in the code says what it DOES —`,
318
+ 'its logic sits behind a service call, and a method alone never decides semantics. Only the owner can',
319
+ `answer, and the answer is one rule in the owner-reviewed '${ENDPOINTS_CONFIG_PATH}'. Add it to that file`,
320
+ '(create the file with exactly these contents if it does not exist yet; append the rule to "rules" if it does):',
321
+ '```json',
322
+ '{',
323
+ ' "rules": [',
324
+ ' {',
325
+ ` "method": ${JSON.stringify(method)},`,
326
+ ` "paths": [${JSON.stringify(canonicalPath)}],`,
327
+ ' "capability": "<owner choice>",',
328
+ ' "reason": "<owner-written reason and evidence: what this handler really does>"',
329
+ ' }',
330
+ ' ]',
331
+ '}',
332
+ '```',
333
+ `Then replace <owner choice> with the capability the handler really has — ${choices.join(', or ')} —`,
334
+ 'and write the reason as the evidence you read (the code, service contract or table that proves it).',
335
+ ...(route.id === null
336
+ ? []
337
+ : [
338
+ 'Then prove the declaration applied — the capabilities line names the capability and the trace says endpoints.json:',
339
+ `gateforge explain ${shellQuote(route.id)}`,
340
+ ]),
341
+ ];
342
+ }
343
+ /**
344
+ * Builds the answer for a `FASTAPI_PREFIX_UNRESOLVED` finding: an
345
+ * `include_router(...)` mount the detector cannot follow, so no route
346
+ * fact is emitted for it at all.
347
+ *
348
+ * Gateforge never guesses the effective path (a fabricated path is a
349
+ * route the app does not serve), so the block names the ONE mechanism
350
+ * that closes the reason it is actually reporting. The cause code covers
351
+ * several DISTINCT reasons, and the guidance therefore keys on the
352
+ * REASON in the detail, never on the code:
353
+ *
354
+ * - a COMPUTED prefix (`include_router prefix in <file> is computed`,
355
+ * `router '<x>' in <file> declares a computed prefix`): the value is
356
+ * hidden in an expression, so the fix is a literal at the mount site.
357
+ * Nothing else reaches it, and that is verified, not assumed — a
358
+ * `.gateforge/endpoints.json` capability rule cannot match (no route
359
+ * fact is emitted for this mount, so a rule has no method/path to
360
+ * select on) and `gateforge waive` cannot resolve it (`waive: no
361
+ * obligation resolves for …`, exit 2).
362
+ * - an UNRESOLVABLE or AMBIGUOUS target (`include_router target '<x>' in
363
+ * <file> cannot be resolved in the scanned set`, and the import-alias
364
+ * form of the same thing): the mount names a router the scanner cannot
365
+ * follow, so NO prefix edit can apply — the mount may carry no prefix
366
+ * at all. The remedy is a declaration,
367
+ * `.gateforge/fastapi.json`'s `importRoots`, naming the directory the
368
+ * absolute imports in that file are written relative to. Verified
369
+ * against the real python detector on the canonical template shape
370
+ * (`backend/app/main.py` including `app.api.main.api_router`, which
371
+ * includes `app.api.routes.<module>.router`): with the roots declared
372
+ * the whole mount resolves and every route carries its real prefix,
373
+ * with NO application edit — see
374
+ * `pack-fastapi/test/template-mount.test.ts`.
375
+ * - an include CYCLE: no declaration reaches it, so the block says only
376
+ * that.
377
+ *
378
+ * Args:
379
+ * detail: the finding's `why` line (the reason code and its detail).
380
+ * cwd: the repository root, used to derive the import root from the
381
+ * file the finding names — and to print none when it cannot.
382
+ *
383
+ * Returns:
384
+ * string[]: the explanation and the real fix, or an empty array
385
+ * when the detail is not this cause.
386
+ */
387
+ function fastapiPrefixGuidance(detail, cwd) {
388
+ if (!detail.startsWith(`${FASTAPI_PREFIX_UNRESOLVED}:`))
389
+ return [];
390
+ // Every detail names the file the unprovable mount is written in, so
391
+ // the owner is pointed at the exact file rather than at a guess.
392
+ const site = /\bin (\S+) (?:is computed|declares a computed prefix|is an import alias)\b/.exec(detail)?.[1] ?? '';
393
+ if (/is computed|declares a computed prefix/.test(detail)) {
394
+ return [
395
+ 'about this block: this mount writes its prefix from an expression, so the path every route under it ' +
396
+ 'serves cannot be read from the code — a settings attribute, a constant, or a concatenation all ' +
397
+ 'hide the value at scan time. Gateforge will not guess it: a made-up path would describe routes the ' +
398
+ 'application does not serve, so the whole mount stays unresolved until the prefix is provable.',
399
+ `Fix it in ${site === '' ? 'the file the finding names' : site}: give the mount a literal string prefix ` +
400
+ '(for example `app.include_router(router, prefix="/api/v1")`). A module-level constant does not help ' +
401
+ '— the value must be written at the mount site.',
402
+ 'Nothing in Gateforge can close this finding on your behalf: a waiver needs an obligation and this has ' +
403
+ 'none, and a declared endpoint rule has no detected route to attach to. Re-run `gateforge next` after ' +
404
+ 'the edit — the routes then appear with their real prefix.',
405
+ ];
406
+ }
407
+ const ambiguousRoots = ambiguousImportRoots(detail);
408
+ const unresolvedSite = ambiguousRoots !== null
409
+ ? site
410
+ : (/\bin (\S+) (?:cannot be resolved in the scanned set|matches multiple scanned files)\b/.exec(detail)?.[1] ?? site);
411
+ if (ambiguousRoots !== null || /cannot be resolved in the scanned set/.test(detail)) {
412
+ const derived = importRootForMountSite(unresolvedSite, cwd);
413
+ const roots = ambiguousRoots ?? (derived === '' ? null : [derived]);
414
+ const file = unresolvedSite === '' ? 'the file the finding names' : unresolvedSite;
415
+ return [
416
+ 'about this block: this mount includes a router the scanner cannot follow, so the path every route under it',
417
+ 'serves is unknown — the module it names is not one of the scanned files. Gateforge will not guess it: a',
418
+ 'made-up path would describe routes the application does not serve. Making the prefix literal cannot help',
419
+ 'here: this mount is not written with a computed prefix, so there is no prefix expression to replace.',
420
+ `Fix it with a declaration and NO application edit: the import roots tell the scanner which directory the`,
421
+ `absolute imports in ${file} are written relative to.`,
422
+ `Write this file — '${FASTAPI_SCAN_CONFIG_PATH}' — and run \`gateforge next\` again:`,
423
+ '```json',
424
+ JSON.stringify(roots === null
425
+ ? { importRoots: ['<the source directory that file is imported from>'] }
426
+ : { importRoots: roots }, null, 2),
427
+ '```',
428
+ roots === null
429
+ ? 'Replace the placeholder with that directory (one entry per import root). A root that does not hold the'
430
+ : 'The routes under this mount then carry their real prefix and this finding is gone. A root that does not hold the',
431
+ 'unresolved module changes nothing — the scanned set stays closed, never guessed.',
432
+ ];
433
+ }
434
+ if (/include cycle through/.test(detail)) {
435
+ return [
436
+ 'about this block: the routers under this mount include each other in a cycle, so no order of mounts gives one',
437
+ `effective path. No declaration reaches this: break the cycle at the include sites in ${site === '' ? 'the file the finding names' : site},`,
438
+ 'then re-run `gateforge next`.',
439
+ ];
440
+ }
441
+ return [];
442
+ }
443
+ /**
444
+ * The one-line `do:` that opens a `FASTAPI_PREFIX_UNRESOLVED` block. It
445
+ * states the action of the reason {@link fastapiPrefixGuidance} explains:
446
+ * a computed prefix is an application edit, an unfollowable target is a
447
+ * declaration. `''` when the detail is not this cause.
448
+ *
449
+ * Args:
450
+ * detail: the finding's `why` line.
451
+ *
452
+ * Returns:
453
+ * string: the `do:` text, or `''`.
454
+ */
455
+ function fastapiPrefixDo(detail) {
456
+ if (!detail.startsWith(`${FASTAPI_PREFIX_UNRESOLVED}:`))
457
+ return '';
458
+ if (/is computed|declares a computed prefix/.test(detail)) {
459
+ return 'make the mount prefix a literal at the site named below, then run `gateforge next` again';
460
+ }
461
+ if (ambiguousImportRoots(detail) !== null || /cannot be resolved in the scanned set/.test(detail)) {
462
+ return `declare the import roots in '${FASTAPI_SCAN_CONFIG_PATH}' — the exact entry to add is below`;
463
+ }
464
+ return 'break the include cycle at the site named below, then run `gateforge next` again';
465
+ }
466
+ /**
467
+ * The import roots an AMBIGUOUS-target detail already names, one per
468
+ * conflicting file, sorted. `null` when the detail is not ambiguous — the
469
+ * roots are then derived from the file the finding names instead.
470
+ */
471
+ function ambiguousImportRoots(detail) {
472
+ const files = /\(([^)]*)\); the target router cannot be proven uniquely/.exec(detail)?.[1];
473
+ if (files === undefined)
474
+ return null;
475
+ const roots = new Set();
476
+ for (const file of files.split(',')) {
477
+ const trimmed = file.trim();
478
+ const cut = trimmed.lastIndexOf('/');
479
+ if (cut > 0)
480
+ roots.add(trimmed.slice(0, cut));
481
+ }
482
+ return roots.size === 0 ? null : [...roots].sort();
483
+ }
484
+ /**
485
+ * The source directory the finding's file is imported from, derived from
486
+ * that file alone: the SHORTEST directory prefix under which one of its
487
+ * own absolute imports is a real path on disk (`backend/app/api/main.py`
488
+ * importing `app.api.routes` → `backend`). `''` when it cannot be
489
+ * derived — the file is absent, has no absolute import, or every
490
+ * candidate is the repository root itself — so the guidance then names
491
+ * the declaration without inventing a directory.
492
+ *
493
+ * Args:
494
+ * file: the repo-relative file the finding names.
495
+ * cwd: the repository root.
496
+ *
497
+ * Returns:
498
+ * string: the repo-relative import root, or `''`.
499
+ */
500
+ function importRootForMountSite(file, cwd) {
501
+ if (file === '' || file.startsWith('/'))
502
+ return '';
503
+ let source;
504
+ try {
505
+ source = readFileSync(join(cwd, file), 'utf8');
506
+ }
507
+ catch {
508
+ return '';
509
+ }
510
+ const modules = new Set();
511
+ for (const match of source.matchAll(/^\s*from\s+([A-Za-z_][A-Za-z0-9_.]*)\s+import\b/gmu)) {
512
+ const dotted = match[1];
513
+ if (dotted !== '')
514
+ modules.add(dotted);
515
+ }
516
+ if (modules.size === 0)
517
+ return '';
518
+ const segments = file.split('/');
519
+ // Longest prefix first so the FIRST hit is the shortest root.
520
+ for (let depth = segments.length - 1; depth >= 1; depth -= 1) {
521
+ const root = segments.slice(0, depth).join('/');
522
+ const holds = [...modules].some((dotted) => {
523
+ const base = join(cwd, root, dotted.replaceAll('.', '/'));
524
+ return existsSync(`${base}.py`) || existsSync(join(base, '__init__.py'));
525
+ });
526
+ if (holds)
527
+ return root;
528
+ }
529
+ return '';
530
+ }
531
+ /**
532
+ * The `http.endpoint.requireObservation` scope note (plan Phase 4c,
533
+ * E60), offered on the ONE item it can explain: an unmapped obligation
534
+ * on a route the frontend never calls, while the pinned option is `all`.
535
+ * That obligation exists only because the owner widened the scope, and
536
+ * narrowing it back is a legitimate answer when the route is out of
537
+ * scope. Anywhere else (option absent, consumed endpoints, other
538
+ * causes) nothing is printed — the surface never adds noise.
539
+ *
540
+ * Args:
541
+ candidate: the ranked next item.
542
+ graph: the run's resource graph.
543
+ * observationScope: the effective pinned option.
544
+ * policiesPath: repo-relative policies document path.
545
+ *
546
+ * Returns:
547
+ * string[]: the note lines, or an empty array when it does not apply.
548
+ */
549
+ function observationScopeNote(candidate, graph, observationScope, policiesPath) {
550
+ if (observationScope !== 'all' || candidate.cause !== 'TEST_MAPPING_MISSING')
551
+ return [];
552
+ const route = graph.resources.find((resource) => resource.id !== null &&
553
+ resource.kind === HTTP_ENDPOINT_RESOURCE_KIND &&
554
+ candidate.id.startsWith(`${resource.id}:`) &&
555
+ resource.attributes['frontendConsumed'] !== true);
556
+ if (route === undefined)
557
+ return [];
558
+ const method = route.attributes['method'];
559
+ const path = route.attributes['canonicalPath'];
560
+ const name = typeof method === 'string' && typeof path === 'string' ? `${method} ${path}` : route.name;
561
+ return [
562
+ `scope: ${name} is not consumed by the frontend, so it owes this obligation only because the pinned`,
563
+ `policy option 'http.endpoint.requireObservation' is 'all'. Prove it with a test, or set the option`,
564
+ `back to 'consumed' in ${policiesPath} if this route is out of scope.`,
565
+ ];
566
+ }
567
+ /**
568
+ * The complete behavior setup `gateforge next` prints for a discovered
569
+ * endpoint that has no approved cases yet (plan 2026-09-30 Phase 4).
570
+ *
571
+ * Every block is finished work, not a template: the resource id and
572
+ * route are the ones discovery reported, the effect scope is the
573
+ * repository's own adapter-backed entity, the recipe is the one declared
574
+ * under `fixtures/`, and the case ids are the ids the compiler hashes.
575
+ * When a fact the declaration needs is missing, nothing is printed as if
576
+ * it were known — the reason is printed instead.
577
+ *
578
+ * Args:
579
+ * input: the repository root, the policies document path, the run's
580
+ * graph, and the endpoint's classified resource id.
581
+ *
582
+ * Returns:
583
+ * string[]: the ordered steps, or an empty array when this candidate
584
+ * is not a behavior declaration gap.
585
+ */
586
+ function behaviorDeclarationGuidance(input) {
587
+ const route = input.graph.resources.find((resource) => resource.id === input.resourceId && resource.kind === HTTP_ENDPOINT_RESOURCE_KIND);
588
+ if (route === undefined)
589
+ return [];
590
+ const method = route.attributes['method'];
591
+ const path = route.attributes['canonicalPath'];
592
+ if (typeof method !== 'string' || typeof path !== 'string')
593
+ return [];
594
+ const effects = input.graph.resources
595
+ .filter((resource) => resource.id !== null &&
596
+ resource.id !== input.resourceId &&
597
+ resource.classification?.evidenceAdapter !== undefined)
598
+ .map((resource) => {
599
+ const writable = resource.attributes['updateableFields'];
600
+ return {
601
+ id: resource.name,
602
+ resourceId: resource.id,
603
+ adapter: resource.classification?.evidenceAdapter,
604
+ identityFields: resource.classification?.primaryKey ?? [],
605
+ fields: Array.isArray(writable) && writable.every((field) => typeof field === 'string')
606
+ ? writable
607
+ : (resource.classification?.primaryKey ?? []),
608
+ };
609
+ });
610
+ const endpoint = {
611
+ resourceId: input.resourceId,
612
+ routeName: `${method} ${path}`,
613
+ method,
614
+ path,
615
+ effects,
616
+ };
617
+ const declared = buildEndpointDeclaration({
618
+ endpoint,
619
+ requiredContracts: requiredContractsForEndpoints(input.cwd, input.policiesPath),
620
+ recipe: loadBehaviorRecipes(input.cwd)[0] ?? null,
621
+ caseIdFor: (resourceId, slug) => sha256Canonical({ domain: BEHAVIOR_CASE_DOMAIN, resourceId, id: slug }),
622
+ specFile: 'specs/gateforge-cases.spec.js',
623
+ project: 'chromium',
624
+ runner: input.runner,
625
+ });
626
+ if (declared.entry === null) {
627
+ return [
628
+ `about this gap: ${endpoint.routeName} (${input.resourceId}) has no approved behavior cases, and`,
629
+ 'the complete declaration cannot be printed from what this repository declares:',
630
+ ` ${declared.incompleteReason ?? 'no reason recorded'}`,
631
+ 'next: fix that first, then re-run gateforge next',
632
+ ];
633
+ }
634
+ return [
635
+ `about this gap: ${endpoint.routeName} (${input.resourceId}) is discovered but has no approved`,
636
+ 'behavior cases, so nothing in this repository can prove what it must do. The steps below are',
637
+ 'the whole remaining setup — every block is complete, so paste each one exactly as printed.',
638
+ "step 1 — declare the cases in .gateforge/behavior.yml (add this entry under 'endpoints:'):",
639
+ '```yaml',
640
+ declared.entry,
641
+ '```',
642
+ 'step 2 — create specs/gateforge-cases.spec.js with exactly this content (one test per case;',
643
+ 'the ENGINE drives each case, and the test only asserts the engine sealed it):',
644
+ '```js',
645
+ renderProofSpec({ resourceId: input.resourceId, cases: declared.cases }),
646
+ '```',
647
+ 'step 3 — map every case to its test in .gateforge/test-map.yml (add these entries under',
648
+ "'tests:'; if the file does not exist yet, create it starting with 'schemaVersion: 1' and",
649
+ "'tests:'):",
650
+ '```yaml',
651
+ renderTestMapEntries({
652
+ cases: declared.cases,
653
+ specFile: 'specs/gateforge-cases.spec.js',
654
+ project: 'chromium',
655
+ runner: input.runner,
656
+ }),
657
+ '```',
658
+ 'step 4 — run the gate:',
659
+ ' npm run gate',
660
+ 'then re-run gateforge next to see what, if anything, is still open',
661
+ ];
662
+ }
663
+ /**
664
+ * The `task` behavior pack, offered under the same rule as every other
665
+ * pack: it is named only when the repository actually shows the
666
+ * machinery AND the engine can grade the claim. The engine's own
667
+ * `queueObserver` is that second half — without it every `task:*` case
668
+ * fails closed, so offering the pack would print a flag whose cases can
669
+ * never be satisfied. Both halves are required, so a repository
670
+ * without an observer is byte-identical to a repository with no
671
+ * background work.
672
+ *
673
+ * Args:
674
+ * graph: the run's resource graph.
675
+ * queueObserverConfigured: whether the loaded config declares one.
676
+ *
677
+ * Returns:
678
+ * string[]: the offer lines, or an empty array when it does not apply.
679
+ */
680
+ function taskPackOffer(graph, queueObserverConfigured) {
681
+ if (!queueObserverConfigured)
682
+ return [];
683
+ const taskResource = graph.resources.find((resource) => resource.kind === 'task.resource' && resource.id !== null);
684
+ if (taskResource === undefined)
685
+ return [];
686
+ return [
687
+ 'the task behavior pack is gradable in this repository (a queueObserver is configured',
688
+ `and '${taskResource.id}' is a discovered task resource), so its cases can be enabled:`,
689
+ ' task — the engine reads the delivery queue itself to grade these contracts',
690
+ ' gateforge init --behavior-packs task',
691
+ ];
692
+ }
693
+ /**
694
+ * The contracts the repository's policy document requires of every HTTP
695
+ * endpoint. Unreadable or absent policies yield none, which keeps the
696
+ * guidance quiet on a repository that has approved no behavior yet.
697
+ *
698
+ * Args:
699
+ * cwd: absolute repository root.
700
+ * policiesPath: repo-relative policies document path.
701
+ *
702
+ * Returns:
703
+ * string[]: the required contract names, deduplicated in print order.
704
+ */
705
+ function requiredContractsForEndpoints(cwd, policiesPath) {
706
+ let text;
707
+ try {
708
+ text = readFileSync(join(cwd, policiesPath), 'utf8');
709
+ }
710
+ catch {
711
+ return [];
712
+ }
713
+ const parsed = PolicyFileSchema.safeParse(parseYaml(text));
714
+ if (!parsed.success)
715
+ return [];
716
+ const contracts = [];
717
+ for (const policy of parsed.data.policies) {
718
+ const coversEndpoints = policy.when?.kind === undefined || policy.when.kind === HTTP_ENDPOINT_RESOURCE_KIND;
719
+ if (!coversEndpoints)
720
+ continue;
721
+ for (const contract of policy.require) {
722
+ if (!contracts.includes(contract))
723
+ contracts.push(contract);
724
+ }
725
+ }
726
+ return contracts;
727
+ }
115
728
  /**
116
729
  * Runs the `gateforge next` subcommand.
117
730
  *
@@ -137,6 +750,7 @@ export async function nextCommand(io, argv) {
137
750
  const asJson = options['json'] === true;
138
751
  const witnessVerifierKey = io.env[VERIFIER_KEY_ENV];
139
752
  const config = loadConfigAt(io.cwd);
753
+ const cacheExclusions = loadCacheExclusions(io.cwd, config);
140
754
  const providerIdentity = diffScoped
141
755
  ? resolveProvider(config.changed.provider, io.cwd, io.env).provider
142
756
  : 'all-files';
@@ -147,7 +761,7 @@ export async function nextCommand(io, argv) {
147
761
  let preFiles = null;
148
762
  let snapshotUnavailable = false;
149
763
  try {
150
- preFiles = collectInputFiles(io.cwd, config, stateDir);
764
+ preFiles = collectInputFiles(io.cwd, config, stateDir, [], [], cacheExclusions);
151
765
  }
152
766
  catch (error) {
153
767
  if (error instanceof SnapshotUnavailableError) {
@@ -160,6 +774,14 @@ export async function nextCommand(io, argv) {
160
774
  throw error;
161
775
  }
162
776
  }
777
+ // A dangling symlink, or one pointing at a directory, is captured by
778
+ // its link text, so the run continues; one plain notice line names what
779
+ // does not resolve and whether an action is needed. In --json mode
780
+ // stdout stays a single JSON document, so the notice goes to stderr
781
+ // there.
782
+ for (const notice of symlinkNotices(preFiles ?? [])) {
783
+ writeLine(asJson ? io.stderr : io.stdout, notice);
784
+ }
163
785
  const pipeline = await runPipeline({
164
786
  cwd: io.cwd,
165
787
  env: io.env,
@@ -172,7 +794,7 @@ export async function nextCommand(io, argv) {
172
794
  let changedInputs = false;
173
795
  if (!snapshotUnavailable) {
174
796
  try {
175
- const postFiles = collectInputFiles(io.cwd, config, stateDir);
797
+ const postFiles = collectInputFiles(io.cwd, config, stateDir, [], [], cacheExclusions);
176
798
  if (preFiles !== null && diffInputFiles(preFiles, postFiles).length > 0) {
177
799
  changedInputs = true;
178
800
  }
@@ -188,6 +810,7 @@ export async function nextCommand(io, argv) {
188
810
  id: plugin.id,
189
811
  version: plugin.version,
190
812
  })),
813
+ cacheExclusions,
191
814
  }).inputDigest;
192
815
  }
193
816
  }
@@ -211,14 +834,19 @@ export async function nextCommand(io, argv) {
211
834
  let discoveryResult;
212
835
  if (diffScoped) {
213
836
  const sidecar = loadOptionalTestMap(io.cwd);
214
- const runnerConfig = findPlaywrightConfig(io.cwd);
837
+ const runnerConfig = findRunnerConfigPath(io.cwd, config.runner);
215
838
  let testFiles = [];
216
839
  if (runnerConfig !== null) {
217
840
  try {
218
- const discovered = await discoverTestCatalog({ cwd: io.cwd, config, collectPytest: true });
841
+ const discovered = await discoverTestCatalog({
842
+ cwd: io.cwd,
843
+ config,
844
+ collectPytest: true,
845
+ excludeFile: engineGeneratedStateFileFilter(io.cwd, stateDir),
846
+ });
219
847
  discoveryResult = discovered;
220
848
  testFiles = discovered.catalog.entries
221
- .filter((entry) => entry.runner === 'playwright')
849
+ .filter((entry) => entry.runner === config.runner)
222
850
  .map((entry) => entry.file);
223
851
  }
224
852
  catch (error) {
@@ -278,14 +906,23 @@ export async function nextCommand(io, argv) {
278
906
  const mapped = await resolveRepositoryMappings({
279
907
  cwd: io.cwd,
280
908
  config,
909
+ stateDir,
281
910
  obligations: pipeline.policy.obligations,
282
911
  ...(discoveryResult !== undefined
283
- ? { catalog: discoveryResult.catalog, nativeClaims: discoveryResult.nativeClaims }
912
+ ? {
913
+ catalog: discoveryResult.catalog,
914
+ nativeClaims: discoveryResult.nativeClaims,
915
+ nativeErrors: discoveryResult.nativeErrors,
916
+ nativeInstances: discoveryResult.nativeInstances,
917
+ }
284
918
  : {}),
285
919
  behaviorCatalog: pipeline.behaviorCatalog,
286
920
  });
287
921
  const claimInventory = mapped.claimInventory;
288
- const mappingBlockers = mappingBlocking(mapped.resolution.problems);
922
+ const mappingBlockers = [
923
+ ...mappingBlocking(mapped.resolution.problems),
924
+ ...nativeInventoryBlocking(mapped.nativeLoadProblem),
925
+ ];
289
926
  const mappedCoverage = mappedCoverageFrom(mapped.resolution, pipeline.policy.obligations, pipeline.graph);
290
927
  const evaluated = evaluateRun({
291
928
  cwd: io.cwd,
@@ -296,6 +933,7 @@ export async function nextCommand(io, argv) {
296
933
  blocking: [...pipeline.policy.blocking, ...mismatchBlocking, ...mappingBlockers],
297
934
  stateDir,
298
935
  now: pipeline.now,
936
+ engineAlembicRecords: pipeline.engineAlembicRecords,
299
937
  changedFiles,
300
938
  claimInventory,
301
939
  mappedCoverage,
@@ -319,6 +957,56 @@ export async function nextCommand(io, argv) {
319
957
  return 0;
320
958
  }
321
959
  const first = candidates[0];
960
+ const unresolvedRoute = pipeline.classification.decisions.find((decision) => decision.name === first.id &&
961
+ decision.kind === 'http.endpoint' &&
962
+ decision.classification === null &&
963
+ decision.blocks.some((block) => block.code === 'PLANE_UNRESOLVED'));
964
+ const routeResource = unresolvedRoute === undefined
965
+ ? undefined
966
+ : pipeline.graph.resources.find((resource) => resource.name === unresolvedRoute.name);
967
+ const method = routeResource?.attributes['method'];
968
+ const path = routeResource?.attributes['canonicalPath'];
969
+ const routeName = typeof method === 'string' && typeof path === 'string'
970
+ ? `${method} ${path}`
971
+ : unresolvedRoute?.name;
972
+ const routeGuidance = unresolvedRoute === undefined || routeName === undefined
973
+ ? null
974
+ : unresolvedRouteGuidance(routeName, unresolvedRoute.name, unresolvedRoute.source, io.cwd);
975
+ // An endpoint whose semantics no detector could prove is answered by
976
+ // the owner-authored capability rule, so the top item carries the exact
977
+ // entry instead of the read-only dump the fallback `do:` names. A
978
+ // FastAPI prefix no detector could read is answered the same way: the
979
+ // block names the one edit that closes it, never a read-only command.
980
+ const endpointGuidance = routeGuidance === null ? endpointSemanticsGuidance(first.why, pipeline.graph) : [];
981
+ const prefixGuidance = routeGuidance === null ? fastapiPrefixGuidance(first.why, io.cwd) : [];
982
+ const classifierBlocks = classifierBlockGuidance(first, pipeline.classification.decisions);
983
+ const guide = ENVIRONMENT_GUIDES[first.cause] ?? null;
984
+ const scopeNote = observationScopeNote(first, pipeline.graph, pipeline.observationScope, config.policies);
985
+ // The behavior setup is printed whenever the run still owes a behavior
986
+ // DECLARATION and the top item is one of the three "this repository has
987
+ // no proof yet" causes. A brand-new repository is usually missing all
988
+ // three at once (no cases, no tests, no mapping), and answering only
989
+ // the top one would send the owner back for a second `next` run with
990
+ // the same answer.
991
+ const behaviorGap = evaluated.blocking.find((entry) => entry.cause === 'ENDPOINT_BEHAVIOR_MISSING');
992
+ const behaviorGuidance = behaviorGap !== undefined && SETUP_CAUSES.includes(first.cause)
993
+ ? behaviorDeclarationGuidance({
994
+ cwd: io.cwd,
995
+ policiesPath: config.policies,
996
+ graph: pipeline.graph,
997
+ resourceId: behaviorGap.resourceId ?? behaviorGap.name ?? '',
998
+ runner: config.runner,
999
+ })
1000
+ : [];
1001
+ // The per-tenant singleton guidance (plan 2026-09-25 Phase 4b item 3)
1002
+ // rides the same advisory tail the other owner notes use, and is the
1003
+ // SAME {@link singletonPerTenantGuidanceLines} output `check` renders
1004
+ // as a finding — a graph with no tagged resource yields an empty list
1005
+ // and prints nothing at all, so the next action stays byte-identical.
1006
+ const singletonNote = singletonPerTenantGuidanceLines(pipeline.graph.resources);
1007
+ // The task pack is offered only when the engine could actually grade
1008
+ // it — a configured queueObserver plus a discovered task resource.
1009
+ const taskOffer = taskPackOffer(pipeline.graph, config.queueObserver !== undefined);
322
1010
  if (asJson) {
323
1011
  writeLine(io.stdout, JSON.stringify({
324
1012
  next: first.id,
@@ -326,13 +1014,54 @@ export async function nextCommand(io, argv) {
326
1014
  why: first.why,
327
1015
  do: first.do,
328
1016
  remainingBlocking: candidates.length - 1,
1017
+ guide,
1018
+ ...(routeGuidance === null ? {} : { guidance: routeGuidance }),
1019
+ ...(behaviorGuidance.length === 0 ? {} : { behaviorGuidance }),
1020
+ ...(scopeNote.length === 0 ? {} : { scopeNote }),
1021
+ ...(singletonNote.length === 0 ? {} : { singletonGuidance: singletonNote }),
1022
+ ...(taskOffer.length === 0 ? {} : { taskPackOffer: taskOffer }),
1023
+ ...(endpointGuidance.length === 0 ? {} : { endpointSemanticsGuidance: endpointGuidance }),
1024
+ ...(prefixGuidance.length === 0 ? {} : { fastapiPrefixGuidance: prefixGuidance }),
1025
+ ...(classifierBlocks === null ? {} : { classifierBlockGuidance: classifierBlocks.lines }),
329
1026
  }));
330
1027
  }
331
1028
  else {
332
1029
  writeLine(io.stdout, `next: ${first.id}`);
333
1030
  writeLine(io.stdout, `cause: ${first.cause}`);
334
1031
  writeLine(io.stdout, `why: ${first.why}`);
335
- writeLine(io.stdout, `do: ${first.do}`);
1032
+ if (guide !== null)
1033
+ writeLine(io.stdout, `guide: ${guide}`);
1034
+ if (routeGuidance !== null) {
1035
+ writeLine(io.stdout, 'do: confirm the route owner and run only the matching plane command below');
1036
+ for (const line of routeGuidance)
1037
+ writeLine(io.stdout, line);
1038
+ }
1039
+ else if (endpointGuidance.length > 0) {
1040
+ writeLine(io.stdout, `do: declare what this endpoint does in '${ENDPOINTS_CONFIG_PATH}' — the exact entry to add is below`);
1041
+ for (const line of endpointGuidance)
1042
+ writeLine(io.stdout, line);
1043
+ }
1044
+ else if (prefixGuidance.length > 0) {
1045
+ writeLine(io.stdout, `do: ${fastapiPrefixDo(first.why)}`);
1046
+ for (const line of prefixGuidance)
1047
+ writeLine(io.stdout, line);
1048
+ }
1049
+ else if (classifierBlocks !== null) {
1050
+ writeLine(io.stdout, `do: ${classifierBlocks.do}`);
1051
+ for (const line of classifierBlocks.lines)
1052
+ writeLine(io.stdout, line);
1053
+ }
1054
+ else {
1055
+ writeLine(io.stdout, `do: ${first.do}`);
1056
+ }
1057
+ for (const line of behaviorGuidance)
1058
+ writeLine(io.stdout, line);
1059
+ for (const line of scopeNote)
1060
+ writeLine(io.stdout, line);
1061
+ for (const line of singletonNote)
1062
+ writeLine(io.stdout, line);
1063
+ for (const line of taskOffer)
1064
+ writeLine(io.stdout, line);
336
1065
  }
337
1066
  return 1;
338
1067
  }