@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
@@ -1,3 +1,114 @@
1
+ /** No `ui.action` anchor to pair with: the observe channel's record is its own anchor. */
2
+ const OBSERVE_ANCHORS = [null];
3
+ /**
4
+ * The two adapter advisories a run reports, neither of which blocks:
5
+ *
6
+ * - ADAPTER_CANNOT_WITNESS: a create obligation whose adapter can
7
+ * neither list the collection nor bind a natural key. The engine
8
+ * cannot prove such a create — a row that is absent from a partial
9
+ * or missing list proves nothing (E4). A finding, not a new blocking
10
+ * default: the obligation still fails on its own evidence.
11
+ * - ADAPTER_VOLATILE_FIELD_SKIPPED: the exact-value echo skipped a
12
+ * field the adapter DECLARES server-computed (E18a). Either evidence
13
+ * channel qualifies: the browser channel's `ui.action` entered input,
14
+ * or the observe channel's witness-observed request fields (a
15
+ * `persistence.observed` record has no `ui.action` anchor). Only keys
16
+ * the journey actually sent are reported. The owner must see every
17
+ * skip, so it is reported rather than silently honoured.
18
+ *
19
+ * Args:
20
+ * cwd: repo root (the adapters directory lives under it).
21
+ * pipeline: the completed pipeline run.
22
+ * verdicts: the evaluated verdicts (for the volatile skips).
23
+ * stateDir: run-state directory holding the sealed records.
24
+ *
25
+ * Returns:
26
+ * Promise<BlockingEntry[]>: non-blocking report entries, sorted.
27
+ */
28
+ async function adapterAdvisories(cwd, pipeline, verdicts, stateDir) {
29
+ const entries = [];
30
+ const adaptersDir = join(cwd, '.gateforge/adapters');
31
+ const reports = await auditAdapters(adaptersDir);
32
+ const byName = new Map(reports.map((report) => [report.name, report]));
33
+ for (const verdict of verdicts) {
34
+ if (verdict.verdict === 'satisfied')
35
+ continue;
36
+ if (verdict.obligation.contract !== 'persistence:create')
37
+ continue;
38
+ const resourceId = verdict.obligation.resourceId;
39
+ const report = byName.get(resourceId);
40
+ if (report === undefined || !report.ok)
41
+ continue;
42
+ if (report.declares.list || report.declares.naturalKey)
43
+ continue;
44
+ if (verdict.reason !== null && !verdict.reason.includes('no witnessed'))
45
+ continue;
46
+ entries.push({
47
+ kind: 'finding',
48
+ resourceId,
49
+ name: null,
50
+ detail: `create for '${resourceId}' cannot be witnessed by adapter '${report.name}': it can neither ` +
51
+ 'list the collection nor bind a natural key, so a created row could never be shown to have ' +
52
+ 'been absent before and present after (a partial list proves nothing)',
53
+ location: null,
54
+ cause: 'ADAPTER_CANNOT_WITNESS',
55
+ nextAction: CAUSE_NEXT_ACTIONS.ADAPTER_CANNOT_WITNESS,
56
+ });
57
+ }
58
+ // The run's own witnessed records, as sealed: a declared skip is read
59
+ // from the evidence itself, never from a suite-declared expectation.
60
+ const byId = new Map();
61
+ try {
62
+ const raw = JSON.parse(readFileSync(join(stateDir, 'records.json'), 'utf8'));
63
+ if (Array.isArray(raw)) {
64
+ for (const record of raw) {
65
+ if (typeof record !== 'object' || record === null)
66
+ continue;
67
+ const id = record.recordId;
68
+ if (typeof id === 'string')
69
+ byId.set(id, record);
70
+ }
71
+ }
72
+ }
73
+ catch {
74
+ // No sealed records (a static run): nothing to report a skip about.
75
+ }
76
+ for (const verdict of verdicts) {
77
+ if (verdict.verdict !== 'satisfied')
78
+ continue;
79
+ const used = verdict.recordIds.map((id) => byId.get(id) ?? null);
80
+ const actions = used.filter((record) => record !== null && record['kind'] === 'ui.action');
81
+ const skipped = [];
82
+ for (const record of used) {
83
+ if (record === null)
84
+ continue;
85
+ // The browser channel declares the entered values on its ui.action
86
+ // anchor; an observe persistence record has no anchor and carries
87
+ // the witness-observed request fields itself.
88
+ const anchors = actions.length > 0 ? actions : OBSERVE_ANCHORS;
89
+ for (const anchor of anchors) {
90
+ for (const skip of volatileEchoSkips(anchor, record)) {
91
+ if (!skipped.includes(skip.field))
92
+ skipped.push(skip.field);
93
+ }
94
+ }
95
+ }
96
+ if (skipped.length === 0)
97
+ continue;
98
+ entries.push({
99
+ kind: 'finding',
100
+ resourceId: verdict.obligation.resourceId,
101
+ name: null,
102
+ detail: `the exact-value echo skipped ${skipped.length} field(s) the adapter declares ` +
103
+ `server-computed: ${skipped.sort().join(', ')} — the entered values were not compared with the ` +
104
+ 'persisted state, and the engine-observed values are what the app stored',
105
+ location: null,
106
+ cause: 'ADAPTER_VOLATILE_FIELD_SKIPPED',
107
+ nextAction: CAUSE_NEXT_ACTIONS.ADAPTER_VOLATILE_FIELD_SKIPPED,
108
+ });
109
+ }
110
+ return entries;
111
+ }
1
112
  /**
2
113
  * `gateforge check`: the full gate — discover → obligations → claims →
3
114
  * verdicts → report, with exit codes per architecture contract 4
@@ -14,36 +125,306 @@
14
125
  * produce identical resource-change sets for identical repos).
15
126
  *
16
127
  * Current claim declarations come from `.gateforge/test-map.yml` and,
17
- * when available, a verified receipt for the current input digest. Raw
18
- * `claims.json` contents and live annotations are not check bindings.
128
+ * when available, a verified receipt for the current input digest. Static
129
+ * annotations are compared with generated sidecar entries but are not direct
130
+ * check bindings; raw `claims.json` is never a declaration source.
19
131
  */
20
- import { cpSync, existsSync, mkdirSync } from 'node:fs';
21
- import { CAUSE_NEXT_ACTIONS, engineBundleDigestOf, executionBoundaryDigestOf, LOCAL_UNISOLATED_BOUNDARY, renderRun, runExitCode, } from '@gate-forge/core';
22
- import { discoverTestCatalog, findPlaywrightConfig } from '@gate-forge/pack-playwright';
132
+ import { cpSync, existsSync, lstatSync, mkdirSync, readFileSync } from 'node:fs';
133
+ import { spawnSync } from 'node:child_process';
134
+ import { createHash } from 'node:crypto';
135
+ import { join } from 'node:path';
136
+ import { performance } from 'node:perf_hooks';
137
+ import { BLOCKING_VERDICTS, decideStrictness, loadQuarantines, QUARANTINE_DIR, resolveStrictnessMode, strictnessSummaryLine, CAUSE_NEXT_ACTIONS, canonicalJson, ENGINE_UPGRADE_REFUSAL_PREFIX, volatileEchoSkips, engineBundleDigestOf, executionBoundaryDigestOf, GateReceiptSchema, humanMessage, LOCAL_UNISOLATED_BOUNDARY, renderRun, runExitCode, } from '@gate-forge/core';
138
+ import { discoverTestCatalog, findPlaywrightConfig, scanTestFiles, untrustedEnv, } from '@gate-forge/pack-playwright';
23
139
  import { parseArgs, stringFlag } from '../args.js';
24
140
  import { resolveAdoptedBaseline } from '../adopted-baseline.js';
25
141
  import { UsageError } from '../errors.js';
26
142
  import { writeLine } from '../io.js';
27
143
  import { trustedPolicyDigestForConfig } from '../execution.js';
28
- import { obligationFingerprint, evaluateRun } from '../evaluate.js';
29
- import { loadOptionalTestMap, mappedCoverageFrom, mappingBlocking, resolveRepositoryMappings, TEST_MAP_RELATIVE } from '../mapping.js';
144
+ import { obligationFingerprint, evaluateRun, scopeBlocking } from '../evaluate.js';
145
+ import { auditAdapters } from '../adapter-audit.js';
146
+ import { singletonPerTenantAdvisories } from '../singleton-guidance.js';
147
+ import { responseFieldAdvisories } from '../response-field-guidance.js';
148
+ import { annotationMapSyncAdvisories, findRunnerConfigPath, loadOptionalTestMap, mappedCoverageFrom, mappingBlocking, nativeInventoryBlocking, resolveRepositoryMappings, TEST_MAP_RELATIVE } from '../mapping.js';
30
149
  import { collectInputFiles, computeInputSnapshot, diffInputFiles, SnapshotUnavailableError, UnsupportedSnapshotError, } from '../input-snapshot.js';
31
150
  import { runPipeline, resolveRepoPath, sourcesByResourceId } from '../pipeline.js';
151
+ import { digestPytestInputs, interpreterIdentity, pytestCacheKey, readPytestCache, resolveCacheControl, writePytestCache, } from '../run-cache.js';
32
152
  import { RuntimeBlockError, loadRuntimeConfigAt, prepareRuntime } from '../runtime.js';
33
153
  import { digestRuntimeReuseMounts } from '../runtime-reuse.js';
34
154
  import { authenticatedChangedInputs, loadReceiptFor, receiptGateBlocking, scopedReceiptCoverageBlocking, } from '../receipts.js';
35
- import { resolveProvider } from '../providers.js';
155
+ import { resealChainBlocking, retainedCarriedEvidence } from '../reseal-chain.js';
156
+ import { mergeRequestScopePreflight, resolveProvider } from '../providers.js';
36
157
  import { computeEvaluationScope, detectStagedWorkingTreeMismatches, } from '../scope.js';
37
- import { assertRuntimeReuseOwnerApproval, freezeStagedCandidate, materializeStagedCandidate, recheckStagedCandidate, releaseStagedCandidate, StagedCandidateBlockError, } from '../staged-candidate.js';
38
- import { httpRoutesView, resolveStateDir } from '../state.js';
158
+ import { assertRuntimeReuseOwnerApproval, freezeCommitCandidate, freezeStagedCandidate, materializeStagedCandidate, recheckStagedCandidate, releaseStagedCandidate, StagedCandidateBlockError, } from '../staged-candidate.js';
159
+ import { httpRoutesView, readCandidateTreeEntries, readStateDocument, resolveStateDir } from '../state.js';
160
+ import { engineGeneratedStateFileFilter } from '../state-artifacts.js';
39
161
  import { assertReceiptApprovedPolicy, evaluateApprovedPolicy, resolveApprovedPolicyDigest, } from '../trusted-policy.js';
40
162
  import { loadConfigAt, parseRunFormat, rejectUnknownFlags, VERSION } from './common.js';
41
163
  import { resolveVerifierKeyring } from '../verifier-keys.js';
42
164
  import { renderEndpointInventory } from '../endpoint-report.js';
43
- import { computeCandidateTreeId, resolveGitDir } from '../candidate-tree.js';
165
+ import { computeCandidateTreeSnapshot, resolveGitDir, sanitizedAuthorityEnv } from '../candidate-tree.js';
44
166
  import { DOCS_EXCLUSIONS_GUARANTEE, loadDocsExclusions } from '../docs-exclusions.js';
45
- export const CHECK_USAGE = 'usage: gateforge check [--changed] [--staged] [--require-e2e] [--format text|json|sarif]\n' +
46
- ' [--approved-policy-digest <hex64>]\n' +
167
+ import { CACHE_EXCLUSIONS_GUARANTEE, loadCacheExclusions } from '../cache-exclusions.js';
168
+ import { engineIdentity, reportEngineLine } from '../engine-identity.js';
169
+ /**
170
+ * Compares sealed candidate entries with the current tree and explains the files behind a mismatch.
171
+ *
172
+ * Args:
173
+ * sealed: entries persisted with the receipt.
174
+ * current: entries from the current candidate-tree walk.
175
+ * workspace: absolute repository root.
176
+ * stateDir: absolute run-state directory containing the receipt.
177
+ * env: sanitized process environment for Git ignore checks.
178
+ *
179
+ * Returns:
180
+ * string: actionable file-level mismatch details, or an empty string when unavailable or unchanged.
181
+ */
182
+ function candidateTreeMismatchSummary(sealed, current, workspace, stateDir, env) {
183
+ const sealedByPath = new Map(sealed.map((entry) => [entry.path, entry]));
184
+ const currentByPath = new Map(current.map((entry) => [entry.path, entry]));
185
+ const changes = [];
186
+ for (const [path, entry] of currentByPath) {
187
+ const before = sealedByPath.get(path);
188
+ if (before === undefined)
189
+ changes.push({ kind: 'added', path });
190
+ else if (before.mode !== entry.mode || before.sha !== entry.sha)
191
+ changes.push({ kind: 'changed', path });
192
+ }
193
+ for (const path of sealedByPath.keys()) {
194
+ if (!currentByPath.has(path))
195
+ changes.push({ kind: 'removed', path });
196
+ }
197
+ changes.sort((a, b) => (a.path < b.path ? -1 : a.path > b.path ? 1 : 0));
198
+ if (changes.length === 0)
199
+ return '';
200
+ const lines = changes.slice(0, 20).map(({ kind, path }) => {
201
+ const ignored = spawnSync('git', ['--no-replace-objects', 'check-ignore', '--quiet', '--', path], {
202
+ cwd: workspace,
203
+ env: sanitizedAuthorityEnv(env),
204
+ stdio: 'ignore',
205
+ }).status === 0;
206
+ return ` ${kind} ${JSON.stringify(path)}${ignored ? ' (ignored by git but part of the tested tree)' : ''}`;
207
+ });
208
+ if (changes.length > lines.length)
209
+ lines.push(` ... ${changes.length - lines.length} additional path changes`);
210
+ let postSealHint = '';
211
+ try {
212
+ // Filesystem mtimes advance in coarse clock ticks (milliseconds), so a
213
+ // quick edit right after sealing can carry the receipt's exact mtime;
214
+ // a tie therefore counts as "after the seal".
215
+ const receiptTime = lstatSync(join(stateDir, 'receipt.json')).mtimeMs;
216
+ const allChangedAfterSeal = changes.every(({ path }) => lstatSync(join(workspace, path)).mtimeMs >= receiptTime);
217
+ if (allChangedAfterSeal) {
218
+ postSealHint =
219
+ ' these paths changed after the run was sealed — often another pre-commit hook or a build step; ' +
220
+ 'run those before the suite or make them non-mutating.';
221
+ }
222
+ }
223
+ catch {
224
+ // Missing paths or receipt timestamps cannot support a post-seal claim.
225
+ }
226
+ const docsOnly = changes.every(({ path }) => /^(?:docs?|guides?)\//i.test(path) || /\.(?:md|mdx|rst)$/i.test(path));
227
+ const docsHint = docsOnly
228
+ ? ' Only documentation paths changed; if these are approved documentation folders, run `gateforge init --docs-exclude <folders>`.'
229
+ : '';
230
+ return ` candidate tree files:\n${lines.join('\n')}${postSealHint}${docsHint}`;
231
+ }
232
+ /**
233
+ * Returns an authenticated receipt for a candidate base, distinguishing a
234
+ * matching tree from an authenticated stale-tree binding. With owner-approved
235
+ * docs/cache exclusions the comparison uses the FILTERED snapshot identity
236
+ * (the same one the full gate seals): the raw candidate tree carries excluded
237
+ * bytes the receipt deliberately ignores, so an exact raw-tree match is
238
+ * impossible and the filtered tree id decides instead.
239
+ *
240
+ * Args:
241
+ * io: process context.
242
+ * checkoutDir: isolated checkout of the immutable candidate.
243
+ * candidate: frozen commit identity and tree.
244
+ * options: receipt key and optional policy pin.
245
+ *
246
+ * Returns:
247
+ * VerifiedCandidateFastPath | null: authenticated clean receipt, or null
248
+ * to use the full path.
249
+ */
250
+ function verifiedCandidateFastPathReceipt(io, checkoutDir, candidate, options) {
251
+ try {
252
+ const config = loadConfigAt(checkoutDir);
253
+ const receiptDocument = readStateDocument(resolveStateDir(io.cwd), 'receipt.json');
254
+ const parsed = GateReceiptSchema.safeParse(receiptDocument);
255
+ if (!parsed.success || config.enforcement?.receiptStage === undefined)
256
+ return null;
257
+ const docsExclusions = loadDocsExclusions(checkoutDir, config);
258
+ const cacheExclusions = loadCacheExclusions(checkoutDir, config);
259
+ const hasOwnerExclusions = docsExclusions.length > 0 || cacheExclusions.length > 0;
260
+ const receipt = parsed.data;
261
+ const currentEngine = engineIdentity();
262
+ const currentPolicyDigest = trustedPolicyDigestForConfig(checkoutDir, config);
263
+ const resolution = resolveApprovedPolicyDigest({
264
+ flag: options.approvedPolicyDigest,
265
+ env: io.env,
266
+ candidateCwd: checkoutDir,
267
+ candidateConfig: config,
268
+ });
269
+ // Owner exclusions raise the ownership bar exactly like the full gate:
270
+ // without the external pin the exclusions (and this fast path) fail closed.
271
+ const policyGate = evaluateApprovedPolicy(resolution, currentPolicyDigest, config.enforcement.strictE2E === true || hasOwnerExclusions);
272
+ if (policyGate.status !== 'enforced' ||
273
+ receipt.trustedPolicyDigest !== currentPolicyDigest ||
274
+ receipt.engine === undefined ||
275
+ receipt.engine.version !== currentEngine.version ||
276
+ receipt.engine.source !== currentEngine.source ||
277
+ receipt.engine.unpublished !== currentEngine.unpublished ||
278
+ receipt.engineBundleDigest !== engineBundleDigestOf(currentEngine.version, currentPolicyDigest) ||
279
+ receipt.receiptStage !== config.enforcement.receiptStage ||
280
+ receipt.verdictSummary.blocking !== 0 ||
281
+ (receipt.scope !== undefined && receipt.scope !== 'full')) {
282
+ return null;
283
+ }
284
+ const firstParent = candidate.parentShas[0] ?? null;
285
+ let priorParent = null;
286
+ if (firstParent !== null) {
287
+ const parentResult = spawnSync('git', ['rev-parse', '--verify', `${firstParent}^`], {
288
+ cwd: io.cwd,
289
+ env: sanitizedAuthorityEnv(io.env),
290
+ encoding: 'utf8',
291
+ });
292
+ const value = (parentResult.stdout ?? '').trim();
293
+ if (parentResult.error === undefined && parentResult.status === 0 && /^[0-9a-f]{40}$/.test(value)) {
294
+ priorParent = value;
295
+ }
296
+ }
297
+ const baseMatches = (receipt.gitSha === candidate.headSha && receipt.parentSha === firstParent) ||
298
+ (receipt.gitSha === firstParent && receipt.parentSha === priorParent);
299
+ if (!baseMatches)
300
+ return null;
301
+ const currentBoundary = executionBoundaryDigestOf(io.env['GATEFORGE_AUTHORITY_BOUNDARY']?.trim() || LOCAL_UNISOLATED_BOUNDARY);
302
+ const verified = loadReceiptFor(resolveStateDir(io.cwd), options.verifierKeyring, {
303
+ inputDigest: receipt.inputDigest,
304
+ trustedPolicyDigest: currentPolicyDigest,
305
+ executionBoundaryDigest: currentBoundary,
306
+ scope: 'full',
307
+ });
308
+ if (verified.status !== 'ok')
309
+ return null;
310
+ const approvedBinding = assertReceiptApprovedPolicy(verified.receipt, policyGate.approved);
311
+ if (!approvedBinding.ok)
312
+ return null;
313
+ // Currency check: the receipt binds the tree identity the full gate would
314
+ // have sealed. With exclusions that is the FILTERED tree of the checkout
315
+ // (docs/cache bytes excluded), recomputed here from the candidate bytes.
316
+ let expectedTreeId = candidate.treeId;
317
+ if (hasOwnerExclusions) {
318
+ const gitDir = resolveGitDir(checkoutDir, io.env);
319
+ expectedTreeId =
320
+ gitDir === null
321
+ ? null
322
+ : computeCandidateTreeSnapshot(gitDir, checkoutDir, io.env, resolveStateDir(checkoutDir), 'record', [], docsExclusions, cacheExclusions).treeId;
323
+ }
324
+ if (expectedTreeId === null)
325
+ return null;
326
+ return { receipt: verified.receipt, treeMatches: verified.receipt.candidateTreeId === expectedTreeId, expectedTreeId };
327
+ }
328
+ catch {
329
+ return null;
330
+ }
331
+ }
332
+ /**
333
+ * Renders the signed summary used when discovery is safely skipped.
334
+ *
335
+ * Args:
336
+ * format: text or JSON output requested by the caller.
337
+ * receipt: authenticated full-scope receipt.
338
+ * candidateTreeId: frozen candidate tree identity.
339
+ *
340
+ * Returns:
341
+ * string: auditable fast-path result.
342
+ */
343
+ function renderFastPathReceipt(format, receipt, candidateTreeId) {
344
+ const diagnosticContext = {
345
+ scope: 'full',
346
+ candidateTreeId,
347
+ inputDigest: receipt.inputDigest,
348
+ evidenceState: 'receipt-verified-fast-path',
349
+ authority: 'authoritative',
350
+ };
351
+ if (format === 'json') {
352
+ return canonicalJson({
353
+ fastPath: true,
354
+ receiptStage: receipt.receiptStage ?? null,
355
+ engine: receipt.engine ?? null,
356
+ summary: receipt.verdictSummary,
357
+ blocking: [],
358
+ diagnosticContext,
359
+ });
360
+ }
361
+ const summary = receipt.verdictSummary;
362
+ return [
363
+ `gateforge run: ${String(summary.total)} obligation(s) — ${String(summary.satisfied)} satisfied, ${String(summary.waived)} waived, 0 blocking`,
364
+ 'receipt: verified for the exact candidate tree; discovery and test execution were not started (fast path)',
365
+ `diagnostic context: scope=full candidateTreeId=${candidateTreeId} inputDigest=${receipt.inputDigest} evidence=receipt-verified-fast-path authority=authoritative`,
366
+ ].join('\n');
367
+ }
368
+ /**
369
+ * Finds endpoints whose only statically matched tests intercept their route.
370
+ *
371
+ * Args:
372
+ * endpoints: compiled endpoint identities.
373
+ * tests: statically discovered tests and their route-interception facts.
374
+ *
375
+ * Returns:
376
+ * BlockingEntry[]: non-blocking report entries for mocked-only routes.
377
+ */
378
+ function mockedOnlyEndpointAdvisories(endpoints, tests) {
379
+ /**
380
+ * Compiles a Playwright-style route glob for a full-path comparison.
381
+ *
382
+ * Args:
383
+ * pattern: statically discovered route glob.
384
+ *
385
+ * Returns:
386
+ * RegExp: matcher for one candidate URL or canonical path.
387
+ */
388
+ const routeRegex = (pattern) => {
389
+ /**
390
+ * Escapes ordinary glob text for use in the route regular expression.
391
+ *
392
+ * Args:
393
+ * value: text between wildcard markers.
394
+ *
395
+ * Returns:
396
+ * string: escaped regular-expression source.
397
+ */
398
+ const escape = (value) => value.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
399
+ return new RegExp(`^${pattern
400
+ .split('**')
401
+ .map((part) => part.split('*').map(escape).join('[^/]*'))
402
+ .join('.*')}$`);
403
+ };
404
+ const entries = [];
405
+ for (const endpoint of endpoints) {
406
+ const targetPath = endpoint.canonicalPath;
407
+ const matchingTests = tests.filter((test) => (test.facts.pageRouteTargets ?? []).some((pattern) => {
408
+ const matches = routeRegex(pattern);
409
+ return matches.test(targetPath) || matches.test(`http://gateforge.invalid${targetPath}`);
410
+ }));
411
+ if (matchingTests.length === 0 || matchingTests.some((test) => test.facts.pageRoute === null))
412
+ continue;
413
+ const testNames = matchingTests.map((test) => `${test.file} (${test.title})`).sort();
414
+ entries.push({
415
+ kind: 'finding',
416
+ resourceId: null,
417
+ name: null,
418
+ detail: `only mocked tests reach ${endpoint.method} ${targetPath}: ${testNames.join(', ')}`,
419
+ location: null,
420
+ cause: null,
421
+ nextAction: 'Add a witnessed test that reaches the server instead of intercepting this route.',
422
+ });
423
+ }
424
+ return entries;
425
+ }
426
+ export const CHECK_USAGE = 'usage: gateforge check [--changed] [--staged] [--candidate-commit <sha>] [--require-e2e] [--format text|json|sarif]\n' +
427
+ ' [--approved-policy-digest <hex64>] [--timing] [--no-cache]\n' +
47
428
  ' verifier key: GATEFORGE_WITNESS_VERIFIER_KEY or GATEFORGE_WITNESS_VERIFIER_KEY_FILE\n' +
48
429
  ' approved policy digest: the OWNER-APPROVED policy revision pin. Never sourced from\n' +
49
430
  ' candidate-controlled files in strict mode — provision it via the protected\n' +
@@ -66,16 +447,34 @@ export async function checkCommand(io, argv) {
66
447
  writeLine(io.stdout, CHECK_USAGE);
67
448
  return 0;
68
449
  }
69
- rejectUnknownFlags(options, ['changed', 'staged', 'require-e2e', 'format', 'approved-policy-digest', 'help'], CHECK_USAGE);
450
+ rejectUnknownFlags(options, ['changed', 'staged', 'candidate-commit', 'require-e2e', 'format', 'approved-policy-digest', 'timing', 'no-cache', 'help'], CHECK_USAGE);
70
451
  if (options['staged'] === true && options['changed'] === true) {
71
452
  throw new UsageError('check: --staged already scopes the run to the staged candidate; --changed cannot be combined');
72
453
  }
73
454
  const format = parseRunFormat(stringFlag(options, 'format') ?? 'text');
74
455
  const requireE2E = options['require-e2e'] === true;
75
456
  const approvedPolicyDigest = stringFlag(options, 'approved-policy-digest');
457
+ const timing = options['timing'] === true;
458
+ const noCache = options['no-cache'] === true;
76
459
  const verifierKeyring = resolveVerifierKeyring(io.cwd, io.env, [resolveStateDir(io.cwd)]);
460
+ const candidateCommitSha = stringFlag(options, 'candidate-commit');
461
+ if (options['staged'] === true && candidateCommitSha !== undefined) {
462
+ throw new UsageError('check: --candidate-commit cannot be combined with --staged');
463
+ }
464
+ if (candidateCommitSha !== undefined) {
465
+ return stagedCheckCommand(io, {
466
+ candidateCommitSha,
467
+ diffScoped: options['changed'] === true,
468
+ requireE2E,
469
+ format,
470
+ approvedPolicyDigest,
471
+ verifierKeyring,
472
+ timing,
473
+ noCache,
474
+ });
475
+ }
77
476
  if (options['staged'] === true) {
78
- return stagedCheckCommand(io, { requireE2E, format, approvedPolicyDigest, verifierKeyring });
477
+ return stagedCheckCommand(io, { diffScoped: true, requireE2E, format, approvedPolicyDigest, verifierKeyring, timing, noCache });
79
478
  }
80
479
  return runCheckGate(io, {
81
480
  diffScoped: options['changed'] === true,
@@ -83,6 +482,8 @@ export async function checkCommand(io, argv) {
83
482
  format,
84
483
  approvedPolicyDigest,
85
484
  verifierKeyring,
485
+ timing,
486
+ noCache,
86
487
  });
87
488
  }
88
489
  /**
@@ -111,7 +512,10 @@ export async function checkCommand(io, argv) {
111
512
  async function stagedCheckCommand(io, options) {
112
513
  let frozen;
113
514
  try {
114
- frozen = freezeStagedCandidate(io.cwd, io.env);
515
+ frozen =
516
+ options.candidateCommitSha === undefined
517
+ ? freezeStagedCandidate(io.cwd, io.env)
518
+ : freezeCommitCandidate(io.cwd, io.env, options.candidateCommitSha);
115
519
  }
116
520
  catch (error) {
117
521
  if (error instanceof StagedCandidateBlockError) {
@@ -133,10 +537,11 @@ async function stagedCheckCommand(io, options) {
133
537
  // staged tree; only the marker-relevant empty dirs are mirrored).
134
538
  const checkoutConfig = loadConfigAt(checkoutDir);
135
539
  const docsExclusions = loadDocsExclusions(checkoutDir, checkoutConfig);
540
+ const cacheExclusions = loadCacheExclusions(checkoutDir, checkoutConfig);
136
541
  for (const dir of [checkoutConfig.adapters, checkoutConfig.waivers]) {
137
542
  const userDir = resolveRepoPath(io.cwd, dir);
138
543
  const checkoutPath = resolveRepoPath(checkoutDir, dir);
139
- if (existsSync(userDir) && !existsSync(checkoutPath)) {
544
+ if (options.candidateCommitSha === undefined && existsSync(userDir) && !existsSync(checkoutPath)) {
140
545
  mkdirSync(checkoutPath, { recursive: true });
141
546
  }
142
547
  }
@@ -157,11 +562,46 @@ async function stagedCheckCommand(io, options) {
157
562
  env: io.env,
158
563
  candidateCwd: checkoutDir,
159
564
  candidateConfig: checkoutConfig,
160
- }), candidatePolicyDigest, checkoutConfig.enforcement?.strictE2E === true || docsExclusions.length > 0);
565
+ }), candidatePolicyDigest, checkoutConfig.enforcement?.strictE2E === true || docsExclusions.length > 0 || cacheExclusions.length > 0);
161
566
  if (policyGate.status === 'blocked') {
162
567
  releaseStagedCandidate(frozen);
163
568
  return renderStagedBlock(io, policyGate.cause, policyGate.detail, policyGate.nextAction);
164
569
  }
570
+ if (options.candidateCommitSha !== undefined &&
571
+ options.requireE2E &&
572
+ options.format !== 'sarif') {
573
+ const fastPathReceipt = verifiedCandidateFastPathReceipt(io, checkoutDir, frozen, {
574
+ approvedPolicyDigest: options.approvedPolicyDigest,
575
+ verifierKeyring: options.verifierKeyring,
576
+ });
577
+ if (fastPathReceipt !== null) {
578
+ if (!fastPathReceipt.treeMatches) {
579
+ const stateDir = resolveStateDir(io.cwd);
580
+ const sealedEntries = readCandidateTreeEntries(stateDir);
581
+ const gitDir = resolveGitDir(checkoutDir, io.env);
582
+ const snapshot = sealedEntries === null || gitDir === null
583
+ ? null
584
+ : computeCandidateTreeSnapshot(gitDir, checkoutDir, io.env, resolveStateDir(checkoutDir), 'record', [], docsExclusions, cacheExclusions);
585
+ const treeDiff = sealedEntries === null || snapshot === null
586
+ ? ''
587
+ : candidateTreeMismatchSummary(sealedEntries, snapshot.entries, checkoutDir, stateDir, io.env);
588
+ const nextAction = CAUSE_NEXT_ACTIONS.EVIDENCE_STALE;
589
+ const detail = humanMessage({
590
+ cause: 'EVIDENCE_STALE',
591
+ detail: `require-e2e: authenticated receipt is bound to candidate tree ${fastPathReceipt.receipt.candidateTreeId ?? '<unavailable>'}, ` +
592
+ `not ${fastPathReceipt.expectedTreeId ?? '<unavailable>'}.${treeDiff}`,
593
+ // The detail names the command that re-seals this candidate;
594
+ // the block's own `next action:` line keeps the cause prose.
595
+ nextAction: 'gateforge test-gates --changed',
596
+ });
597
+ releaseStagedCandidate(frozen);
598
+ return renderStagedBlock(io, 'EVIDENCE_STALE', detail, nextAction);
599
+ }
600
+ writeLine(io.stdout, renderFastPathReceipt(options.format === 'json' ? 'json' : 'text', fastPathReceipt.receipt, fastPathReceipt.expectedTreeId ?? frozen.treeId));
601
+ releaseStagedCandidate(frozen);
602
+ return 0;
603
+ }
604
+ }
165
605
  const runtimeDoc = loadRuntimeConfigAt(checkoutDir, checkoutConfig.runtime);
166
606
  if (runtimeDoc !== null) {
167
607
  assertRuntimeReuseOwnerApproval(frozen.approvedReusePaths, runtimeDoc.prepare?.reuse ?? []);
@@ -197,20 +637,26 @@ async function stagedCheckCommand(io, options) {
197
637
  cpSync(userState, resolveStateDir(checkoutDir), { recursive: true });
198
638
  }
199
639
  const code = await runCheckGate({ ...io, cwd: checkoutDir }, {
200
- diffScoped: true,
640
+ diffScoped: options.diffScoped,
201
641
  requireE2E: options.requireE2E,
202
642
  format: options.format,
203
643
  approvedPolicyDigest: options.approvedPolicyDigest,
204
644
  verifierKeyring: options.verifierKeyring,
205
- fixedChangedFiles: frozen.changedPaths,
645
+ fixedCandidateTreeId: frozen.treeId,
646
+ ...(options.diffScoped ? { fixedChangedFiles: frozen.changedPaths } : {}),
206
647
  runtimeReuseDigest,
207
648
  runtimeReuseMounts,
208
649
  runtimeReuseCheck: () => digestRuntimeReuseMounts(runtimeReuseMounts),
650
+ ...(options.timing === true ? { timing: true } : {}),
651
+ // The scratch checkout's state dir is thrown away — the cache lives
652
+ // in the USER's persistent run-state dir (same repo, content keys).
653
+ ...(options.noCache === true ? { noCache: true } : { cacheStateDir: resolveStateDir(io.cwd) }),
209
654
  });
210
- // Re-check BEFORE authorizing: different bytes never pass.
211
- const recheck = recheckStagedCandidate(io.cwd, io.env, frozen);
212
- if (!recheck.ok) {
213
- return renderStagedBlock(io, 'ENFORCEMENT_UNTRUSTED', recheck.detail, 'Re-run the gate for the current staged candidate.');
655
+ if (options.candidateCommitSha === undefined) {
656
+ const recheck = recheckStagedCandidate(io.cwd, io.env, frozen);
657
+ if (!recheck.ok) {
658
+ return renderStagedBlock(io, 'ENFORCEMENT_UNTRUSTED', recheck.detail, 'Re-run the gate for the current staged candidate.');
659
+ }
214
660
  }
215
661
  return code;
216
662
  }
@@ -246,6 +692,74 @@ function renderStagedBlock(io, cause, detail, nextAction) {
246
692
  writeLine(io.stdout, `next action: ${nextAction}`);
247
693
  return 1;
248
694
  }
695
+ /**
696
+ * Names the report's exit-code line for what it is when a non-blocking
697
+ * mode softened the run's exit code.
698
+ *
699
+ * The text report always carries the STRICT result's exit code. In
700
+ * `strict` mode that is the code the process exits with, so the line is
701
+ * left byte-identical. When a mode softens it, the same bare
702
+ * `exit code: 1` would contradict `EXIT=0` in a CI log and to an agent
703
+ * reading the report, so it is relabelled as the value a blocking mode
704
+ * would have produced. Nothing is invented: a report without that line
705
+ * is returned untouched.
706
+ *
707
+ * Args:
708
+ * report: the rendered text report.
709
+ * strictExitCode: the exit code the strict result maps to.
710
+ * exitCode: the exit code this run actually exits with.
711
+ *
712
+ * Returns:
713
+ * string: the report with its exit-code line relabelled when softened.
714
+ */
715
+ export function labelSoftenedExitCode(report, strictExitCode, exitCode) {
716
+ if (strictExitCode === exitCode)
717
+ return report;
718
+ const lines = report.split('\n');
719
+ // The LAST such line is the report's own verdict; a fixture or a
720
+ // quoted payload earlier in the text is never relabelled.
721
+ let index = -1;
722
+ for (let at = lines.length - 1; at >= 0; at -= 1) {
723
+ if (/^exit code: \d+$/.test(lines[at] ?? '')) {
724
+ index = at;
725
+ break;
726
+ }
727
+ }
728
+ if (index < 0)
729
+ return report;
730
+ lines[index] = `would exit ${String(strictExitCode)} in blocking mode`;
731
+ return lines.join('\n');
732
+ }
733
+ /**
734
+ * Validates persisted pytest collection data before it can bypass a child run.
735
+ *
736
+ * Args:
737
+ * value: parsed cache payload.
738
+ *
739
+ * Returns:
740
+ * boolean: true only for a complete collection result with valid fields.
741
+ */
742
+ function isPytestCollectionResult(value) {
743
+ if (typeof value !== 'object' || value === null || Array.isArray(value))
744
+ return false;
745
+ const result = value;
746
+ if ((result['status'] !== 'discovered' && result['status'] !== 'unavailable') ||
747
+ typeof result['detail'] !== 'string' ||
748
+ !Array.isArray(result['cases']) ||
749
+ !Array.isArray(result['collectionErrors']) ||
750
+ (result['exitCode'] !== null && typeof result['exitCode'] !== 'number')) {
751
+ return false;
752
+ }
753
+ return (result['cases'].every((testCase) => {
754
+ if (typeof testCase !== 'object' || testCase === null || Array.isArray(testCase))
755
+ return false;
756
+ const row = testCase;
757
+ return (typeof row['nodeId'] === 'string' &&
758
+ typeof row['file'] === 'string' &&
759
+ Array.isArray(row['titlePath']) &&
760
+ row['titlePath'].every((title) => typeof title === 'string'));
761
+ }) && result['collectionErrors'].every((error) => typeof error === 'string'));
762
+ }
249
763
  /**
250
764
  * The gate body shared by `check`, `check --changed`, and the Phase 5
251
765
  * `check --staged` candidate run (via a scratch checkout cwd).
@@ -259,6 +773,7 @@ function renderStagedBlock(io, cause, detail, nextAction) {
259
773
  * @throws fail-closed errors (exit 2) from config/plugin/pipeline layers.
260
774
  */
261
775
  export async function runCheckGate(io, options) {
776
+ const gateStartedAtMs = performance.now();
262
777
  const { diffScoped, requireE2E, format } = options;
263
778
  const fixedChangedFiles = options.fixedChangedFiles;
264
779
  const runtimeReuseDigest = options.runtimeReuseDigest;
@@ -272,9 +787,29 @@ export async function runCheckGate(io, options) {
272
787
  // fails closed. Legacy v1 `recordIdsMac` never authorizes, even when
273
788
  // it verifies.
274
789
  const config = loadConfigAt(io.cwd);
790
+ // A merge-request pipeline with no base commit would resolve `auto` to
791
+ // the local staged diff — zero changed files in a CI job, and a gate
792
+ // that fails an hour later on debt nobody changed. Refuse in seconds.
793
+ if (diffScoped) {
794
+ const refusal = mergeRequestScopePreflight(config, io.env);
795
+ if (refusal !== null)
796
+ throw new UsageError(refusal);
797
+ }
798
+ // Owner-chosen strictness. A missing key
799
+ // resolves to `strict`, which is byte-for-byte today's behavior: the
800
+ // decision below is a pure mapping of an ALREADY-COMPUTED strict
801
+ // result, so no mode can change what was evaluated, only what the
802
+ // process returns. `changed` needs the diff machinery, so it reuses
803
+ // the `--changed` path (provider + scope expansion) for its decision
804
+ // while the full debt still reaches the report.
805
+ const gateMode = resolveStrictnessMode(config);
806
+ const gateModeChanged = gateMode === 'changed' && !diffScoped && fixedChangedFiles === undefined;
807
+ const scopeAwareRun = diffScoped || gateModeChanged;
275
808
  const docsExclusions = loadDocsExclusions(io.cwd, config);
276
- const docsApprovalDigest = docsExclusions.length === 0 ? null : trustedPolicyDigestForConfig(io.cwd, config);
277
- const docsApprovalResolution = docsExclusions.length === 0
809
+ const cacheExclusions = loadCacheExclusions(io.cwd, config);
810
+ const hasOwnerExclusions = docsExclusions.length > 0 || cacheExclusions.length > 0;
811
+ const docsApprovalDigest = hasOwnerExclusions ? trustedPolicyDigestForConfig(io.cwd, config) : null;
812
+ const docsApprovalResolution = !hasOwnerExclusions
278
813
  ? null
279
814
  : resolveApprovedPolicyDigest({
280
815
  flag: options.approvedPolicyDigest,
@@ -293,7 +828,7 @@ export async function runCheckGate(io, options) {
293
828
  : 'mismatch';
294
829
  const providerIdentity = fixedChangedFiles !== undefined
295
830
  ? 'local-staged'
296
- : diffScoped
831
+ : scopeAwareRun
297
832
  ? resolveProvider(config.changed.provider, io.cwd, io.env).provider
298
833
  : 'all-files';
299
834
  const stateDir = resolveStateDir(io.cwd);
@@ -306,8 +841,12 @@ export async function runCheckGate(io, options) {
306
841
  // unsafe --out overlap fails closed before any evaluation.
307
842
  let preFiles = null;
308
843
  let snapshotUnavailable = false;
844
+ // Content-addressed run cache: lives in
845
+ // the EXCLUDED run-state dir (never in the input digest), forced off by
846
+ // --no-cache / GATEFORGE_NO_CACHE / CI. A speed-up, never proof.
847
+ const cacheControl = resolveCacheControl(io.env, options.cacheStateDir ?? stateDir, options.noCache === true);
309
848
  try {
310
- preFiles = collectInputFiles(io.cwd, config, stateDir, runtimeReuseMounts, docsExclusions);
849
+ preFiles = collectInputFiles(io.cwd, config, stateDir, runtimeReuseMounts, docsExclusions, cacheExclusions);
311
850
  }
312
851
  catch (error) {
313
852
  if (error instanceof SnapshotUnavailableError) {
@@ -327,7 +866,27 @@ export async function runCheckGate(io, options) {
327
866
  provider: providerIdentity,
328
867
  stateDir,
329
868
  ...(fixedChangedFiles !== undefined ? { changedFilesOverride: fixedChangedFiles } : {}),
869
+ pluginCache: cacheControl,
870
+ });
871
+ // Owner quarantine population: check is
872
+ // the debt view, so an owner-quarantined test is reported here too —
873
+ // loaded against the INJECTED run clock, never the wall clock. It is
874
+ // only reported when the population exists, so a repository that never
875
+ // quarantined anything gets exactly the document it had before.
876
+ const quarantines = loadQuarantines(join(io.cwd, ...QUARANTINE_DIR.split('/')), {
877
+ now: pipeline.now,
330
878
  });
879
+ for (const notice of pipeline.alembicNotices) {
880
+ writeLine(io.stdout, `alembic: ${notice}`);
881
+ }
882
+ if (diffScoped && format === 'text') {
883
+ const base = providerIdentity === 'github-pr'
884
+ ? io.env['GITHUB_BASE_REF'] ?? '<missing GITHUB_BASE_REF>'
885
+ : providerIdentity === 'gitlab-mr'
886
+ ? io.env['CI_MERGE_REQUEST_DIFF_BASE_SHA'] ?? '<missing merge-request base>'
887
+ : 'staged index vs HEAD';
888
+ writeLine(io.stdout, `changed files: ${pipeline.changedFiles.length} (${providerIdentity}, ${base})`);
889
+ }
331
890
  if (options.runtimeReuseCheck !== undefined) {
332
891
  let currentReuseDigest;
333
892
  try {
@@ -353,7 +912,7 @@ export async function runCheckGate(io, options) {
353
912
  let diagnosticEvidenceState = 'not-required';
354
913
  if (!snapshotUnavailable) {
355
914
  try {
356
- const postFiles = collectInputFiles(io.cwd, config, stateDir, runtimeReuseMounts, docsExclusions);
915
+ const postFiles = collectInputFiles(io.cwd, config, stateDir, runtimeReuseMounts, docsExclusions, cacheExclusions);
357
916
  if (preFiles !== null && diffInputFiles(preFiles, postFiles).length > 0) {
358
917
  changedInputs = true;
359
918
  }
@@ -372,6 +931,7 @@ export async function runCheckGate(io, options) {
372
931
  runtimeReuseDigest,
373
932
  runtimeReuseMounts,
374
933
  docsExclusions,
934
+ cacheExclusions,
375
935
  });
376
936
  expectedDigest = currentSnapshot.inputDigest;
377
937
  }
@@ -424,17 +984,26 @@ export async function runCheckGate(io, options) {
424
984
  // `all-files` as the diff provider.
425
985
  let scopeDecision = { mode: 'all', changedFiles: [], expandedBecause: [], unmappedFiles: [] };
426
986
  let mismatchBlocking = [];
427
- if (diffScoped) {
428
- // Phase 4 expansion inputs (E15): test inventory is loaded only when
429
- // test infrastructure exists (playwright config or mapping sidecar);
430
- // repositories without either keep the exact historical behavior.
987
+ let scopeDiscoveryTimings;
988
+ if (scopeAwareRun) {
989
+ // Phase 4 expansion inputs (E15): the test inventory is loaded only
990
+ // when test infrastructure exists for the CONFIGURED runner (`runner:`
991
+ // in `.gateforge.yml`; an absent key means playwright, so a repository
992
+ // without it keeps the exact historical behavior) or a mapping
993
+ // sidecar.
431
994
  const sidecar = loadOptionalTestMap(io.cwd);
432
- const runnerConfig = findPlaywrightConfig(io.cwd);
995
+ const runnerConfig = findRunnerConfigPath(io.cwd, config.runner);
433
996
  let testFiles = [];
434
997
  if (runnerConfig !== null) {
435
998
  try {
436
- testFiles = (await discoverTestCatalog({ cwd: io.cwd, config })).catalog.entries
437
- .filter((entry) => entry.runner === 'playwright')
999
+ const scopeDiscovery = await discoverTestCatalog({
1000
+ cwd: io.cwd,
1001
+ config,
1002
+ excludeFile: engineGeneratedStateFileFilter(io.cwd, stateDir),
1003
+ });
1004
+ scopeDiscoveryTimings = scopeDiscovery.timings;
1005
+ testFiles = scopeDiscovery.catalog.entries
1006
+ .filter((entry) => entry.runner === config.runner)
438
1007
  .map((entry) => entry.file);
439
1008
  }
440
1009
  catch {
@@ -504,24 +1073,101 @@ export async function runCheckGate(io, options) {
504
1073
  }
505
1074
  }
506
1075
  }
507
- // A check binds claims from the tracked sidecar plus a complete,
508
- // authenticated execution result for this input digest. Live annotations
509
- // and partial run-state claims are not check declarations.
1076
+ // Static annotations are compared with generated sidecar entries. The
1077
+ // advisory is deliberately separate from blockers for this warning-only
1078
+ // release period; only the tracked sidecar and a verified receipt bind
1079
+ // claims during check.
1080
+ // Environment-dependent registration warnings are stderr advisories;
1081
+ // they never declare claims or alter the gate result.
1082
+ const currentTestMap = loadOptionalTestMap(io.cwd);
1083
+ const annotationScanStartedAtMs = performance.now();
1084
+ const annotationScan = scanTestFiles({
1085
+ cwd: io.cwd,
1086
+ include: config.project.paths.include,
1087
+ exclude: config.project.paths.exclude,
1088
+ excludeFile: engineGeneratedStateFileFilter(io.cwd, stateDir),
1089
+ });
1090
+ const tsScanMs = performance.now() - annotationScanStartedAtMs;
1091
+ for (const warning of annotationScan.registrationWarnings) {
1092
+ writeLine(io.stderr, `check: registration warning ${warning.file}:${String(warning.location.line)}: ` +
1093
+ `${warning.titlePath.join(' > ')} is conditional on ${warning.environmentVariable}; ` +
1094
+ 'keep test registration independent of Gateforge run variables');
1095
+ }
1096
+ const annotationAdvisories = annotationMapSyncAdvisories(annotationScan, currentTestMap);
1097
+ const mockedOnlyAdvisories = mockedOnlyEndpointAdvisories(pipeline.endpointInventory.endpoints, annotationScan.entries);
510
1098
  let claimInventory = claimBindings;
511
1099
  let mappingBlockers = [];
512
1100
  let mappedCoverage = [];
513
- if (loadOptionalTestMap(io.cwd) !== null) {
1101
+ let mappingDiscoveryTimings;
1102
+ const pytestCacheCounts = { hits: 0, misses: 0 };
1103
+ const pytestCollection = async (suite, suiteCwd, collectorArgv, collect) => {
1104
+ if (cacheControl.disabled)
1105
+ return collect();
1106
+ const inputDigest = digestPytestInputs(io.cwd, stateDir, cacheControl.stateDir);
1107
+ const collectorEnv = { ...untrustedEnv(io.env), PYTHONDONTWRITEBYTECODE: '1' };
1108
+ const collectorInterpreter = interpreterIdentity(collectorArgv[0] ?? '', collectorEnv);
1109
+ if (inputDigest === null || collectorInterpreter === null) {
1110
+ pytestCacheCounts.misses += 1;
1111
+ return collect();
1112
+ }
1113
+ const environmentDigest = createHash('sha256')
1114
+ .update(JSON.stringify(Object.entries(collectorEnv).sort(([a], [b]) => a.localeCompare(b))))
1115
+ .digest('hex');
1116
+ const key = pytestCacheKey({
1117
+ name: suite.name,
1118
+ cwd: suiteCwd,
1119
+ argv: suite.argv,
1120
+ collectorArgv,
1121
+ testPaths: suite.testPaths,
1122
+ timeoutMs: suite.timeoutMs,
1123
+ }, inputDigest, collectorInterpreter, environmentDigest);
1124
+ let cached = null;
1125
+ try {
1126
+ cached = readPytestCache(cacheControl.stateDir, key);
1127
+ }
1128
+ catch {
1129
+ cached = null;
1130
+ }
1131
+ if (isPytestCollectionResult(cached)) {
1132
+ pytestCacheCounts.hits += 1;
1133
+ return cached;
1134
+ }
1135
+ pytestCacheCounts.misses += 1;
1136
+ const result = await collect();
1137
+ if (result.status === 'discovered' && result.exitCode === 0) {
1138
+ try {
1139
+ writePytestCache(cacheControl.stateDir, key, result);
1140
+ }
1141
+ catch {
1142
+ // Storage failure costs only a future miss; collection is authoritative.
1143
+ }
1144
+ }
1145
+ return result;
1146
+ };
1147
+ if (currentTestMap !== null) {
514
1148
  const mapped = await resolveRepositoryMappings({
515
1149
  cwd: io.cwd,
516
1150
  config,
1151
+ stateDir,
517
1152
  obligations: pipeline.policy.obligations,
518
1153
  claimBindings,
519
1154
  behaviorCatalog: pipeline.behaviorCatalog,
1155
+ pytestCollection,
520
1156
  });
1157
+ mappingDiscoveryTimings = mapped.discoveryTimings;
521
1158
  claimInventory = mapped.claimInventory;
522
- mappingBlockers = mappingBlocking(mapped.resolution.problems);
1159
+ mappingBlockers = [
1160
+ ...mappingBlocking(mapped.resolution.problems),
1161
+ ...nativeInventoryBlocking(mapped.nativeLoadProblem),
1162
+ ];
523
1163
  mappedCoverage = mappedCoverageFrom(mapped.resolution, pipeline.policy.obligations, pipeline.graph);
524
1164
  }
1165
+ const adoptedBaseline = resolveAdoptedBaseline(io.cwd, config.baselines);
1166
+ // A re-sealed run grades the evidence UNION: this run's own records
1167
+ // plus the parent's carried ones, authenticated by the retained
1168
+ // parent envelope. `resealChainBlocking` below is what recomputes the
1169
+ // whole chain and fails closed on any difference.
1170
+ const carriedEvidence = retainedCarriedEvidence(stateDir);
525
1171
  const evaluated = evaluateRun({
526
1172
  cwd: io.cwd,
527
1173
  config,
@@ -534,15 +1180,21 @@ export async function runCheckGate(io, options) {
534
1180
  blocking: [...pipeline.policy.blocking, ...mismatchBlocking, ...mappingBlockers],
535
1181
  stateDir,
536
1182
  now: pipeline.now,
1183
+ engineAlembicRecords: pipeline.engineAlembicRecords,
537
1184
  // One effective scope (§12.2), decided before grading: an expanded
538
1185
  // (gate-defining) diff evaluates everything — obligations AND
539
1186
  // blockers — exactly like the unrestricted run.
540
- changedFiles: scopeDecision.mode === 'all' ? null : scopeDecision.changedFiles,
1187
+ // Only an EXPLICIT `--changed` narrows what gets graded. `mode:
1188
+ // changed` reuses the same scope computation for its DECISION while
1189
+ // the full debt stays in the report — that is the whole difference
1190
+ // between the two.
1191
+ changedFiles: diffScoped && scopeDecision.mode !== 'all' ? scopeDecision.changedFiles : null,
541
1192
  claimInventory,
542
1193
  mappedCoverage,
543
1194
  witnessVerifierKey,
544
1195
  witnessVerifierKeys: verifierKeyring?.keys.map((entry) => entry.key),
545
- baseline: resolveAdoptedBaseline(io.cwd, config.baselines),
1196
+ ...(carriedEvidence === null ? {} : { carriedEvidence }),
1197
+ baseline: adoptedBaseline,
546
1198
  evidenceContext: {
547
1199
  expectedInputDigest: expectedDigest,
548
1200
  snapshotUnavailable,
@@ -550,6 +1202,59 @@ export async function runCheckGate(io, options) {
550
1202
  changedInputs,
551
1203
  },
552
1204
  });
1205
+ const baselineReport = adoptedBaseline === null
1206
+ ? undefined
1207
+ : {
1208
+ obligations: evaluated.baselined?.obligations ?? 0,
1209
+ blockingEntries: evaluated.baselined?.blockingEntries ?? 0,
1210
+ ...(evaluated.baselined?.classificationBlocked !== undefined
1211
+ ? { classificationBlocked: evaluated.baselined.classificationBlocked }
1212
+ : {}),
1213
+ adoptedAt: adoptedBaseline.adoptedAt,
1214
+ ageDays: Math.max(0, Math.floor((Date.parse(pipeline.now) - Date.parse(adoptedBaseline.adoptedAt)) / 86_400_000)),
1215
+ neverWitnessed: evaluated.baselined?.neverWitnessed ?? 0,
1216
+ };
1217
+ const baselineDriftAdvisories = [];
1218
+ if (scopeDecision.mode === 'changed' &&
1219
+ adoptedBaseline?.obligationFingerprintsById !== undefined &&
1220
+ adoptedBaseline.obligationSourcesById !== undefined) {
1221
+ const currentSources = sourcesByResourceId(pipeline.graph, pipeline.behaviorCatalog);
1222
+ const currentFingerprints = new Map(pipeline.policy.obligations.map((obligation) => [
1223
+ obligation.id,
1224
+ obligationFingerprint(obligation),
1225
+ ]));
1226
+ const lostByFile = new Map();
1227
+ for (const [id, oldFingerprint] of adoptedBaseline.obligationFingerprintsById) {
1228
+ const currentFingerprint = currentFingerprints.get(id);
1229
+ if (currentFingerprint === undefined ||
1230
+ currentFingerprint === oldFingerprint ||
1231
+ !adoptedBaseline.fingerprints.has(oldFingerprint)) {
1232
+ continue;
1233
+ }
1234
+ const sourcePaths = new Set([
1235
+ ...(adoptedBaseline.obligationSourcesById.get(id) ?? []),
1236
+ ...(currentSources.get(id) ?? []),
1237
+ ]);
1238
+ for (const file of scopeDecision.changedFiles) {
1239
+ if (!sourcePaths.has(file))
1240
+ continue;
1241
+ const obligations = lostByFile.get(file) ?? new Set();
1242
+ obligations.add(id);
1243
+ lostByFile.set(file, obligations);
1244
+ }
1245
+ }
1246
+ for (const [file, obligations] of [...lostByFile].sort(([a], [b]) => a.localeCompare(b))) {
1247
+ baselineDriftAdvisories.push({
1248
+ kind: 'finding',
1249
+ resourceId: null,
1250
+ name: null,
1251
+ detail: `${obligations.size} adopted baseline obligation(s) lost their baseline because ${file} changed`,
1252
+ location: null,
1253
+ cause: null,
1254
+ nextAction: 'Compare baseline files with `gateforge baseline diff <before> <after>`.',
1255
+ });
1256
+ }
1257
+ }
553
1258
  // `--require-e2e` (plan Phase 4 item 5, ADR 0005 D3): the strict
554
1259
  // saved-state gate. Without a valid, non-stale receipt for the CURRENT
555
1260
  // input digest the run blocks — missing receipt (RUN_INCOMPLETE),
@@ -616,7 +1321,7 @@ export async function runCheckGate(io, options) {
616
1321
  candidateCwd: io.cwd,
617
1322
  candidateConfig: config,
618
1323
  });
619
- const gate = evaluateApprovedPolicy(resolution, candidatePolicyDigest, config.enforcement?.strictE2E === true || docsExclusions.length > 0);
1324
+ const gate = evaluateApprovedPolicy(resolution, candidatePolicyDigest, config.enforcement?.strictE2E === true || hasOwnerExclusions);
620
1325
  if (gate.status === 'blocked') {
621
1326
  diagnosticEvidenceState = 'owner-policy-blocked';
622
1327
  receiptBlocking = [
@@ -633,11 +1338,12 @@ export async function runCheckGate(io, options) {
633
1338
  }
634
1339
  else {
635
1340
  const gitDir = resolveGitDir(io.cwd, io.env);
636
- const candidateTreeId = options.fixedCandidateTreeId !== undefined
637
- ? options.fixedCandidateTreeId
638
- : gitDir === null
639
- ? null
640
- : computeCandidateTreeId(gitDir, io.cwd, io.env, stateDir, 'record', runtimeReuseMounts, docsExclusions);
1341
+ const candidateTreeSnapshot = gitDir === null
1342
+ ? null
1343
+ : computeCandidateTreeSnapshot(gitDir, io.cwd, io.env, stateDir, 'record', runtimeReuseMounts, docsExclusions, cacheExclusions);
1344
+ const candidateTreeId = docsExclusions.length > 0 || cacheExclusions.length > 0
1345
+ ? (candidateTreeSnapshot?.treeId ?? null)
1346
+ : (options.fixedCandidateTreeId ?? candidateTreeSnapshot?.treeId ?? null);
641
1347
  diagnosticCandidateTreeId = candidateTreeId;
642
1348
  const load = loadReceiptFor(stateDir, verifierKeyring, {
643
1349
  inputDigest: expectedDigest,
@@ -653,11 +1359,31 @@ export async function runCheckGate(io, options) {
653
1359
  });
654
1360
  diagnosticEvidenceState = load.status === 'ok' ? 'receipt-verified' : `receipt-${load.status}`;
655
1361
  if (load.status === 'ok') {
1362
+ if (load.receipt.engine !== undefined &&
1363
+ load.receipt.engine.version !== engineIdentity().version) {
1364
+ const detail = `require-e2e: receipt engine version '${load.receipt.engine.version}' differs from ` +
1365
+ `installed version '${engineIdentity().version}'`;
1366
+ receiptBlocking = [
1367
+ {
1368
+ kind: 'finding',
1369
+ resourceId: null,
1370
+ name: null,
1371
+ detail: humanMessage({
1372
+ cause: 'ENFORCEMENT_UNTRUSTED',
1373
+ detail,
1374
+ nextAction: 'gateforge test-gates --changed',
1375
+ }),
1376
+ location: null,
1377
+ cause: 'ENFORCEMENT_UNTRUSTED',
1378
+ nextAction: 'gateforge test-gates --changed',
1379
+ },
1380
+ ];
1381
+ }
656
1382
  // A provisioned pin binds the receipt too: a receipt sealed
657
1383
  // under a since-revoked/different approved revision is a typed
658
1384
  // reject, and under a pin the binding must be present. When the
659
1385
  // binding decides, the coverage check below is skipped.
660
- if (gate.status === 'enforced') {
1386
+ if (receiptBlocking.length === 0 && gate.status === 'enforced') {
661
1387
  const binding = assertReceiptApprovedPolicy(load.receipt, gate.approved);
662
1388
  if (!binding.ok) {
663
1389
  receiptBlocking = [
@@ -678,6 +1404,25 @@ export async function runCheckGate(io, options) {
678
1404
  // changed-scope receipt must cover every obligation this
679
1405
  // evaluation demands or the typed blocker names the gap.
680
1406
  receiptBlocking = scopedReceiptCoverageBlocking(load.receipt, requiredCoverage());
1407
+ // Re-seal recomputation (plan phase 3): a `test-only`
1408
+ // receipt is a claim. The chain it names is authenticated
1409
+ // with THIS keyring, the two sealed trees are re-diffed
1410
+ // with THIS engine, the change set is re-classified and
1411
+ // the affected set recomputed — any difference is a typed
1412
+ // EVIDENCE_STALE naming the exact mismatch.
1413
+ if (receiptBlocking.length === 0 && load.receipt.resealedFrom !== undefined) {
1414
+ receiptBlocking = resealChainBlocking({
1415
+ stateDir,
1416
+ receipt: load.receipt,
1417
+ verifierKeyring,
1418
+ gitDir,
1419
+ cwd: io.cwd,
1420
+ env: io.env,
1421
+ ...(config.enforcement?.resealRuntimeFiles !== undefined
1422
+ ? { runtimeFileGlobs: config.enforcement.resealRuntimeFiles }
1423
+ : {}),
1424
+ }).map((entry) => ({ ...entry, detail: `require-e2e: ${entry.detail}` }));
1425
+ }
681
1426
  }
682
1427
  if (receiptBlocking.length > 0)
683
1428
  diagnosticEvidenceState = 'receipt-verified-with-blocking-entry';
@@ -686,31 +1431,94 @@ export async function runCheckGate(io, options) {
686
1431
  receiptBlocking = receiptGateBlocking(load);
687
1432
  if (load.status === 'stale') {
688
1433
  const changedPaths = authenticatedChangedInputs(stateDir, verifierKeyring, currentSnapshot);
1434
+ const docsOnly = changedPaths.length > 0 && changedPaths.every((path) => /^(?:docs?|guides?)\//i.test(path) || /\.(?:md|mdx|rst|txt)$/i.test(path));
689
1435
  const changedSummary = changedPaths.length > 0
690
- ? ` changed inputs: ${changedPaths.join(', ')}.`
1436
+ ? ` changed inputs: ${changedPaths.join(', ')}.` +
1437
+ (docsOnly
1438
+ ? ' Only documentation paths changed; if these are approved documentation folders, run `gateforge init --docs-exclude <folders>`.'
1439
+ : '')
691
1440
  : ' the saved input inventory is unavailable or the change is in gate context rather than file bytes.';
692
- const revalidation = 'gateforge test-gates --changed --scope full --run-timeout-min 5';
693
- receiptBlocking = receiptBlocking.map((entry) => ({
694
- ...entry,
695
- detail: `${entry.detail}${changedSummary}`,
696
- nextAction: `Run \`${revalidation}\` to test the full configured scope within five minutes.`,
697
- }));
1441
+ const sealedTreeEntries = readCandidateTreeEntries(stateDir);
1442
+ const treeDiff = load.detail.toLowerCase().includes('candidate tree') &&
1443
+ candidateTreeSnapshot !== null &&
1444
+ sealedTreeEntries !== null
1445
+ ? candidateTreeMismatchSummary(sealedTreeEntries, candidateTreeSnapshot.entries, io.cwd, stateDir, io.env)
1446
+ : '';
1447
+ // The engine-upgrade refusal is already one complete sentence
1448
+ // naming the cause and the fix; the changed-input summary
1449
+ // belongs to the digest line beside it. Both name the same one
1450
+ // command that re-seals.
1451
+ receiptBlocking = receiptBlocking.map((entry) => entry.detail.startsWith(ENGINE_UPGRADE_REFUSAL_PREFIX)
1452
+ ? entry
1453
+ : {
1454
+ ...entry,
1455
+ detail: `${entry.detail}${changedSummary}${treeDiff}`,
1456
+ nextAction: 'gateforge test-gates --changed',
1457
+ });
698
1458
  }
699
1459
  }
700
1460
  }
701
1461
  }
702
1462
  }
1463
+ const inScopeSourcePaths = diffScoped && scopeDecision.mode === 'changed'
1464
+ ? sourcesByResourceId(pipeline.graph, pipeline.behaviorCatalog)
1465
+ : null;
1466
+ const changedSourcePaths = new Set(scopeDecision.changedFiles);
1467
+ // Scope metadata stays exactly as a non-diff run reports it unless the
1468
+ // caller actually asked for `--changed`.
1469
+ const reportScope = {
1470
+ mode: diffScoped ? scopeDecision.mode : 'all',
1471
+ expandedBecause: diffScoped ? scopeDecision.expandedBecause : [],
1472
+ };
1473
+ const reportVerdicts = inScopeSourcePaths === null
1474
+ ? evaluated.verdicts
1475
+ : evaluated.verdicts.map((verdict) => ({
1476
+ ...verdict,
1477
+ inScopeBecause: [
1478
+ ...new Set(inScopeSourcePaths.get(verdict.obligation.resourceId) ?? []),
1479
+ ]
1480
+ .filter((file) => changedSourcePaths.has(file))
1481
+ .sort(),
1482
+ }));
703
1483
  const evaluatedBlocking = [...evaluated.blocking, ...receiptBlocking];
704
- const report = renderRun(evaluated.verdicts, {
1484
+ const newDebt = diffScoped
1485
+ ? reportVerdicts
1486
+ .filter((verdict) => BLOCKING_VERDICTS.includes(verdict.verdict))
1487
+ .map((verdict) => verdict.obligation.id)
1488
+ .sort()
1489
+ : null;
1490
+ const adapterFindings = await adapterAdvisories(io.cwd, pipeline, evaluated.verdicts, stateDir);
1491
+ // Per-tenant singletons (plan Phase 4b item 3): one advisory per tagged
1492
+ // resource that owes a create. Absent the tag this is an empty list, so
1493
+ // a repo without one is byte-identical.
1494
+ const singletonFindings = singletonPerTenantAdvisories(pipeline.graph.resources, new Set(evaluated.verdicts
1495
+ .filter((verdict) => verdict.obligation.contract === 'persistence:create')
1496
+ .map((verdict) => verdict.obligation.resourceId)));
1497
+ let report = renderRun(reportVerdicts, {
705
1498
  format,
706
1499
  blocking: evaluatedBlocking,
1500
+ advisories: [
1501
+ ...annotationAdvisories,
1502
+ ...mockedOnlyAdvisories,
1503
+ ...baselineDriftAdvisories,
1504
+ ...adapterFindings,
1505
+ ...singletonFindings,
1506
+ // Frontend reads a response field the model does not declare (plan
1507
+ // Phase 4b item 5). One non-blocking advisory per gap; empty unless
1508
+ // a joined endpoint pairs a proven response model with a read, so
1509
+ // a repository without both packs renders byte-identically.
1510
+ ...responseFieldAdvisories(pipeline.endpointInventory.endpoints),
1511
+ ],
707
1512
  waiverCounts: evaluated.waiverCounts,
708
- baseline: evaluated.baselined ?? undefined,
1513
+ baseline: baselineReport,
709
1514
  run: pipeline.manifest,
710
1515
  toolVersion: VERSION,
711
- scope: { mode: scopeDecision.mode, expandedBecause: scopeDecision.expandedBecause },
1516
+ engine: engineIdentity(),
1517
+ engineLine: reportEngineLine(),
1518
+ lifecycleDerivation: pipeline.lifecycleDerivation,
1519
+ scope: reportScope,
712
1520
  diagnosticContext: {
713
- scope: scopeDecision.mode === 'changed' ? 'changed' : 'full',
1521
+ scope: reportScope.mode === 'changed' ? 'changed' : 'full',
714
1522
  candidateTreeId: diagnosticCandidateTreeId,
715
1523
  inputDigest: expectedDigest,
716
1524
  evidenceState: diagnosticEvidenceState,
@@ -725,8 +1533,146 @@ export async function runCheckGate(io, options) {
725
1533
  guarantee: DOCS_EXCLUSIONS_GUARANTEE,
726
1534
  },
727
1535
  }),
1536
+ ...(cacheExclusions.length === 0
1537
+ ? {}
1538
+ : {
1539
+ cacheExclusions: {
1540
+ files: cacheExclusions,
1541
+ approvalDigest: docsApprovalResolution?.status === 'ok' ? docsApprovalResolution.digest : null,
1542
+ approvalStatus: docsApprovalStatus ?? 'missing',
1543
+ guarantee: CACHE_EXCLUSIONS_GUARANTEE,
1544
+ },
1545
+ }),
728
1546
  },
729
1547
  });
1548
+ if (newDebt !== null) {
1549
+ if (format === 'json') {
1550
+ const document = JSON.parse(report);
1551
+ report = canonicalJson({ ...document, newDebt: { count: newDebt.length, obligationIds: newDebt } });
1552
+ }
1553
+ else if (format === 'text') {
1554
+ const debtLine = humanMessage({
1555
+ detail: `this change adds ${String(newDebt.length)} unproven obligations: ${newDebt.join(', ') || '<none>'}`,
1556
+ type: 'new-debt',
1557
+ nextAction: 'gateforge test-gates --changed',
1558
+ });
1559
+ report = `${report}\n${debtLine}`;
1560
+ }
1561
+ }
1562
+ if (options.timing === true) {
1563
+ // Per-step wall-clock timings: additive
1564
+ // observability behind `--timing`, never an input to any verdict.
1565
+ const collectionMs = (scopeDiscoveryTimings?.totalMs ?? 0) + (mappingDiscoveryTimings?.totalMs ?? 0);
1566
+ const timing = {
1567
+ detectorsMs: Math.round(pipeline.timings.pluginsMs),
1568
+ collectionMs: Math.round(collectionMs),
1569
+ tsScanMs: Math.round(tsScanMs),
1570
+ planningMs: Math.round(pipeline.timings.totalMs - pipeline.timings.pluginsMs),
1571
+ totalMs: Math.round(performance.now() - gateStartedAtMs),
1572
+ };
1573
+ if (format === 'json') {
1574
+ const document = JSON.parse(report);
1575
+ report = canonicalJson({ ...document, timing });
1576
+ }
1577
+ else if (format === 'text') {
1578
+ report =
1579
+ `${report}\ntiming: detectors=${String(timing.detectorsMs)}ms collection=${String(timing.collectionMs)}ms ` +
1580
+ `tsScan=${String(timing.tsScanMs)}ms planning=${String(timing.planningMs)}ms total=${String(timing.totalMs)}ms`;
1581
+ }
1582
+ }
1583
+ {
1584
+ // Cache accounting (additive `cache` key): how
1585
+ // many detector/pytest results were reused vs recomputed. Never an
1586
+ // input to any verdict.
1587
+ const cacheCounts = {
1588
+ hits: pipeline.cache.hits + pytestCacheCounts.hits,
1589
+ misses: pipeline.cache.misses + pytestCacheCounts.misses,
1590
+ };
1591
+ if (format === 'json') {
1592
+ const document = JSON.parse(report);
1593
+ report = canonicalJson({ ...document, cache: { hits: cacheCounts.hits, misses: cacheCounts.misses } });
1594
+ }
1595
+ else if (format === 'text' && cacheCounts.hits + cacheCounts.misses > 0) {
1596
+ report = `${report}\ncache: ${String(cacheCounts.hits)} hit(s), ${String(cacheCounts.misses)} miss(es)`;
1597
+ }
1598
+ }
1599
+ // Owner-chosen strictness: the decision
1600
+ // is a pure mapping of the strict result that was ALREADY computed, so
1601
+ // no mode can change what was evaluated. Exit 2 (config/usage) keeps
1602
+ // its meaning; only the debt exit 1 is ever softened.
1603
+ const strictExit = runExitCode({ verdicts: evaluated.verdicts, blocking: evaluatedBlocking });
1604
+ const blockingTotal = evaluated.verdicts.filter((verdict) => BLOCKING_VERDICTS.includes(verdict.verdict)).length +
1605
+ evaluatedBlocking.length;
1606
+ const sourcePaths = sourcesByResourceId(pipeline.graph, pipeline.behaviorCatalog);
1607
+ const decision = decideStrictness({
1608
+ mode: gateMode,
1609
+ strictExitCode: strictExit,
1610
+ blockingTotal,
1611
+ // An expanded scope (a gate-defining input changed) is full scope:
1612
+ // the change owns all of the debt, exactly like `--changed` says.
1613
+ ...(gateMode === 'changed'
1614
+ ? {
1615
+ changed: {
1616
+ active: true,
1617
+ blockingInScope: scopeDecision.mode === 'changed'
1618
+ ? evaluated.verdicts.filter((verdict) => BLOCKING_VERDICTS.includes(verdict.verdict) &&
1619
+ (sourcePaths.get(verdict.obligation.resourceId) ?? []).some((file) => changedSourcePaths.has(file))).length +
1620
+ scopeBlocking(evaluatedBlocking, changedSourcePaths, sourcePaths).length
1621
+ : blockingTotal,
1622
+ },
1623
+ }
1624
+ : {}),
1625
+ });
1626
+ if (decision.wouldBlock && decision.exitCode !== decision.strictExitCode) {
1627
+ // The softened decision is announced on stderr too: a CI log that
1628
+ // only keeps stdout must not read as "nothing was wrong".
1629
+ writeLine(io.stderr, `check: ${strictnessSummaryLine(decision)} — the gate exits 0 in mode '${decision.mode}', ` +
1630
+ `strict mode would exit ${String(decision.strictExitCode)}`);
1631
+ }
1632
+ const quarantineLine = quarantines.active.length === 0
1633
+ ? ''
1634
+ : `quarantined: ${String(quarantines.active.length)} (expires ${quarantines.active
1635
+ .map((entry) => `${entry.quarantine.testKey} @ ${entry.quarantine.expiresAt}`)
1636
+ .join(', ')})`;
1637
+ if (format === 'json') {
1638
+ if (gateMode !== 'strict' || quarantines.active.length > 0) {
1639
+ const document = JSON.parse(report);
1640
+ report = canonicalJson({
1641
+ ...document,
1642
+ ...(gateMode === 'strict'
1643
+ ? {}
1644
+ : {
1645
+ strictness: {
1646
+ mode: decision.mode,
1647
+ wouldBlock: decision.wouldBlock,
1648
+ blockingInScope: decision.blockingInScope,
1649
+ blockingTotal: decision.blockingTotal,
1650
+ },
1651
+ }),
1652
+ ...(quarantines.active.length === 0
1653
+ ? {}
1654
+ : {
1655
+ quarantine: {
1656
+ count: quarantines.active.length,
1657
+ tests: quarantines.active.map((entry) => ({
1658
+ testKey: entry.quarantine.testKey,
1659
+ expiresAt: entry.quarantine.expiresAt,
1660
+ owner: entry.quarantine.owner,
1661
+ })),
1662
+ },
1663
+ }),
1664
+ });
1665
+ }
1666
+ }
1667
+ else if (format === 'text') {
1668
+ // Text only: SARIF must stay machine-parseable JSON, and the json
1669
+ // document carries the structured blocks above. The report's own
1670
+ // `exit code:` line always carries the strict result; when this mode
1671
+ // softened it, the line is labelled as the value a blocking mode
1672
+ // would have produced, so it can never contradict the code the
1673
+ // process actually exits with.
1674
+ report = `${labelSoftenedExitCode(report, decision.strictExitCode, decision.exitCode)}\n${strictnessSummaryLine(decision)}${quarantineLine === '' ? '' : `\n${quarantineLine}`}`;
1675
+ }
730
1676
  if (format === 'text') {
731
1677
  // Plan phase 7: the endpoint inventory rides the text report —
732
1678
  // totals, unmatched calls, unconsumed routes, and ambiguous joins
@@ -739,6 +1685,6 @@ export async function runCheckGate(io, options) {
739
1685
  'plus a provenanced claimed ui anchor (see ADR 0004 D7/D8).');
740
1686
  }
741
1687
  writeLine(io.stdout, report);
742
- return runExitCode({ verdicts: evaluated.verdicts, blocking: evaluatedBlocking });
1688
+ return decision.exitCode;
743
1689
  }
744
1690
  //# sourceMappingURL=check.js.map