@gate-forge/cli 0.7.1 → 0.9.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (296) hide show
  1. package/README.md +91 -704
  2. package/dist/adapter-audit.d.ts +208 -0
  3. package/dist/adapter-audit.d.ts.map +1 -0
  4. package/dist/adapter-audit.js +579 -0
  5. package/dist/adapter-audit.js.map +1 -0
  6. package/dist/adapter-scaffold.d.ts +91 -0
  7. package/dist/adapter-scaffold.d.ts.map +1 -0
  8. package/dist/adapter-scaffold.js +474 -0
  9. package/dist/adapter-scaffold.js.map +1 -0
  10. package/dist/adopted-baseline.d.ts +10 -0
  11. package/dist/adopted-baseline.d.ts.map +1 -1
  12. package/dist/adopted-baseline.js +18 -1
  13. package/dist/adopted-baseline.js.map +1 -1
  14. package/dist/args.d.ts +15 -0
  15. package/dist/args.d.ts.map +1 -1
  16. package/dist/args.js +61 -2
  17. package/dist/args.js.map +1 -1
  18. package/dist/behavior-setup.d.ts +239 -0
  19. package/dist/behavior-setup.d.ts.map +1 -0
  20. package/dist/behavior-setup.js +751 -0
  21. package/dist/behavior-setup.js.map +1 -0
  22. package/dist/broker.d.ts.map +1 -1
  23. package/dist/broker.js +28 -2
  24. package/dist/broker.js.map +1 -1
  25. package/dist/cache-exclusions.d.ts +45 -0
  26. package/dist/cache-exclusions.d.ts.map +1 -0
  27. package/dist/cache-exclusions.js +205 -0
  28. package/dist/cache-exclusions.js.map +1 -0
  29. package/dist/candidate-tree.d.ts +86 -14
  30. package/dist/candidate-tree.d.ts.map +1 -1
  31. package/dist/candidate-tree.js +236 -62
  32. package/dist/candidate-tree.js.map +1 -1
  33. package/dist/ci-witnessed-template.d.ts +43 -0
  34. package/dist/ci-witnessed-template.d.ts.map +1 -0
  35. package/dist/ci-witnessed-template.js +283 -0
  36. package/dist/ci-witnessed-template.js.map +1 -0
  37. package/dist/cli.d.ts +1 -1
  38. package/dist/cli.d.ts.map +1 -1
  39. package/dist/cli.js +31 -4
  40. package/dist/cli.js.map +1 -1
  41. package/dist/commands/adapters.d.ts +15 -0
  42. package/dist/commands/adapters.d.ts.map +1 -0
  43. package/dist/commands/adapters.js +355 -0
  44. package/dist/commands/adapters.js.map +1 -0
  45. package/dist/commands/adopt.d.ts +7 -0
  46. package/dist/commands/adopt.d.ts.map +1 -1
  47. package/dist/commands/adopt.js +44 -2
  48. package/dist/commands/adopt.js.map +1 -1
  49. package/dist/commands/baseline.d.ts.map +1 -1
  50. package/dist/commands/baseline.js +42 -1
  51. package/dist/commands/baseline.js.map +1 -1
  52. package/dist/commands/blocking.d.ts +105 -2
  53. package/dist/commands/blocking.d.ts.map +1 -1
  54. package/dist/commands/blocking.js +395 -53
  55. package/dist/commands/blocking.js.map +1 -1
  56. package/dist/commands/check.d.ts +36 -0
  57. package/dist/commands/check.d.ts.map +1 -1
  58. package/dist/commands/check.js +1068 -64
  59. package/dist/commands/check.js.map +1 -1
  60. package/dist/commands/classify.d.ts +2 -1
  61. package/dist/commands/classify.d.ts.map +1 -1
  62. package/dist/commands/classify.js +188 -5
  63. package/dist/commands/classify.js.map +1 -1
  64. package/dist/commands/enforce.d.ts +4 -4
  65. package/dist/commands/enforce.d.ts.map +1 -1
  66. package/dist/commands/enforce.js +41 -9
  67. package/dist/commands/enforce.js.map +1 -1
  68. package/dist/commands/enforcement.d.ts +13 -1
  69. package/dist/commands/enforcement.d.ts.map +1 -1
  70. package/dist/commands/enforcement.js +880 -33
  71. package/dist/commands/enforcement.js.map +1 -1
  72. package/dist/commands/explain.d.ts +1 -1
  73. package/dist/commands/explain.d.ts.map +1 -1
  74. package/dist/commands/explain.js +162 -3
  75. package/dist/commands/explain.js.map +1 -1
  76. package/dist/commands/history.d.ts +12 -0
  77. package/dist/commands/history.d.ts.map +1 -0
  78. package/dist/commands/history.js +45 -0
  79. package/dist/commands/history.js.map +1 -0
  80. package/dist/commands/init-presets.d.ts +155 -0
  81. package/dist/commands/init-presets.d.ts.map +1 -0
  82. package/dist/commands/init-presets.js +203 -0
  83. package/dist/commands/init-presets.js.map +1 -0
  84. package/dist/commands/init.d.ts +7 -12
  85. package/dist/commands/init.d.ts.map +1 -1
  86. package/dist/commands/init.js +987 -99
  87. package/dist/commands/init.js.map +1 -1
  88. package/dist/commands/keys.d.ts.map +1 -1
  89. package/dist/commands/keys.js +29 -13
  90. package/dist/commands/keys.js.map +1 -1
  91. package/dist/commands/next.d.ts.map +1 -1
  92. package/dist/commands/next.js +846 -19
  93. package/dist/commands/next.js.map +1 -1
  94. package/dist/commands/pre-commit.d.ts +25 -0
  95. package/dist/commands/pre-commit.d.ts.map +1 -1
  96. package/dist/commands/pre-commit.js +91 -6
  97. package/dist/commands/pre-commit.js.map +1 -1
  98. package/dist/commands/quarantine.d.ts +16 -0
  99. package/dist/commands/quarantine.d.ts.map +1 -0
  100. package/dist/commands/quarantine.js +213 -0
  101. package/dist/commands/quarantine.js.map +1 -0
  102. package/dist/commands/run.d.ts +39 -0
  103. package/dist/commands/run.d.ts.map +1 -0
  104. package/dist/commands/run.js +196 -0
  105. package/dist/commands/run.js.map +1 -0
  106. package/dist/commands/test-gates.d.ts +284 -2
  107. package/dist/commands/test-gates.d.ts.map +1 -1
  108. package/dist/commands/test-gates.js +3620 -187
  109. package/dist/commands/test-gates.js.map +1 -1
  110. package/dist/commands/tests.d.ts +1 -1
  111. package/dist/commands/tests.d.ts.map +1 -1
  112. package/dist/commands/tests.js +264 -29
  113. package/dist/commands/tests.js.map +1 -1
  114. package/dist/docs-exclusions.d.ts.map +1 -1
  115. package/dist/docs-exclusions.js +18 -3
  116. package/dist/docs-exclusions.js.map +1 -1
  117. package/dist/endpoint-compiler.d.ts.map +1 -1
  118. package/dist/endpoint-compiler.js +78 -9
  119. package/dist/endpoint-compiler.js.map +1 -1
  120. package/dist/engine-browser.d.ts +183 -0
  121. package/dist/engine-browser.d.ts.map +1 -0
  122. package/dist/engine-browser.js +381 -0
  123. package/dist/engine-browser.js.map +1 -0
  124. package/dist/engine-identity.d.ts +100 -0
  125. package/dist/engine-identity.d.ts.map +1 -0
  126. package/dist/engine-identity.js +182 -0
  127. package/dist/engine-identity.js.map +1 -0
  128. package/dist/evaluate.d.ts +105 -1
  129. package/dist/evaluate.d.ts.map +1 -1
  130. package/dist/evaluate.js +149 -18
  131. package/dist/evaluate.js.map +1 -1
  132. package/dist/execution.d.ts +253 -9
  133. package/dist/execution.d.ts.map +1 -1
  134. package/dist/execution.js +309 -12
  135. package/dist/execution.js.map +1 -1
  136. package/dist/gateforge-owned.d.ts +78 -0
  137. package/dist/gateforge-owned.d.ts.map +1 -0
  138. package/dist/gateforge-owned.js +254 -0
  139. package/dist/gateforge-owned.js.map +1 -0
  140. package/dist/git-hooks.d.ts +35 -0
  141. package/dist/git-hooks.d.ts.map +1 -1
  142. package/dist/git-hooks.js +140 -1
  143. package/dist/git-hooks.js.map +1 -1
  144. package/dist/git-ignored.d.ts +27 -0
  145. package/dist/git-ignored.d.ts.map +1 -0
  146. package/dist/git-ignored.js +102 -0
  147. package/dist/git-ignored.js.map +1 -0
  148. package/dist/git-objects.d.ts +60 -0
  149. package/dist/git-objects.d.ts.map +1 -0
  150. package/dist/git-objects.js +152 -0
  151. package/dist/git-objects.js.map +1 -0
  152. package/dist/glob.d.ts +33 -14
  153. package/dist/glob.d.ts.map +1 -1
  154. package/dist/glob.js +96 -5
  155. package/dist/glob.js.map +1 -1
  156. package/dist/history.d.ts +52 -0
  157. package/dist/history.d.ts.map +1 -0
  158. package/dist/history.js +116 -0
  159. package/dist/history.js.map +1 -0
  160. package/dist/host-load.d.ts +49 -0
  161. package/dist/host-load.d.ts.map +1 -0
  162. package/dist/host-load.js +78 -0
  163. package/dist/host-load.js.map +1 -0
  164. package/dist/index.d.ts +4 -1
  165. package/dist/index.d.ts.map +1 -1
  166. package/dist/index.js +2 -1
  167. package/dist/index.js.map +1 -1
  168. package/dist/input-snapshot.d.ts +63 -9
  169. package/dist/input-snapshot.d.ts.map +1 -1
  170. package/dist/input-snapshot.js +195 -17
  171. package/dist/input-snapshot.js.map +1 -1
  172. package/dist/io.d.ts +49 -0
  173. package/dist/io.d.ts.map +1 -1
  174. package/dist/io.js +22 -0
  175. package/dist/io.js.map +1 -1
  176. package/dist/mapping.d.ts +84 -1
  177. package/dist/mapping.d.ts.map +1 -1
  178. package/dist/mapping.js +276 -5
  179. package/dist/mapping.js.map +1 -1
  180. package/dist/native-freeze.d.ts +217 -0
  181. package/dist/native-freeze.d.ts.map +1 -0
  182. package/dist/native-freeze.js +332 -0
  183. package/dist/native-freeze.js.map +1 -0
  184. package/dist/pipeline.d.ts +67 -1
  185. package/dist/pipeline.d.ts.map +1 -1
  186. package/dist/pipeline.js +164 -6
  187. package/dist/pipeline.js.map +1 -1
  188. package/dist/planes-inference.d.ts +12 -5
  189. package/dist/planes-inference.d.ts.map +1 -1
  190. package/dist/planes-inference.js +13 -15
  191. package/dist/planes-inference.js.map +1 -1
  192. package/dist/playwright-browsers.d.ts +210 -0
  193. package/dist/playwright-browsers.d.ts.map +1 -0
  194. package/dist/playwright-browsers.js +364 -0
  195. package/dist/playwright-browsers.js.map +1 -0
  196. package/dist/plugins.d.ts +15 -5
  197. package/dist/plugins.d.ts.map +1 -1
  198. package/dist/plugins.js +59 -9
  199. package/dist/plugins.js.map +1 -1
  200. package/dist/progress.d.ts +148 -0
  201. package/dist/progress.d.ts.map +1 -0
  202. package/dist/progress.js +263 -0
  203. package/dist/progress.js.map +1 -0
  204. package/dist/providers.d.ts +26 -1
  205. package/dist/providers.d.ts.map +1 -1
  206. package/dist/providers.js +39 -0
  207. package/dist/providers.js.map +1 -1
  208. package/dist/receipts.d.ts +1 -0
  209. package/dist/receipts.d.ts.map +1 -1
  210. package/dist/receipts.js +35 -7
  211. package/dist/receipts.js.map +1 -1
  212. package/dist/repo-scan.d.ts +15 -1
  213. package/dist/repo-scan.d.ts.map +1 -1
  214. package/dist/repo-scan.js +329 -34
  215. package/dist/repo-scan.js.map +1 -1
  216. package/dist/reseal-chain.d.ts +184 -0
  217. package/dist/reseal-chain.d.ts.map +1 -0
  218. package/dist/reseal-chain.js +735 -0
  219. package/dist/reseal-chain.js.map +1 -0
  220. package/dist/reseal-evidence.d.ts +241 -0
  221. package/dist/reseal-evidence.d.ts.map +1 -0
  222. package/dist/reseal-evidence.js +319 -0
  223. package/dist/reseal-evidence.js.map +1 -0
  224. package/dist/reseal.d.ts +181 -0
  225. package/dist/reseal.d.ts.map +1 -0
  226. package/dist/reseal.js +1620 -0
  227. package/dist/reseal.js.map +1 -0
  228. package/dist/response-field-guidance.d.ts +82 -0
  229. package/dist/response-field-guidance.d.ts.map +1 -0
  230. package/dist/response-field-guidance.js +184 -0
  231. package/dist/response-field-guidance.js.map +1 -0
  232. package/dist/route-plane-proposals.d.ts +100 -0
  233. package/dist/route-plane-proposals.d.ts.map +1 -0
  234. package/dist/route-plane-proposals.js +213 -0
  235. package/dist/route-plane-proposals.js.map +1 -0
  236. package/dist/run-cache.d.ts +260 -0
  237. package/dist/run-cache.d.ts.map +1 -0
  238. package/dist/run-cache.js +771 -0
  239. package/dist/run-cache.js.map +1 -0
  240. package/dist/run-preflight.d.ts +77 -0
  241. package/dist/run-preflight.d.ts.map +1 -0
  242. package/dist/run-preflight.js +774 -0
  243. package/dist/run-preflight.js.map +1 -0
  244. package/dist/run-recipe.d.ts +107 -0
  245. package/dist/run-recipe.d.ts.map +1 -0
  246. package/dist/run-recipe.js +295 -0
  247. package/dist/run-recipe.js.map +1 -0
  248. package/dist/run-reliability.d.ts +126 -0
  249. package/dist/run-reliability.d.ts.map +1 -0
  250. package/dist/run-reliability.js +221 -0
  251. package/dist/run-reliability.js.map +1 -0
  252. package/dist/runtime.d.ts +15 -0
  253. package/dist/runtime.d.ts.map +1 -1
  254. package/dist/runtime.js +11 -1
  255. package/dist/runtime.js.map +1 -1
  256. package/dist/scope.d.ts +20 -0
  257. package/dist/scope.d.ts.map +1 -1
  258. package/dist/scope.js +26 -5
  259. package/dist/scope.js.map +1 -1
  260. package/dist/secret-guard.d.ts +36 -0
  261. package/dist/secret-guard.d.ts.map +1 -0
  262. package/dist/secret-guard.js +63 -0
  263. package/dist/secret-guard.js.map +1 -0
  264. package/dist/singleton-guidance.d.ts +82 -0
  265. package/dist/singleton-guidance.d.ts.map +1 -0
  266. package/dist/singleton-guidance.js +138 -0
  267. package/dist/singleton-guidance.js.map +1 -0
  268. package/dist/staged-candidate.d.ts +17 -0
  269. package/dist/staged-candidate.d.ts.map +1 -1
  270. package/dist/staged-candidate.js +50 -0
  271. package/dist/staged-candidate.js.map +1 -1
  272. package/dist/state-artifacts.d.ts +70 -0
  273. package/dist/state-artifacts.d.ts.map +1 -0
  274. package/dist/state-artifacts.js +215 -0
  275. package/dist/state-artifacts.js.map +1 -0
  276. package/dist/state.d.ts +170 -2
  277. package/dist/state.d.ts.map +1 -1
  278. package/dist/state.js +248 -8
  279. package/dist/state.js.map +1 -1
  280. package/dist/unmatched-routes.d.ts +60 -0
  281. package/dist/unmatched-routes.d.ts.map +1 -0
  282. package/dist/unmatched-routes.js +131 -0
  283. package/dist/unmatched-routes.js.map +1 -0
  284. package/dist/verifier-keys.d.ts +33 -2
  285. package/dist/verifier-keys.d.ts.map +1 -1
  286. package/dist/verifier-keys.js +95 -9
  287. package/dist/verifier-keys.js.map +1 -1
  288. package/guides/CONNECT-YOUR-PROJECT.md +425 -0
  289. package/guides/QUICKSTART.md +306 -26
  290. package/guides/REFERENCE.md +1710 -0
  291. package/guides/RUNNER-NEUTRAL-EVIDENCE.md +199 -0
  292. package/guides/TEST-ENVIRONMENT.md +1044 -6
  293. package/guides/UPGRADE-0.6-to-0.7.md +3 -3
  294. package/guides/UPGRADE-0.7-to-0.8.md +114 -0
  295. package/guides/UPGRADE-0.8-to-0.9.md +104 -0
  296. package/package.json +10 -9
@@ -6,7 +6,7 @@
6
6
  * Two modes:
7
7
  *
8
8
  * **Legacy `--suite` mode** — the orchestration surface G6's Playwright
9
- * pack consumes (see packages/cli/README.md "test-gates protocol"). The
9
+ * pack consumes (see packages/cli/guides/REFERENCE.md "test-gates protocol"). The
10
10
  * CLI implements the orchestration; the Playwright side — the loopback
11
11
  * witness service and the claims/records reporter — is a documented
12
12
  * contract G6 fills:
@@ -54,40 +54,66 @@
54
54
  * Without the flag the mode stays `full` — byte-identical behavior.
55
55
  */
56
56
  import { spawn, spawnSync } from 'node:child_process';
57
- import { randomUUID } from 'node:crypto';
58
- import { mkdtempSync, readFileSync, realpathSync, rmSync, writeFileSync } from 'node:fs';
57
+ import { createHash, randomUUID } from 'node:crypto';
58
+ import { existsSync, mkdirSync, mkdtempSync, readFileSync, realpathSync, rmSync, writeFileSync } from 'node:fs';
59
+ import { setTimeout as delay } from 'node:timers/promises';
59
60
  import { tmpdir } from 'node:os';
60
61
  import { dirname, isAbsolute, join, relative, resolve, sep } from 'node:path';
61
- import { AttestationSchema, BEHAVIOR_CASE_KIND, BehaviorCasePayloadSchema, CAUSE_NEXT_ACTIONS, canonicalJson, caseExecutionDigestOf, EMPTY_BEHAVIOR_CATALOG_DIGEST, engineBundleDigestOf, EvidenceRecordSchema, executionBoundaryDigestOf, LOCAL_UNISOLATED_BOUNDARY, isWitnessedRecord, renderRun, requiredCaseSetDigestOf, runExitCode, sha256Canonical, selectionDigestOf, targetArtifactDigestOf, verifyAttestationMac, } from '@gate-forge/core';
62
- import { buildWitnessedPytestChildEnv, discoverTestCatalog, listNativePlaywrightTests, PlaywrightAdapter, readRunnerOutcomes, startSupervisorSpoolDrain, startWitnessProcess, SupervisorClient, TestDiscoveryError, } from '@gate-forge/pack-playwright';
63
- import { parseArgs, stringFlag } from '../args.js';
62
+ import { AttestationSchema, BEHAVIOR_CASE_KIND, BehaviorCasePayloadSchema, BehaviorCatalogRegistrationSchema, CAUSE_NEXT_ACTIONS, canonicalJson, compareStrings, caseExecutionDigestOf, EMPTY_BEHAVIOR_CATALOG_DIGEST, engineBundleDigestOf, EvidenceRecordSchema, GateReceiptSchema, ExecutionResultSchema, executionBoundaryDigestOf, LOCAL_UNISOLATED_BOUNDARY, humanMessage, isWitnessedRecord, renderRun, requiredCaseSetDigestOf, repositoryDebtOf, runExitCode, sha256Canonical, selectionDigestOf, targetArtifactDigestOf, verifyAttestationMac, executionResultDigestOf, testOutcomesDigestOf, verifyRunRecord, BLOCKING_VERDICTS, decideStrictness, loadQuarantines, QUARANTINE_DIR, resolveStrictnessMode, strictnessSummaryLine, twinDivergenceDetail, twinLinksFor, twinPathDivergence, withoutQuarantinedBindings, } from '@gate-forge/core';
63
+ import { appendFreezeReleaseEvent, armFreezeControl, buildWitnessedPytestChildEnv, canonicalFreezeJson, defaultPlaywrightCommand, diffNativePlaywrightTests, discoverTestCatalog, findPlaywrightConfig, isPlaywrightRunnerInstall, listNativePlaywrightTests, mintFreezeSigningKeyPair, nativeConfigDirOf, playwrightTestModulePath, removeFreezeSpecDir, signFreezeRelease, spoolPathFor, supervisedRunnerChildEnv, writeFreezeRefusal, resolveProjectStorageState, CypressRunnerAdapter, PlaywrightAdapter, PytestRunnerAdapter, readRunnerOutcomes, startSupervisorSpoolDrain, startWitnessProcess, SupervisorClient, TestDiscoveryError, VitestRunnerAdapter, RUN_HEADER, VERIFIER_HEADER, DEFAULT_RUN_TIMEOUT_MS, ENV_CHAOS_MAX_DELAY_MS, ENV_CHAOS_REORDER, ENV_CHAOS_SEED, ENV_PROXY_TARGET, ENV_TWIN_INVENTORY, ENV_TWIN_QUERY_KEYS, ENV_TWIN_SHAPES, } from '@gate-forge/pack-playwright';
64
+ import { parseArgs, repeatableStringFlag, stringFlag } from '../args.js';
64
65
  import { resolveAdoptedBaseline } from '../adopted-baseline.js';
65
66
  import { UsageError } from '../errors.js';
66
67
  import { writeLine } from '../io.js';
67
68
  import { runDiagnosticSuites, runWitnessedPytestSuites } from '../diagnostics.js';
68
- import { claimInjectionsFor, planScopedExpectedSet, trustedPolicyDigestForConfig, issueGateReceipt, parentSha, planExpectedSet, sealExecutionResult, supervisionBlocking, SUPERVISED_INVOCATION, } from '../execution.js';
69
- import { evaluateRun } from '../evaluate.js';
69
+ import { claimInjectionsFor, planScopedExpectedSet, trustedPolicyDigestForConfig, issueGateReceipt, issueRunRecord, parentSha, planExpectedSet, plannedProjectScopes, plannedRowsWithProjectDependencies, sealExecutionResult, supervisionBlocking, SUPERVISED_INVOCATION, } from '../execution.js';
70
+ import { evaluateRun, scopeBlocking } from '../evaluate.js';
70
71
  import { installedPlaywrightCompatibilityError } from '../package-compatibility.js';
71
72
  import { DOCS_EXCLUSIONS_GUARANTEE, loadDocsExclusions } from '../docs-exclusions.js';
73
+ import { CACHE_EXCLUSIONS_GUARANTEE, loadCacheExclusions } from '../cache-exclusions.js';
72
74
  import { collectInputFiles, computeInputSnapshot, diffInputFiles, SnapshotUnavailableError, UnsupportedSnapshotError, } from '../input-snapshot.js';
73
- import { mappingBlocking, mappedCoverageFrom, observeObligationIds, resolveRepositoryMappings, serverE2eObligationIds, TEST_MAP_RELATIVE } from '../mapping.js';
74
- import { runPipeline } from '../pipeline.js';
75
- import { tryReuseReceipt } from '../receipts.js';
76
- import { computeCandidateTreeId, resolveGitDir } from '../candidate-tree.js';
77
- import { resolveProvider } from '../providers.js';
75
+ import { findRunnerConfigPath, mappingBlocking, mappedCoverageFrom, nativeInventoryBlocking, nativeInventoryProblem, observeObligationIds, resolveRepositoryMappings, serverE2eObligationIds, TEST_MAP_RELATIVE } from '../mapping.js';
76
+ import { runPipeline, sourcesByResourceId } from '../pipeline.js';
77
+ import { loadReceiptFor, receiptScope, tryReuseReceipt } from '../receipts.js';
78
+ import { carryDiffIsWithinScope, classifyResealChange, parentCommitAcceptance, resealDisregardNotice, RESEAL_REFUSAL_SUFFIX, resealRefusal, } from '../reseal.js';
79
+ import { authenticateContributingEvidence, carriedEvidenceDigestOf, carriedEvidenceDocuments, carriedTestIdentities, clearRetainedParentEvidence, readRetainedParentEvidence, readRunAttestation, stringField, writeRetainedParentEvidence, } from '../reseal-evidence.js';
80
+ import { clearResealChain, RESEAL_CHAIN_MAX_HOPS, resealChainHopCount, retainedChainCarriedTests, retainedEvidenceContributors, writeResealChainHop, writeResealChainParentEvidence, } from '../reseal-chain.js';
81
+ import { obligationFingerprint } from '../evaluate.js';
82
+ import { computeEvaluationScope } from '../scope.js';
83
+ import { candidateTreeCoversCommit, computeCandidateTreeSnapshot, listTrackedPaths, resolveGitDir, sanitizedAuthorityEnv } from '../candidate-tree.js';
84
+ import { acceptedFreezeRequest, classifyGeneratedTargets, planNativeFreeze, preparedCandidateViolations, unfrozenPrerequisiteState, } from '../native-freeze.js';
85
+ import { loadRuntimeConfigAt } from '../runtime.js';
86
+ import { mergeRequestScopePreflight, resolveProvider } from '../providers.js';
87
+ import { engineIdentity, reportEngineLine } from '../engine-identity.js';
78
88
  import { assertReceiptApprovedPolicy, evaluateApprovedPolicy, resolveApprovedPolicyDigest } from '../trusted-policy.js';
79
- import { clearGateReceipt, httpRoutesView, readJsonArray, resolveStateDir, stateObligations, writeClaimInjections, writeClassificationsView, writeEnv, writeExecutionResult, writeGateReceipt, writeHttpRoutesView, writeInputSnapshot, writeManifest, writeObligations, writeReport, } from '../state.js';
89
+ import { clearGateReceipt, clearRunRecord, httpRoutesView, readJsonArray, readStateDocument, resolveStateDir, stateObligations, writeClaimInjections, writeClassificationsView, writeEnv, writeExecutionResult, writeCandidateTreeEntries, writeGateReceipt, writeHttpRoutesView, writeInputSnapshot, writeManifest, writeObligations, writeLastFullRunSummary, writeReport, writeRunRecord, writeTwinInventory, writeTwinShapes, } from '../state.js';
90
+ import { engineGeneratedStateFileFilter } from '../state-artifacts.js';
80
91
  import { loadConfigAt, parseRunFormat, rejectUnknownFlags, VERIFIER_KEY_ENV, VERIFIER_KEY_FILE_ENV, VERSION, } from './common.js';
81
92
  import { resolveVerifierKeyring } from '../verifier-keys.js';
93
+ import { hostLoadFailureNotices, startHostLoadSampler } from '../host-load.js';
94
+ import { captureServiceLogs, runHarnessSetup, runHarnessTeardown, } from '../run-reliability.js';
95
+ import { pruneRunHistory, recordRunHistory } from '../history.js';
96
+ import { ProgressStream, resolveProgressTarget } from '../progress.js';
97
+ import { writeRunScopeView, writeTestFailures } from '../state.js';
82
98
  export const TEST_GATES_USAGE = 'usage: gateforge test-gates [--changed] [--scope full|changed] [--suite <command>] [--out <dir>] ' +
83
- '[--result-only] [--format text|json|sarif] [--witness-url <url>] [--run-token <token>] ' +
84
- '[--run-timeout-min <minutes>] ' +
99
+ '[--result-only] [--test <selector>] [--format text|json|sarif] [--witness-url <url>] [--run-token <token>] ' +
100
+ '[--run-timeout-min <minutes>] [--progress stderr|file:<path>|off|auto] ' +
85
101
  `(verifier key via ${VERIFIER_KEY_ENV} or ${VERIFIER_KEY_FILE_ENV})\n` +
86
102
  ' --scope changed (supervised --changed only): plan, execute, and seal only the slice of tests\n' +
87
103
  ' claiming obligations affected by the resolved changed-file set; an affected obligation with no\n' +
88
104
  ' testable declared mapping blocks (EVIDENCE_SCOPE_INCOMPLETE) — narrower selection is never guessed\n' +
89
- ' --result-only (requires --changed --scope changed): report selected results without gate authority or receipt changes; ' +
90
- 'external witnesses require a separate --out directory and --run-token';
105
+ ' --result-only (requires --changed --scope changed, or --test): report selected results without gate\n' +
106
+ ' authority or receipt changes; external witnesses require a separate --out directory and --run-token\n' +
107
+ ' --chaos <seed> (requires --result-only): make the witness proxy delay and reorder app responses\n' +
108
+ ' from a seeded schedule, so rare response-order races fail on purpose. The seed IS the schedule:\n' +
109
+ ' the same seed replays it exactly. Bounds come from run.chaos (maxDelayMs, reorder). A chaos run is a\n' +
110
+ ' finding tool: it never seals a receipt and never writes the run record. With --witness-url the plan\n' +
111
+ ' travels with the run context, so the witness needs nothing configured on its side, and a run against a\n' +
112
+ ' witness that was itself started with GATEFORGE_CHAOS_SEED is refused before any test runs\n' +
113
+ ' --test <selector> (repeatable, requires --result-only): run only the named tests, witnessed. A\n' +
114
+ ' selector is a logical key or a unique substring of one. A hand-picked test list never seals a\n' +
115
+ ' receipt, so it is refused without --result-only. An unknown or ambiguous selector exits 2 with\n' +
116
+ ' the candidate keys listed — a narrower selection is never guessed';
91
117
  /**
92
118
  * Runs the test-gates subcommand.
93
119
  *
@@ -106,7 +132,7 @@ export async function testGatesCommand(io, argv) {
106
132
  writeLine(io.stdout, TEST_GATES_USAGE);
107
133
  return 0;
108
134
  }
109
- rejectUnknownFlags(options, ['suite', 'out', 'format', 'witness-url', 'run-token', 'run-timeout-min', 'changed', 'scope', 'result-only', 'help'], TEST_GATES_USAGE);
135
+ rejectUnknownFlags(options, ['suite', 'out', 'format', 'witness-url', 'run-token', 'run-timeout-min', 'progress', 'changed', 'scope', 'result-only', 'test', 'chaos', 'help'], TEST_GATES_USAGE);
110
136
  const compatibilityError = installedPlaywrightCompatibilityError();
111
137
  if (compatibilityError !== null) {
112
138
  writeLine(io.stderr, compatibilityError);
@@ -137,8 +163,30 @@ export async function testGatesCommand(io, argv) {
137
163
  }
138
164
  scope = scopeFlag;
139
165
  }
140
- if (resultOnly && (!changed || scope !== 'changed' || suite !== undefined)) {
141
- throw new UsageError('test-gates: --result-only requires --changed --scope changed and cannot be combined with --suite');
166
+ // --test (repeatable): the hand-picked, witnessed single-test check.
167
+ // Resolution against the planned rows happens later, once the plan is
168
+ // fixed; here we only read the raw list and guard the contract that a
169
+ // named run can never carry gate authority.
170
+ const testSelectors = repeatableStringFlag(options, 'test');
171
+ if (testSelectors !== undefined && !resultOnly) {
172
+ throw new UsageError('test-gates: --test requires --result-only — a hand-picked test list never seals a receipt, ' +
173
+ 'so run the full or scoped gate to issue one');
174
+ }
175
+ if (testSelectors !== undefined && suite !== undefined) {
176
+ throw new UsageError('test-gates: --test runs through the supervised runner adapter and cannot be combined with --suite');
177
+ }
178
+ // --chaos <seed>: the timing-chaos switch. Same authority contract as
179
+ // --test - a chaos run FINDS races, it never seals - and the seed is
180
+ // the whole configuration: one non-negative integer replays one
181
+ // schedule exactly.
182
+ const chaosSeed = stringFlag(options, 'chaos');
183
+ const chaos = chaosSeed === undefined ? null : parseChaosSeed(chaosSeed, resultOnly);
184
+ // A named run builds its plan from the FULL planned rows and then
185
+ // narrows to the named keys, so it relaxes the diff-linked
186
+ // `--changed --scope changed` requirement --result-only otherwise has.
187
+ const namedSelection = testSelectors !== undefined;
188
+ if (resultOnly && !namedSelection && (!changed || scope !== 'changed' || suite !== undefined)) {
189
+ throw new UsageError('test-gates: --result-only requires --changed --scope changed (or --test <selector>) and cannot be combined with --suite');
142
190
  }
143
191
  if (resultOnly && witnessUrl === undefined && out !== undefined) {
144
192
  throw new UsageError('test-gates: --result-only accepts --out only with --witness-url; without an external witness it owns a private temporary state directory');
@@ -160,8 +208,15 @@ export async function testGatesCommand(io, argv) {
160
208
  `not the configured authoritative state directory '${resolveStateDir(io.cwd)}'`);
161
209
  }
162
210
  }
211
+ // A usage error must cost seconds, not a spawned witness and a test
212
+ // suite: an unusable --progress target is rejected before anything
213
+ // runs. (The target itself is resolved again once the trusted config
214
+ // is loaded, so the `run.progress` key gets the same treatment.)
215
+ const progressFlag = stringFlag(options, 'progress');
216
+ if (progressFlag !== undefined)
217
+ resolveProgressTarget(progressFlag, undefined, io.env);
163
218
  const verifierKeyring = resolveVerifierKeyring(io.cwd, io.env, [resolveStateDir(io.cwd, out)]);
164
- if (changed) {
219
+ if (changed || namedSelection) {
165
220
  const isolatedStateDir = resultOnly && witnessUrl === undefined ? mkdtempSync(join(tmpdir(), 'gateforge-selected-result-')) : undefined;
166
221
  try {
167
222
  return await runSupervisedTestGates(io, {
@@ -170,8 +225,11 @@ export async function testGatesCommand(io, argv) {
170
225
  witnessUrl,
171
226
  runToken: stringFlag(options, 'run-token'),
172
227
  runTimeoutMs: parseRunTimeoutMin(stringFlag(options, 'run-timeout-min')),
228
+ progress: progressFlag,
173
229
  scope,
174
230
  resultOnly,
231
+ testSelectors,
232
+ chaos,
175
233
  verifierKeyring,
176
234
  });
177
235
  }
@@ -263,6 +321,20 @@ async function legacyTestGates(io, options) {
263
321
  // fixture call answers 401 (x-gateforge-run mismatch).
264
322
  const runToken = options.runToken;
265
323
  const config = loadConfigAt(io.cwd);
324
+ const cacheExclusions = loadCacheExclusions(io.cwd, config);
325
+ const cachePolicyDigest = cacheExclusions.length > 0 ? trustedPolicyDigestForConfig(io.cwd, config) : null;
326
+ const cacheApprovalResolution = cacheExclusions.length > 0
327
+ ? resolveApprovedPolicyDigest({ env: io.env, candidateCwd: io.cwd, candidateConfig: config })
328
+ : null;
329
+ const cachePolicyGate = cachePolicyDigest === null || cacheApprovalResolution === null
330
+ ? null
331
+ : evaluateApprovedPolicy(cacheApprovalResolution, cachePolicyDigest, true);
332
+ if (cachePolicyGate?.status === 'blocked') {
333
+ writeLine(io.stderr, `test-gates: ${cachePolicyGate.cause}: ${cachePolicyGate.detail}`);
334
+ writeLine(io.stderr, `next action: ${cachePolicyGate.nextAction}`);
335
+ return 1;
336
+ }
337
+ const cacheApprovalDigest = cachePolicyGate?.status === 'enforced' ? cachePolicyGate.approved : null;
266
338
  const stateDir = resolveStateDir(io.cwd, out);
267
339
  const verifierKeyring = options.verifierKeyring ?? resolveVerifierKeyring(io.cwd, io.env, [stateDir]);
268
340
  const witnessVerifierKey = verifierKeyring?.active.key;
@@ -273,7 +345,7 @@ async function legacyTestGates(io, options) {
273
345
  let preFiles = null;
274
346
  let snapshotUnavailable = false;
275
347
  try {
276
- preFiles = collectInputFiles(io.cwd, config, stateDir);
348
+ preFiles = collectInputFiles(io.cwd, config, stateDir, [], [], cacheExclusions);
277
349
  }
278
350
  catch (error) {
279
351
  if (error instanceof SnapshotUnavailableError) {
@@ -301,7 +373,7 @@ async function legacyTestGates(io, options) {
301
373
  let trustedDigest = null;
302
374
  if (!snapshotUnavailable) {
303
375
  try {
304
- const postDiscovery = collectInputFiles(io.cwd, config, stateDir);
376
+ const postDiscovery = collectInputFiles(io.cwd, config, stateDir, [], [], cacheExclusions);
305
377
  const drift = preFiles === null ? [] : diffInputFiles(preFiles, postDiscovery);
306
378
  if (drift.length > 0) {
307
379
  throw new UsageError(`input tree changed around discovery (${drift.slice(0, 3).join('; ')}${drift.length > 3 ? '; …' : ''}); ` +
@@ -318,6 +390,7 @@ async function legacyTestGates(io, options) {
318
390
  id: plugin.id,
319
391
  version: plugin.version,
320
392
  })),
393
+ cacheExclusions,
321
394
  }).inputDigest;
322
395
  }
323
396
  catch (error) {
@@ -379,7 +452,7 @@ async function legacyTestGates(io, options) {
379
452
  // The effective-classification view (plan phase 5): derived from this
380
453
  // run's signals, for verifier-side consumers only — never engine input.
381
454
  writeClassificationsView(stateDir, pipeline.classificationsView);
382
- const envRecord = writeEnv(stateDir, manifest, witnessUrl ?? null, runToken);
455
+ const envRecord = writeEnv(stateDir, manifest, witnessUrl ?? null, runToken, io.env);
383
456
  let suiteFailed = false;
384
457
  if (suite !== undefined) {
385
458
  const suiteEnv = {
@@ -438,7 +511,7 @@ async function legacyTestGates(io, options) {
438
511
  let changedInputs = false;
439
512
  if (!snapshotUnavailable && preFiles !== null) {
440
513
  try {
441
- const postSuite = collectInputFiles(io.cwd, config, stateDir);
514
+ const postSuite = collectInputFiles(io.cwd, config, stateDir, [], [], cacheExclusions);
442
515
  changedInputs = diffInputFiles(preFiles, postSuite).length > 0;
443
516
  }
444
517
  catch {
@@ -466,6 +539,7 @@ async function legacyTestGates(io, options) {
466
539
  blocking: pipeline.policy.blocking,
467
540
  stateDir,
468
541
  now: pipeline.now,
542
+ engineAlembicRecords: pipeline.engineAlembicRecords,
469
543
  changedFiles: null,
470
544
  witnessVerifierKey,
471
545
  witnessVerifierKeys: verifierKeyring?.keys.map((entry) => entry.key),
@@ -478,12 +552,35 @@ async function legacyTestGates(io, options) {
478
552
  changedInputs,
479
553
  },
480
554
  });
555
+ const diagnosticContext = cacheExclusions.length === 0
556
+ ? undefined
557
+ : {
558
+ scope: 'full',
559
+ candidateTreeId: null,
560
+ inputDigest: expectedDigest,
561
+ evidenceState: snapshotUnavailable
562
+ ? 'snapshot-unavailable'
563
+ : changedInputs
564
+ ? 'inputs-changed-during-run'
565
+ : 'observed',
566
+ authority: 'non-authoritative',
567
+ cacheExclusions: {
568
+ files: cacheExclusions,
569
+ approvalDigest: cacheApprovalDigest,
570
+ approvalStatus: 'matched',
571
+ guarantee: CACHE_EXCLUSIONS_GUARANTEE,
572
+ },
573
+ };
481
574
  const report = renderRun(evaluated.verdicts, {
482
575
  format,
483
576
  blocking: evaluated.blocking,
484
577
  waiverCounts: evaluated.waiverCounts,
485
578
  run: manifest,
486
579
  toolVersion: VERSION,
580
+ engine: engineIdentity(),
581
+ engineLine: reportEngineLine(),
582
+ lifecycleDerivation: pipeline.lifecycleDerivation,
583
+ diagnosticContext,
487
584
  });
488
585
  writeLine(io.stdout, report);
489
586
  writeReport(stateDir, renderRun(evaluated.verdicts, {
@@ -492,10 +589,894 @@ async function legacyTestGates(io, options) {
492
589
  waiverCounts: evaluated.waiverCounts,
493
590
  run: manifest,
494
591
  toolVersion: VERSION,
592
+ engine: engineIdentity(),
593
+ engineLine: reportEngineLine(),
594
+ lifecycleDerivation: pipeline.lifecycleDerivation,
595
+ diagnosticContext,
495
596
  }));
496
597
  const gateCode = runExitCode({ verdicts: evaluated.verdicts, blocking: evaluated.blocking });
497
598
  return suiteFailed && gateCode === 0 ? 1 : gateCode;
498
599
  }
600
+ /** The documented default bound when `run.chaos.maxDelayMs` is unset. */
601
+ const CHAOS_DEFAULT_MAX_DELAY_MS = 400;
602
+ /** The hard ceiling on a configured bound (a chaos run is a finding tool). */
603
+ const CHAOS_MAX_DELAY_CEILING_MS = 5_000;
604
+ /**
605
+ * Validates `--chaos <seed>` against the same authority contract as
606
+ * `--test`: a chaos run reports, it never seals, and a seed that is not
607
+ * a non-negative integer is refused in seconds — before a witness, a
608
+ * browser or a suite is spawned.
609
+ *
610
+ * An EXTERNAL witness (`--witness-url`) is accepted here: the plan
611
+ * travels with the run-context binding (see {@link WitnessRunOptions}),
612
+ * so the repository's own witness needs nothing configured on its side.
613
+ *
614
+ * Args:
615
+ * raw: the value the operator typed.
616
+ * resultOnly: whether `--result-only` was given.
617
+ *
618
+ * Returns:
619
+ * { seed: number }: the accepted seed (the bounds are resolved later,
620
+ * from the trusted config).
621
+ *
622
+ * @throws UsageError: without `--result-only`, or on a seed that is not
623
+ * a non-negative integer.
624
+ */
625
+ function parseChaosSeed(raw, resultOnly) {
626
+ if (!resultOnly) {
627
+ throw new UsageError('test-gates: --chaos requires --result-only — a run whose timing was perturbed on purpose finds races, ' +
628
+ 'it never proves a commit; run the normal gate to issue a receipt');
629
+ }
630
+ if (!/^\d+$/.test(raw)) {
631
+ throw new UsageError(`test-gates: --chaos takes a non-negative integer seed (0, 1, 2, ...), got '${raw}'`);
632
+ }
633
+ return { seed: Number(raw) };
634
+ }
635
+ /** True when a binding echo is the additive `applied` block we sent. */
636
+ function isAppliedWitnessOptions(value) {
637
+ if (typeof value !== 'object' || value === null)
638
+ return false;
639
+ const record = value;
640
+ return 'chaos' in record && 'twinShapes' in record;
641
+ }
642
+ /** The run options as the plain json the binding body carries. */
643
+ function runOptionsJson(options) {
644
+ return {
645
+ ...(options.chaos === undefined ? {} : { chaos: { ...options.chaos } }),
646
+ ...(options.twinShapes === undefined
647
+ ? {}
648
+ : {
649
+ twinShapes: {
650
+ queryKeys: [...options.twinShapes.queryKeys],
651
+ inventory: [...options.twinShapes.inventory],
652
+ },
653
+ }),
654
+ };
655
+ }
656
+ /**
657
+ * Refuses a NORMAL run whose external witness perturbs timing on its
658
+ * own, before a single test executes.
659
+ *
660
+ * The run owns the plan now: a witness only perturbs when THIS run
661
+ * asked for it through the binding, and this run only asks with
662
+ * `--chaos --result-only`. So a plan the witness reports for a run
663
+ * that asked for none can only have come from the witness's own
664
+ * ENVIRONMENT — and a perturbed run must never seal.
665
+ *
666
+ * A witness too old to have the route answers 404: it cannot perturb
667
+ * timing it was never told to, so the run is exactly what it always
668
+ * was.
669
+ *
670
+ * Args:
671
+ * witnessUrl: the external witness origin.
672
+ * runToken: the run token the supervisor surface authenticates with.
673
+ * verifierKey: the supervisor verifier key.
674
+ *
675
+ * @throws UsageError: when the witness reports a plan this run did not
676
+ * ask for, or cannot be asked at all.
677
+ */
678
+ async function refuseChaosWitnessOnSealingRun(witnessUrl, runToken, verifierKey) {
679
+ let body;
680
+ let status;
681
+ try {
682
+ const response = await fetch(`${witnessUrl}/runs/chaos-schedule`, {
683
+ headers: { [RUN_HEADER]: runToken, [VERIFIER_HEADER]: verifierKey },
684
+ });
685
+ status = response.status;
686
+ body = response.ok ? (await response.json()) : null;
687
+ }
688
+ catch (error) {
689
+ throw new UsageError(`test-gates: the external witness at '${witnessUrl}' could not be asked whether it perturbs timing on its ` +
690
+ `own (${error.message}) — a sealing run never assumes its witness is not perturbing timing`);
691
+ }
692
+ if (status === 404 || body === null)
693
+ return;
694
+ const reported = body.chaos ?? null;
695
+ if (reported === null)
696
+ return;
697
+ throw new UsageError(`test-gates: the external witness at '${witnessUrl}' was started with a timing-chaos plan (seed ` +
698
+ `${String(reported.seed)}), and a witness that perturbs timing can never serve a run that seals — unset ` +
699
+ `${ENV_CHAOS_SEED} when starting it (this run never asked for chaos), or re-run with --chaos ` +
700
+ `${String(reported.seed)} --result-only to report under the same plan`);
701
+ }
702
+ /**
703
+ * Resolves the tuned bounds of a chaos run from the trusted config. The
704
+ * config only TUNES: `run.chaos` present without `--chaos` leaves every
705
+ * byte of a normal run exactly as it was.
706
+ *
707
+ * Args:
708
+ * config: the trusted configuration.
709
+ * seed: the accepted `--chaos` seed.
710
+ *
711
+ * Returns:
712
+ * ChaosRun: the plan the witness proxy will execute.
713
+ *
714
+ * @throws UsageError: when `run.chaos.maxDelayMs` exceeds the ceiling.
715
+ */
716
+ function chaosRunOf(config, seed) {
717
+ const maxDelayMs = config.run?.chaos?.maxDelayMs ?? CHAOS_DEFAULT_MAX_DELAY_MS;
718
+ if (maxDelayMs > CHAOS_MAX_DELAY_CEILING_MS) {
719
+ throw new UsageError(`test-gates: run.chaos.maxDelayMs must be at most ${String(CHAOS_MAX_DELAY_CEILING_MS)} (got ${String(maxDelayMs)})`);
720
+ }
721
+ return { seed, maxDelayMs, reorder: config.run?.chaos?.reorder ?? true };
722
+ }
723
+ /**
724
+ * The plain line for a linked twin pair that ran but could not be
725
+ * compared, because a side sent no request through the witness.
726
+ *
727
+ * Args:
728
+ * link: the linked pair.
729
+ * witnessedObserved: whether the witnessed test's requests were seen.
730
+ * rawObserved: whether the raw test's requests were seen.
731
+ *
732
+ * Returns:
733
+ * string: the stderr line naming the unobserved side and the fix.
734
+ */
735
+ export function twinPairNotComparedLine(link, witnessedObserved, rawObserved) {
736
+ const unobserved = [
737
+ ...(witnessedObserved ? [] : [`the witnessed test '${link.witnessed}'`]),
738
+ ...(rawObserved ? [] : [`the raw test '${link.raw}'`]),
739
+ ].join(' and ');
740
+ const fix = rawObserved
741
+ ? ''
742
+ : ' — a raw twin is observed only when it runs with the Gateforge test fixture, which opens an observation-only session for it (it issues no evidence)';
743
+ return `test-gates: twin pair not compared: ${unobserved} sent no request through the witness${fix}`;
744
+ }
745
+ /** Candidate keys listed in an unresolved-selector error are capped at this many. */
746
+ const SELECTOR_CANDIDATE_LIMIT = 20;
747
+ /**
748
+ * Next action of an unresolvable `--test` selector. `tests discover
749
+ * --json` prints the derived catalog — the ONLY surface that lists
750
+ * every test logical key a selector can resolve to (`discover --json`
751
+ * dumps the resource graph instead, which never names a test).
752
+ */
753
+ const SELECTOR_NEXT_ACTION = 'gateforge tests discover --json';
754
+ /**
755
+ * Renders the candidate logical keys for an unresolved `--test`
756
+ * selector. Never guess a selection: the operator gets the exact keys
757
+ * to pick from.
758
+ *
759
+ * Args:
760
+ * keys: every planned logical key of the run.
761
+ *
762
+ * Returns:
763
+ * string: the capped, sorted candidate list.
764
+ */
765
+ function selectorCandidates(keys) {
766
+ const sorted = [...keys].sort();
767
+ const shown = sorted.slice(0, SELECTOR_CANDIDATE_LIMIT).map((key) => ` - ${key}`).join('\n');
768
+ const hidden = sorted.length - Math.min(sorted.length, SELECTOR_CANDIDATE_LIMIT);
769
+ return hidden > 0 ? `${shown}\n ... and ${String(hidden)} more` : shown;
770
+ }
771
+ /**
772
+ * Resolves hand-picked `--test` selectors against the PLANNED rows (the
773
+ * expected set fixed before the run), never against raw runner output:
774
+ * a selector can only ever name a test the gate already planned.
775
+ *
776
+ * A selector matches an exact logical key first, then a
777
+ * case-insensitive substring of one. Zero matches and ambiguous
778
+ * substrings both fail closed (exit 2) with the candidate keys listed.
779
+ *
780
+ * Args:
781
+ * selectors: the selectors as typed, in argv order.
782
+ * rows: the planned rows (only their logical keys are read).
783
+ *
784
+ * Returns:
785
+ * NamedTestSelection[]: one entry per selector, in argv order.
786
+ * @throws UsageError (exit 2) when a selector matches nothing or more
787
+ * than one planned test.
788
+ */
789
+ export function resolveTestSelectors(selectors, rows) {
790
+ const keys = [];
791
+ const seen = new Set();
792
+ for (const row of rows) {
793
+ if (seen.has(row.logicalKey))
794
+ continue;
795
+ seen.add(row.logicalKey);
796
+ keys.push(row.logicalKey);
797
+ }
798
+ return selectors.map((selector) => {
799
+ const exact = keys.filter((key) => key === selector);
800
+ const candidates = exact.length > 0 ? exact : keys.filter((key) => key.toLowerCase().includes(selector.toLowerCase()));
801
+ if (candidates.length === 0) {
802
+ throw new UsageError(humanMessage({
803
+ detail: `no planned test matches the selector '${selector}' — nothing ran`,
804
+ nextAction: SELECTOR_NEXT_ACTION,
805
+ type: 'test-selector-unknown',
806
+ }) +
807
+ (keys.length === 0
808
+ ? ' (this run planned no tests)'
809
+ : `\ncandidate logical keys:\n${selectorCandidates(keys)}`));
810
+ }
811
+ if (candidates.length > 1) {
812
+ throw new UsageError(humanMessage({
813
+ detail: `the selector '${selector}' matches ${String(candidates.length)} planned tests — pick one exact logical key`,
814
+ nextAction: SELECTOR_NEXT_ACTION,
815
+ type: 'test-selector-ambiguous',
816
+ }) + `\ncandidate logical keys:\n${selectorCandidates(candidates)}`);
817
+ }
818
+ return { selector, logicalKeys: candidates };
819
+ });
820
+ }
821
+ /**
822
+ * Resolves the exact merge-base commit from a supported CI diff provider.
823
+ *
824
+ * Args:
825
+ * io: process context with CI provider environment.
826
+ * provider: configured changed-file provider identity.
827
+ *
828
+ * Returns:
829
+ * string | null: verified 40-character base commit, or null when unavailable.
830
+ */
831
+ function resolveCarryForwardBaseSha(io, provider) {
832
+ if (provider === 'gitlab-mr') {
833
+ const sha = io.env['CI_MERGE_REQUEST_DIFF_BASE_SHA']?.trim() ?? '';
834
+ return /^[0-9a-f]{40}$/.test(sha) ? sha : null;
835
+ }
836
+ if (provider !== 'github-pr')
837
+ return null;
838
+ const baseRef = io.env['GITHUB_BASE_REF']?.trim() ?? '';
839
+ if (baseRef.length === 0 || baseRef.startsWith('-') || /[\\s\\0]/.test(baseRef))
840
+ return null;
841
+ const result = spawnSync('git', ['--no-replace-objects', 'merge-base', 'HEAD', baseRef], {
842
+ cwd: io.cwd,
843
+ env: sanitizedAuthorityEnv(io.env),
844
+ encoding: 'utf8',
845
+ });
846
+ const sha = (result.stdout ?? '').trim();
847
+ return result.error === undefined && result.status === 0 && /^[0-9a-f]{40}$/.test(sha) ? sha : null;
848
+ }
849
+ /**
850
+ * Builds a refusal naming the first binding that failed.
851
+ *
852
+ * Args:
853
+ * reason: plain words — no cause code, no digest.
854
+ *
855
+ * Returns:
856
+ * ParentVerification: the refusal.
857
+ */
858
+ function refuse(reason) {
859
+ return { parent: null, reason };
860
+ }
861
+ /**
862
+ * Shortens a commit for a human-facing line.
863
+ *
864
+ * Args:
865
+ * sha: a commit, or null when none is known.
866
+ *
867
+ * Returns:
868
+ * string: the 7-character prefix, or words when there is no commit.
869
+ */
870
+ function shortSha(sha) {
871
+ const trimmed = (sha ?? '').trim();
872
+ return /^[0-9a-f]{7,40}$/.test(trimmed) ? trimmed.slice(0, 7) : 'an unknown commit';
873
+ }
874
+ /**
875
+ * Whether the run state holds a document under this name at all — the
876
+ * difference between "the previous run cannot be re-sealed" (something
877
+ * to explain) and "there is no previous run" (nothing to say).
878
+ *
879
+ * Args:
880
+ * stateDir: absolute run-state directory.
881
+ * name: the state document's file name.
882
+ *
883
+ * Returns:
884
+ * boolean: true when the document exists and parses as JSON.
885
+ */
886
+ function hasStateDocument(stateDir, name) {
887
+ try {
888
+ return readStateDocument(stateDir, name) !== null;
889
+ }
890
+ catch {
891
+ return false;
892
+ }
893
+ }
894
+ /**
895
+ * The commit a parent document is held to, or the plain refusal that
896
+ * says why it is bound to none.
897
+ *
898
+ * A re-seal binds the parent to the commit the parent itself names:
899
+ * the previous pipeline tested that commit's bytes, and this run
900
+ * froze a descendant of it, so the two sealed trees differ only by
901
+ * this run's change set. No CI variable is involved — a merge
902
+ * request's diff base is a different commit from the one the previous
903
+ * pipeline tested, and nothing sets such a variable to the parent.
904
+ * The plain carry-forward path keeps its exact merge-base rule.
905
+ *
906
+ * Args:
907
+ * input: the repository coordinates, including the binding.
908
+ * ownSha: the commit the parent document names, or null when it
909
+ * names none.
910
+ *
911
+ * Returns:
912
+ * the bound commit, or the first binding that failed in plain words.
913
+ */
914
+ function boundParentCommit(input, ownSha) {
915
+ if (input.parentCommitBinding !== 'own-ancestor-commit') {
916
+ if (input.baseSha.length === 0)
917
+ return { sha: null, reason: 'no merge-base commit is known' };
918
+ return { sha: input.baseSha, reason: null };
919
+ }
920
+ const commit = (ownSha ?? '').trim();
921
+ const acceptance = parentCommitAcceptance(input.gitDir, input.io.env, commit);
922
+ if (acceptance === 'ancestor')
923
+ return { sha: commit, reason: null };
924
+ if (acceptance === 'missing') {
925
+ return {
926
+ sha: null,
927
+ reason: /^[0-9a-f]{40}$/.test(commit)
928
+ ? `it was sealed at commit ${shortSha(commit)}, which this repository cannot read`
929
+ : 'it names no commit, so there is nothing to bind it to',
930
+ };
931
+ }
932
+ return { sha: null, reason: `it was sealed at commit ${shortSha(commit)}, which is not an ancestor of HEAD` };
933
+ }
934
+ /**
935
+ * Authenticates a clean full-scope receipt for the exact merge-base commit.
936
+ *
937
+ * Args:
938
+ * input: candidate policy, external pin, key ring, state directory, and merge base.
939
+ *
940
+ * Returns:
941
+ * ParentVerification: the verified uncarried root receipt, or the first
942
+ * binding that failed in plain words.
943
+ */
944
+ function verifyCarryForwardParent(input) {
945
+ try {
946
+ if (input.verifierKeyring === null)
947
+ return refuse('no verifier key is available to authenticate it');
948
+ const parsed = GateReceiptSchema.safeParse(readStateDocument(input.stateDir, 'receipt.json'));
949
+ if (!parsed.success)
950
+ return refuse('it is not a gate receipt Gateforge can read');
951
+ const receipt = parsed.data;
952
+ const bound = boundParentCommit(input, receipt.gitSha);
953
+ if (bound.reason !== null)
954
+ return refuse(bound.reason);
955
+ // The sealed candidate is a WORKSPACE tree (it carries the repo's
956
+ // untracked and gitignored bytes too), so it is never equal to the
957
+ // commit's tree. What must hold is that it COVERS the bound
958
+ // commit's committed content: the parent proves those exact bytes,
959
+ // and everything else it sealed is diffed against this run's tree.
960
+ const treeId = receipt.candidateTreeId;
961
+ if (input.gitDir === null ||
962
+ treeId === null ||
963
+ !candidateTreeCoversCommit(input.gitDir, input.io.env, treeId, `${bound.sha}^{tree}`, input.docsExclusions, input.cacheExclusions)) {
964
+ return refuse(`its sealed tree is not the tree of commit ${shortSha(bound.sha)} (uncommitted changes were tested)`);
965
+ }
966
+ if (input.parentCommitBinding !== 'own-ancestor-commit' && receipt.gitSha !== input.baseSha) {
967
+ return refuse(`it was sealed at commit ${shortSha(receipt.gitSha)}, the merge base is ${shortSha(input.baseSha)}`);
968
+ }
969
+ if (receipt.verifierKeyId !== input.verifierKeyring.active.keyId) {
970
+ return refuse('it was signed with a different verifier key');
971
+ }
972
+ if (receipt.trustedPolicyDigest !== input.trustedPolicyDigest)
973
+ return refuse('the trusted policy changed');
974
+ if (receipt.approvedPolicyDigest !== input.approvedPolicyDigest)
975
+ return refuse('the approved policy changed');
976
+ if (receipt.receiptStage !== input.config.enforcement?.receiptStage)
977
+ return refuse('the receipt stage changed');
978
+ // A plain carried or sliced run proves a slice, so it never
979
+ // re-seals. A RE-SEAL is different: it names the parent it carried
980
+ // from in `resealedFrom` and the whole repository in
981
+ // `coveredObligationFingerprints`, which is exactly what a
982
+ // further re-seal needs to carry from.
983
+ const isReseal = receipt.changeClass === 'test-only' && receipt.resealedFrom !== undefined;
984
+ if ((receipt.carriedFrom !== undefined ||
985
+ receipt.parentReceiptDigest !== undefined ||
986
+ (receipt.scope !== undefined && receipt.scope !== 'full')) &&
987
+ !isReseal) {
988
+ return refuse('a carried or sliced run never re-seals');
989
+ }
990
+ if (receipt.engine === undefined ||
991
+ receipt.engine.version !== engineIdentity().version ||
992
+ receipt.engine.source !== engineIdentity().source ||
993
+ receipt.engine.unpublished !== engineIdentity().unpublished ||
994
+ receipt.engineBundleDigest !== engineBundleDigestOf(VERSION, input.trustedPolicyDigest)) {
995
+ return refuse('the engine changed');
996
+ }
997
+ if (receipt.targetArtifactDigest !== targetArtifactDigestOf(treeId)) {
998
+ return refuse('its sealed target artifact is not the tree it names');
999
+ }
1000
+ if (receipt.verdictSummary.blocking !== 0 ||
1001
+ receipt.verdictSummary.satisfied + receipt.verdictSummary.waived !== receipt.verdictSummary.total) {
1002
+ return refuse('it was not a clean run');
1003
+ }
1004
+ // The parent is loaded against the coverage it sealed: a
1005
+ // whole-suite run, or — for a re-seal parent — the exact set of
1006
+ // obligation fingerprints this repository declares, which the
1007
+ // loader compares against the receipt's own list.
1008
+ const loaded = loadReceiptFor(input.stateDir, input.verifierKeyring, {
1009
+ inputDigest: receipt.inputDigest,
1010
+ trustedPolicyDigest: input.trustedPolicyDigest,
1011
+ candidateTreeId: treeId,
1012
+ executionBoundaryDigest: input.executionBoundaryDigest,
1013
+ ...(isReseal
1014
+ ? { scope: 'changed', coveredObligationFingerprints: input.repositoryFingerprints ?? [] }
1015
+ : { scope: 'full' }),
1016
+ });
1017
+ if (loaded.status !== 'ok')
1018
+ return refuse(receiptLoadRefusal(loaded.status));
1019
+ const approved = assertReceiptApprovedPolicy(loaded.receipt, input.approvedPolicyDigest);
1020
+ if (!approved.ok)
1021
+ return refuse('the approved policy changed');
1022
+ return {
1023
+ parent: {
1024
+ receipt: loaded.receipt,
1025
+ receiptDigest: sha256Canonical(loaded.receipt),
1026
+ treeId,
1027
+ execution: loaded.executionResult,
1028
+ },
1029
+ reason: null,
1030
+ };
1031
+ }
1032
+ catch {
1033
+ return refuse('it could not be read');
1034
+ }
1035
+ }
1036
+ /**
1037
+ * Names, in plain words, why a stored gate receipt no longer loads.
1038
+ *
1039
+ * Args:
1040
+ * status: the receipt loader's own verdict.
1041
+ *
1042
+ * Returns:
1043
+ * string: the first binding that failed, in words.
1044
+ */
1045
+ function receiptLoadRefusal(status) {
1046
+ if (status === 'execution-mismatch')
1047
+ return 'its execution result was replaced by a later run';
1048
+ if (status === 'unverified' || status === 'unknown-key' || status === 'key-mismatch') {
1049
+ return 'its signature does not verify with this keyring';
1050
+ }
1051
+ if (status === 'malformed')
1052
+ return 'it is not a gate receipt Gateforge can read';
1053
+ if (status === 'stale')
1054
+ return 'it is bound to a different run than this one';
1055
+ return 'it does not describe a whole-suite run of this repository';
1056
+ }
1057
+ /**
1058
+ * Authenticates a clean full-scope receipt for the exact merge-base commit.
1059
+ *
1060
+ * Args:
1061
+ * input: candidate policy, external pin, key ring, state directory, and merge base.
1062
+ *
1063
+ * Returns:
1064
+ * VerifiedCarryForwardParent | null: verified uncarried root receipt, or null to keep current behavior.
1065
+ */
1066
+ function verifiedCarryForwardParent(input) {
1067
+ return verifyCarryForwardParent(input).parent;
1068
+ }
1069
+ /**
1070
+ * Authenticates the run record a FAILED whole-suite run left behind as
1071
+ * the re-seal parent. A failing run seals no receipt (and clears the
1072
+ * old one), so without this the exact case a test-only re-seal exists
1073
+ * for could never re-seal.
1074
+ *
1075
+ * Every binding a receipt parent is held to is demanded here too — the
1076
+ * MAC under the active key, the same merge-base commit, the same
1077
+ * approved policy, engine bundle, execution boundary and target
1078
+ * artifact, the same candidate-tree coverage — and the execution result
1079
+ * must be the one the record names, with its own recomputed outcome
1080
+ * digest. A run record is a parent, never proof: it is accepted only as
1081
+ * the document a re-seal recomputes from.
1082
+ *
1083
+ * Args:
1084
+ * input: the same coordinates a receipt parent is verified against.
1085
+ *
1086
+ * Returns:
1087
+ * ParentVerification: the verified run-record parent, or the first
1088
+ * binding that failed in plain words.
1089
+ */
1090
+ function verifyRunRecordParent(input) {
1091
+ try {
1092
+ if (input.verifierKeyring === null)
1093
+ return refuse('no verifier key is available to authenticate it');
1094
+ const document = readStateDocument(input.stateDir, 'run-record.json');
1095
+ if (document === null)
1096
+ return refuse('the previous run left no run record');
1097
+ const verified = verifyRunRecord(input.verifierKeyring.active.key, document);
1098
+ if (!verified.ok)
1099
+ return refuse('its signature does not verify with this keyring');
1100
+ const record = verified.record;
1101
+ const bound = boundParentCommit(input, record.gitSha);
1102
+ if (bound.reason !== null)
1103
+ return refuse(bound.reason);
1104
+ const treeId = record.candidateTreeId;
1105
+ if (input.gitDir === null ||
1106
+ treeId === null ||
1107
+ !candidateTreeCoversCommit(input.gitDir, input.io.env, treeId, `${bound.sha}^{tree}`, input.docsExclusions, input.cacheExclusions)) {
1108
+ return refuse(`its sealed tree is not the tree of commit ${shortSha(bound.sha)} (uncommitted changes were tested)`);
1109
+ }
1110
+ if (input.parentCommitBinding !== 'own-ancestor-commit' && record.gitSha !== input.baseSha) {
1111
+ return refuse(`it was sealed at commit ${shortSha(record.gitSha)}, the merge base is ${shortSha(input.baseSha)}`);
1112
+ }
1113
+ if (record.verifierKeyId !== input.verifierKeyring.active.keyId) {
1114
+ return refuse('it was signed with a different verifier key');
1115
+ }
1116
+ if (record.trustedPolicyDigest !== input.trustedPolicyDigest)
1117
+ return refuse('the trusted policy changed');
1118
+ if (record.approvedPolicyDigest !== input.approvedPolicyDigest)
1119
+ return refuse('the approved policy changed');
1120
+ if (record.engineBundleDigest !== engineBundleDigestOf(VERSION, input.trustedPolicyDigest)) {
1121
+ return refuse('the engine changed');
1122
+ }
1123
+ if (record.executionBoundaryDigest !== input.executionBoundaryDigest) {
1124
+ return refuse('the execution boundary changed');
1125
+ }
1126
+ const execution = ExecutionResultSchema.safeParse(readStateDocument(input.stateDir, 'execution-result.json'));
1127
+ if (!execution.success)
1128
+ return refuse('its execution result was replaced by a later run');
1129
+ const result = execution.data;
1130
+ // The record is only a parent for the run it actually describes:
1131
+ // the execution result must be the one it names, carry the whole
1132
+ // suite it planned, and grade to the outcome digest it bound.
1133
+ if (executionResultDigestOf(result) !== record.executionResultDigest ||
1134
+ result.catalogDigest !== record.catalogDigest ||
1135
+ result.planned.length !== record.plannedTests ||
1136
+ result.outcomes.filter((outcome) => outcome.status === 'passed').length !== record.passedTests ||
1137
+ testOutcomesDigestOf(result.outcomes) !== record.testOutcomesDigest) {
1138
+ return refuse('its execution result was replaced by a later run');
1139
+ }
1140
+ return {
1141
+ parent: {
1142
+ kind: 'run-record',
1143
+ digest: sha256Canonical(record),
1144
+ receipt: null,
1145
+ record,
1146
+ treeId,
1147
+ sha: bound.sha,
1148
+ execution: result,
1149
+ },
1150
+ reason: null,
1151
+ };
1152
+ }
1153
+ catch {
1154
+ return refuse('it could not be read');
1155
+ }
1156
+ }
1157
+ /**
1158
+ * Resolves the sealed parent a re-seal may carry from, preferring the
1159
+ * stronger document: a verified gate receipt when the last run was
1160
+ * clean, else the run record a failed run left behind. Both are
1161
+ * authenticated the same way, and neither is ever accepted anywhere
1162
+ * else as proof.
1163
+ *
1164
+ * Args:
1165
+ * input: the repository coordinates both verifiers are held to.
1166
+ *
1167
+ * Returns:
1168
+ * ParentVerification: the verified parent, or — when neither document
1169
+ * qualifies — the first failed binding of the document the run state
1170
+ * actually holds, so the refusal is never silent.
1171
+ */
1172
+ function resolveResealParent(input) {
1173
+ const receiptParent = verifyCarryForwardParent(input);
1174
+ if (receiptParent.parent !== null) {
1175
+ return {
1176
+ parent: {
1177
+ kind: 'receipt',
1178
+ digest: receiptParent.parent.receiptDigest,
1179
+ receipt: receiptParent.parent.receipt,
1180
+ record: null,
1181
+ treeId: receiptParent.parent.treeId,
1182
+ sha: receiptParent.parent.receipt.gitSha ?? '',
1183
+ execution: receiptParent.parent.execution,
1184
+ },
1185
+ reason: null,
1186
+ };
1187
+ }
1188
+ const recordParent = verifyRunRecordParent(input);
1189
+ if (recordParent.parent !== null)
1190
+ return recordParent;
1191
+ // Neither qualifies. A run record IS the previous run when one is
1192
+ // there; a receipt only speaks for it when no record was left.
1193
+ return hasStateDocument(input.stateDir, 'run-record.json') ? recordParent : receiptParent;
1194
+ }
1195
+ /**
1196
+ * Decides the test-only re-seal: may this `--scope changed` run re-run
1197
+ * exactly the tests the sealed change set can affect and re-seal from
1198
+ * the verified parent?
1199
+ *
1200
+ * The parent is EITHER a verified gate receipt (the run was clean) or a
1201
+ * verified run record (the run failed a test and therefore sealed no
1202
+ * receipt — the consumer's 563/562 case). A run record is a weaker
1203
+ * proof in exactly one way that matters: it may hold a failure. So the
1204
+ * rule that makes it usable is that every test which did NOT pass in
1205
+ * it must be INSIDE the affected set — the change must have touched it
1206
+ * — and must pass in this re-run. Anything else is a full run.
1207
+ *
1208
+ * Every other rule is checked by Gateforge itself, never by the
1209
+ * candidate: the change set is diffed from the two sealed trees, the
1210
+ * paths are classified from the runner's own catalog, the parent's
1211
+ * outcomes must be clean for every test outside the affected set, and a
1212
+ * vanished test must be explained by a changed file. Any doubt returns
1213
+ * one plain reason line, and the caller then runs exactly as it did
1214
+ * before.
1215
+ *
1216
+ * Args:
1217
+ * input: the sealed parent, the frozen tree, the catalog, the current
1218
+ * obligations, and the repository coordinates.
1219
+ *
1220
+ * Returns:
1221
+ * the re-seal plan, or the single reason it is refused (both null
1222
+ * when no parent exists at all, which keeps a run without a parent
1223
+ * byte-identical to before).
1224
+ */
1225
+ export function decideTestOnlyReseal(input) {
1226
+ const parent = input.parent;
1227
+ if (parent === null)
1228
+ return { plan: null, reason: null };
1229
+ if (!input.enabled) {
1230
+ return {
1231
+ plan: null,
1232
+ reason: resealRefusal('the re-seal path is off (`enforcement.reseal` is not true)'),
1233
+ };
1234
+ }
1235
+ if (parent.kind === 'receipt' && parent.receipt !== null) {
1236
+ // A re-seal parent is a whole-suite proof in its own way: it names
1237
+ // the parent it carried from and seals a `coveredObligation-
1238
+ // Fingerprints` list covering the whole repository, so the next
1239
+ // re-seal carries from exactly the same coverage. A plain slice
1240
+ // covers less, and a plain full run is graded in full.
1241
+ const isReseal = parent.receipt.changeClass === 'test-only' && parent.receipt.resealedFrom !== undefined;
1242
+ if (isReseal) {
1243
+ const covered = new Set(parent.receipt.coveredObligationFingerprints ?? []);
1244
+ const uncovered = input.obligations
1245
+ .map((obligation) => obligationFingerprint(obligation))
1246
+ .filter((fingerprint) => !covered.has(fingerprint));
1247
+ if (uncovered.length > 0) {
1248
+ return {
1249
+ plan: null,
1250
+ reason: resealRefusal(`the previous re-seal covered ${String(input.obligations.length - uncovered.length)} of ` +
1251
+ `${String(input.obligations.length)} obligation(s), so it proves no whole-suite run`),
1252
+ };
1253
+ }
1254
+ }
1255
+ else if (receiptScope(parent.receipt) !== 'full') {
1256
+ return { plan: null, reason: resealRefusal('the previous receipt sealed a slice, not a whole-suite run') };
1257
+ }
1258
+ else if (parent.receipt.verdictSummary.total !== input.obligations.length) {
1259
+ return {
1260
+ plan: null,
1261
+ reason: resealRefusal(`the previous receipt graded ${String(parent.receipt.verdictSummary.total)} obligation(s) ` +
1262
+ `while this candidate declares ${String(input.obligations.length)}`),
1263
+ };
1264
+ }
1265
+ }
1266
+ else if (parent.execution.planned.length === 0) {
1267
+ // A run record is only a whole-suite parent when the run it
1268
+ // describes actually planned the suite. Obligations cannot have
1269
+ // drifted under it either: the record binds the trusted policy and
1270
+ // the owner-approved policy digest this run is pinned to.
1271
+ return { plan: null, reason: resealRefusal("the previous run's record planned no test, so it proves no whole-suite run") };
1272
+ }
1273
+ const classification = classifyResealChange({
1274
+ gitDir: input.gitDir,
1275
+ env: input.io.env,
1276
+ cwd: input.io.cwd,
1277
+ parentTreeId: parent.treeId,
1278
+ currentTreeId: input.currentTreeId,
1279
+ testFiles: [...new Set(input.catalog.entries.map((entry) => entry.file))],
1280
+ // The two sealed COMMIT trees say which paths are tracked SOURCE, and
1281
+ // the classifier needs them for a decision that has nothing to do with
1282
+ // an owner declaration: a declared browser state counts as generated
1283
+ // output only when neither commit tracks it. So they travel on their
1284
+ // own terms, whenever both exist — an owner declaration merely adds
1285
+ // the second use of the same reading.
1286
+ ...(input.currentCommitTreeId !== undefined && parent.sha.length > 0
1287
+ ? { parentCommitTreeId: `${parent.sha}^{tree}`, currentCommitTreeId: input.currentCommitTreeId }
1288
+ : {}),
1289
+ ...(input.runtimeFileGlobs !== undefined ? { runtimeFileGlobs: input.runtimeFileGlobs } : {}),
1290
+ ...(input.inputFiles !== undefined ? { inputFiles: input.inputFiles } : {}),
1291
+ });
1292
+ if (!classification.eligible) {
1293
+ return { plan: null, reason: classification.reason };
1294
+ }
1295
+ const affectedFiles = new Set(classification.affectedTestFiles);
1296
+ const catalogKeys = new Set(input.catalog.entries.map((entry) => entry.logicalKey));
1297
+ const affectedKeys = new Set(input.catalog.entries.filter((entry) => affectedFiles.has(entry.file)).map((entry) => entry.logicalKey));
1298
+ const changedFiles = new Set(classification.changedPaths);
1299
+ const previousRun = parent.kind === 'run-record';
1300
+ for (const planned of parent.execution.planned) {
1301
+ if (catalogKeys.has(planned.logicalKey) || changedFiles.has(planned.file))
1302
+ continue;
1303
+ return {
1304
+ plan: null,
1305
+ reason: resealRefusal(`the previous ${previousRun ? 'run' : 'receipt'}'s test ${planned.logicalKey} no longer exists and ` +
1306
+ 'no changed file explains it'),
1307
+ };
1308
+ }
1309
+ const statusByKey = new Map(parent.execution.outcomes.map((outcome) => [outcome.logicalKey, outcome.status]));
1310
+ for (const planned of parent.execution.planned) {
1311
+ if (affectedKeys.has(planned.logicalKey) || !catalogKeys.has(planned.logicalKey))
1312
+ continue;
1313
+ if (statusByKey.get(planned.logicalKey) !== 'passed') {
1314
+ return {
1315
+ plan: null,
1316
+ // A receipt only ever exists for a clean run, so a receipt
1317
+ // parent can only fail this rule on a doctored outcome; a run
1318
+ // record fails it the ordinary way, one test that did not pass.
1319
+ reason: previousRun
1320
+ ? resealRefusal(`the previous run's test ${planned.logicalKey} failed outside the affected set`)
1321
+ : resealRefusal(`the previous receipt's test ${planned.logicalKey} did not pass outside the affected set`),
1322
+ };
1323
+ }
1324
+ }
1325
+ return {
1326
+ plan: {
1327
+ classification,
1328
+ parentKind: parent.kind,
1329
+ parentDigest: parent.digest,
1330
+ parentTreeId: parent.treeId,
1331
+ parentSha: parent.sha,
1332
+ affectedFiles: classification.affectedTestFiles,
1333
+ // A parent that is itself a re-seal planned only the tests IT
1334
+ // re-ran, so the chain's own count is authoritative; a
1335
+ // whole-suite parent counts the same way from its own plan.
1336
+ carriedTests: input.chainCarriedTests ??
1337
+ parent.execution.planned.filter((planned) => catalogKeys.has(planned.logicalKey) && !affectedKeys.has(planned.logicalKey)).length,
1338
+ },
1339
+ reason: null,
1340
+ };
1341
+ }
1342
+ /** Runs configured harness setup and teardown around one supervised suite.
1343
+ *
1344
+ * Args:
1345
+ * io: process context.
1346
+ * options: parsed supervised-run flags.
1347
+ *
1348
+ * Returns:
1349
+ * Promise<number>: the suite result, or 1 when harness setup/teardown fails.
1350
+ */
1351
+ export async function runSupervisedTestGates(io, options) {
1352
+ const config = loadConfigAt(io.cwd);
1353
+ // The existing owner-pinned runtime declaration names test inputs too.
1354
+ // Values come only from the operator, never from candidate configuration.
1355
+ // Checked HERE, before a harness command, the pipeline, or the
1356
+ // candidate's own runner configuration runs: a reserved control this
1357
+ // run refuses must never reach candidate code first.
1358
+ const declaredRunnerEnvNames = loadRuntimeConfigAt(io.cwd, config.runtime)?.envAllowlist;
1359
+ if (declaredRunnerEnvNames !== undefined) {
1360
+ for (const name of declaredRunnerEnvNames) {
1361
+ if (!/^[A-Za-z_][A-Za-z0-9_]*$/.test(name) ||
1362
+ /^(?:GATEFORGE_|NODE_OPTIONS$|NODE_PATH$|LD_|DYLD_|PYTHONPATH$|PYTHONHOME$|BASH_ENV$|ENV$)/i.test(name)) {
1363
+ throw new UsageError(`test-gates: runtime envAllowlist cannot grant '${name}' to test code; ` +
1364
+ 'engine wiring and process-loader controls stay outside the runner');
1365
+ }
1366
+ }
1367
+ }
1368
+ // A merge-request pipeline with no base commit resolves the `auto`
1369
+ // provider to the local staged diff: zero changed files, and a gate
1370
+ // that fails an hour later on debt nobody changed. Refuse in seconds,
1371
+ // before a harness starts or a witness is spawned.
1372
+ if (options.scope === 'changed') {
1373
+ const refusal = mergeRequestScopePreflight(config, io.env);
1374
+ if (refusal !== null)
1375
+ throw new UsageError(refusal);
1376
+ }
1377
+ const startedAtMs = Date.now();
1378
+ const historyStateDir = resolveStateDir(io.cwd, options.out);
1379
+ pruneRunHistory(join(historyStateDir, 'history'), config.history?.retentionDays);
1380
+ const diagnosticsDir = join(historyStateDir, 'diagnostics');
1381
+ mkdirSync(diagnosticsDir, { recursive: true });
1382
+ writeFileSync(join(diagnosticsDir, 'adapter-timing.jsonl'), '', 'utf8');
1383
+ writeFileSync(join(diagnosticsDir, 'test-timing.jsonl'), '', 'utf8');
1384
+ const setupFailure = await runHarnessSetup(config.harness, io.cwd, io.env);
1385
+ if (setupFailure !== null) {
1386
+ writeLine(io.stderr, `HARNESS_FAILED ${setupFailure.step}: command exited ${String(setupFailure.exitCode)}\n${setupFailure.output}`);
1387
+ const teardownFailure = await runHarnessTeardown(config.harness, io.cwd, io.env);
1388
+ if (teardownFailure !== null) {
1389
+ writeLine(io.stderr, `HARNESS_FAILED down: command exited ${String(teardownFailure.exitCode)}\n${teardownFailure.output}`);
1390
+ }
1391
+ recordRunHistory(historyStateDir, config.history?.retentionDays, {
1392
+ runId: randomUUID(),
1393
+ finishedAt: new Date().toISOString(),
1394
+ status: 'failed',
1395
+ testCount: 0,
1396
+ failedCount: 0,
1397
+ }, []);
1398
+ return 1;
1399
+ }
1400
+ let runCode = 1;
1401
+ let teardownFailure = null;
1402
+ try {
1403
+ runCode = await runSupervisedTestGatesInner(io, options, declaredRunnerEnvNames);
1404
+ if (config.diagnostics?.hostLoad === true) {
1405
+ const loadPath = join(diagnosticsDir, 'host-load.json');
1406
+ const timingPath = join(diagnosticsDir, 'test-timing.jsonl');
1407
+ if (existsSync(loadPath) && existsSync(timingPath)) {
1408
+ try {
1409
+ const load = JSON.parse(readFileSync(loadPath, 'utf8'));
1410
+ const tests = readFileSync(timingPath, 'utf8')
1411
+ .split(/\r?\n/)
1412
+ .filter(Boolean)
1413
+ .flatMap((line) => {
1414
+ try {
1415
+ return [JSON.parse(line)];
1416
+ }
1417
+ catch {
1418
+ return [];
1419
+ }
1420
+ });
1421
+ for (const notice of hostLoadFailureNotices(load.samples, tests)) {
1422
+ writeLine(io.stderr, notice);
1423
+ }
1424
+ }
1425
+ catch (error) {
1426
+ writeLine(io.stderr, `warning: host-load failure annotations could not be read: ${error.message}`);
1427
+ }
1428
+ }
1429
+ }
1430
+ }
1431
+ finally {
1432
+ if (runCode !== 0) {
1433
+ try {
1434
+ const artifact = await captureServiceLogs(config.harness?.serviceLogs, historyStateDir, io.cwd, io.env);
1435
+ if (artifact !== null)
1436
+ writeLine(io.stderr, `service logs saved: ${artifact}`);
1437
+ }
1438
+ catch (error) {
1439
+ writeLine(io.stderr, `warning: service logs could not be captured: ${error.message}`);
1440
+ }
1441
+ }
1442
+ teardownFailure = await runHarnessTeardown(config.harness, io.cwd, io.env);
1443
+ if (teardownFailure !== null) {
1444
+ writeLine(io.stderr, `HARNESS_FAILED down: command exited ${String(teardownFailure.exitCode)}\n${teardownFailure.output}`);
1445
+ }
1446
+ }
1447
+ const effectiveRunCode = teardownFailure !== null && runCode === 0 ? 1 : runCode;
1448
+ let executionHistory = null;
1449
+ const executionPath = join(historyStateDir, 'execution-result.json');
1450
+ if (existsSync(executionPath)) {
1451
+ try {
1452
+ const parsed = ExecutionResultSchema.safeParse(JSON.parse(readFileSync(executionPath, 'utf8')));
1453
+ if (parsed.success && Date.parse(parsed.data.startedAt) >= startedAtMs)
1454
+ executionHistory = parsed.data;
1455
+ }
1456
+ catch (error) {
1457
+ writeLine(io.stderr, `warning: run history could not read execution outcomes: ${error.message}`);
1458
+ }
1459
+ }
1460
+ const latestOutcomes = new Map();
1461
+ for (const outcome of executionHistory?.outcomes ?? []) {
1462
+ const previous = latestOutcomes.get(outcome.logicalKey);
1463
+ if (previous === undefined || outcome.attempt >= previous.attempt)
1464
+ latestOutcomes.set(outcome.logicalKey, outcome);
1465
+ }
1466
+ const historyTests = [...latestOutcomes.values()].map((outcome) => ({
1467
+ logicalKey: outcome.logicalKey,
1468
+ status: outcome.status,
1469
+ }));
1470
+ const failedCount = historyTests.filter((test) => test.status === 'failed').length;
1471
+ recordRunHistory(historyStateDir, config.history?.retentionDays, {
1472
+ runId: executionHistory?.runId ?? randomUUID(),
1473
+ finishedAt: new Date().toISOString(),
1474
+ status: effectiveRunCode === 0 ? 'passed' : 'failed',
1475
+ testCount: executionHistory?.planned.length ?? 0,
1476
+ failedCount,
1477
+ }, historyTests);
1478
+ return effectiveRunCode;
1479
+ }
499
1480
  /**
500
1481
  * The supervised `--changed` path (plan Phase 4, ADR 0005 D2/D3):
501
1482
  * resolve catalog + mappings → fix the expected set → prepare the
@@ -517,12 +1498,243 @@ async function legacyTestGates(io, options) {
517
1498
  * supervision/evidence failure, 2 config/usage.
518
1499
  * @throws fail-closed errors (exit 2) from config/plugin/pipeline layers.
519
1500
  */
520
- export async function runSupervisedTestGates(io, options) {
1501
+ /**
1502
+ * Projects every EXPIRED owner quarantine into a blocking finding that
1503
+ * names the test and its expiry. An expired
1504
+ * quarantine is not silently ignored: it is a stale escape hatch, and
1505
+ * the required test is back in the run.
1506
+ *
1507
+ * Args:
1508
+ * expired: the expired partition of the loaded quarantine population.
1509
+ *
1510
+ * Returns:
1511
+ * BlockingEntry[]: one typed `QUARANTINE_EXPIRED` finding per expiry,
1512
+ * sorted by test key (the loader's order).
1513
+ */
1514
+ export function expiredQuarantineBlocking(expired) {
1515
+ return expired.map((entry) => ({
1516
+ kind: 'finding',
1517
+ resourceId: null,
1518
+ name: entry.quarantine.testKey,
1519
+ detail: `quarantine of '${entry.quarantine.testKey}' expired at ${entry.quarantine.expiresAt} ` +
1520
+ `(file ${QUARANTINE_DIR}/${entry.file}) — it is ignored and the test is required again; ` +
1521
+ 'renew it with an owner approval or delete it',
1522
+ location: null,
1523
+ cause: 'QUARANTINE_EXPIRED',
1524
+ nextAction: CAUSE_NEXT_ACTIONS.QUARANTINE_EXPIRED,
1525
+ }));
1526
+ }
1527
+ /**
1528
+ * The `<file>#<title path>` instance identities of every quarantined
1529
+ * catalog row — the form both the runner-outcomes document and the
1530
+ * witness session trace report.
1531
+ *
1532
+ * Args:
1533
+ * catalog: the current test catalog (null when discovery failed).
1534
+ * quarantinedKeys: logical keys the owner quarantined.
1535
+ *
1536
+ * Returns:
1537
+ * Set<string>: instance identities of quarantined tests.
1538
+ */
1539
+ function quarantinedInstanceKeys(catalog, quarantinedKeys) {
1540
+ const keys = new Set();
1541
+ if (catalog === null || quarantinedKeys.size === 0)
1542
+ return keys;
1543
+ for (const entry of catalog.entries) {
1544
+ if (!quarantinedKeys.has(entry.logicalKey))
1545
+ continue;
1546
+ keys.add(`${entry.file}#${entry.titlePath.join('>')}`);
1547
+ }
1548
+ return keys;
1549
+ }
1550
+ /**
1551
+ * The framework test ids (`parameterIdentity`) of every quarantined
1552
+ * catalog row: the identity claims and evidence records carry, so the
1553
+ * evaluator can discard that test's proof before any verifier sees it.
1554
+ *
1555
+ * Args:
1556
+ * catalog: the current test catalog.
1557
+ * quarantinedKeys: logical keys the owner quarantined.
1558
+ *
1559
+ * Returns:
1560
+ * Set<string>: framework ids belonging to quarantined tests (empty
1561
+ * ids are skipped — a row without a framework id claims nothing).
1562
+ */
1563
+ function quarantinedFrameworkIds(catalog, quarantinedKeys) {
1564
+ const ids = new Set();
1565
+ if (quarantinedKeys.size === 0)
1566
+ return ids;
1567
+ for (const entry of catalog.entries) {
1568
+ const identity = entry.parameterIdentity;
1569
+ if (identity === null || identity.length === 0)
1570
+ continue;
1571
+ if (quarantinedKeys.has(entry.logicalKey))
1572
+ ids.add(identity);
1573
+ }
1574
+ return ids;
1575
+ }
1576
+ /**
1577
+ * Builds one planned row from a contract-enumerated test identity
1578
+ * (plan 2026-09-25, runner-agnostic evidence): the adapter's logical
1579
+ * key (`<file>#<title path>`), null project, and the runner's own
1580
+ * framework id. Supervision joins planned, executed, and traced rows
1581
+ * on (project, file, title path) — the same identity join the
1582
+ * Playwright plan uses.
1583
+ *
1584
+ * Args:
1585
+ * test: the enumerated test identity.
1586
+ *
1587
+ * Returns:
1588
+ * PlannedRow: the planned instance plus its supervision input.
1589
+ */
1590
+ function plannedRowOfIdentity(test) {
1591
+ return {
1592
+ planned: {
1593
+ logicalKey: test.logicalKey,
1594
+ project: test.project,
1595
+ file: test.file,
1596
+ titlePath: [...test.titlePath],
1597
+ frameworkId: test.frameworkId ?? null,
1598
+ },
1599
+ input: {
1600
+ logicalKey: test.logicalKey,
1601
+ project: test.project,
1602
+ file: test.file,
1603
+ titlePath: [...test.titlePath],
1604
+ blockingAnnotations: [...test.blockingAnnotations],
1605
+ },
1606
+ };
1607
+ }
1608
+ /**
1609
+ * Constructs the contract adapter for the configured runner (plan
1610
+ * 2026-09-25, runner-agnostic evidence). Enumeration needs no trusted
1611
+ * wiring; execution receives it through the constructor options so the
1612
+ * runner child never reads more than the non-secret run identity.
1613
+ *
1614
+ * Args:
1615
+ * runner: the configured runner name (`config.runner`).
1616
+ * wiring: run-scoped, non-secret witness wiring for `execute`.
1617
+ *
1618
+ * Returns:
1619
+ * RunnerAdapter: the adapter serving that runner.
1620
+ * @throws UsageError on a runner name with no adapter (the config
1621
+ * schema rejects unknown values first — this is a defensive seam).
1622
+ */
1623
+ function runnerAdapterFor(runner, wiring = {}) {
1624
+ const witness = {
1625
+ ...(wiring.witnessUrl !== undefined && wiring.witnessUrl !== '' ? { url: wiring.witnessUrl } : {}),
1626
+ ...(wiring.runToken !== undefined && wiring.runToken !== '' ? { token: wiring.runToken } : {}),
1627
+ };
1628
+ // The app origin the session proxy fronts crosses INSIDE the wiring
1629
+ // object every adapter reads (`witness.appBaseUrl`), except pytest,
1630
+ // whose option is declared at the top level. Passing it beside the
1631
+ // witness object (a spread) type-checks and is then SILENTLY DROPPED
1632
+ // by the vitest and cypress adapters, which left their runner child
1633
+ // with an empty GATEFORGE_APP_BASE_URL and every supertest/Cypress
1634
+ // request refused as in-process.
1635
+ const appBaseUrl = wiring.appBaseUrl !== undefined && wiring.appBaseUrl !== '' ? { appBaseUrl: wiring.appBaseUrl } : {};
1636
+ const sessionWiring = { ...witness, ...appBaseUrl };
1637
+ switch (runner) {
1638
+ case 'pytest':
1639
+ return new PytestRunnerAdapter({ witness, ...appBaseUrl });
1640
+ case 'vitest':
1641
+ return new VitestRunnerAdapter({ witness: sessionWiring });
1642
+ case 'cypress':
1643
+ return new CypressRunnerAdapter({ witness: sessionWiring });
1644
+ default:
1645
+ throw new UsageError(`test-gates: no runner adapter for '${runner}' (expected playwright | pytest | vitest | cypress)`);
1646
+ }
1647
+ }
1648
+ /**
1649
+ * Writes the WITNESS-ISSUED ledger into the run's `records.json` after
1650
+ * the supervisor drain has finalized every session.
1651
+ *
1652
+ * The Playwright reporter may copy the ledger for its advisory output
1653
+ * before the final drain sweep issues Observe or server-persistence
1654
+ * records. Every runner therefore uses this final trusted fetch while
1655
+ * the witness is alive. A transport failure writes nothing and names
1656
+ * itself on stderr; unissued evidence can never receive credit.
1657
+ *
1658
+ * Args:
1659
+ * io: the CLI IO (stderr carries the diagnostic).
1660
+ * stateDir: the run state directory.
1661
+ * witnessUrl: the running witness base URL.
1662
+ * runToken: the run token authenticating the ledger read.
1663
+ *
1664
+ * Returns:
1665
+ * Promise<void>: resolves once the document is written (or the fetch
1666
+ * failed and said so).
1667
+ */
1668
+ async function writeWitnessLedgerDocument(io, stateDir, witnessUrl, runToken) {
1669
+ try {
1670
+ const response = await fetch(`${witnessUrl}/records`, {
1671
+ headers: { [RUN_HEADER]: runToken },
1672
+ });
1673
+ if (!response.ok) {
1674
+ writeLine(io.stderr, `test-gates: the witness ledger could not be read (HTTP ${String(response.status)}) — evidence stays uncredited`);
1675
+ return;
1676
+ }
1677
+ const body = (await response.json());
1678
+ const records = Array.isArray(body.records) ? body.records : [];
1679
+ writeFileSync(join(stateDir, 'records.json'), `${JSON.stringify(records, null, 2)}\n`, 'utf8');
1680
+ }
1681
+ catch (error) {
1682
+ writeLine(io.stderr, `test-gates: the witness ledger could not be read (${error.message}) — evidence stays uncredited`);
1683
+ }
1684
+ }
1685
+ /**
1686
+ * The directory the native playwright child runs from: the directory
1687
+ * holding the config enumeration selected (the repo root for a
1688
+ * root-level config, the project directory for a nested one). It is the
1689
+ * base every relative path the suite itself writes or reads resolves
1690
+ * from, so the gate's own checks must use it rather than the repo root.
1691
+ */
1692
+ function nativePlaywrightConfigDir(cwd) {
1693
+ const config = findPlaywrightConfig(cwd);
1694
+ return config === null ? cwd : dirname(resolve(cwd, config));
1695
+ }
1696
+ async function runSupervisedTestGatesInner(io, options, declaredRunnerEnvNames) {
521
1697
  const { out, format, witnessUrl, runTimeoutMs } = options;
522
1698
  const runtimeReuseDigest = options.runtimeReuseDigest;
523
1699
  const runtimeReuseMounts = options.runtimeReuseMounts ?? [];
524
1700
  const config = loadConfigAt(io.cwd);
1701
+ // The configured runner (plan 2026-09-25, runner-agnostic evidence):
1702
+ // `playwright` (the default) keeps the byte-identical supervised path;
1703
+ // pytest/vitest/cypress enumerate, execute, and report through the
1704
+ // RunnerAdapter contract behind the SAME witness session, run token,
1705
+ // supervision, receipts, and strictness machinery.
1706
+ const runnerName = config.runner;
1707
+ // The timing-chaos plan for THIS run (E63). Null without the flag:
1708
+ // then the witness is spawned with no plan and every byte of the run
1709
+ // is exactly what it was before chaos existed. The bounds come from
1710
+ // `run.chaos` either way: a SPAWNED witness is configured with them
1711
+ // in its environment, an EXTERNAL one through the run-context
1712
+ // binding. The run owns the plan in both cases.
1713
+ const chaosRun = options.chaos === undefined || options.chaos === null ? null : chaosRunOf(config, options.chaos.seed);
1714
+ // The schedule the witness actually used (filled in before it stops);
1715
+ // null until then, and for every run without `--chaos`.
1716
+ let chaosSchedule = null;
1717
+ // Twin path coverage (E64): the divergences this run found, filled in
1718
+ // from the witness's recorded shapes before it stops. Empty for every
1719
+ // run without `enforcement.twinPaths`, and empty again when a linked
1720
+ // pair did not both run — a divergence needs two sides observed in
1721
+ // the SAME run, never shapes carried over from another.
1722
+ let twinDivergences = [];
1723
+ if (runnerName === 'pytest') {
1724
+ const configured = (config.diagnostics?.suites ?? []).filter((suite) => suite.runner === 'pytest');
1725
+ if (configured.length > 1) {
1726
+ throw new UsageError(`test-gates: runner 'pytest' executes exactly one configured pytest suite, but ${String(configured.length)} are ` +
1727
+ `configured (${configured.map((suite) => suite.name).join(', ')}) — keep a single suite under runner 'pytest' ` +
1728
+ '(a second suite would run under the wrong argv; narrower selection is never guessed)');
1729
+ }
1730
+ }
1731
+ // Owner-chosen strictness. Absent key =
1732
+ // `strict` = today's exact behavior; the decision below only ever
1733
+ // maps an ALREADY-COMPUTED strict result onto the owner's exit code,
1734
+ // never changes what was executed or graded.
1735
+ const gateMode = resolveStrictnessMode(config);
525
1736
  const docsExclusions = loadDocsExclusions(io.cwd, config);
1737
+ const cacheExclusions = loadCacheExclusions(io.cwd, config);
526
1738
  const stateDir = resolveStateDir(io.cwd, out);
527
1739
  const verifierKeyring = options.verifierKeyring ?? resolveVerifierKeyring(io.cwd, io.env, [stateDir]);
528
1740
  const witnessVerifierKey = verifierKeyring?.active.key;
@@ -531,18 +1743,14 @@ export async function runSupervisedTestGates(io, options) {
531
1743
  // Scoped sealing (Goal 2): resolve the changed-file basis through the
532
1744
  // SAME configured provider `check --changed` uses (auto → GHA/GitLab/
533
1745
  // staged), and stamp the resolved identity into the run manifest so a
534
- // scoped run names the diff basis it sliced from. Full mode keeps
535
- // `all-files` — byte-identical to the historical run.
536
1746
  const providerIdentity = options.fixedChangedFiles !== undefined
537
1747
  ? 'local-staged'
538
- : options.scope === 'changed'
539
- ? resolveProvider(config.changed.provider, io.cwd, io.env).provider
540
- : 'all-files';
1748
+ : resolveProvider(config.changed.provider, io.cwd, io.env).provider;
541
1749
  // 1. Inventory + stability + input digest (same discipline as check).
542
1750
  let preFiles = null;
543
1751
  let snapshotUnavailable = false;
544
1752
  try {
545
- preFiles = collectInputFiles(io.cwd, config, stateDir, runtimeReuseMounts, docsExclusions);
1753
+ preFiles = collectInputFiles(io.cwd, config, stateDir, runtimeReuseMounts, docsExclusions, cacheExclusions);
546
1754
  }
547
1755
  catch (error) {
548
1756
  if (error instanceof SnapshotUnavailableError)
@@ -562,6 +1770,20 @@ export async function runSupervisedTestGates(io, options) {
562
1770
  ? { changedFilesOverride: options.fixedChangedFiles }
563
1771
  : {}),
564
1772
  });
1773
+ // The graded scope, published to the in-runner reporter BEFORE the
1774
+ // suite starts: a reporter that graded a selection must not print a
1775
+ // repository verdict. Debt itself is the gate's alone — the reporter
1776
+ // has no waivers, no scope and no baseline, so it never grades it.
1777
+ const runScope = options.testSelectors !== undefined ? 'named' : options.scope === 'changed' ? 'changed' : 'full';
1778
+ writeRunScopeView(stateDir, runScope);
1779
+ const adoptedBaseline = resolveAdoptedBaseline(io.cwd, config.baselines);
1780
+ // Owner quarantine: loaded against the
1781
+ // INJECTED run clock, never the wall clock. ACTIVE quarantines remove
1782
+ // their test from the REQUIRED set and its evidence is discarded;
1783
+ // EXPIRED ones are ignored and each BLOCKS, naming the test.
1784
+ const quarantines = loadQuarantines(join(io.cwd, ...QUARANTINE_DIR.split('/')), { now: pipeline.now });
1785
+ const quarantinedKeys = new Set(quarantines.active.map((entry) => entry.quarantine.testKey));
1786
+ const providerChangedFiles = options.fixedChangedFiles ?? pipeline.changedFiles;
565
1787
  // The scoped slice's changed set: exactly what the resolved provider
566
1788
  // reported for THIS tree (the pipeline already ran it — one resolution,
567
1789
  // one diff basis stamped in the manifest).
@@ -572,7 +1794,7 @@ export async function runSupervisedTestGates(io, options) {
572
1794
  let expectedDigest = null;
573
1795
  let inputSnapshot = null;
574
1796
  if (!snapshotUnavailable) {
575
- const postDiscovery = collectInputFiles(io.cwd, config, stateDir, runtimeReuseMounts, docsExclusions);
1797
+ const postDiscovery = collectInputFiles(io.cwd, config, stateDir, runtimeReuseMounts, docsExclusions, cacheExclusions);
576
1798
  const drift = preFiles === null ? [] : diffInputFiles(preFiles, postDiscovery);
577
1799
  if (drift.length > 0) {
578
1800
  throw new UsageError(`input tree changed around discovery (${drift.slice(0, 3).join('; ')}${drift.length > 3 ? '; …' : ''}); ` +
@@ -589,6 +1811,7 @@ export async function runSupervisedTestGates(io, options) {
589
1811
  runtimeReuseDigest,
590
1812
  runtimeReuseMounts,
591
1813
  docsExclusions,
1814
+ cacheExclusions,
592
1815
  });
593
1816
  expectedDigest = inputSnapshot.evidenceInputDigest;
594
1817
  }
@@ -612,11 +1835,16 @@ export async function runSupervisedTestGates(io, options) {
612
1835
  // EVALUATED are pinned before any suite execution. At seal time the
613
1836
  // same values are recomputed — a live-workspace edit mid-run is an
614
1837
  // explicit drift block, never a mixed-bytes seal.
1838
+ //
1839
+ // The walk is taken ONCE with its ENTRIES, not just its id: the global
1840
+ // preparation freeze below compares those exact baseline bytes against
1841
+ // the prepared candidate, so the baseline assertion and the index
1842
+ // guard keep reading the same raw inventory the freeze reads.
615
1843
  const freezeGitDir = resolveGitDir(io.cwd, io.env);
616
- const frozenTreeId = options.fixedCandidateTreeId ??
617
- (freezeGitDir === null
618
- ? null
619
- : computeCandidateTreeId(freezeGitDir, io.cwd, io.env, stateDir, 'record', runtimeReuseMounts, docsExclusions));
1844
+ const baselineSnapshot = freezeGitDir === null
1845
+ ? null
1846
+ : computeCandidateTreeSnapshot(freezeGitDir, io.cwd, io.env, stateDir, 'record', runtimeReuseMounts, docsExclusions, cacheExclusions);
1847
+ const frozenTreeId = options.fixedCandidateTreeId ?? baselineSnapshot?.treeId ?? null;
620
1848
  const frozenParentSha = options.fixedParentSha !== undefined ? options.fixedParentSha : parentSha(io.cwd);
621
1849
  // 2. Catalog + mappings (Phase 3 resolver) → expected set + claim
622
1850
  // injections + typed mapping blockers. A failed discovery blocks the
@@ -624,6 +1852,24 @@ export async function runSupervisedTestGates(io, options) {
624
1852
  let discoveryError = null;
625
1853
  let catalog = null;
626
1854
  let nativeClaims = [];
1855
+ let nativeErrors = [];
1856
+ let nativeInstances = [];
1857
+ // The project dependency graph the enumeration captured from the
1858
+ // RUNNER's resolved config (`setup` depends on nothing, the projects
1859
+ // that read its artifact depend on `setup`). Empty when the
1860
+ // enumeration could not read it — absence, never a guessed empty one.
1861
+ let projectDependencies = {};
1862
+ // Whether the enumeration actually READ the runner's resolved project
1863
+ // graph. The map itself is defaulted to `{}` so every existing caller
1864
+ // keeps working, but `{}` and "unreadable" are different facts: the
1865
+ // global preparation freeze may only derive an ordering from a graph it
1866
+ // really captured, so absence is carried separately and never guessed.
1867
+ let projectGraphCaptured = false;
1868
+ // The `use.storageState` path each project declared, as the RUNNER
1869
+ // resolved it: the standard auth pattern's dependent project reads the
1870
+ // state its setup project saved. Empty when the enumeration captured
1871
+ // none — absence, never a guessed empty one.
1872
+ let projectStorageStates = {};
627
1873
  try {
628
1874
  // collectPytest is REQUIRED here (GAP 1 fix, server-witnessed
629
1875
  // channel): the supervised run's expected set, mapping resolution,
@@ -634,13 +1880,54 @@ export async function runSupervisedTestGates(io, options) {
634
1880
  // failure is honest data: the suite's runner summary turns
635
1881
  // `unavailable`, `inventoryComplete` goes false, and the gate blocks
636
1882
  // TEST_INVENTORY_INCOMPLETE — never a silently narrower inventory.
637
- const discovered = await discoverTestCatalog({ cwd: io.cwd, config, collectPytest: true });
1883
+ const discovered = await discoverTestCatalog({
1884
+ cwd: io.cwd,
1885
+ config,
1886
+ collectPytest: true,
1887
+ // The state directory this run ACTUALLY resolved (`--out` aware):
1888
+ // the supervised run's own generated config — and, for a
1889
+ // repository carrying one, an earlier build's freeze control files
1890
+ // — must not be harvested back as declared tests on a repeat run.
1891
+ excludeFile: engineGeneratedStateFileFilter(io.cwd, stateDir),
1892
+ });
638
1893
  catalog = discovered.catalog;
639
1894
  nativeClaims = discovered.nativeClaims;
1895
+ nativeErrors = discovered.nativeErrors;
1896
+ nativeInstances = discovered.nativeInstances;
1897
+ projectDependencies = discovered.projectDependencies ?? {};
1898
+ projectStorageStates = discovered.projectStorageStates ?? {};
1899
+ projectGraphCaptured = discovered.projectDependencies !== undefined;
1900
+ for (const warning of discovered.registrationWarnings) {
1901
+ writeLine(io.stderr, `test-gates: registration warning ${warning.file}:${String(warning.location.line)}: ` +
1902
+ `${warning.titlePath.join(' > ')} is conditional on ${warning.environmentVariable}; ` +
1903
+ 'keep test registration independent of Gateforge run variables');
1904
+ }
640
1905
  }
641
1906
  catch (error) {
642
1907
  discoveryError = error instanceof TestDiscoveryError ? error.message : error.message;
643
1908
  }
1909
+ // A declared state is honored as DATA, and only when it names a file
1910
+ // inside the candidate. A relative declaration is resolved from the
1911
+ // native config directory — the cwd the suite's own setup test wrote
1912
+ // the file from — while the candidate root stays the containment
1913
+ // boundary. Refused here, loudly and before anything is spawned,
1914
+ // because dropping it instead would run the project logged out and
1915
+ // report a green gate over a suite that never really exercised the
1916
+ // authenticated UI. With an operator's whole-run
1917
+ // GATEFORGE_SESSION_STATE set, no declaration is used at all, so none
1918
+ // is read or checked either — precedence means the losing value never
1919
+ // reaches the filesystem.
1920
+ if (io.env['GATEFORGE_SESSION_STATE'] === undefined) {
1921
+ const nativeConfigDir = nativePlaywrightConfigDir(io.cwd);
1922
+ for (const [project, declared] of Object.entries(projectStorageStates)) {
1923
+ try {
1924
+ resolveProjectStorageState(declared, io.cwd, project, nativeConfigDir);
1925
+ }
1926
+ catch (error) {
1927
+ throw new UsageError(`test-gates: ${error.message}`);
1928
+ }
1929
+ }
1930
+ }
644
1931
  const trustedPolicy = trustedPolicyDigestForConfig(io.cwd, config);
645
1932
  // Policy-revision ownership (review 2026-09-13 P1 #5, ADR 0005 D6):
646
1933
  // the candidate's policy digest is compared against the OWNER-APPROVED
@@ -649,7 +1936,7 @@ export async function runSupervisedTestGates(io, options) {
649
1936
  // reuse, or suite execution. A provisioned pin binds EVERY run here;
650
1937
  // strict mode without a pin fails closed; a candidate whose revision
651
1938
  // is not the approved one never reaches the runner.
652
- const policyGate = evaluateApprovedPolicy(resolveApprovedPolicyDigest({ env: io.env, candidateCwd: io.cwd, candidateConfig: config }), trustedPolicy, config.enforcement?.strictE2E === true || docsExclusions.length > 0);
1939
+ const policyGate = evaluateApprovedPolicy(resolveApprovedPolicyDigest({ env: io.env, candidateCwd: io.cwd, candidateConfig: config }), trustedPolicy, config.enforcement?.strictE2E === true || docsExclusions.length > 0 || cacheExclusions.length > 0);
653
1940
  if (policyGate.status === 'blocked') {
654
1941
  if (!options.resultOnly)
655
1942
  clearGateReceipt(stateDir);
@@ -685,49 +1972,433 @@ export async function runSupervisedTestGates(io, options) {
685
1972
  // evidence — the drain registers exactly this set pre-run and
686
1973
  // finalizes passed sessions against it.
687
1974
  let observeObligations = [];
1975
+ let fullPlannedCount = 0;
1976
+ // The FULL planned set every narrowing selected from. The dependency
1977
+ // closure below reads it to pull in the tests of a `setup` project a
1978
+ // narrowed plan's dependent tests need (see
1979
+ // `plannedRowsWithProjectDependencies`).
1980
+ let allPlannedRows = [];
1981
+ let affectedTestCount = 0;
1982
+ // The claimed files' slice (changed scope) a non-Playwright runner
1983
+ // plans from — empty in full scope and for `playwright`.
1984
+ let affectedRequiredFiles = [];
1985
+ // The verified parent a re-seal carries from — a gate receipt or a
1986
+ // run record — with the exact documents a consumer needs to
1987
+ // recompute the re-seal (the parent document, its execution result,
1988
+ // and this run's catalog). Retained next to the new receipt as
1989
+ // MAC-bound run state.
1990
+ let reSealParent = null;
1991
+ let reSealPlan = null;
1992
+ // Framework ids whose claims and records must never grade (owner
1993
+ // quarantine); empty when nothing is quarantined.
1994
+ let excludedTestIds = [];
1995
+ // Hoisted: a named run grades the obligations its selection declares,
1996
+ // which the mapping resolution below is the only trusted source for.
1997
+ let gradedResolution = null;
1998
+ // The parent run's authenticated witness EVIDENCE, reduced to what
1999
+ // the carried tests proved: the union this run grades and seals is
2000
+ // this plus its own fresh records. Resolved at the re-seal decision,
2001
+ // BEFORE this run overwrites the state documents that hold it. In a
2002
+ // chain, several runs contributed to that union, so it keeps every
2003
+ // contributing run's envelope and the channel each one authorizes.
2004
+ let reSealParentEvidence = null;
2005
+ // Hoisted: the validated sidecar, the only declaration source the
2006
+ // witness-side case assignments are built from.
2007
+ let behaviorSidecar = null;
688
2008
  if (catalog !== null) {
689
2009
  const mapped = await resolveRepositoryMappings({
690
2010
  cwd: io.cwd,
691
2011
  config,
692
2012
  obligations: pipeline.policy.obligations,
2013
+ stateDir,
693
2014
  catalog,
694
2015
  nativeClaims,
695
2016
  behaviorCatalog: pipeline.behaviorCatalog,
2017
+ nativeErrors,
2018
+ nativeInstances,
696
2019
  });
2020
+ behaviorSidecar = mapped.sidecar;
697
2021
  mappingBlockers = mappingBlocking(mapped.resolution.problems);
698
- claimInventory = mapped.claimInventory;
699
- plannedRows = planExpectedSet(catalog);
700
- injections = claimInjectionsFor(mapped.resolution, catalog);
701
- mappedCoverage = mappedCoverageFrom(mapped.resolution, pipeline.policy.obligations, pipeline.graph);
2022
+ // Quarantined tests prove nothing: their declarations and their
2023
+ // coverage bindings leave the mapping surface BEFORE planning, so an
2024
+ // obligation only they covered becomes uncovered and stays `missing`.
2025
+ gradedResolution = withoutQuarantinedBindings(mapped.resolution, quarantinedKeys);
2026
+ excludedTestIds = [...quarantinedFrameworkIds(catalog, quarantinedKeys)].sort();
2027
+ claimInventory = mapped.claimInventory.filter((claim) => !excludedTestIds.includes(claim.testId));
2028
+ const fullPlannedRows = planExpectedSet(catalog).filter((row) => !quarantinedKeys.has(row.planned.logicalKey));
2029
+ fullPlannedCount = fullPlannedRows.length;
2030
+ allPlannedRows = fullPlannedRows;
2031
+ plannedRows = fullPlannedRows;
2032
+ injections = claimInjectionsFor(gradedResolution, catalog);
2033
+ mappedCoverage = mappedCoverageFrom(gradedResolution, pipeline.policy.obligations, pipeline.graph);
702
2034
  serverE2eObligations = serverE2eObligationIds(mapped.resolution);
703
2035
  observeObligations = observeObligationIds(mapped.resolution);
2036
+ // Adopted baseline debt (E62): the changed-scope planner must agree
2037
+ // with this run's own grading, which waives exactly the obligations
2038
+ // the ADOPTED baseline forgives (`applyBaseline`). Strict E2E
2039
+ // re-grades every waiver back to blocking, so there the planner
2040
+ // forgives nothing and an unmapped affected obligation still blocks.
2041
+ const scopeBaseline = config.enforcement?.strictE2E === true ? null : resolveAdoptedBaseline(io.cwd, config.baselines);
2042
+ const affectedPlan = planScopedExpectedSet({
2043
+ catalog,
2044
+ resolution: gradedResolution,
2045
+ obligations: pipeline.policy.obligations,
2046
+ graph: pipeline.graph,
2047
+ changedFiles: providerChangedFiles,
2048
+ behaviorCatalog: pipeline.behaviorCatalog,
2049
+ ...(scopeBaseline !== null ? { forgivenFingerprints: scopeBaseline.fingerprints } : {}),
2050
+ });
2051
+ affectedTestCount = affectedPlan.plannedRows.length;
2052
+ affectedRequiredFiles = affectedPlan.requiredFiles;
704
2053
  if (options.scope === 'changed') {
705
- // The affected slice (Goal 2): changed files → resources (the same
706
- // join-aware source map the diff scoping grades by) → obligations →
707
- // declared-claiming tests. Unclaimed affected obligations become
708
- // typed EVIDENCE_SCOPE_INCOMPLETE blockers — the gate is never
709
- // silently narrowed past an obligation nothing can test.
710
- const scopedPlan = planScopedExpectedSet({
711
- catalog,
712
- resolution: mapped.resolution,
713
- obligations: pipeline.policy.obligations,
714
- graph: pipeline.graph,
715
- changedFiles: scopeChangedFiles ?? [],
716
- behaviorCatalog: pipeline.behaviorCatalog,
717
- });
718
- plannedRows = scopedPlan.plannedRows;
719
- coveredFingerprints = scopedPlan.coveredFingerprints;
720
- scopeBlockers = scopedPlan.unclaimed.map((entry) => ({
721
- kind: 'finding',
722
- resourceId: null,
723
- name: entry.obligationId,
724
- detail: entry.detail,
725
- location: null,
726
- cause: 'EVIDENCE_SCOPE_INCOMPLETE',
727
- nextAction: CAUSE_NEXT_ACTIONS.EVIDENCE_SCOPE_INCOMPLETE,
728
- }));
2054
+ // Test-only re-seal (plan phase 2). A verified parent and a
2055
+ // frozen tree are the only inputs; everything else — the change
2056
+ // set, the classification, the carried outcomes — Gateforge
2057
+ // recomputes itself. A refused re-seal prints ONE plain reason
2058
+ // line and the run continues through the unchanged path below.
2059
+ // The parent is bound to the commit the parent document itself
2060
+ // names, which must be an ancestor of HEAD: a merge request's
2061
+ // diff base is a different commit, and no CI variable names the
2062
+ // one the previous pipeline tested.
2063
+ // The first binding this run itself cannot offer a parent for, in
2064
+ // the same plain words a rejected parent document gets. null means
2065
+ // every precondition holds and the parent must be looked up.
2066
+ const reSealPrecondition = options.testSelectors !== undefined || options.resultOnly
2067
+ ? 'a named/result-only run never re-seals'
2068
+ : freezeGitDir === null || frozenTreeId === null
2069
+ ? 'this run froze no candidate tree'
2070
+ : expectedDigest === null
2071
+ ? 'this run pinned no input digest'
2072
+ : approvedPolicyDigest === null
2073
+ ? 'this run pinned no owner-approved policy'
2074
+ : catalog.inventoryComplete
2075
+ ? null
2076
+ : 'the test inventory is incomplete';
2077
+ const reSealParentLookup = reSealPrecondition === null
2078
+ ? resolveResealParent({
2079
+ io,
2080
+ config,
2081
+ stateDir,
2082
+ verifierKeyring,
2083
+ baseSha: '',
2084
+ parentCommitBinding: 'own-ancestor-commit',
2085
+ repositoryFingerprints: [
2086
+ ...new Set(pipeline.policy.obligations.map((obligation) => obligationFingerprint(obligation))),
2087
+ ].sort(),
2088
+ gitDir: freezeGitDir,
2089
+ docsExclusions,
2090
+ cacheExclusions,
2091
+ trustedPolicyDigest: trustedPolicy,
2092
+ approvedPolicyDigest: approvedPolicyDigest,
2093
+ executionBoundaryDigest,
2094
+ })
2095
+ : { parent: null, reason: reSealPrecondition };
2096
+ const reSealParentCandidate = reSealParentLookup.parent;
2097
+ // A chain of consecutive re-seals is bounded: past the bound the
2098
+ // carried evidence has drifted too far to recompute honestly, so
2099
+ // this run takes the full path instead (one plain reason line).
2100
+ const reSeal = reSealParentCandidate !== null &&
2101
+ resealChainHopCount(stateDir) >= RESEAL_CHAIN_MAX_HOPS
2102
+ ? {
2103
+ plan: null,
2104
+ reason: resealRefusal(`the run state already retains ${String(RESEAL_CHAIN_MAX_HOPS)} consecutive re-seals, the ` +
2105
+ 'bound this path may chain to'),
2106
+ }
2107
+ : decideTestOnlyReseal({
2108
+ io,
2109
+ gitDir: freezeGitDir,
2110
+ parent: reSealParentCandidate,
2111
+ currentTreeId: frozenTreeId,
2112
+ catalog,
2113
+ obligations: pipeline.policy.obligations,
2114
+ enabled: config.enforcement?.reseal === true,
2115
+ ...(config.enforcement?.resealRuntimeFiles !== undefined
2116
+ ? { runtimeFileGlobs: config.enforcement.resealRuntimeFiles }
2117
+ : {}),
2118
+ // The commit this run froze is the receipt's own `gitSha`:
2119
+ // it, and the parent's, are the two commit trees that say
2120
+ // which paths are TRACKED. Absent (outside a checkout) the
2121
+ // declaration can hide nothing, so the classifier refuses
2122
+ // exactly as it does without it.
2123
+ ...(pipeline.manifest.gitSha !== null
2124
+ ? { currentCommitTreeId: `${pipeline.manifest.gitSha}^{tree}` }
2125
+ : {}),
2126
+ // The input inventory is what separates generated output from
2127
+ // authority: a declared browser state the digest binds is
2128
+ // never carried as a generated-state change. Absent (no
2129
+ // usable snapshot) the classifier simply holds no inventory.
2130
+ ...(preFiles !== null ? { inputFiles: new Set(preFiles.map((entry) => entry.path)) } : {}),
2131
+ });
2132
+ if (reSeal.reason !== null)
2133
+ writeLine(io.stderr, `test-gates: ${reSeal.reason}`);
2134
+ // A parent document the run state holds but cannot be re-sealed
2135
+ // from is a refusal the consumer must SEE: the run continues on
2136
+ // the ordinary changed-scope path, which looks identical to a run
2137
+ // that never had a parent. With the path off, or with no parent
2138
+ // document at all, nothing is printed and the run is byte-identical
2139
+ // to before.
2140
+ else if (config.enforcement?.reseal === true &&
2141
+ reSealParentLookup.reason !== null &&
2142
+ (hasStateDocument(stateDir, 'receipt.json') || hasStateDocument(stateDir, 'run-record.json'))) {
2143
+ writeLine(io.stderr, `test-gates: the previous run cannot be re-sealed from: ${reSealParentLookup.reason} ${RESEAL_REFUSAL_SUFFIX}`);
2144
+ }
2145
+ reSealPlan = reSeal.plan;
2146
+ reSealParent = reSeal.plan === null ? null : reSealParentCandidate;
2147
+ // What the WHOLE chain carries: a parent that is itself a
2148
+ // re-seal planned only the tests it re-ran, so its own plan
2149
+ // cannot count the rest. Absent a retained chain, the plan's own
2150
+ // count stands (a whole-suite parent, exactly as before).
2151
+ const reSealCarried = reSealPlan === null
2152
+ ? null
2153
+ : retainedChainCarriedTests({ stateDir, childFiles: reSealPlan.affectedFiles });
2154
+ if (reSealPlan !== null && reSealCarried !== null) {
2155
+ reSealPlan = { ...reSealPlan, carriedTests: reSealCarried.count };
2156
+ }
2157
+ // The parent's witness EVIDENCE is the copy the run RETAINED when
2158
+ // it sealed its own receipt or run record — never the live state
2159
+ // documents, which any run in between (a materialization
2160
+ // pre-step that rewrites `manifest.json`, a hand-picked
2161
+ // selection) has already overwritten. A re-seal carries a carried
2162
+ // test's outcomes AND the records those outcomes were witnessed
2163
+ // with — and in a chain, the records EVERY contributing run
2164
+ // witnessed, each under its own envelope.
2165
+ if (reSeal.plan !== null && reSealParent !== null) {
2166
+ const retained = readRetainedParentEvidence(stateDir);
2167
+ const contributors = retained === null
2168
+ ? null
2169
+ : retainedEvidenceContributors({
2170
+ stateDir,
2171
+ parent: { kind: reSealParent.kind, receipt: reSealParent.receipt, record: reSealParent.record },
2172
+ parentAttestation: retained.attestation,
2173
+ verifierKeyring,
2174
+ });
2175
+ const authenticated = retained === null || contributors === null
2176
+ ? { ok: false, reason: 'it retains no copy of the evidence its own document sealed' }
2177
+ : contributors.reason === null
2178
+ ? authenticateContributingEvidence(retained, contributors.contributors, verifierKeyring === null ? [] : verifierKeyring.keys.map((entry) => entry.key))
2179
+ : { ok: false, reason: contributors.reason };
2180
+ // The envelopes of every contributing run, kept for the chain
2181
+ // hop this re-seal writes: each run's records are authorized by
2182
+ // its own envelope and by nobody else's.
2183
+ const contributorAttestations = contributors?.contributors.map((contributor) => contributor.attestation) ?? [];
2184
+ if (!authenticated.ok) {
2185
+ writeLine(io.stderr, `test-gates: the previous run cannot be re-sealed from: ${authenticated.reason} ${RESEAL_REFUSAL_SUFFIX}`);
2186
+ reSealPlan = null;
2187
+ reSealParent = null;
2188
+ }
2189
+ else {
2190
+ const identities = reSealCarried?.identities ?? carriedTestIdentities(reSealParent.execution, reSeal.plan.affectedFiles);
2191
+ const carriedFiles = reSealCarried?.files ?? new Set(reSealParent.execution.outcomes
2192
+ .filter((outcome) => !reSeal.plan?.affectedFiles.includes(outcome.file))
2193
+ .map((outcome) => outcome.file));
2194
+ // A witness-issued record is stamped with the CLAIMING test's
2195
+ // identity, which for a mapped test is the mapping key: the
2196
+ // trusted resolution of this very run, never the record's word.
2197
+ for (const group of gradedResolution?.obligations ?? []) {
2198
+ for (const binding of group.bindings) {
2199
+ if (binding.instances.some((instance) => carriedFiles.has(instance.file))) {
2200
+ identities.add(binding.logicalKey);
2201
+ }
2202
+ }
2203
+ }
2204
+ const carriedDocuments = carriedEvidenceDocuments(authenticated.evidence, identities);
2205
+ reSealParentEvidence = {
2206
+ ...carriedDocuments,
2207
+ attestations: contributorAttestations,
2208
+ contributions: authenticated.evidence.contributions,
2209
+ contributingRunIds: [...new Set(authenticated.evidence.contributions.map((entry) => entry.runId))],
2210
+ };
2211
+ writeResealChainParentEvidence(stateDir, reSealParentEvidence);
2212
+ }
2213
+ }
2214
+ if (reSeal.plan !== null) {
2215
+ const affected = new Set(reSeal.plan.affectedFiles);
2216
+ plannedRows = fullPlannedRows.filter((row) => affected.has(row.planned.file) && !quarantinedKeys.has(row.planned.logicalKey));
2217
+ // The sealed parent proved every obligation in the repository;
2218
+ // this run re-proves the ones its re-run tests declare. The
2219
+ // covered set is that union, so a consumer's own diff-scoped
2220
+ // check still decides what the receipt covers.
2221
+ coveredFingerprints = [
2222
+ ...new Set(pipeline.policy.obligations.map((obligation) => obligationFingerprint(obligation))),
2223
+ ].sort();
2224
+ affectedRequiredFiles = reSeal.plan.affectedFiles;
2225
+ // A test-only change cannot open an obligation through app
2226
+ // sources, so the changed-scope "no testable slice" blockers
2227
+ // (the mapping gap this path exists to route around) do not
2228
+ // apply: the parent receipt already covered them.
2229
+ scopeBlockers = [];
2230
+ }
2231
+ else {
2232
+ plannedRows = affectedPlan.plannedRows.filter((row) => !quarantinedKeys.has(row.planned.logicalKey));
2233
+ coveredFingerprints = affectedPlan.coveredFingerprints;
2234
+ scopeBlockers = affectedPlan.unclaimed.map((entry) => ({
2235
+ kind: 'finding',
2236
+ resourceId: null,
2237
+ name: entry.obligationId,
2238
+ detail: entry.detail,
2239
+ location: null,
2240
+ cause: 'EVIDENCE_SCOPE_INCOMPLETE',
2241
+ nextAction: CAUSE_NEXT_ACTIONS.EVIDENCE_SCOPE_INCOMPLETE,
2242
+ }));
2243
+ if (affectedPlan.adopted.length > 0) {
2244
+ writeLine(io.stderr, `test-gates: ${String(affectedPlan.adopted.length)} affected obligation(s) have no declared ` +
2245
+ 'mapping and are forgiven by the adopted baseline; they stay uncovered by this slice');
2246
+ }
2247
+ }
2248
+ }
2249
+ }
2250
+ // Twin path coverage (E64): the linked raw/witnessed pairs this run
2251
+ // should compare, resolved BEFORE the suite runs so the witness can
2252
+ // wire the proxy and mark the raw twins' sessions observation-only.
2253
+ // Absent `enforcement.twinPaths` this is empty and the run is
2254
+ // byte-identical to a repository that never heard of twins.
2255
+ const twinPathsMode = config.enforcement?.twinPaths ?? null;
2256
+ const twinLinks = twinPathsMode === null || catalog === null
2257
+ ? []
2258
+ : twinLinksFor(catalog.entries.map((entry) => ({ logicalKey: entry.logicalKey, title: entry.title })), Object.fromEntries((behaviorSidecar?.tests ?? [])
2259
+ .filter((entry) => entry.twinOf !== undefined)
2260
+ .map((entry) => [entry.key, entry.twinOf])));
2261
+ // Twin coverage is only WORTH wiring when there is a pair to compare:
2262
+ // with the option on and no link, the run records no shape, writes no
2263
+ // inventory and adds no report key — byte-identical to a run that
2264
+ // never heard of twins.
2265
+ const twinComparisonOn = twinPathsMode !== null && twinLinks.length > 0;
2266
+ // The raw twins' REGISTERED identities (project, file, titlePath) —
2267
+ // not their runner test ids. The id the catalog enumerated is not the
2268
+ // id the test runs under: Playwright hashes the test's file path
2269
+ // relative to the config it loaded, so a supervised run driving a
2270
+ // trusted config from another directory mints different ids from the
2271
+ // same tests. The identity is the join key both sides speak.
2272
+ const twinRawIdentities = new Set();
2273
+ for (const link of twinLinks) {
2274
+ const raw = plannedRows.find((row) => row.planned.logicalKey === link.raw);
2275
+ if (raw !== undefined) {
2276
+ twinRawIdentities.add(`${raw.planned.project ?? ''}\u0000${raw.planned.file}\u0000${raw.planned.titlePath.join('>')}`);
2277
+ }
2278
+ }
2279
+ // Runner-agnostic expected set (plan 2026-09-25): a NON-Playwright
2280
+ // runner enumerates through the RunnerAdapter contract — the expected
2281
+ // set is fixed BEFORE the run from the runner's own collection, and
2282
+ // the plan is the enumeration (whole set in full scope, the claimed
2283
+ // files' slice in changed scope). `playwright` never runs this: its
2284
+ // planning above is byte-identical to before. An unavailable
2285
+ // enumeration plans nothing and blocks the inventory below — never a
2286
+ // guessed half-set, never a silent whole-suite widening.
2287
+ let runnerEnumeration = null;
2288
+ if (runnerName !== 'playwright' && catalog !== null && discoveryError === null) {
2289
+ // Bound to a `const` first: the plan below narrows on the ENUMERATION,
2290
+ // and a `let` that later feeds a closure reads as its own initializer
2291
+ // again. Nothing about the enumeration is assumed — an adapter that
2292
+ // cannot list its tests returns `status: 'unavailable'`, and that
2293
+ // plans nothing rather than planning a guessed half-set.
2294
+ const enumeration = await runnerAdapterFor(runnerName).enumerate(io.cwd);
2295
+ runnerEnumeration = enumeration;
2296
+ if (enumeration.status === 'discovered') {
2297
+ const enumeratedRows = enumeration.tests.map(plannedRowOfIdentity);
2298
+ fullPlannedCount = enumeratedRows.length;
2299
+ plannedRows =
2300
+ options.scope === 'changed'
2301
+ ? enumeratedRows.filter((row) => affectedRequiredFiles.includes(row.planned.file))
2302
+ : enumeratedRows;
729
2303
  }
730
2304
  }
2305
+ // Named selection (`--test`): the plan is built from the FULL planned
2306
+ // rows above and only then narrowed to the named logical keys, so the
2307
+ // expected set is still fixed before the run. An unresolvable selector
2308
+ // throws a UsageError (exit 2) before any witness or runner spawns.
2309
+ const namedSelections = options.testSelectors === undefined
2310
+ ? null
2311
+ : resolveTestSelectors(options.testSelectors, plannedRows.map((row) => ({ logicalKey: row.planned.logicalKey })));
2312
+ // The selected logical keys, hoisted for the grading step below: a
2313
+ // named run grades exactly the claims of the tests it ran.
2314
+ const namedTestIds = namedSelections === null
2315
+ ? null
2316
+ : [...new Set(namedSelections.flatMap((entry) => [...entry.logicalKeys]))].sort();
2317
+ // What the SELECTION declares, through EITHER surface: the trusted
2318
+ // mapping resolution's bindings (the sidecar) or the current claim
2319
+ // declarations of the selected tests (native Playwright annotations
2320
+ // and sidecar-derived claims). Both are the same current inventory
2321
+ // the verdict engine grades against; the union is the graded set of a
2322
+ // named run. A test that declares nothing contributes nothing.
2323
+ // A test-only re-seal grades exactly what its re-run tests declare:
2324
+ // every other obligation keeps the parent receipt's attested outcome,
2325
+ // which is digest-bound through `resealedFrom`.
2326
+ const gradedTestIds = namedTestIds ?? (reSealPlan === null ? null : plannedRows.map((row) => row.planned.logicalKey));
2327
+ const namedObligationIds = (() => {
2328
+ if (gradedTestIds === null)
2329
+ return null;
2330
+ const selected = new Set(gradedTestIds);
2331
+ // A claim names the declaring test the way its runner does: a
2332
+ // sidecar row carries the logical key, a native Playwright
2333
+ // annotation the framework id. The selected entries' own framework
2334
+ // identities are the second half of that join.
2335
+ const selectedFrameworks = new Set();
2336
+ for (const entry of catalog?.entries ?? []) {
2337
+ if (!selected.has(entry.logicalKey))
2338
+ continue;
2339
+ if (entry.parameterIdentity !== null && entry.parameterIdentity.length > 0) {
2340
+ selectedFrameworks.add(entry.parameterIdentity);
2341
+ }
2342
+ }
2343
+ const declared = new Set();
2344
+ for (const group of gradedResolution?.obligations ?? []) {
2345
+ if (group.bindings.some((binding) => selected.has(binding.logicalKey))) {
2346
+ declared.add(group.obligationId);
2347
+ }
2348
+ }
2349
+ for (const claim of claimInventory) {
2350
+ if (selected.has(claim.testId) || selectedFrameworks.has(claim.testId)) {
2351
+ declared.add(claim.obligationId);
2352
+ }
2353
+ }
2354
+ return [...declared].sort();
2355
+ })();
2356
+ if (namedSelections !== null) {
2357
+ const named = new Set(namedTestIds ?? []);
2358
+ plannedRows = plannedRows.filter((row) => named.has(row.planned.logicalKey));
2359
+ // A test this run did not execute can never have produced
2360
+ // evidence, so a claim row alone proves nothing: the graded SET is
2361
+ // `namedObligationIds` below, and the declaration inventory stays
2362
+ // whole. (A per-test filter here would silently drop a
2363
+ // declaration whose source location a sibling declaration in the
2364
+ // same file already occupies — the inventory is deduplicated per
2365
+ // source location, not per test.)
2366
+ }
2367
+ // Dependency closure for a NARROWED plan (`--scope changed` or
2368
+ // `--test`): Playwright runs a dependency project's tests before the
2369
+ // dependent project, so a plan that selected only a `chromium` test
2370
+ // must also carry the `setup` project's tests. Without them the run
2371
+ // executes the dependent test with no auth artifact (it fails), and
2372
+ // the `dependencies` edge the synthesized config would emit names a
2373
+ // project that config does not define — which Playwright refuses to
2374
+ // load at all. The closure reads the FULL planned set, and a FULL run
2375
+ // (or a config with no dependencies) already contains those rows, so
2376
+ // this adds nothing and the plan is byte-identical. The added rows
2377
+ // are part of the plan from here on: they are registered in the
2378
+ // expected set, scoped per project, and counted in the scope line.
2379
+ plannedRows = plannedRowsWithProjectDependencies(plannedRows, allPlannedRows, projectDependencies);
2380
+ // Per-test narrowing (additive): a named run hands the runner the exact
2381
+ // `file:line` of every selected test the catalog located, so a runner
2382
+ // that can filter below file granularity executes exactly those tests
2383
+ // and never their file neighbours. A row the catalog never located
2384
+ // contributes nothing (the run then stays at file granularity). Empty
2385
+ // outside a named run, which keeps every other run byte-identical.
2386
+ const namedTestLocations = namedSelections === null
2387
+ ? []
2388
+ : plannedRows
2389
+ .map((row) => {
2390
+ const entry = catalog?.entries.find((candidate) => candidate.logicalKey === row.planned.logicalKey);
2391
+ return entry === undefined ? null : `${entry.file}:${String(entry.sourceLocation.line)}`;
2392
+ })
2393
+ .filter((location) => location !== null)
2394
+ .sort();
2395
+ if (format === 'text') {
2396
+ writeLine(io.stdout, namedSelections !== null
2397
+ ? `scope: named (${plannedRows.length} tests) — ${humanMessage({ detail: 'a hand-picked test list never seals a receipt; a run of the whole suite does', type: 'partial-selection', nextAction: 'gateforge test-gates' })}`
2398
+ : options.scope === 'changed'
2399
+ ? `scope: changed (${plannedRows.length} tests) — ${providerChangedFiles.length} changed files (provider: ${providerIdentity})`
2400
+ : `scope: full (${fullPlannedCount} planned tests) — add --scope changed for the ${affectedTestCount} tests affected by ${providerChangedFiles.length} changed files (provider: ${providerIdentity})`);
2401
+ }
731
2402
  const inventoryBlocking = discoveryError !== null
732
2403
  ? [
733
2404
  {
@@ -740,26 +2411,44 @@ export async function runSupervisedTestGates(io, options) {
740
2411
  nextAction: CAUSE_NEXT_ACTIONS.TEST_INVENTORY_INCOMPLETE,
741
2412
  },
742
2413
  ]
743
- : !catalog?.inventoryComplete
744
- ? [
745
- {
746
- kind: 'finding',
747
- resourceId: null,
748
- name: null,
749
- detail: 'test inventory incomplete (parse errors, budget cuts, or unenumerated cases) — the expected set cannot be sealed over an incomplete inventory',
750
- location: null,
751
- cause: 'TEST_INVENTORY_INCOMPLETE',
752
- nextAction: CAUSE_NEXT_ACTIONS.TEST_INVENTORY_INCOMPLETE,
753
- },
754
- ]
755
- : [];
2414
+ : nativeErrors.length > 0
2415
+ ? nativeInventoryBlocking(nativeInventoryProblem(nativeErrors))
2416
+ : runnerEnumeration !== null && runnerEnumeration.status !== 'discovered'
2417
+ ? [
2418
+ {
2419
+ kind: 'finding',
2420
+ resourceId: null,
2421
+ name: null,
2422
+ detail: `the configured runner '${runnerName}' could not enumerate its expected set: ${runnerEnumeration.detail} — nothing executed proves nothing`,
2423
+ location: null,
2424
+ cause: 'TEST_INVENTORY_INCOMPLETE',
2425
+ nextAction: CAUSE_NEXT_ACTIONS.TEST_INVENTORY_INCOMPLETE,
2426
+ },
2427
+ ]
2428
+ : !catalog?.inventoryComplete
2429
+ ? [
2430
+ {
2431
+ kind: 'finding',
2432
+ resourceId: null,
2433
+ name: null,
2434
+ detail: 'test inventory incomplete (parse errors, budget cuts, or unenumerated cases) — the expected set cannot be sealed over an incomplete inventory',
2435
+ location: null,
2436
+ cause: 'TEST_INVENTORY_INCOMPLETE',
2437
+ nextAction: CAUSE_NEXT_ACTIONS.TEST_INVENTORY_INCOMPLETE,
2438
+ },
2439
+ ]
2440
+ : [];
756
2441
  const selection = {
757
- runner: 'playwright',
2442
+ runner: runnerName,
758
2443
  // The selection mode names the slice honestly: a scoped run seals
759
- // `mapped-selection` so its execution result (and every receipt
760
- // binding it) can never be mistaken for a whole-suite seal. The
761
- // digest covers the mode, so full and scoped receipts never collide.
762
- mode: options.scope === 'changed' ? 'mapped-selection' : 'full-relevant-suite',
2444
+ // `mapped-selection` and a hand-picked run reports `named-selection`,
2445
+ // so neither can ever be mistaken for a whole-suite seal. The digest
2446
+ // covers the mode, so full, scoped, and named runs never collide.
2447
+ mode: namedSelections !== null
2448
+ ? 'named-selection'
2449
+ : options.scope === 'changed'
2450
+ ? 'mapped-selection'
2451
+ : 'full-relevant-suite',
763
2452
  logicalKeys: plannedRows.map((row) => row.planned.logicalKey),
764
2453
  };
765
2454
  const selectionDigest = selectionDigestOf(selection);
@@ -812,6 +2501,7 @@ export async function runSupervisedTestGates(io, options) {
812
2501
  blocking: [...pipeline.policy.blocking, ...mappingBlockers, ...inventoryBlocking, ...scopeBlockers],
813
2502
  stateDir,
814
2503
  now: pipeline.now,
2504
+ engineAlembicRecords: pipeline.engineAlembicRecords,
815
2505
  // Scoped reuse re-grades exactly the sealed slice (the reuse
816
2506
  // contract above already pinned scope + covered set); full reuse
817
2507
  // stays unscoped. A scoped run without the flag never happens.
@@ -822,7 +2512,7 @@ export async function runSupervisedTestGates(io, options) {
822
2512
  // Goal 1: the reused gate grades through the SAME adopted-baseline
823
2513
  // seam as check — baselined obligations waive (loudly) instead of
824
2514
  // blocking the reused evaluation.
825
- baseline: resolveAdoptedBaseline(io.cwd, config.baselines),
2515
+ baseline: adoptedBaseline,
826
2516
  mappedCoverage,
827
2517
  evidenceContext: {
828
2518
  expectedInputDigest: expectedDigest,
@@ -837,8 +2527,11 @@ export async function runSupervisedTestGates(io, options) {
837
2527
  waiverCounts: evaluated.waiverCounts,
838
2528
  run: { ...pipeline.manifest, invocationId, inputDigest: expectedDigest ?? undefined },
839
2529
  toolVersion: VERSION,
2530
+ engine: engineIdentity(),
2531
+ engineLine: reportEngineLine(),
2532
+ lifecycleDerivation: pipeline.lifecycleDerivation,
840
2533
  diagnosticContext: {
841
- scope: options.scope ?? 'full',
2534
+ scope: namedTestIds !== null ? 'named' : (options.scope ?? 'full'),
842
2535
  candidateTreeId: frozenTreeId,
843
2536
  inputDigest: expectedDigest,
844
2537
  evidenceState: 'receipt-reused',
@@ -853,6 +2546,16 @@ export async function runSupervisedTestGates(io, options) {
853
2546
  guarantee: DOCS_EXCLUSIONS_GUARANTEE,
854
2547
  },
855
2548
  }),
2549
+ ...(cacheExclusions.length === 0
2550
+ ? {}
2551
+ : {
2552
+ cacheExclusions: {
2553
+ files: cacheExclusions,
2554
+ approvalDigest: approvedPolicyDigest ?? trustedPolicy,
2555
+ approvalStatus: 'matched',
2556
+ guarantee: CACHE_EXCLUSIONS_GUARANTEE,
2557
+ },
2558
+ }),
856
2559
  },
857
2560
  });
858
2561
  writeLine(io.stdout, report);
@@ -868,6 +2571,152 @@ export async function runSupervisedTestGates(io, options) {
868
2571
  // slice receipt over nothing is ever minted, and the previous receipt
869
2572
  // is invalidated (E07 discipline).
870
2573
  if (options.scope === 'changed' && plannedRows.length === 0) {
2574
+ const baseSha = resolveCarryForwardBaseSha(io, providerIdentity);
2575
+ const carryParent = !options.resultOnly &&
2576
+ expectedDigest !== null &&
2577
+ frozenTreeId !== null &&
2578
+ approvedPolicyDigest !== null &&
2579
+ baseSha !== null
2580
+ ? verifiedCarryForwardParent({
2581
+ io,
2582
+ config,
2583
+ stateDir,
2584
+ verifierKeyring,
2585
+ baseSha,
2586
+ gitDir: freezeGitDir,
2587
+ docsExclusions,
2588
+ cacheExclusions,
2589
+ trustedPolicyDigest: trustedPolicy,
2590
+ approvedPolicyDigest,
2591
+ executionBoundaryDigest,
2592
+ })
2593
+ : null;
2594
+ const playwrightConfig = findRunnerConfigPath(io.cwd, runnerName);
2595
+ const scopeDecision = catalog === null
2596
+ ? null
2597
+ : computeEvaluationScope({
2598
+ config,
2599
+ changedFiles: providerChangedFiles,
2600
+ testFiles: catalog.entries.map((entry) => entry.file),
2601
+ runnerConfigs: playwrightConfig === null ? [] : [playwrightConfig],
2602
+ mappingSidecar: existsSync(join(io.cwd, ...TEST_MAP_RELATIVE.split('/'))),
2603
+ knownSourceFiles: pipeline.graph.resources.map((resource) => resource.source),
2604
+ strictE2E: false,
2605
+ });
2606
+ const behaviorBindings = behaviorReceiptBindings(pipeline.behaviorCatalog);
2607
+ const scannedEveryChangedFile = providerChangedFiles.length > 0 &&
2608
+ config.plugins.length > 0 &&
2609
+ pipeline.contributions.length === config.plugins.length &&
2610
+ providerChangedFiles.every((path) => pipeline.contributions.every((contribution) => contribution.scannedPaths?.includes(path) === true));
2611
+ // A sealed candidate tree carries gitignored and untracked bytes,
2612
+ // so a verified parent proves the outcomes for ITS bytes. The
2613
+ // plain carry-forward evaluates only the provider's changed files,
2614
+ // so it may reuse the parent's outcomes exclusively when the two
2615
+ // sealed trees differ in nothing else — a gitignored dependency or
2616
+ // an untracked file would be a proof nobody produced. (The re-seal
2617
+ // path needs no such test: it classifies the whole difference.)
2618
+ const carryDiffWithinScope = carryParent !== null &&
2619
+ frozenTreeId !== null &&
2620
+ freezeGitDir !== null &&
2621
+ scopeDecision !== null &&
2622
+ carryDiffIsWithinScope({
2623
+ gitDir: freezeGitDir,
2624
+ env: io.env,
2625
+ parentTreeId: carryParent.treeId,
2626
+ currentTreeId: frozenTreeId,
2627
+ evaluatedPaths: scopeDecision.changedFiles,
2628
+ });
2629
+ // A planned re-seal is never a carry-forward: it re-runs the
2630
+ // affected tests and seals its own receipt. `affectedTestCount`
2631
+ // is the CHANGED-SCOPE plan's count, which a test-only change
2632
+ // leaves at zero — exactly the case this path would swallow.
2633
+ const carryIsSafe = reSealPlan === null &&
2634
+ carryParent !== null &&
2635
+ expectedDigest !== null &&
2636
+ frozenTreeId !== null &&
2637
+ pipeline.manifest.gitSha !== null &&
2638
+ catalog?.inventoryComplete === true &&
2639
+ discoveryError === null &&
2640
+ scopeDecision?.mode === 'changed' &&
2641
+ scopeDecision.expandedBecause.length === 0 &&
2642
+ scopeDecision.unmappedFiles.length === 0 &&
2643
+ carryDiffWithinScope &&
2644
+ coveredFingerprints.length === 0 &&
2645
+ affectedTestCount === 0 &&
2646
+ scopeBlockers.length === 0 &&
2647
+ mappingBlockers.length === 0 &&
2648
+ inventoryBlocking.length === 0 &&
2649
+ pipeline.policy.blocking.length === 0 &&
2650
+ (config.diagnostics?.suites.length ?? 0) === 0 &&
2651
+ pipeline.policy.obligations.length === carryParent.receipt.verdictSummary.total &&
2652
+ carryParent.receipt.behaviorCatalogDigest === behaviorBindings.behaviorCatalogDigest &&
2653
+ carryParent.receipt.requiredCaseSetDigest === behaviorBindings.requiredCaseSetDigest &&
2654
+ scannedEveryChangedFile;
2655
+ const activeVerifierKeyring = verifierKeyring;
2656
+ if (carryIsSafe &&
2657
+ activeVerifierKeyring !== null &&
2658
+ baseSha !== null &&
2659
+ pipeline.manifest.gitSha !== null &&
2660
+ freezeGitDir !== null &&
2661
+ carryParent !== null &&
2662
+ expectedDigest !== null &&
2663
+ frozenTreeId !== null) {
2664
+ const candidateSnapshot = computeCandidateTreeSnapshot(freezeGitDir, io.cwd, io.env, stateDir, 'record', runtimeReuseMounts, docsExclusions, cacheExclusions);
2665
+ if (candidateSnapshot.treeId === frozenTreeId) {
2666
+ const carried = issueGateReceipt({
2667
+ verifierKey: activeVerifierKeyring.active.key,
2668
+ verifierKeyId: activeVerifierKeyring.active.keyId,
2669
+ runId: carryParent.receipt.runId,
2670
+ invocationId: carryParent.receipt.invocationId,
2671
+ inputDigest: expectedDigest,
2672
+ gitSha: pipeline.manifest.gitSha,
2673
+ parentSha: baseSha,
2674
+ trustedPolicyDigest: trustedPolicy,
2675
+ approvedPolicyDigest,
2676
+ receiptStage: config.enforcement?.receiptStage,
2677
+ engine: engineIdentity(),
2678
+ carriedFrom: baseSha,
2679
+ parentReceiptDigest: carryParent.receiptDigest,
2680
+ invocation: carryParent.receipt.invocation,
2681
+ selectionDigest: carryParent.receipt.selectionDigest,
2682
+ catalogDigest: carryParent.receipt.catalogDigest,
2683
+ executionResultDigest: carryParent.receipt.executionResultDigest,
2684
+ evidenceAttestationDigest: carryParent.receipt.evidenceAttestationDigest,
2685
+ candidateTreeId: frozenTreeId,
2686
+ behaviorCatalogDigest: behaviorBindings.behaviorCatalogDigest,
2687
+ requiredCaseSetDigest: behaviorBindings.requiredCaseSetDigest,
2688
+ caseExecutionDigest: carryParent.receipt.caseExecutionDigest,
2689
+ engineBundleDigest: engineBundleDigestOf(VERSION, trustedPolicy),
2690
+ executionBoundaryDigest,
2691
+ targetArtifactDigest: targetArtifactDigestOf(frozenTreeId),
2692
+ verdictSummary: carryParent.receipt.verdictSummary,
2693
+ issuedAt: pipeline.now,
2694
+ });
2695
+ const carryReport = canonicalJson({
2696
+ schemaVersion: 1,
2697
+ carriedForward: true,
2698
+ carriedFrom: baseSha,
2699
+ parentReceiptDigest: carryParent.receiptDigest,
2700
+ receiptId: carried.receiptId,
2701
+ candidateTreeId: frozenTreeId,
2702
+ inputDigest: expectedDigest,
2703
+ scope: 'changed',
2704
+ changedFiles: [...providerChangedFiles],
2705
+ testsPerformedThisInvocation: 0,
2706
+ summary: carryParent.receipt.verdictSummary,
2707
+ evidenceState: 'receipt-carried-forward',
2708
+ engine: { ...engineIdentity() },
2709
+ });
2710
+ writeGateReceipt(stateDir, carried);
2711
+ writeCandidateTreeEntries(stateDir, candidateSnapshot.entries);
2712
+ writeReport(stateDir, carryReport);
2713
+ writeLine(io.stdout, format === 'json'
2714
+ ? carryReport
2715
+ : `receipt ${carried.receiptId} carried forward from ${baseSha}; 0 tests run; full parent receipt and complete changed-file scan verified`);
2716
+ writeLine(io.stderr, `receipt ${carried.receiptId} carried forward; 0 tests performed this invocation`);
2717
+ return 0;
2718
+ }
2719
+ }
871
2720
  if (!options.resultOnly)
872
2721
  clearGateReceipt(stateDir);
873
2722
  const emptySliceBlocking = inventoryBlocking.length > 0
@@ -879,9 +2728,11 @@ export async function runSupervisedTestGates(io, options) {
879
2728
  resourceId: null,
880
2729
  name: null,
881
2730
  detail: scopeBlockers.length > 0
882
- ? `changed-scope planning produced no testable slice: ${String(scopeBlockers.length)} affected obligation(s) ` +
883
- 'have no declared mapping to a test the current catalog enumerates — narrower selection is never guessed'
884
- : 'changed-scope planning found no obligations affected by the changed files — a slice receipt over nothing is never sealed; run full scope',
2731
+ ? `no runnable slice: ${String(scopeBlockers.length)} affected obligation(s) have no declared mapping; changed files: ` +
2732
+ `${providerChangedFiles.length > 0 ? providerChangedFiles.join(', ') : '<none>'}. ` +
2733
+ 'Run `gateforge test-gates --changed` for the full relevant suite.'
2734
+ : `0 obligations affected by: ${providerChangedFiles.length > 0 ? providerChangedFiles.join(', ') : '<no changed files>'}; ` +
2735
+ 'run full scope, or approve documentation folders with `gateforge init --docs-exclude <folders>`',
885
2736
  location: null,
886
2737
  cause: 'EVIDENCE_SCOPE_INCOMPLETE',
887
2738
  nextAction: CAUSE_NEXT_ACTIONS.EVIDENCE_SCOPE_INCOMPLETE,
@@ -902,11 +2753,12 @@ export async function runSupervisedTestGates(io, options) {
902
2753
  ],
903
2754
  stateDir,
904
2755
  now: pipeline.now,
2756
+ engineAlembicRecords: pipeline.engineAlembicRecords,
905
2757
  changedFiles: scopeChangedFiles,
906
2758
  claimInventory,
907
2759
  witnessVerifierKey,
908
2760
  witnessVerifierKeys: verifierKeyring?.keys.map((entry) => entry.key),
909
- baseline: resolveAdoptedBaseline(io.cwd, config.baselines),
2761
+ baseline: adoptedBaseline,
910
2762
  mappedCoverage,
911
2763
  evidenceContext: {
912
2764
  expectedInputDigest: expectedDigest,
@@ -921,6 +2773,30 @@ export async function runSupervisedTestGates(io, options) {
921
2773
  waiverCounts: evaluated.waiverCounts,
922
2774
  run: { ...pipeline.manifest, invocationId, inputDigest: expectedDigest ?? undefined },
923
2775
  toolVersion: VERSION,
2776
+ engine: engineIdentity(),
2777
+ engineLine: reportEngineLine(),
2778
+ lifecycleDerivation: pipeline.lifecycleDerivation,
2779
+ diagnosticContext: {
2780
+ scope: namedTestIds !== null ? 'named' : (options.scope ?? 'full'),
2781
+ candidateTreeId: frozenTreeId,
2782
+ inputDigest: expectedDigest,
2783
+ evidenceState: snapshotUnavailable ? 'snapshot-unavailable' : 'not-executed',
2784
+ // Nothing ran, so nothing was delayed: the seed is still named,
2785
+ // with an empty schedule, rather than a run that quietly forgets
2786
+ // it was asked to perturb timing.
2787
+ ...(chaosRun === null ? {} : { chaos: { ...chaosRun, schedule: [] } }),
2788
+ authority: options.resultOnly ? 'non-authoritative' : 'authoritative',
2789
+ ...(cacheExclusions.length === 0
2790
+ ? {}
2791
+ : {
2792
+ cacheExclusions: {
2793
+ files: cacheExclusions,
2794
+ approvalDigest: approvedPolicyDigest ?? trustedPolicy,
2795
+ approvalStatus: 'matched',
2796
+ guarantee: CACHE_EXCLUSIONS_GUARANTEE,
2797
+ },
2798
+ }),
2799
+ },
924
2800
  });
925
2801
  writeLine(io.stdout, report);
926
2802
  writeLine(io.stderr, 'test-gates: --scope changed produced no runnable slice — nothing was executed and no receipt was sealed');
@@ -940,6 +2816,15 @@ export async function runSupervisedTestGates(io, options) {
940
2816
  writeObligations(stateDir, stateObligations(pipeline.policy.obligations, pipeline.graph));
941
2817
  writeHttpRoutesView(stateDir, httpRoutes);
942
2818
  writeClassificationsView(stateDir, pipeline.classificationsView);
2819
+ // The route inventory a recorded twin shape resolves against, so a
2820
+ // shape names a route template (`/accounts/{}`) and never a concrete
2821
+ // id. Written ONLY when a pair can actually be compared: a run with
2822
+ // the option on and no link adds no state file at all.
2823
+ const twinQueryKeys = config.enforcement?.twinQueryKeys ?? [];
2824
+ const twinInventoryPath = join(stateDir, 'twin-inventory.json');
2825
+ if (twinComparisonOn) {
2826
+ writeTwinInventory(twinInventoryPath, httpRoutes.map((route) => route.canonicalPath).filter((template) => template.length > 0));
2827
+ }
943
2828
  let runToken = options.runToken ?? randomUUID();
944
2829
  let spawnedWitness = null;
945
2830
  if (witnessUrl !== undefined) {
@@ -983,6 +2868,78 @@ export async function runSupervisedTestGates(io, options) {
983
2868
  ...(io.env['GATEFORGE_PROBE_DB_CONTAINER'] !== undefined && io.env['GATEFORGE_PROBE_DB_CONTAINER'] !== ''
984
2869
  ? { GATEFORGE_PROBE_DB_CONTAINER: io.env['GATEFORGE_PROBE_DB_CONTAINER'] }
985
2870
  : {}),
2871
+ // Browser cache the ENGINE's own Chromium comes from. The
2872
+ // doctor and the run preflight read this same variable through
2873
+ // `io.env`, so it is forwarded explicitly rather than inherited
2874
+ // from `process.env`: an injected Io environment would
2875
+ // otherwise let the readiness checks inspect one cache while the
2876
+ // witness child launched from another, and the engine browser
2877
+ // would fail with "Executable doesn't exist" for a directory the
2878
+ // operator was just told was ready. An operator-chosen directory,
2879
+ // never a secret (same class as HOME).
2880
+ ...(io.env['PLAYWRIGHT_BROWSERS_PATH'] !== undefined && io.env['PLAYWRIGHT_BROWSERS_PATH'] !== ''
2881
+ ? { PLAYWRIGHT_BROWSERS_PATH: io.env['PLAYWRIGHT_BROWSERS_PATH'] }
2882
+ : {}),
2883
+ // Trusted fixture/actor provider (non-secret path): strong
2884
+ // behavior cases mint their fixtures and actor credentials from
2885
+ // the operator's approved module, engine-side. The suite never
2886
+ // sees it, and without it the cases block fail-closed.
2887
+ ...(io.env['GATEFORGE_FIXTURE_PROVIDER'] !== undefined &&
2888
+ io.env['GATEFORGE_FIXTURE_PROVIDER'] !== ''
2889
+ ? { GATEFORGE_FIXTURE_PROVIDER: io.env['GATEFORGE_FIXTURE_PROVIDER'] }
2890
+ : {}),
2891
+ // Engine-owned queue observer: the
2892
+ // witness reads the delivery queue itself, so a repository with a
2893
+ // `queueObserver` block hands it the approved declaration (the
2894
+ // connection material stays in the witness process). Without the
2895
+ // block nothing is passed and every `engine-task` case blocks
2896
+ // fail-closed — the spawn environment stays byte-identical.
2897
+ ...(config.queueObserver === undefined
2898
+ ? {}
2899
+ : {
2900
+ GATEFORGE_QUEUE_OBSERVER: config.queueObserver.kind,
2901
+ GATEFORGE_QUEUE_OBSERVER_CONFIG: JSON.stringify(config.queueObserver),
2902
+ }),
2903
+ // Suite-driven Observe claims need session-attributed traffic too.
2904
+ // Engine-driven Playwright repositories without these declarations
2905
+ // keep their existing proxy-free wiring.
2906
+ ...(runnerName === 'pytest' || runnerName === 'vitest' || runnerName === 'cypress' ||
2907
+ (runnerName === 'playwright' && observeObligations.length > 0)
2908
+ ? appBase !== ''
2909
+ ? { [ENV_PROXY_TARGET]: appBase }
2910
+ : {}
2911
+ : {}),
2912
+ // Timing chaos (E63): the seeded release plan, plus — for the
2913
+ // Playwright path, whose sessions are engine-browser scoped and
2914
+ // therefore proxy-free by default — the observation proxy the
2915
+ // plan delays. Both are strictly opt-in: without `--chaos` this
2916
+ // spawn is byte-identical to the one it always was.
2917
+ ...(chaosRun === null
2918
+ ? {}
2919
+ : {
2920
+ [ENV_CHAOS_SEED]: String(chaosRun.seed),
2921
+ [ENV_CHAOS_MAX_DELAY_MS]: String(chaosRun.maxDelayMs),
2922
+ [ENV_CHAOS_REORDER]: chaosRun.reorder ? 'on' : 'off',
2923
+ ...(appBase !== '' ? { [ENV_PROXY_TARGET]: appBase } : {}),
2924
+ }),
2925
+ // Twin path coverage (E64): the observation-only shape
2926
+ // recording, the owner's query-key allowlist and the route
2927
+ // inventory the shapes resolve against. Like chaos, the
2928
+ // Playwright path needs the observation proxy wired explicitly
2929
+ // (its sessions are engine-browser scoped and therefore
2930
+ // proxy-free by default), because a shape can only come from a
2931
+ // request the proxy saw. The raw twins themselves are NOT
2932
+ // listed here: their mark travels with the expected-set
2933
+ // registration, keyed by identity. With no link to compare this
2934
+ // spawn is byte-identical to the one it always was.
2935
+ ...(twinComparisonOn
2936
+ ? {
2937
+ [ENV_TWIN_SHAPES]: 'on',
2938
+ ...(twinQueryKeys.length > 0 ? { [ENV_TWIN_QUERY_KEYS]: twinQueryKeys.join(',') } : {}),
2939
+ [ENV_TWIN_INVENTORY]: twinInventoryPath,
2940
+ ...(appBase !== '' ? { [ENV_PROXY_TARGET]: appBase } : {}),
2941
+ }
2942
+ : {}),
986
2943
  });
987
2944
  }
988
2945
  catch (error) {
@@ -993,20 +2950,79 @@ export async function runSupervisedTestGates(io, options) {
993
2950
  if (expectedDigest !== null) {
994
2951
  manifest = { ...manifest, invocationId, inputDigest: expectedDigest };
995
2952
  }
2953
+ // The run OPTIONS (chaos, twin shapes) travel with the context, so a
2954
+ // repository that starts its OWN witness gets both features with
2955
+ // nothing configured on the witness side. A run that asks for
2956
+ // nothing sends no `options` key at all: the body is byte-identical
2957
+ // to what it always was.
2958
+ const runOptions = {
2959
+ ...(chaosRun === null ? {} : { chaos: chaosRun }),
2960
+ ...(twinComparisonOn
2961
+ ? {
2962
+ twinShapes: {
2963
+ queryKeys: twinQueryKeys,
2964
+ inventory: httpRoutes.map((route) => route.canonicalPath).filter((template) => template.length > 0),
2965
+ },
2966
+ }
2967
+ : {}),
2968
+ };
2969
+ let appliedOptions = null;
996
2970
  if (effectiveWitnessUrl !== undefined &&
997
2971
  witnessVerifierKey !== undefined &&
998
2972
  expectedDigest !== null) {
999
- await bindWitnessContext(effectiveWitnessUrl, runToken, witnessVerifierKey, {
2973
+ appliedOptions = await bindWitnessContext(effectiveWitnessUrl, runToken, witnessVerifierKey, {
1000
2974
  runId: manifest.runId,
1001
2975
  invocationId,
1002
2976
  inputDigest: expectedDigest,
2977
+ ...(Object.keys(runOptions).length === 0 ? {} : { options: runOptionsJson(runOptions) }),
2978
+ });
2979
+ }
2980
+ // A witness that does not echo its options is older than them, and
2981
+ // this run would then perturb or compare nothing while reporting as
2982
+ // if it had. Say which, rather than reporting the fiction.
2983
+ if (chaosRun !== null && appliedOptions?.chaos == null) {
2984
+ if (spawnedWitness !== null)
2985
+ await stopWitnessProcess(spawnedWitness);
2986
+ throw new UsageError(`test-gates: --chaos ${String(chaosRun.seed)} needs a witness that accepts run options; the witness at ` +
2987
+ `'${effectiveWitnessUrl ?? ''}' confirmed no chaos plan, so no schedule was applied and this run would ` +
2988
+ 'report a finding it never made — upgrade the witness');
2989
+ }
2990
+ if (twinComparisonOn && appliedOptions?.twinShapes == null) {
2991
+ writeLine(io.stderr, 'test-gates: twin path coverage needs a witness that accepts run options — this witness does not; ' +
2992
+ 'pairs were not compared');
2993
+ }
2994
+ // A witness that perturbs timing on its OWN (its environment, never
2995
+ // this run's binding) can never serve a run that seals.
2996
+ if (chaosRun === null &&
2997
+ witnessUrl !== undefined &&
2998
+ effectiveWitnessUrl !== undefined &&
2999
+ witnessVerifierKey !== undefined) {
3000
+ await refuseChaosWitnessOnSealingRun(effectiveWitnessUrl, runToken, witnessVerifierKey);
3001
+ }
3002
+ // The compiled behavior catalog is a PRE-run fact, so the witness binds
3003
+ // it now — before any session opens — exactly like the run context. A
3004
+ // repository with no behavior document makes no call and runs
3005
+ // byte-identical; a refused bind fails the run instead of leaving every
3006
+ // behavior obligation silently unprovable.
3007
+ if (effectiveWitnessUrl !== undefined &&
3008
+ witnessVerifierKey !== undefined &&
3009
+ pipeline.behaviorCatalog !== null &&
3010
+ pipeline.behaviorCatalog.cases.length > 0) {
3011
+ await registerWitnessBehaviorCatalog({
3012
+ witnessUrl: effectiveWitnessUrl,
3013
+ runToken,
3014
+ verifierKey: witnessVerifierKey,
3015
+ catalog: pipeline.behaviorCatalog,
3016
+ assignments: behaviorCaseAssignments(catalog ?? EMPTY_CATALOG, behaviorSidecar),
3017
+ routes: httpRoutes,
3018
+ authorityProfileDigest: engineBundleDigestOf(VERSION, trustedPolicy),
1003
3019
  });
1004
3020
  }
1005
3021
  writeManifest(stateDir, manifest);
1006
3022
  writeObligations(stateDir, stateObligations(pipeline.policy.obligations, pipeline.graph));
1007
3023
  writeHttpRoutesView(stateDir, httpRoutes);
1008
3024
  writeClassificationsView(stateDir, pipeline.classificationsView);
1009
- const envRecord = writeEnv(stateDir, manifest, effectiveWitnessUrl ?? null, runToken);
3025
+ const envRecord = writeEnv(stateDir, manifest, effectiveWitnessUrl ?? null, runToken, io.env);
1010
3026
  writeClaimInjections(stateDir, injections);
1011
3027
  // 4.5 Supervisor credentials are REQUIRED in supervised mode (review
1012
3028
  // fixes 2/3): the expected-set registration, the session-lifecycle
@@ -1024,30 +3040,67 @@ export async function runSupervisedTestGates(io, options) {
1024
3040
  }
1025
3041
  const supervisor = new SupervisorClient(effectiveWitnessUrl, runToken, witnessVerifierKey);
1026
3042
  // 4.6 Expected-set registration BEFORE the run (review fix 2a): the
1027
- // expected tests come from an INDEPENDENT enumeration — a separate
1028
- // `playwright --list` child with a scrubbed (GATEFORGE-free) env and a
1029
- // finite timeout — never from suite-writable state. The witness binds
1030
- // the set to this run; from now on /sessions/open accepts only tests
1031
- // in it, and the execution trace groups sessions by these identities.
1032
- const enumeration = await listNativePlaywrightTests({ cwd: io.cwd });
1033
- // Scoped registration (Goal 2): in a `changed`-scope run the expected
1034
- // set IS the planned slice — the witness binds and the trace groups
1035
- // exactly the tests the seal will vouch for. Full mode registers the
1036
- // whole enumeration, byte-identical to before. (A planned instance the
1037
- // enumeration never lists stays out of the set and can never open a
1038
- // session — the same completeness machinery blocks it downstream.)
3043
+ // expected tests come from an INDEPENDENT enumeration — Playwright
3044
+ // through a separate `playwright --list` child with a scrubbed
3045
+ // (GATEFORGE-free) env and a finite timeout; pytest/vitest/cypress
3046
+ // through the contract adapter's enumerate() — never from
3047
+ // suite-writable state. The witness binds the set to this run; from
3048
+ // now on /sessions/open accepts only tests in it, and the execution
3049
+ // trace groups sessions by these identities.
1039
3050
  const plannedIdentities = new Set(plannedRows.map((row) => `${row.planned.project ?? ''}\u0000${row.planned.file}\u0000${row.planned.titlePath.join('>')}`));
1040
- const registeredInstances = options.scope === 'changed'
1041
- ? enumeration.instances.filter((instance) => plannedIdentities.has(`${instance.project ?? ''}\u0000${instance.file}\u0000${instance.titlePath.join('>')}`))
1042
- : enumeration.instances;
1043
- const registered = await supervisor.registerExpectedSet({
1044
- tests: registeredInstances.map((instance) => ({
1045
- testId: instance.frameworkId,
1046
- project: instance.project.length > 0 ? instance.project : null,
1047
- file: instance.file,
1048
- titlePath: instance.titlePath,
1049
- })),
1050
- });
3051
+ const registered = await (async () => {
3052
+ if (runnerName !== 'playwright') {
3053
+ // The contract enumeration (fixed above, before the policy gate
3054
+ // boundaries) IS the independent expected set. The runner's own
3055
+ // spool identity is registered so the trace names what the child
3056
+ // will report.
3057
+ const tests = (runnerEnumeration?.tests ?? [])
3058
+ .filter((test) => options.scope === 'changed' || selection.mode === 'named-selection'
3059
+ ? plannedIdentities.has(`${test.project ?? ''}\u0000${test.file}\u0000${test.titlePath.join('>')}`)
3060
+ : true)
3061
+ .map((test) => ({
3062
+ testId: test.frameworkId ?? test.logicalKey,
3063
+ project: test.project,
3064
+ file: test.file,
3065
+ titlePath: [...test.titlePath],
3066
+ ...(twinRawIdentities.has(`${test.project ?? ''}\u0000${test.file}\u0000${test.titlePath.join('>')}`)
3067
+ ? { observationOnly: true }
3068
+ : {}),
3069
+ }));
3070
+ return supervisor.registerExpectedSet({ tests });
3071
+ }
3072
+ const enumeration = await listNativePlaywrightTests({ cwd: io.cwd });
3073
+ // A named run registers the NAMED tests, for the same reason it
3074
+ // executes them: the witness binds and the trace groups exactly the
3075
+ // tests the report will speak about.
3076
+ // Scoped registration (Goal 2): in a `changed`-scope run the expected
3077
+ // set IS the planned slice — the witness binds and the trace groups
3078
+ // exactly the tests the seal will vouch for. Full mode registers the
3079
+ // whole enumeration, byte-identical to before. (A planned instance the
3080
+ // enumeration never lists stays out of the set and can never open a
3081
+ // session — the same completeness machinery blocks it downstream.)
3082
+ const registeredInstances = options.scope === 'changed' || selection.mode === 'named-selection'
3083
+ ? enumeration.instances.filter((instance) => plannedIdentities.has(`${instance.project ?? ''}\u0000${instance.file}\u0000${instance.titlePath.join('>')}`))
3084
+ : enumeration.instances;
3085
+ return supervisor.registerExpectedSet({
3086
+ tests: registeredInstances.map((instance) => ({
3087
+ testId: instance.frameworkId,
3088
+ project: instance.project.length > 0 ? instance.project : null,
3089
+ file: instance.file,
3090
+ titlePath: instance.titlePath,
3091
+ // Twin path coverage (E64): a raw twin is marked by its
3092
+ // REGISTERED IDENTITY, which is the one part of a registration
3093
+ // that is the same in enumeration and execution. Its runner test
3094
+ // id is not: Playwright derives it from the test's file path
3095
+ // relative to the config it loaded, so an id enumerated from the
3096
+ // repository's own config is not the id the supervised run
3097
+ // opens the session with.
3098
+ ...(twinRawIdentities.has(`${instance.project ?? ''}\u0000${instance.file}\u0000${instance.titlePath.join('>')}`)
3099
+ ? { observationOnly: true }
3100
+ : {}),
3101
+ })),
3102
+ });
3103
+ })();
1051
3104
  // Progress goes to stderr: with --format json, stdout carries ONLY the
1052
3105
  // machine-readable report.
1053
3106
  writeLine(io.stderr, `expected set registered (${String(registered.count)} test(s), digest ${registered.enumerationDigest.slice(0, 12)}…)`);
@@ -1062,25 +3115,21 @@ export async function runSupervisedTestGates(io, options) {
1062
3115
  // paths as constructor options. The child env therefore carries ONLY
1063
3116
  // the witness URL + run token + app base — never run-state paths
1064
3117
  // (execution-authority fix; `buildRunnerChildEnv` refuses them).
1065
- const adapter = new PlaywrightAdapter({
1066
- config,
1067
- run: {
1068
- testFiles: plannedRows.map((row) => row.planned.file),
1069
- ...(io.env['GATEFORGE_APP_BASE_URL'] ? { appBaseUrl: io.env['GATEFORGE_APP_BASE_URL'] } : {}),
1070
- ...(io.env['GATEFORGE_SESSION_STATE'] ? { storageState: io.env['GATEFORGE_SESSION_STATE'] } : {}),
1071
- projects: [
1072
- ...new Set(plannedRows.map((row) => row.planned.project).filter((project) => project !== null)),
1073
- ],
1074
- // Operator-provided whole-run bound for multi-hour suites (default
1075
- // 30 minutes stands when absent — same expected set and
1076
- // completeness rules either way).
1077
- ...(runTimeoutMs !== undefined ? { timeoutMs: runTimeoutMs } : {}),
1078
- },
1079
- });
1080
- const suiteEnv = {
1081
- GATEFORGE_RUN_TOKEN: envRecord.GATEFORGE_RUN_TOKEN,
1082
- GATEFORGE_CLI_VERSION: VERSION,
1083
- };
3118
+ // Non-Playwright runners skip this entire Playwright-specific block:
3119
+ // their trusted wiring crosses to the child through the adapter
3120
+ // constructor (runnerAdapterFor below), and their registration comes
3121
+ // from the contract enumeration (4.6), so there is no Playwright
3122
+ // --list to re-diff.
3123
+ // A record with NO prototype, not an object literal: the declared
3124
+ // runtime allowlist below carries arbitrary operator-chosen NAMES, and
3125
+ // `__proto__` is both a legal one and a property every plain object
3126
+ // inherits — assigning it to a literal stores no own key at all (the
3127
+ // inherited accessor swallows it), so the name would silently vanish
3128
+ // from the child's own baseline and the freeze controller could never
3129
+ // project a body worker back to it.
3130
+ const suiteEnv = Object.create(null);
3131
+ suiteEnv['GATEFORGE_RUN_TOKEN'] = envRecord.GATEFORGE_RUN_TOKEN;
3132
+ suiteEnv['GATEFORGE_CLI_VERSION'] = VERSION;
1084
3133
  if (envRecord.GATEFORGE_WITNESS_URL !== null) {
1085
3134
  suiteEnv['GATEFORGE_WITNESS_URL'] = envRecord.GATEFORGE_WITNESS_URL;
1086
3135
  }
@@ -1093,6 +3142,186 @@ export async function runSupervisedTestGates(io, options) {
1093
3142
  if (typeof value === 'string' && value !== '')
1094
3143
  suiteEnv[name] = value;
1095
3144
  }
3145
+ if (declaredRunnerEnvNames !== undefined) {
3146
+ for (const name of declaredRunnerEnvNames) {
3147
+ // OWN membership on the ambient environment, for the same reason the
3148
+ // record above has no prototype: a declared name is an arbitrary
3149
+ // name, and `__proto__`, `constructor` and `toString` are properties
3150
+ // every plain object inherits, so a plain lookup would put `Object`
3151
+ // or `Object.prototype` itself into the baseline for a variable the
3152
+ // operator never set.
3153
+ if (!Object.hasOwn(io.env, name))
3154
+ continue;
3155
+ const value = io.env[name];
3156
+ if (value !== undefined && value !== '')
3157
+ suiteEnv[name] = value;
3158
+ }
3159
+ }
3160
+ // 6.1 The GLOBAL native preparation freeze: ONE native process, ONE
3161
+ // prepared candidate. A native prerequisite stage produces its
3162
+ // artifacts — the standard auth pattern's saved session above all —
3163
+ // WHILE the behavioral projects are already scheduled, so a candidate
3164
+ // frozen only before the spawn can never equal the workspace the bodies
3165
+ // actually run against. The engine therefore adds ONE controller
3166
+ // project, gives it the full upstream prerequisite closure of the
3167
+ // planned captured graph, gives every other planned project that
3168
+ // controller as a dependency, and freezes the candidate exactly once in
3169
+ // between. Nothing else moves: an operator's whole-run state still
3170
+ // outranks every declaration and bypasses this path exactly as before, a
3171
+ // run that planned no project has nothing to freeze, and a non-native
3172
+ // runner never enters it.
3173
+ const plannedScopes = plannedProjectScopes(plannedRows, projectDependencies, projectStorageStates);
3174
+ let freezePlan = null;
3175
+ let freezeTargets = null;
3176
+ let freezePrerequisites = [];
3177
+ let freezeKeys = null;
3178
+ let freezeNonce = null;
3179
+ // The barrier needs a REAL Playwright child: its own phase scheduler,
3180
+ // worker host and `playwright/test` module are what order the
3181
+ // controller between the prerequisites and the bodies. The predicate
3182
+ // is the same one the pack applies before it emits the controller
3183
+ // project, so both sides agree on whether a barrier is possible.
3184
+ const nativeRunnerCommand = runnerName === 'playwright' ? defaultPlaywrightCommand(io.cwd) : null;
3185
+ if (nativeRunnerCommand !== null &&
3186
+ plannedScopes.length > 0 &&
3187
+ isPlaywrightRunnerInstall(nativeRunnerCommand) &&
3188
+ io.env['GATEFORGE_SESSION_STATE'] === undefined) {
3189
+ try {
3190
+ const plan = planNativeFreeze({
3191
+ projectScopes: plannedScopes,
3192
+ projectDependencies: projectGraphCaptured ? projectDependencies : undefined,
3193
+ });
3194
+ // An unavailable or ambiguous captured graph is refused BEFORE the
3195
+ // spawn: a half-known graph would order this run wrongly while
3196
+ // looking complete.
3197
+ if ('problem' in plan)
3198
+ throw new Error(plan.problem);
3199
+ freezePlan = plan.plan;
3200
+ const trackedPaths = freezeGitDir === null ? null : listTrackedPaths(freezeGitDir, io.env);
3201
+ if (trackedPaths === null) {
3202
+ throw new Error('the tracked-path inventory could not be read, so no generated target can be told apart from source');
3203
+ }
3204
+ freezeTargets = classifyGeneratedTargets({
3205
+ root: io.cwd,
3206
+ nativeConfigDir: nativeConfigDirOf(io.cwd),
3207
+ storageStates: projectStorageStates,
3208
+ tracked: trackedPaths,
3209
+ inputFiles: new Set((preFiles ?? []).map((entry) => entry.path)),
3210
+ docsExclusions,
3211
+ cacheExclusions,
3212
+ });
3213
+ freezeKeys = mintFreezeSigningKeyPair();
3214
+ freezeNonce = randomUUID();
3215
+ freezePrerequisites = plannedRows
3216
+ .filter((row) => row.planned.project !== null &&
3217
+ (freezePlan?.prerequisiteProjects.includes(row.planned.project) ?? false))
3218
+ .map((row) => ({ file: row.planned.file, titlePath: [...row.planned.titlePath] }));
3219
+ }
3220
+ catch (error) {
3221
+ if (spawnedWitness !== null)
3222
+ await stopWitnessProcess(spawnedWitness);
3223
+ throw new UsageError(`test-gates: the global native preparation freeze refuses this run — ${error.message}`);
3224
+ }
3225
+ }
3226
+ const armedFreeze = freezePlan === null || freezeTargets === null || freezeKeys === null || freezeNonce === null
3227
+ ? null
3228
+ : armFreezeControl({
3229
+ runId: manifest.runId,
3230
+ invocationId,
3231
+ nonce: freezeNonce,
3232
+ stateDir,
3233
+ // The SAME install this run spawns, so the generated controller
3234
+ // imports one consistent runner module (`@playwright/test`'s
3235
+ // package root, or `playwright/test`).
3236
+ testModulePath: playwrightTestModulePath(defaultPlaywrightCommand(io.cwd)),
3237
+ releasePublicKey: freezeKeys.publicKeyBase64,
3238
+ // The runner child's OWN environment, captured before any project
3239
+ // worker exists — the only honest baseline a body worker's
3240
+ // inherited preparation environment can be projected back to.
3241
+ baseEnv: supervisedRunnerChildEnv(suiteEnv, io.cwd),
3242
+ timeoutMs: Math.min(Math.max(runTimeoutMs ?? DEFAULT_RUN_TIMEOUT_MS, 120_000), 900_000),
3243
+ });
3244
+ // The identity the freeze accepted, written by the handler below and
3245
+ // read once when this run seals. It is read through a NAMED accessor
3246
+ // on purpose: the handler runs from the drain's own callback, so the
3247
+ // assignment is not this function's straight line, and a compiler that
3248
+ // sees only the initializer would narrow the variable to `null` and
3249
+ // quietly seal the pre-run tree for a run that really froze a prepared
3250
+ // one. The accessor carries the union type explicitly, so the read is
3251
+ // the truth and not an inference about it.
3252
+ let preparedIdentity = null;
3253
+ const acceptedPreparedIdentity = () => preparedIdentity;
3254
+ // Per-project file selection (setup-dependency fix): the plan already
3255
+ // knows which files belong to which project, and project identity is
3256
+ // the join key the registered expected set speaks — so a
3257
+ // `{ name: 'setup', testMatch: … }` config cannot collect every selected
3258
+ // file under every project. Each scope also carries the dependency EDGES
3259
+ // the enumeration captured and the `use.storageState` PATH each project
3260
+ // declared, so the project that reads the saved session is handed it
3261
+ // while the setup project keeps running unauthenticated. An operator's
3262
+ // GATEFORGE_SESSION_STATE still outranks both (above).
3263
+ const adapter = runnerName === 'playwright'
3264
+ ? new PlaywrightAdapter({
3265
+ config,
3266
+ discover: { excludeFile: engineGeneratedStateFileFilter(io.cwd, stateDir) },
3267
+ run: {
3268
+ testFiles: plannedRows.map((row) => row.planned.file),
3269
+ // A named run executes exactly the named tests, not their
3270
+ // whole spec files.
3271
+ ...(namedTestLocations.length > 0 ? { testLocations: namedTestLocations } : {}),
3272
+ ...(io.env['GATEFORGE_APP_BASE_URL'] ? { appBaseUrl: io.env['GATEFORGE_APP_BASE_URL'] } : {}),
3273
+ ...(io.env['GATEFORGE_SESSION_STATE'] ? { storageState: io.env['GATEFORGE_SESSION_STATE'] } : {}),
3274
+ projects: [
3275
+ ...new Set(plannedRows.map((row) => row.planned.project).filter((project) => project !== null)),
3276
+ ],
3277
+ projectScopes: plannedScopes,
3278
+ ...(armedFreeze === null || freezePlan === null
3279
+ ? {}
3280
+ : {
3281
+ freeze: {
3282
+ control: armedFreeze.control,
3283
+ prerequisiteProjects: freezePlan.prerequisiteProjects,
3284
+ },
3285
+ }),
3286
+ // Operator-provided whole-run bound for multi-hour suites (default
3287
+ // 30 minutes stands when absent — same expected set and
3288
+ // completeness rules either way).
3289
+ ...(runTimeoutMs !== undefined ? { timeoutMs: runTimeoutMs } : {}),
3290
+ },
3291
+ })
3292
+ : null;
3293
+ if (adapter !== null) {
3294
+ // Registration must be identical under planning's scrubbed env and
3295
+ // the exact safe run variables before any Playwright test can execute.
3296
+ //
3297
+ // Either refusal ends this run BEFORE the supervised window, so it
3298
+ // never reaches the cleanup that follows the final control-spec pin.
3299
+ // The generated controller spec is removed here for the same reason
3300
+ // the witness is stopped here: a run that is over must leave nothing
3301
+ // of itself behind, whatever it refused on.
3302
+ try {
3303
+ const wiredNative = await listNativePlaywrightTests({
3304
+ cwd: io.cwd,
3305
+ wiredEnv: suiteEnv,
3306
+ });
3307
+ const registrationDiff = diffNativePlaywrightTests(nativeInstances, wiredNative.instances);
3308
+ if (registrationDiff.scrubbedOnly.length > 0 || registrationDiff.wiredOnly.length > 0) {
3309
+ const details = [
3310
+ ...registrationDiff.scrubbedOnly.map((instance) => `only with scrubbed env: ${instance.file} [${instance.project}] ${instance.titlePath.join(' > ')}`),
3311
+ ...registrationDiff.wiredOnly.map((instance) => `only with wired env: ${instance.file} [${instance.project}] ${instance.titlePath.join(' > ')}`),
3312
+ ];
3313
+ throw new UsageError('test-gates: Playwright registration differs between scrubbed and wired --list; no tests were executed\n' +
3314
+ details.join('\n'));
3315
+ }
3316
+ }
3317
+ catch (error) {
3318
+ if (spawnedWitness !== null)
3319
+ await stopWitnessProcess(spawnedWitness);
3320
+ if (armedFreeze !== null)
3321
+ removeFreezeSpecDir(armedFreeze.control);
3322
+ throw error;
3323
+ }
3324
+ }
1096
3325
  // 6. Execute through the adapter under trusted-config synthesis (the
1097
3326
  // consumer config file is never loaded) under the SUPERVISOR SPOOL
1098
3327
  // DRAIN (review fix 3): while the runner executes, the CLI polls the
@@ -1107,7 +3336,206 @@ export async function runSupervisedTestGates(io, options) {
1107
3336
  // the server-e2e obligations with the witness and forwards the suite's
1108
3337
  // persistence intents (an untrusted spool) so the witness — never the
1109
3338
  // suite — probes the adapter and stamps the evidence.
3339
+ // The CI progress stream (additive): every line below is a fact the
3340
+ // supervisor already holds — the registered expected-set size, the
3341
+ // test identity the drain sees, the catalog title, the outcome, and
3342
+ // (for a failure) the runner's own first error line behind the
3343
+ // credential guard. Nothing here reads, filters, or tails runner
3344
+ // output, so the stream cannot carry a secret by construction. It is
3345
+ // off locally, and it decides nothing: no gate reads it.
3346
+ const progressTarget = resolveProgressTarget(options.progress, config.run?.progress, io.env);
3347
+ const progress = new ProgressStream({
3348
+ writer: progressTarget,
3349
+ runner: runnerName,
3350
+ scope: runScope,
3351
+ expected: selection.logicalKeys.length,
3352
+ writeLine: (line) => writeLine(io.stderr, line),
3353
+ warn: (line) => writeLine(io.stderr, line),
3354
+ });
3355
+ // The trusted freeze handler. It runs OFF the drain's own serialization
3356
+ // (see `supervisor/drain.ts`): it waits for the supervisor to seal the
3357
+ // prerequisite sessions, and those seals are produced by that same
3358
+ // drain, so chaining this wait in front of them would deadlock.
3359
+ let drainHandle = null;
3360
+ const handleFreezeRequest = async (request) => {
3361
+ if (freezePlan === null ||
3362
+ freezeTargets === null ||
3363
+ freezeKeys === null ||
3364
+ freezeNonce === null ||
3365
+ armedFreeze === null) {
3366
+ throw new Error('this run armed no preparation freeze to serve');
3367
+ }
3368
+ // Every refusal this handler raises is ALSO written to the control
3369
+ // directory's refusal document. That document is failure-only by
3370
+ // construction — no controller path treats it as permission to
3371
+ // continue — so publishing it can only end the controller's wait
3372
+ // sooner, never satisfy it. Without it a permanent refusal (a
3373
+ // prerequisite that sealed failed, skipped, retried or duplicated)
3374
+ // would burn the controller's whole bound before failing anyway.
3375
+ try {
3376
+ await serveFreezeRequest(request);
3377
+ }
3378
+ catch (error) {
3379
+ writeFreezeRefusal(armedFreeze.control, error.message);
3380
+ throw error;
3381
+ }
3382
+ };
3383
+ const serveFreezeRequest = async (request) => {
3384
+ if (freezePlan === null ||
3385
+ freezeTargets === null ||
3386
+ freezeKeys === null ||
3387
+ freezeNonce === null ||
3388
+ armedFreeze === null) {
3389
+ throw new Error('this run armed no preparation freeze to serve');
3390
+ }
3391
+ const accepted = acceptedFreezeRequest(request, {
3392
+ runId: manifest.runId,
3393
+ invocationId,
3394
+ nonce: freezeNonce,
3395
+ project: freezePlan.controllerProject,
3396
+ });
3397
+ if (typeof accepted === 'string')
3398
+ throw new Error(accepted);
3399
+ // (1) Every prerequisite must already be PROVEN passed under the
3400
+ // AUTHENTICATED supervisor trace. A genuine sealed pass with zero
3401
+ // witness activity counts: a setup project's honest job is to produce
3402
+ // an artifact, and admitting that artifact is exactly what the diff
3403
+ // below is for. No activity threshold is invented here.
3404
+ //
3405
+ // Only genuinely PENDING prerequisites are waited for (no session
3406
+ // yet). A prerequisite that already sealed as failed/skipped, that
3407
+ // opened more than one session, or whose trace cannot be read is
3408
+ // TERMINAL and refuses at once — waiting cannot change it, so the
3409
+ // bound is only there for a prerequisite the runner has not reached.
3410
+ const bound = Date.now() + Math.max(600_000, 120_000);
3411
+ let pending = ['the witness has not reported the prerequisite stage yet'];
3412
+ while (pending.length > 0) {
3413
+ if (Date.now() >= bound) {
3414
+ throw new Error(`the prerequisite stage did not report within the freeze's own bound (${pending.join('; ')})`);
3415
+ }
3416
+ const trace = await supervisor.executionTrace();
3417
+ const state = unfrozenPrerequisiteState({
3418
+ trace: trace?.tests ?? null,
3419
+ prerequisites: freezePrerequisites,
3420
+ });
3421
+ if (state.refused.length > 0)
3422
+ throw new Error(state.refused.join('; '));
3423
+ pending = state.pending;
3424
+ if (pending.length > 0)
3425
+ await delay(100);
3426
+ }
3427
+ // (2) The input inventory must not have moved while the prerequisites
3428
+ // ran: this run will seal against the digest it pinned at discovery.
3429
+ if (!snapshotUnavailable && preFiles !== null) {
3430
+ const nowFiles = collectInputFiles(io.cwd, config, stateDir, runtimeReuseMounts, docsExclusions, cacheExclusions);
3431
+ const drift = diffInputFiles(preFiles, nowFiles);
3432
+ if (drift.length > 0) {
3433
+ throw new Error(`the input inventory moved during native preparation (${drift.slice(0, 3).join('; ')})`);
3434
+ }
3435
+ }
3436
+ // (3) The control spec the CLI pinned BEFORE the run must still be
3437
+ // the bytes on disk, and the release document must not exist yet.
3438
+ // Both are checked BEFORE anything is snapshotted or signed: they
3439
+ // are inputs to the release decision, not consequences of it.
3440
+ //
3441
+ // The spec is GENERATED engine code and the controller can rewrite
3442
+ // its own file (it runs as a worker on this same host, from its own
3443
+ // private per-run directory), so a release signed over a digest
3444
+ // nothing re-checks would bind a control file nobody verified. The
3445
+ // CLI therefore compares the file itself, never the file's own
3446
+ // report of itself.
3447
+ const specBytesNow = readFileSync(armedFreeze.control.specPath);
3448
+ const specDigestNow = createHash('sha256').update(specBytesNow).digest('hex');
3449
+ if (specDigestNow !== armedFreeze.specDigest) {
3450
+ throw new Error(`the generated freeze controller spec no longer matches the bytes this run pinned (expected ` +
3451
+ `${armedFreeze.specDigest.slice(0, 12)}…, found ${specDigestNow.slice(0, 12)}…)`);
3452
+ }
3453
+ // The publisher is ONE-SHOT per invocation and has not run yet: this
3454
+ // handler is the only writer of the release document, and it writes
3455
+ // it at the END of this function. A release file that already exists
3456
+ // when the request is accepted was therefore NOT written by this run
3457
+ // — it is a leftover, a replay of an earlier invocation's document,
3458
+ // or a forgery.
3459
+ //
3460
+ // Signing anyway would let the publisher OVERWRITE a planted
3461
+ // document, so a controller that read the planted bytes and a
3462
+ // controller that read the genuine ones would reach opposite
3463
+ // conclusions about one and the same run. Refusing here makes the
3464
+ // handshake deterministic instead: an unexpected release document
3465
+ // ends the barrier through the FAILURE-ONLY channel, naming its
3466
+ // path, and is never mistaken for the one positive signal that
3467
+ // unblocks a body. It grants no authority — the ephemeral signature
3468
+ // is still the only thing that can unblock a controller, and the
3469
+ // worker still verifies the release cryptographically.
3470
+ if (existsSync(armedFreeze.control.releasePath)) {
3471
+ throw new Error(`a freeze release document already existed at '${armedFreeze.control.releasePath}' when the controller ` +
3472
+ 'asked to be frozen, so this run did not write it — an unexpected (planted, stale or replayed) release ' +
3473
+ 'is never overwritten into a genuine one (fail closed)');
3474
+ }
3475
+ // (4) ONE prepared snapshot, admitted against the frozen baseline:
3476
+ // only admissible generated-target additions and modifications pass.
3477
+ if (freezeGitDir === null || baselineSnapshot === null) {
3478
+ throw new Error('this run pinned no candidate baseline, so no prepared candidate can be frozen');
3479
+ }
3480
+ const preparedSnapshot = computeCandidateTreeSnapshot(freezeGitDir, io.cwd, io.env, stateDir, 'record', runtimeReuseMounts, docsExclusions, cacheExclusions);
3481
+ const violations = preparedCandidateViolations({
3482
+ root: io.cwd,
3483
+ baseline: baselineSnapshot.entries,
3484
+ prepared: preparedSnapshot.entries,
3485
+ targets: freezeTargets,
3486
+ });
3487
+ if (violations.length > 0)
3488
+ throw new Error(violations.join('; '));
3489
+ // (5) Publish. The ordering marker is appended FIRST so that every
3490
+ // body project's begin is provably later than the accepted freeze, then
3491
+ // the SIGNED release the controller verifies before it proceeds. The
3492
+ // private key never leaves this function's closure.
3493
+ appendFreezeReleaseEvent(spoolPathFor(stateDir, manifest.runId), {
3494
+ project: freezePlan.controllerProject,
3495
+ preparedTreeId: preparedSnapshot.treeId,
3496
+ specDigest: armedFreeze.specDigest,
3497
+ });
3498
+ drainHandle?.markFreezeRelease({
3499
+ preparedTreeId: preparedSnapshot.treeId,
3500
+ specDigest: armedFreeze.specDigest,
3501
+ });
3502
+ const sealedAt = new Date().toISOString();
3503
+ writeFileSync(armedFreeze.control.releasePath, `${canonicalFreezeJson(signFreezeRelease(freezeKeys.privateKey, {
3504
+ schemaVersion: 1,
3505
+ project: freezePlan.controllerProject,
3506
+ runId: manifest.runId,
3507
+ invocationId,
3508
+ nonce: freezeNonce,
3509
+ preparedTreeId: preparedSnapshot.treeId,
3510
+ specDigest: armedFreeze.specDigest,
3511
+ sealedAt,
3512
+ }))}\n`, 'utf8');
3513
+ preparedIdentity = {
3514
+ preparedTreeId: preparedSnapshot.treeId,
3515
+ runId: manifest.runId,
3516
+ invocationId,
3517
+ nonce: freezeNonce,
3518
+ sealedAt,
3519
+ };
3520
+ options.onPreparedCandidate?.(preparedIdentity);
3521
+ writeLine(io.stderr, `prepared candidate frozen at ${preparedSnapshot.treeId.slice(0, 12)}… ` +
3522
+ `(${String(freezeTargets.eligible.size)} generated target(s) admitted)`);
3523
+ };
3524
+ progress.start();
1110
3525
  const drain = startSupervisorSpoolDrain({
3526
+ // The GLOBAL preparation freeze rides the same pump: the controller's
3527
+ // request is noticed here, and the handler above owns every authority
3528
+ // decision the release depends on.
3529
+ ...(freezePlan === null || armedFreeze === null
3530
+ ? {}
3531
+ : {
3532
+ freeze: {
3533
+ controllerProject: freezePlan.controllerProject,
3534
+ bodyProjects: freezePlan.bodyProjects,
3535
+ requestPath: armedFreeze.control.requestPath,
3536
+ onRequest: handleFreezeRequest,
3537
+ },
3538
+ }),
1111
3539
  stateDir,
1112
3540
  runId: manifest.runId,
1113
3541
  witnessUrl: effectiveWitnessUrl,
@@ -1115,7 +3543,29 @@ export async function runSupervisedTestGates(io, options) {
1115
3543
  verifierKey: witnessVerifierKey,
1116
3544
  serverE2eObligations,
1117
3545
  observeObligations,
3546
+ onTestEvent: (event) => {
3547
+ const title = event.titlePath.join(' > ');
3548
+ if (event.kind === 'testBegin') {
3549
+ progress.beginTest(title);
3550
+ return;
3551
+ }
3552
+ // A worker-side end carries no outcome (the runner's reporter
3553
+ // still owes it): counting it would report a test twice.
3554
+ if (event.outcome === undefined)
3555
+ return;
3556
+ progress.endTest({
3557
+ logicalKey: `${event.file ?? ''}#${event.titlePath.join('>')}`,
3558
+ title,
3559
+ outcome: progressOutcomeOf(event.outcome),
3560
+ ...(event.errorMessage === undefined ? {} : { message: event.errorMessage }),
3561
+ ...(event.stackFrames === undefined ? {} : { stackFrames: event.stackFrames }),
3562
+ });
3563
+ },
1118
3564
  });
3565
+ // The handler closes over the handle so an accepted freeze can record
3566
+ // its own ordering marker identity; the assignment happens before the
3567
+ // first poll, and the handler only ever runs later.
3568
+ drainHandle = drain;
1119
3569
  let envelope;
1120
3570
  // The witness-side execution trace (review fix 2b) — THE execution
1121
3571
  // authority supervision grades completeness from. Fetched while the
@@ -1123,10 +3573,19 @@ export async function runSupervisedTestGates(io, options) {
1123
3573
  let sessionTrace = null;
1124
3574
  let lifecycleConflicts = [];
1125
3575
  let intentFailures = [];
3576
+ // The FINAL control-spec verdict, decided in the `finally` below — at
3577
+ // the close of the supervised window, which is the last moment the
3578
+ // generated spec is read — and consumed below, after the run sealed.
3579
+ let controlSpecDrift = null;
1126
3580
  // Witnessed pytest participants (server-witnessed persistence channel):
1127
3581
  // typed blocking details for any witnessed suite that did not complete
1128
3582
  // cleanly — collected inside the supervised window below.
1129
3583
  let witnessedBlocking = [];
3584
+ const executionStartedAt = performance.now();
3585
+ let executionDurationMs = null;
3586
+ const hostLoadCollector = config.diagnostics?.hostLoad === true
3587
+ ? startHostLoadSampler(stateDir, (message) => writeLine(io.stderr, `warning: ${message}`))
3588
+ : null;
1130
3589
  try {
1131
3590
  // 6.5 WITNESSED pytest participants run INSIDE the supervised window
1132
3591
  // (server-witnessed persistence channel, GAP 2 fix): the drain is
@@ -1140,7 +3599,10 @@ export async function runSupervisedTestGates(io, options) {
1140
3599
  // witness probes the adapter itself — and a witnessed suite that runs
1141
3600
  // red or unfinished BLOCKS the gate: the mapped server-e2e test's red
1142
3601
  // is never graded green.
1143
- if ((config.diagnostics?.suites ?? []).some((suite) => suite.witnessed === true)) {
3602
+ // Playwright-only participant: with `runner: pytest` the configured
3603
+ // suite IS the supervised run the adapter executes below, so a
3604
+ // separate witnessed pass would execute it twice.
3605
+ if (runnerName === 'playwright' && (config.diagnostics?.suites ?? []).some((suite) => suite.witnessed === true)) {
1144
3606
  const witnessed = await runWitnessedPytestSuites({
1145
3607
  config,
1146
3608
  cwd: io.cwd,
@@ -1168,11 +3630,50 @@ export async function runSupervisedTestGates(io, options) {
1168
3630
  nextAction: CAUSE_NEXT_ACTIONS['RUN_INCOMPLETE'],
1169
3631
  }));
1170
3632
  }
1171
- envelope = await adapter.execute({ logicalKeys: selection.logicalKeys }, {
1172
- stateDir,
1173
- runId: manifest.runId,
1174
- vars: suiteEnv,
1175
- });
3633
+ if (adapter !== null) {
3634
+ envelope = await adapter.execute({ logicalKeys: selection.logicalKeys }, {
3635
+ stateDir,
3636
+ runId: manifest.runId,
3637
+ vars: suiteEnv,
3638
+ });
3639
+ }
3640
+ else if (runnerEnumeration?.status === 'discovered') {
3641
+ // The RunnerAdapter contract (plan 2026-09-25): the exact
3642
+ // selection, run identity, and wall-clock bound cross as data; the
3643
+ // adapter spawns the runner and reads its structured report. The
3644
+ // verdict still comes from supervision + the witness trace. The
3645
+ // selection MODE travels with it: a `named-selection` run narrows
3646
+ // to the named tests wherever the runner can, and a run without
3647
+ // `--test` executes exactly what it always did.
3648
+ const request = {
3649
+ logicalKeys: selection.logicalKeys,
3650
+ stateDir,
3651
+ runId: manifest.runId,
3652
+ timeoutMs: runTimeoutMs ?? DEFAULT_RUN_TIMEOUT_MS,
3653
+ cwd: io.cwd,
3654
+ mode: selection.mode,
3655
+ ...(selection.mode === 'named-selection' ? { testLocations: namedTestLocations } : {}),
3656
+ };
3657
+ envelope = await runnerAdapterFor(runnerName, {
3658
+ witnessUrl: effectiveWitnessUrl,
3659
+ runToken,
3660
+ appBaseUrl: io.env['GATEFORGE_APP_BASE_URL'] ?? '',
3661
+ }).execute(request);
3662
+ }
3663
+ else {
3664
+ // The runner could not enumerate its expected set: nothing is
3665
+ // selected, so launching would widen to the whole suite. Fail
3666
+ // closed here — the inventory blocking entry above names the cause.
3667
+ envelope = {
3668
+ processExit: null,
3669
+ complete: false,
3670
+ incompleteDetail: runnerEnumeration === null
3671
+ ? 'test inventory could not be enumerated — the configured runner never produced an expected set'
3672
+ : runnerEnumeration.detail,
3673
+ outcomes: [],
3674
+ fixtureOutcome: 'unknown',
3675
+ };
3676
+ }
1176
3677
  }
1177
3678
  finally {
1178
3679
  // Final spool sweep + force-close of runner-left-open sessions,
@@ -1195,12 +3696,198 @@ export async function runSupervisedTestGates(io, options) {
1195
3696
  catch {
1196
3697
  sessionTrace = null; // fail closed: a missing authority never grades success
1197
3698
  }
3699
+ if (effectiveWitnessUrl !== undefined) {
3700
+ await writeWitnessLedgerDocument(io, stateDir, effectiveWitnessUrl, runToken);
3701
+ }
3702
+ if (chaosRun !== null && effectiveWitnessUrl !== undefined && witnessVerifierKey !== undefined) {
3703
+ // The replay record, read while the witness is still alive. A
3704
+ // chaos run that cannot explain its own schedule is a finding
3705
+ // nobody can reproduce, so a failed read says so out loud.
3706
+ try {
3707
+ const response = await fetch(`${effectiveWitnessUrl}/runs/chaos-schedule`, {
3708
+ headers: { [RUN_HEADER]: runToken, [VERIFIER_HEADER]: witnessVerifierKey },
3709
+ });
3710
+ if (response.ok) {
3711
+ const body = (await response.json());
3712
+ chaosSchedule = body.chaos?.schedule ?? null;
3713
+ }
3714
+ else {
3715
+ writeLine(io.stderr, `test-gates: the chaos schedule could not be read (HTTP ${String(response.status)}) — this run still reports, without a replay record`);
3716
+ }
3717
+ }
3718
+ catch (error) {
3719
+ writeLine(io.stderr, `test-gates: the chaos schedule could not be read (${error.message}) — this run still reports, without a replay record`);
3720
+ }
3721
+ }
3722
+ if (twinComparisonOn && effectiveWitnessUrl !== undefined && witnessVerifierKey !== undefined) {
3723
+ // Twin path coverage (E64): the honest comparison. The shapes
3724
+ // come from the witness's own per-session proxies and are joined
3725
+ // to the catalog by the session's REGISTERED IDENTITY (project,
3726
+ // file, titlePath) — never by the runner test id, which is not
3727
+ // stable from enumeration to execution (Playwright derives it from
3728
+ // the test's file path relative to the config it loaded). A pair
3729
+ // is compared only when BOTH twins were observed in this run, and
3730
+ // a run that could not read them says so rather than reporting
3731
+ // twins that agree because nobody looked.
3732
+ const shapes = await supervisor.twinShapes();
3733
+ if (shapes === null) {
3734
+ writeLine(io.stderr, 'test-gates: the recorded twin shapes could not be read — this run still reports, without the ' +
3735
+ 'TWIN_PATH_DIVERGENT check (an unread comparison is never a passing one)');
3736
+ }
3737
+ else {
3738
+ const logicalKeyByIdentity = new Map();
3739
+ for (const row of plannedRows) {
3740
+ logicalKeyByIdentity.set(`${row.planned.project ?? ''}\u0000${row.planned.file}\u0000${row.planned.titlePath.join('>')}`, row.planned.logicalKey);
3741
+ }
3742
+ const observed = new Map();
3743
+ for (const twin of shapes.twins) {
3744
+ const logicalKey = twin.identity === null
3745
+ ? undefined
3746
+ : logicalKeyByIdentity.get(`${twin.identity.project ?? ''}\u0000${twin.identity.file}\u0000${twin.identity.titlePath.join('>')}`);
3747
+ if (logicalKey !== undefined) {
3748
+ observed.set(logicalKey, { observationOnly: twin.observationOnly, shapes: [...twin.shapes] });
3749
+ }
3750
+ }
3751
+ writeTwinShapes(stateDir, [...observed.entries()]
3752
+ .sort((left, right) => compareStrings(left[0], right[0]))
3753
+ .map(([logicalKey, entry]) => ({
3754
+ logicalKey,
3755
+ observationOnly: entry.observationOnly,
3756
+ shapes: entry.shapes,
3757
+ })));
3758
+ // A pair both of whose tests are in this run but one side sent no
3759
+ // request through the witness was NOT compared; saying nothing
3760
+ // would read as "the twins agree".
3761
+ const inRun = new Set(namedTestIds ?? plannedRows.map((row) => row.planned.logicalKey));
3762
+ for (const link of twinLinks) {
3763
+ const witnessedShapes = observed.get(link.witnessed);
3764
+ const rawShapes = observed.get(link.raw);
3765
+ if (witnessedShapes === undefined || rawShapes === undefined) {
3766
+ if (inRun.has(link.witnessed) && inRun.has(link.raw)) {
3767
+ writeLine(io.stderr, twinPairNotComparedLine(link, witnessedShapes !== undefined, rawShapes !== undefined));
3768
+ }
3769
+ continue;
3770
+ }
3771
+ twinDivergences = [
3772
+ ...twinDivergences,
3773
+ ...twinPathDivergence({ logicalKey: link.witnessed, shapes: witnessedShapes.shapes }, { logicalKey: link.raw, shapes: rawShapes.shapes }),
3774
+ ];
3775
+ }
3776
+ }
3777
+ }
1198
3778
  if (spawnedWitness !== null) {
1199
3779
  // Graceful stop (the same contract as the consumer teardown): the
1200
3780
  // witness appends its attested manifest envelope at shutdown, so
1201
3781
  // the durable evidence channel is sealed before evaluation.
1202
3782
  await stopWitnessProcess(spawnedWitness);
1203
3783
  }
3784
+ try {
3785
+ hostLoadCollector?.stop();
3786
+ }
3787
+ catch (error) {
3788
+ writeLine(io.stderr, `warning: host-load diagnostics could not be written: ${error.message}`);
3789
+ }
3790
+ executionDurationMs = Math.max(0, Math.round(performance.now() - executionStartedAt));
3791
+ // The FINAL control-spec pin, and the LAST read of the spec.
3792
+ //
3793
+ // It runs here, at the close of the supervised window: after the
3794
+ // runner child exited and the drain stopped, so nothing can still be
3795
+ // executing the controller, and still before ANY receipt, result or
3796
+ // carried re-seal is accepted below — because everything downstream
3797
+ // of this point claims the prepared candidate was frozen under
3798
+ // control nobody replaced. The request-time check proved the pinned
3799
+ // bytes were intact before the release was signed; the bodies then
3800
+ // ran against that control. This is the same guard the synthesized
3801
+ // runner config gets in the pack (`supervised-run.ts`, pinned before
3802
+ // the spawn and compared again after the child exits) and it is
3803
+ // deliberately SEPARATE from it: the trusted config is the whole
3804
+ // authority the runner executes, while the control SPEC is the
3805
+ // handshake document, and one check does not cover the other.
3806
+ //
3807
+ // A control file that moved during the run is an integrity failure,
3808
+ // not a recoverable outcome: fail closed, name the path, write
3809
+ // nothing. As everywhere else here, this is a same-UID
3810
+ // replace-and-restore LIMIT, not a physical sandbox — an attacker
3811
+ // who restores the file between the two reads stays outside this
3812
+ // boundary.
3813
+ if (armedFreeze !== null) {
3814
+ let finalSpecDigest;
3815
+ try {
3816
+ finalSpecDigest = createHash('sha256').update(readFileSync(armedFreeze.control.specPath)).digest('hex');
3817
+ }
3818
+ catch {
3819
+ finalSpecDigest = null;
3820
+ }
3821
+ if (finalSpecDigest !== armedFreeze.specDigest) {
3822
+ controlSpecDrift =
3823
+ `the generated freeze controller spec at '${armedFreeze.control.specPath}' no longer matches the bytes ` +
3824
+ `this run pinned (expected ${armedFreeze.specDigest.slice(0, 12)}…, found ` +
3825
+ `${finalSpecDigest === null ? 'no readable file' : `${finalSpecDigest.slice(0, 12)}…`}), so the ` +
3826
+ 'prepared candidate this run would seal cannot be shown to come from the control it froze under (fail closed)';
3827
+ }
3828
+ // The spec has served its run and nothing above this line reads it
3829
+ // again, so the private directory that held it goes now: no
3830
+ // generated engine file outlives the run inside the candidate's
3831
+ // own bytes. This `finally` covers every outcome of the supervised
3832
+ // window — a completed run, a refusal, an incomplete execution, a
3833
+ // throw — so none of them keeps it.
3834
+ removeFreezeSpecDir(armedFreeze.control);
3835
+ }
3836
+ }
3837
+ // The suite has finished: close the stream (grading follows) and keep
3838
+ // the screened failing-test diagnosis as a Gateforge-owned artifact,
3839
+ // so a CI job never has to publish the runner log to explain a red
3840
+ // test. Both happen only when the stream is on — a local run with the
3841
+ // stream off writes nothing new into the state directory.
3842
+ progress.finish();
3843
+ if (progressTarget !== null) {
3844
+ writeTestFailures(stateDir, manifest.runId, progress.failures);
3845
+ }
3846
+ // A local run has no stream, so the report is the only place its
3847
+ // operator will ever read WHY. The records are the same guarded ones
3848
+ // the stream prints (never runner output), and they are offered to
3849
+ // the report ONLY with the stream off — a stream that already named
3850
+ // the failures must not have them named twice.
3851
+ const localFailures = progressTarget === null
3852
+ ? progress.failures.map((failure) => ({ title: failure.title, message: failure.message }))
3853
+ : [];
3854
+ // Cypress cannot filter below the spec without a plugin the gate
3855
+ // refuses to trust, so a named Cypress run executes the whole spec and
3856
+ // grades ONLY the selected tests: their outcomes and sessions are
3857
+ // dropped (an unselected test never becomes evidence) and the operator
3858
+ // is told exactly how many ran ungraded. Every other runner executes
3859
+ // exactly the selection, so any extra outcome there stays unplanned and
3860
+ // fails the run closed.
3861
+ // Cypress identities of the tests that ran ungraded; the seal drops
3862
+ // them from the executed document too, so an honest ungraded run is
3863
+ // never reported as an unexpected extra execution.
3864
+ let namedUngradedKeys = null;
3865
+ if (selection.mode === 'named-selection' && runnerName === 'cypress') {
3866
+ const selected = new Set(selection.logicalKeys);
3867
+ const ungraded = envelope.outcomes.filter((outcome) => !selected.has(outcome.logicalKey));
3868
+ if (ungraded.length > 0) {
3869
+ writeLine(io.stderr, `also ran ${String(ungraded.length)} other test(s) in the same file — not graded`);
3870
+ envelope = {
3871
+ ...envelope,
3872
+ outcomes: envelope.outcomes.filter((outcome) => selected.has(outcome.logicalKey)),
3873
+ // The process status is the SPEC's, not the selection's: an
3874
+ // ungraded test that fails (its session was never opened,
3875
+ // because the selection registered only the named ones) would
3876
+ // otherwise fail the whole run closed for a test the run
3877
+ // explicitly said it does not grade. The selection's own
3878
+ // outcomes still decide completeness — a selected test that
3879
+ // never ran, or crashed, leaves the run incomplete.
3880
+ processExit: 0,
3881
+ };
3882
+ // The witness trace rows carry file + title path, which is exactly
3883
+ // how a `<file>#<title path>` logical key spells them.
3884
+ const ungradedKeys = new Set(ungraded.map((outcome) => outcome.logicalKey));
3885
+ namedUngradedKeys = ungradedKeys;
3886
+ sessionTrace =
3887
+ sessionTrace === null
3888
+ ? null
3889
+ : sessionTrace.filter((traced) => !ungradedKeys.has(`${traced.file}#${traced.titlePath.join('>')}`));
3890
+ }
1204
3891
  }
1205
3892
  if (options.runtimeReuseCheck !== undefined) {
1206
3893
  let currentReuseDigest;
@@ -1217,17 +3904,41 @@ export async function runSupervisedTestGates(io, options) {
1217
3904
  return 1;
1218
3905
  }
1219
3906
  }
1220
- const outcomesDoc = readRunnerOutcomes(join(stateDir, 'runner-outcomes.json'));
3907
+ // Quarantined instances still RUN (the suite is executed whole) but
3908
+ // they are no longer REQUIRED, so their outcome and their session
3909
+ // trace are recorded as INFORMATION ONLY: leaving them in would make
3910
+ // supervision report them as unexpected extra executions.
3911
+ const quarantinedInstances = quarantinedInstanceKeys(catalog, quarantinedKeys);
3912
+ // Executed rows the seal must not treat as planned executions: the
3913
+ // quarantined instances, plus the tests a named Cypress run had to
3914
+ // execute but never grades. Both are information only.
3915
+ const unrequiredInstances = new Set(quarantinedInstances);
3916
+ for (const key of namedUngradedKeys ?? [])
3917
+ unrequiredInstances.add(key);
3918
+ const rawOutcomesDoc = readRunnerOutcomes(join(stateDir, 'runner-outcomes.json'));
3919
+ const outcomesDoc = unrequiredInstances.size === 0 || rawOutcomesDoc === null
3920
+ ? rawOutcomesDoc
3921
+ : {
3922
+ ...rawOutcomesDoc,
3923
+ outcomes: rawOutcomesDoc.outcomes.filter((row) => !unrequiredInstances.has(`${row.file}#${row.titlePath.join('>')}`)),
3924
+ };
3925
+ if (sessionTrace !== null && unrequiredInstances.size > 0) {
3926
+ sessionTrace = sessionTrace.filter((test) => !unrequiredInstances.has(`${test.file}#${test.titlePath.join('>')}`));
3927
+ }
1221
3928
  const sealed = sealExecutionResult({
1222
3929
  runId: manifest.runId,
1223
3930
  invocationId,
1224
3931
  inputDigest: expectedDigest ?? NO_DIGEST,
1225
3932
  trustedPolicyDigest: trustedPolicy,
1226
- runner: 'playwright',
1227
- // A scoped seal names its selection mode honestly (Goal 2): the
1228
- // execution result — and the receipt digest that binds it — record
1229
- // that a mapped slice ran, never a whole relevant suite.
1230
- ...(options.scope === 'changed' ? { mode: 'mapped-selection' } : {}),
3933
+ // The REAL configured runner (additive values on the frozen schema:
3934
+ // `playwright` stays byte-identical; pytest/vitest/cypress name
3935
+ // themselves honestly in the execution result and every receipt
3936
+ // binding it).
3937
+ runner: runnerName,
3938
+ // A scoped or named run names its selection mode honestly (Goal 2):
3939
+ // the execution result — and the receipt digest that binds it —
3940
+ // record that a slice ran, never a whole relevant suite.
3941
+ ...(selection.mode === 'full-relevant-suite' ? {} : { mode: selection.mode }),
1231
3942
  logicalKeys: selection.logicalKeys,
1232
3943
  catalog: catalog ?? EMPTY_CATALOG,
1233
3944
  claimInventory: nativeClaims,
@@ -1236,6 +3947,12 @@ export async function runSupervisedTestGates(io, options) {
1236
3947
  outcomesDoc,
1237
3948
  sessionTrace,
1238
3949
  enumerationDigest: registered.enumerationDigest,
3950
+ // Timing chaos (E63): the seed, its bounds and the schedule the
3951
+ // proxy used, so a red chaos run can be explained and replayed from
3952
+ // the sealed result alone. Absent without `--chaos`.
3953
+ ...(chaosRun === null
3954
+ ? {}
3955
+ : { chaos: { ...chaosRun, schedule: chaosSchedule ?? [] } }),
1239
3956
  startedAt: pipeline.now,
1240
3957
  finishedAt: pipeline.now,
1241
3958
  });
@@ -1244,7 +3961,7 @@ export async function runSupervisedTestGates(io, options) {
1244
3961
  let changedInputs = false;
1245
3962
  if (!snapshotUnavailable && preFiles !== null) {
1246
3963
  try {
1247
- const postSuite = collectInputFiles(io.cwd, config, stateDir, runtimeReuseMounts, docsExclusions);
3964
+ const postSuite = collectInputFiles(io.cwd, config, stateDir, runtimeReuseMounts, docsExclusions, cacheExclusions);
1248
3965
  changedInputs = diffInputFiles(preFiles, postSuite).length > 0;
1249
3966
  }
1250
3967
  catch {
@@ -1291,11 +4008,55 @@ export async function runSupervisedTestGates(io, options) {
1291
4008
  cause: 'RUN_INCOMPLETE',
1292
4009
  nextAction: CAUSE_NEXT_ACTIONS['RUN_INCOMPLETE'],
1293
4010
  }));
4011
+ // Twin path coverage (E64): the owner-chosen strictness of the
4012
+ // TWIN_PATH_DIVERGENT finding. `advisory` reports it and leaves the
4013
+ // exit code exactly what the run already decided; `block` makes it a
4014
+ // blocking entry. Absent configuration, or twins that agree, this is
4015
+ // empty and the report keeps exactly the keys it always had.
4016
+ const twinEntries = twinDivergences.map((divergence) => ({
4017
+ kind: 'finding',
4018
+ resourceId: null,
4019
+ name: null,
4020
+ detail: twinDivergenceDetail(divergence),
4021
+ location: null,
4022
+ cause: 'TWIN_PATH_DIVERGENT',
4023
+ nextAction: CAUSE_NEXT_ACTIONS['TWIN_PATH_DIVERGENT'],
4024
+ }));
4025
+ const twinAdvisories = twinPathsMode === 'block' ? [] : twinEntries;
4026
+ const twinBlocking = twinPathsMode === 'block' ? twinEntries : [];
4027
+ // An expired quarantine is ignored AND blocking: the owner let this
4028
+ // flake run long enough that nobody renewed it, so the required test
4029
+ // is back in the run and the stale escape hatch must be visible.
1294
4030
  const repositoryBlocking = [
1295
4031
  ...pipeline.policy.blocking,
1296
4032
  ...mappingBlockers,
1297
4033
  ...inventoryBlocking,
4034
+ ...expiredQuarantineBlocking(quarantines.expired),
1298
4035
  ];
4036
+ // The graded evidence of a re-seal is the UNION: the carried parent
4037
+ // records and claims plus this run's own. It is written to the run
4038
+ // state BEFORE grading, so the verdict summary the receipt seals and
4039
+ // every later `check` grade the exact same documents, and the
4040
+ // carriedEvidenceDigest below binds them.
4041
+ let carriedEvidenceDocumentsUnion = null;
4042
+ if (reSealParentEvidence !== null) {
4043
+ const carriedClaims = new Set(reSealParentEvidence.claims.map((claim) => stringField(claim, 'testId')).filter((id) => id !== null));
4044
+ carriedEvidenceDocumentsUnion = {
4045
+ records: [
4046
+ ...reSealParentEvidence.records,
4047
+ ...readJsonArray(stateDir, 'records.json').filter((record) => !reSealParentEvidence.contributingRunIds.includes(stringField(record, 'runId') ?? '')),
4048
+ ],
4049
+ claims: [
4050
+ ...reSealParentEvidence.claims,
4051
+ ...readJsonArray(stateDir, 'claims.json').filter((claim) => {
4052
+ const testId = stringField(claim, 'testId');
4053
+ return testId !== null && !carriedClaims.has(testId);
4054
+ }),
4055
+ ],
4056
+ };
4057
+ writeFileSync(join(stateDir, 'records.json'), `${JSON.stringify(carriedEvidenceDocumentsUnion.records, null, 2)}\n`, 'utf8');
4058
+ writeFileSync(join(stateDir, 'claims.json'), `${JSON.stringify(carriedEvidenceDocumentsUnion.claims, null, 2)}\n`, 'utf8');
4059
+ }
1299
4060
  const evaluationInput = {
1300
4061
  cwd: io.cwd,
1301
4062
  config,
@@ -1303,12 +4064,20 @@ export async function runSupervisedTestGates(io, options) {
1303
4064
  behaviorCatalog: pipeline.behaviorCatalog,
1304
4065
  behaviorAuthorityProfileDigest: pipeline.behaviorCatalog === null ? null : engineBundleDigestOf(VERSION, trustedPolicy),
1305
4066
  obligations: pipeline.policy.obligations,
4067
+ // Named grading: a hand-picked selection never
4068
+ // observed the rest of the repository, so repository-wide findings
4069
+ // (policy, mapping, inventory, expired quarantine) and the scoped
4070
+ // planning gaps stay in the report but block nothing here. What
4071
+ // still blocks is everything about THIS run: supervision, lifecycle,
4072
+ // intent and the witnessed channel, plus (inside the evaluator) any
4073
+ // entry naming a graded obligation and every evidence-context
4074
+ // finding. A named run never forgives a broken run.
1306
4075
  blocking: [
1307
- ...repositoryBlocking,
4076
+ ...(namedTestIds === null ? repositoryBlocking : []),
1308
4077
  // Scoped planning gaps (Goal 2): affected obligations no declared,
1309
4078
  // catalog-live claim covers. Fail closed — never diff-scoped away,
1310
4079
  // never waived, and they alone prevent the receipt.
1311
- ...scopeBlockers,
4080
+ ...(namedTestIds === null ? scopeBlockers : []),
1312
4081
  ...supervisionBlocking(supervisionFindings),
1313
4082
  ...lifecycleBlocking,
1314
4083
  ...intentBlocking,
@@ -1320,20 +4089,35 @@ export async function runSupervisedTestGates(io, options) {
1320
4089
  ],
1321
4090
  stateDir,
1322
4091
  now: pipeline.now,
4092
+ engineAlembicRecords: pipeline.engineAlembicRecords,
1323
4093
  // Scoped evaluation (Goal 2): the gate grades the affected slice —
1324
4094
  // the same join `planScopedExpectedSet` planned from, so the graded
1325
4095
  // obligations are exactly the covered set the receipt seals. Full
1326
4096
  // mode stays unscoped (changedFiles: null), byte-identical.
1327
- changedFiles: scopeChangedFiles,
4097
+ // A re-seal grades the obligations its re-run tests declare (the
4098
+ // `namedObligationIds` above); diff scoping is the empty-slice
4099
+ // planner's axis and means nothing over a test-only change.
4100
+ changedFiles: reSealPlan === null ? scopeChangedFiles : null,
4101
+ // Named grading: the graded set is what the selected tests
4102
+ // declare. Absent for every other run, which then grades the whole
4103
+ // repository exactly as before.
4104
+ ...(namedObligationIds === null ? {} : { namedObligationIds }),
1328
4105
  claimInventory,
4106
+ ...(excludedTestIds.length === 0 ? {} : { excludedTestIds }),
1329
4107
  witnessVerifierKey,
1330
4108
  witnessVerifierKeys: verifierKeyring?.keys.map((entry) => entry.key),
1331
4109
  witnessAttestation: liveAttestation,
4110
+ // Every contributing run's own envelope, authenticated against the
4111
+ // identity and input digest the re-seal's own recomputation bound
4112
+ // it to.
4113
+ ...(reSealParentEvidence === null
4114
+ ? {}
4115
+ : { carriedEvidence: reSealParentEvidence.contributions }),
1332
4116
  // Goal 1: the supervised gate honors the adopted baseline through the
1333
4117
  // SAME fail-closed seam as `check` (no adoption record → nothing is
1334
4118
  // forgiven). Under strictE2E the evaluator still re-grades every
1335
4119
  // waived verdict to blocking — a waiver is not proof.
1336
- baseline: resolveAdoptedBaseline(io.cwd, config.baselines),
4120
+ baseline: adoptedBaseline,
1337
4121
  mappedCoverage,
1338
4122
  evidenceContext: {
1339
4123
  expectedInputDigest: expectedDigest,
@@ -1343,25 +4127,216 @@ export async function runSupervisedTestGates(io, options) {
1343
4127
  changedInputs,
1344
4128
  },
1345
4129
  };
1346
- const evaluated = evaluateRun(evaluationInput);
4130
+ const evaluatedBase = evaluateRun(evaluationInput);
4131
+ // Twin path coverage in `block` mode joins the run's OWN blocking set:
4132
+ // it appears in `blocking` (not only in `advisories`) and it fails the
4133
+ // run the way any other blocking finding does. In `advisory` mode this
4134
+ // is the base evaluation, byte-identical.
4135
+ const evaluated = twinBlocking.length === 0
4136
+ ? evaluatedBase
4137
+ : { ...evaluatedBase, blocking: [...evaluatedBase.blocking, ...twinBlocking] };
4138
+ // Owner-chosen strictness: the mapping from the strict decision to the
4139
+ // effective exit code. `changed` reuses the run's own provider diff and
4140
+ // the evaluator's own attribution rule — an unknown change fails closed.
4141
+ const strictExit = runExitCode({ verdicts: evaluated.verdicts, blocking: evaluated.blocking });
4142
+ const blockingTotal = evaluated.verdicts.filter((verdict) => BLOCKING_VERDICTS.includes(verdict.verdict)).length +
4143
+ evaluated.blocking.length;
4144
+ const changedFileSet = new Set(providerChangedFiles);
4145
+ const strictness = decideStrictness({
4146
+ mode: gateMode,
4147
+ strictExitCode: strictExit,
4148
+ blockingTotal,
4149
+ ...(gateMode === 'changed'
4150
+ ? {
4151
+ changed: {
4152
+ active: true,
4153
+ blockingInScope: evaluated.verdicts.filter((verdict) => BLOCKING_VERDICTS.includes(verdict.verdict) &&
4154
+ (sourcesByResourceId(pipeline.graph, pipeline.behaviorCatalog).get(verdict.obligation.resourceId) ?? []).some((file) => changedFileSet.has(file))).length +
4155
+ scopeBlocking(evaluated.blocking, changedFileSet, sourcesByResourceId(pipeline.graph, pipeline.behaviorCatalog)).length,
4156
+ },
4157
+ }
4158
+ : {}),
4159
+ });
4160
+ // The repository evaluation deliberately drops the named scope: it is
4161
+ // the whole-repository debt a named run reports but does not grade
4162
+ // (and never blocks on). Every other run already grades both halves
4163
+ // identically, so this is a no-op outside a named run.
1347
4164
  const repositoryEvaluation = evaluateRun({
1348
4165
  ...evaluationInput,
4166
+ namedObligationIds: null,
1349
4167
  blocking: repositoryBlocking,
1350
4168
  changedFiles: null,
1351
4169
  });
1352
4170
  const executionSummary = runExecutionSummaryOf({
1353
4171
  executionResult: sealed.result,
1354
4172
  mode: 'executed',
1355
- scope: options.scope === 'changed' ? 'changed' : 'full',
4173
+ scope: namedTestIds !== null ? 'named' : options.scope === 'changed' ? 'changed' : 'full',
1356
4174
  selectedVerdicts: evaluated.verdicts,
1357
4175
  selectedBlocking: evaluated.blocking,
1358
4176
  repositoryVerdicts: repositoryEvaluation.verdicts,
1359
4177
  repositoryBlocking: repositoryEvaluation.blocking,
1360
4178
  unclaimed: countUnclaimedObligations(stateDir, pipeline.policy.obligations),
1361
4179
  });
4180
+ if (options.scope !== 'changed' &&
4181
+ sealed.result.complete &&
4182
+ !options.resultOnly &&
4183
+ executionDurationMs !== null) {
4184
+ writeLastFullRunSummary(stateDir, {
4185
+ testCount: executionSummary.selectedTests.selected,
4186
+ durationMs: executionDurationMs,
4187
+ });
4188
+ }
4189
+ // The tree this run actually TESTED. Without the global native
4190
+ // preparation freeze that is the frozen pre-run tree, exactly as before;
4191
+ // with it, it is the ONE prepared candidate the freeze accepted after
4192
+ // the prerequisite stage — never a rebound baseline, and never a second
4193
+ // snapshot. Both the final drift check and the receipt bind this value.
4194
+ const testedTreeId = acceptedPreparedIdentity()?.preparedTreeId ?? frozenTreeId;
4195
+ // The test-only re-seal must hold against the tree this run actually
4196
+ // TESTED, and the fresh outcomes it issues must be EXACTLY the tests
4197
+ // that classification names — in BOTH directions. Before the global
4198
+ // preparation freeze the tested tree is the pre-run baseline the plan
4199
+ // was decided from; with the freeze it is the PREPARED candidate, and a
4200
+ // native preparation stage that restores a parent state target shrinks
4201
+ // the affected set after the plan was made. An affected file with no
4202
+ // fresh outcome leaves a claim nobody proved; a fresh outcome the
4203
+ // affected set does not name is proof the sealed classification does
4204
+ // not cover, and the independent chain check refuses exactly that as
4205
+ // EVIDENCE_STALE.
4206
+ //
4207
+ // So the classification is recomputed here from the SAME two sealed
4208
+ // trees a consumer recomputes from ONLY when the tested tree moved, the
4209
+ // seal binds THAT result, and an unchanged tested tree reuses the
4210
+ // plan's own classification rather than recomputing nothing new. Either
4211
+ // way the two-sided membership check runs on EVERY re-seal issuance, and
4212
+ // a mismatch is a targeted refusal naming every offending file and the
4213
+ // explicit full-fresh command — never a silent carry of proof that no
4214
+ // longer applies, and never a hop this run's own consumer will reject.
4215
+ let preparedReseal = reSealPlan;
4216
+ let preparedResealRefusal = null;
4217
+ let preparedClassification = null;
4218
+ if (reSealPlan !== null && testedTreeId !== null && testedTreeId !== frozenTreeId && freezeGitDir !== null) {
4219
+ preparedClassification = classifyResealChange({
4220
+ gitDir: freezeGitDir,
4221
+ env: io.env,
4222
+ cwd: io.cwd,
4223
+ parentTreeId: reSealPlan.parentTreeId,
4224
+ currentTreeId: testedTreeId,
4225
+ testFiles: catalog === null ? [] : [...new Set(catalog.entries.map((entry) => entry.file))],
4226
+ // The two commit trees travel whenever both exist: they say which
4227
+ // paths are tracked SOURCE, which is what decides whether a
4228
+ // declared browser state the preparation stage rewrote counts as
4229
+ // generated output at all. An owner declaration only adds the
4230
+ // second use of the same reading, so it no longer gates them.
4231
+ ...(reSealPlan.parentSha.length > 0 && pipeline.manifest.gitSha !== null
4232
+ ? {
4233
+ parentCommitTreeId: `${reSealPlan.parentSha}^{tree}`,
4234
+ currentCommitTreeId: `${pipeline.manifest.gitSha}^{tree}`,
4235
+ }
4236
+ : {}),
4237
+ ...(config.enforcement?.resealRuntimeFiles !== undefined
4238
+ ? { runtimeFileGlobs: config.enforcement.resealRuntimeFiles }
4239
+ : {}),
4240
+ ...(preFiles !== null ? { inputFiles: new Set(preFiles.map((entry) => entry.path)) } : {}),
4241
+ });
4242
+ }
4243
+ if (reSealPlan !== null && testedTreeId !== null) {
4244
+ const recomputed = preparedClassification ?? reSealPlan.classification;
4245
+ if (!recomputed.eligible) {
4246
+ // A change set that no longer classifies against the PREPARED tree
4247
+ // is refused the same actionable way an uncovered carry is: the
4248
+ // offending path the classifier named, and the explicit full-fresh
4249
+ // command that re-runs everything against the prepared candidate.
4250
+ // The feature is never disabled and nothing is silently carried.
4251
+ preparedResealRefusal =
4252
+ `${recomputed.reason ?? 'the change set no longer classifies'} — the prepared candidate tree ` +
4253
+ `${testedTreeId.slice(0, 12)}… differs from the pre-run tree this re-seal was planned from; ` +
4254
+ 're-run the full relevant suite (`gateforge test-gates --changed --scope full`) so every ' +
4255
+ 'affected test executes against the prepared candidate';
4256
+ preparedReseal = null;
4257
+ }
4258
+ else {
4259
+ const freshFiles = new Set(plannedRows.map((row) => row.planned.file));
4260
+ const uncovered = recomputed.affectedTestFiles.filter((file) => !freshFiles.has(file)).sort();
4261
+ // BOTH directions, because the independent chain check requires
4262
+ // both. The second is what a preparation restore produces: the
4263
+ // state returns to its parent revision, the readers that change
4264
+ // dragged into the affected set drop back out of it, and the plan
4265
+ // made before that restore still executes them. Sealing anyway
4266
+ // issues a hop the very next `check` refuses, so it is refused
4267
+ // here, where every extra path and the fix can still be named.
4268
+ const affectedSet = new Set(recomputed.affectedTestFiles);
4269
+ const outside = [...freshFiles].filter((file) => !affectedSet.has(file)).sort();
4270
+ if (uncovered.length > 0 || outside.length > 0) {
4271
+ const freshen = 're-run the full relevant suite (`gateforge test-gates --changed --scope full`) so the re-sealed ' +
4272
+ 'receipt carries outcomes only for the tests its own classification names';
4273
+ if (uncovered.length > 0 && outside.length > 0) {
4274
+ preparedResealRefusal =
4275
+ 'the executed set and the sealed affected set disagree in BOTH directions: this re-seal carried ' +
4276
+ `instead of re-running (${uncovered.join(', ')}) and re-ran test file(s) the affected set does ` +
4277
+ `not name (${outside.join(', ')}) — ${freshen}`;
4278
+ }
4279
+ else if (uncovered.length > 0) {
4280
+ // The prepared-drift wording is true only when the tested tree
4281
+ // actually moved. An unchanged tree has no preparation drift
4282
+ // to blame, so the reason names the membership mismatch itself
4283
+ // rather than inventing a cause for it.
4284
+ if (preparedClassification !== null) {
4285
+ preparedResealRefusal =
4286
+ `native preparation changed the tested bytes in a way that affects test file(s) this re-seal ` +
4287
+ `carried instead of re-running (${uncovered.join(', ')}) — re-run the full relevant suite ` +
4288
+ '(`gateforge test-gates --changed --scope full`) so every affected test executes against the ' +
4289
+ 'prepared candidate';
4290
+ }
4291
+ else {
4292
+ preparedResealRefusal =
4293
+ `this re-seal carried test file(s) its own classification requires it to re-run ` +
4294
+ `(${uncovered.join(', ')}) — ${freshen}`;
4295
+ }
4296
+ }
4297
+ else {
4298
+ preparedResealRefusal =
4299
+ `this re-seal executed test file(s) the sealed affected set does not name (${outside.join(', ')}) — ` +
4300
+ freshen;
4301
+ }
4302
+ preparedReseal = null;
4303
+ }
4304
+ else {
4305
+ // Reuse the plan itself when the tested tree did not move: its
4306
+ // classification is already the one that applies, so rebuilding
4307
+ // an identical object would be a copy with no new information.
4308
+ preparedReseal =
4309
+ preparedClassification === null
4310
+ ? reSealPlan
4311
+ : { ...reSealPlan, classification: preparedClassification };
4312
+ }
4313
+ }
4314
+ }
4315
+ if (preparedResealRefusal !== null) {
4316
+ writeLine(io.stderr, `test-gates: ${resealRefusal(preparedResealRefusal)}`);
4317
+ // No receipt: a test-only seal over this prepared tree would claim
4318
+ // evidence for bytes the change set no longer supports.
4319
+ clearGateReceipt(stateDir);
4320
+ clearResealChain(stateDir);
4321
+ return 1;
4322
+ }
4323
+ if (controlSpecDrift !== null) {
4324
+ writeLine(io.stderr, `test-gates: ${controlSpecDrift}`);
4325
+ // Nothing downstream of this point may be accepted: the graded
4326
+ // report, the receipt, and the carried re-seal all claim this run
4327
+ // froze its candidate under a control nobody replaced. An
4328
+ // authoritative run therefore invalidates the receipt and the chain
4329
+ // it was about to extend; a result-only run owns neither, so its
4330
+ // precedence is untouched.
4331
+ if (!options.resultOnly) {
4332
+ clearGateReceipt(stateDir);
4333
+ clearResealChain(stateDir);
4334
+ }
4335
+ return 1;
4336
+ }
1362
4337
  const diagnosticContext = {
1363
- scope: options.scope,
1364
- candidateTreeId: frozenTreeId,
4338
+ scope: namedTestIds !== null ? 'named' : options.scope,
4339
+ candidateTreeId: testedTreeId,
1365
4340
  inputDigest: expectedDigest,
1366
4341
  evidenceState: snapshotUnavailable
1367
4342
  ? 'snapshot-unavailable'
@@ -1383,32 +4358,241 @@ export async function runSupervisedTestGates(io, options) {
1383
4358
  guarantee: DOCS_EXCLUSIONS_GUARANTEE,
1384
4359
  },
1385
4360
  }),
4361
+ ...(cacheExclusions.length === 0
4362
+ ? {}
4363
+ : {
4364
+ cacheExclusions: {
4365
+ files: cacheExclusions,
4366
+ approvalDigest: approvedPolicyDigest ?? trustedPolicy,
4367
+ approvalStatus: 'matched',
4368
+ guarantee: CACHE_EXCLUSIONS_GUARANTEE,
4369
+ },
4370
+ }),
1386
4371
  };
1387
- const report = renderRun(evaluated.verdicts, {
4372
+ // Report-side strictness + quarantine:
4373
+ // ADDITIVE only. A repository that never softened its gate and never
4374
+ // quarantined a test gets exactly the document it got before.
4375
+ const renderedReport = renderRun(evaluated.verdicts, {
1388
4376
  format,
1389
4377
  blocking: evaluated.blocking,
4378
+ // Twin path coverage (E64): reported, never blocking, in advisory
4379
+ // mode. An empty list adds no report key, so a run without twin
4380
+ // findings keeps exactly the document it always had.
4381
+ ...(twinAdvisories.length === 0 ? {} : { advisories: twinAdvisories }),
1390
4382
  waiverCounts: evaluated.waiverCounts,
1391
4383
  run: manifest,
1392
4384
  toolVersion: VERSION,
4385
+ engine: engineIdentity(),
4386
+ engineLine: reportEngineLine(),
4387
+ lifecycleDerivation: pipeline.lifecycleDerivation,
1393
4388
  execution: executionSummary,
1394
4389
  diagnosticContext,
4390
+ ...(options.resultOnly ? { outcome: 'partial-selection' } : {}),
4391
+ ...(namedSelections !== null ? { selectors: namedSelections } : {}),
4392
+ ...(chaosRun === null
4393
+ ? {}
4394
+ : { chaos: { ...chaosRun, ...(chaosSchedule === null ? {} : { schedule: chaosSchedule }) } }),
4395
+ ...(localFailures.length === 0 ? {} : { failedTests: localFailures }),
4396
+ });
4397
+ /**
4398
+ * The persisted json document: the same report shape stdout shows for a
4399
+ * json run, plus this run's strictness/quarantine blocks. Rendered
4400
+ * independently of `format` because the text run's rendered report is
4401
+ * text, not json.
4402
+ */
4403
+ const jsonReportDocument = () => canonicalJson({
4404
+ ...JSON.parse(renderRun(evaluated.verdicts, {
4405
+ format: 'json',
4406
+ blocking: evaluated.blocking,
4407
+ ...(twinAdvisories.length === 0 ? {} : { advisories: twinAdvisories }),
4408
+ waiverCounts: evaluated.waiverCounts,
4409
+ run: manifest,
4410
+ toolVersion: VERSION,
4411
+ engine: engineIdentity(),
4412
+ lifecycleDerivation: pipeline.lifecycleDerivation,
4413
+ execution: executionSummary,
4414
+ diagnosticContext,
4415
+ ...(options.resultOnly ? { outcome: 'partial-selection' } : {}),
4416
+ ...(namedSelections !== null ? { selectors: namedSelections } : {}),
4417
+ ...(chaosRun === null
4418
+ ? {}
4419
+ : { chaos: { ...chaosRun, ...(chaosSchedule === null ? {} : { schedule: chaosSchedule }) } }),
4420
+ })),
4421
+ ...(gateMode === 'strict'
4422
+ ? {}
4423
+ : {
4424
+ strictness: {
4425
+ mode: strictness.mode,
4426
+ wouldBlock: strictness.wouldBlock,
4427
+ blockingInScope: strictness.blockingInScope,
4428
+ blockingTotal: strictness.blockingTotal,
4429
+ },
4430
+ }),
4431
+ ...(quarantines.active.length === 0
4432
+ ? {}
4433
+ : {
4434
+ quarantine: {
4435
+ count: quarantines.active.length,
4436
+ tests: quarantines.active.map((entry) => ({
4437
+ testKey: entry.quarantine.testKey,
4438
+ expiresAt: entry.quarantine.expiresAt,
4439
+ owner: entry.quarantine.owner,
4440
+ })),
4441
+ },
4442
+ }),
1395
4443
  });
4444
+ const report = format === 'text'
4445
+ ? `${renderedReport}\n${strictnessSummaryLine(strictness)}${quarantines.active.length === 0
4446
+ ? ''
4447
+ : `\nquarantined: ${String(quarantines.active.length)} (expires ${quarantines.active
4448
+ .map((entry) => `${entry.quarantine.testKey} @ ${entry.quarantine.expiresAt}`)
4449
+ .join(', ')})`}`
4450
+ : format === 'json'
4451
+ ? jsonReportDocument()
4452
+ : renderedReport;
1396
4453
  writeLine(io.stdout, report);
1397
- writeReport(stateDir, renderRun(evaluated.verdicts, {
1398
- format: 'json',
1399
- blocking: evaluated.blocking,
1400
- waiverCounts: evaluated.waiverCounts,
1401
- run: manifest,
1402
- toolVersion: VERSION,
1403
- execution: executionSummary,
1404
- diagnosticContext,
1405
- }));
4454
+ // The persisted report carries the SAME document stdout got: a later
4455
+ // consumer must see the strictness the run used and the quarantined
4456
+ // population, never a quieter one.
4457
+ writeReport(stateDir, jsonReportDocument());
1406
4458
  // 10. Only authoritative gate mode invalidates a previous receipt on
1407
4459
  // failure. Result-only reporting never creates, replaces, or clears one.
1408
- const gateCode = runExitCode({ verdicts: evaluated.verdicts, blocking: evaluated.blocking });
1409
- if (gateCode !== 0 || !sealed.result.complete || changedInputs || snapshotUnavailable || expectedDigest === null) {
1410
- if (!options.resultOnly)
4460
+ // Owner-chosen strictness decides the exit code, never the evaluation:
4461
+ // a softened run still reports everything and, when it hides a block,
4462
+ // says so out loud. Setup/integrity failures above (drift, an
4463
+ // unresolvable input digest) are NOT softened — a run that could not
4464
+ // be evaluated honestly has nothing to report.
4465
+ const gateCode = strictness.exitCode;
4466
+ const softened = strictness.exitCode !== strictness.strictExitCode;
4467
+ // The post-run candidate tree, computed ONCE and used by both the
4468
+ // run record below and the drift check after the gate branch.
4469
+ const resultGitDir = resolveGitDir(io.cwd, io.env);
4470
+ const resultTreeSnapshot = resultGitDir === null
4471
+ ? null
4472
+ : computeCandidateTreeSnapshot(resultGitDir, io.cwd, io.env, stateDir, 'record', runtimeReuseMounts, docsExclusions, cacheExclusions);
4473
+ const resultTreeId = resultTreeSnapshot?.treeId ?? null;
4474
+ /**
4475
+ * Retains this run's own witness evidence for the re-seal that may
4476
+ * come for it: the records and claims it just produced, plus the
4477
+ * exact envelope the document it is about to seal binds by digest.
4478
+ *
4479
+ * The copy exists because the LIVE state cannot be trusted to still
4480
+ * hold them: a materialization pre-step rewrites `manifest.json`
4481
+ * (and the witness envelope with it) between this run and the re-seal,
4482
+ * and a run that writes records of its own replaces the documents.
4483
+ * It is retained only when the owner opted into the re-seal, so a
4484
+ * state directory without that opt-in is byte-identical to before.
4485
+ * It is replaced by the next run that seals a document here, and
4486
+ * removed with the one it belongs to.
4487
+ */
4488
+ const retainParentEvidence = () => {
4489
+ if (config.enforcement?.reseal !== true)
4490
+ return;
4491
+ writeRetainedParentEvidence(stateDir, {
4492
+ records: readJsonArray(stateDir, 'records.json'),
4493
+ claims: readJsonArray(stateDir, 'claims.json'),
4494
+ // The witness appends its envelope to the run manifest as it
4495
+ // shuts down, so the manifest is the honest source for a run
4496
+ // whose own live fetch was too late to see it: prefer the
4497
+ // fetched one, fall back to what the run state holds.
4498
+ attestation: liveAttestation ?? readRunAttestation(stateDir),
4499
+ });
4500
+ };
4501
+ /**
4502
+ * Writes the run record of a whole-suite run that sealed no gate
4503
+ * receipt.
4504
+ *
4505
+ * A failing test is exactly the case a test-only re-seal exists for,
4506
+ * and a failing run issues no receipt (it clears the old one), so
4507
+ * without this record the path would be unusable where it matters
4508
+ * most. The record binds the same evidence a receipt binds and NO
4509
+ * verdict: `check`, pre-commit and the broker never read it, so a run
4510
+ * record alone leaves every gate exactly as blocked as it was. It is
4511
+ * written only for an authoritative whole-suite run whose evidence
4512
+ * is honestly bound — never for a slice, a named selection, a
4513
+ * result-only report, a drifting workspace or changed inputs.
4514
+ */
4515
+ const wholeSuiteRunRecord = () => {
4516
+ if (options.resultOnly ||
4517
+ namedTestIds !== null ||
4518
+ options.scope !== 'full' ||
4519
+ witnessVerifierKey === undefined ||
4520
+ approvedPolicyDigest === null ||
4521
+ expectedDigest === null ||
4522
+ snapshotUnavailable ||
4523
+ changedInputs ||
4524
+ resultTreeId === null ||
4525
+ resultTreeId !== testedTreeId ||
4526
+ catalog === null) {
4527
+ return;
4528
+ }
4529
+ writeRunRecord(stateDir, issueRunRecord({
4530
+ verifierKey: witnessVerifierKey,
4531
+ ...(verifierKeyring === null ? {} : { verifierKeyId: verifierKeyring.active.keyId }),
4532
+ runId: manifest.runId,
4533
+ invocationId,
4534
+ inputDigest: expectedDigest,
4535
+ gitSha: manifest.gitSha,
4536
+ parentSha: frozenParentSha,
4537
+ trustedPolicyDigest: trustedPolicy,
4538
+ approvedPolicyDigest,
4539
+ invocation: SUPERVISED_INVOCATION,
4540
+ selectionDigest,
4541
+ catalogDigest,
4542
+ executionResultDigest: sealed.digest,
4543
+ testOutcomesDigest: testOutcomesDigestOf(sealed.result.outcomes),
4544
+ plannedTests: sealed.result.planned.length,
4545
+ passedTests: sealed.result.outcomes.filter((outcome) => outcome.status === 'passed').length,
4546
+ evidenceAttestationDigest: liveAttestation === null ? null : sha256Canonical(liveAttestation),
4547
+ candidateTreeId: resultTreeId,
4548
+ engineBundleDigest: engineBundleDigestOf(VERSION, trustedPolicy),
4549
+ executionBoundaryDigest,
4550
+ issuedAt: pipeline.now,
4551
+ }));
4552
+ // The record and the evidence copy a re-seal reads from it are
4553
+ // written together, or neither is: a record whose own evidence is
4554
+ // not beside it would be refused for a reason the owner cannot fix.
4555
+ retainParentEvidence();
4556
+ };
4557
+ if (namedTestIds !== null) {
4558
+ // A named run is a REPORT, never a gate. It exits 0 only when the
4559
+ // selection itself is honest and complete: every selected test
4560
+ // passed and every obligation its claims declare is satisfied (or
4561
+ // waived by the owner), with no run-execution finding, no
4562
+ // incomplete execution, no changed inputs and a usable snapshot.
4563
+ // Anything else is exit 1. It never exits 2 here: an unresolvable
4564
+ // selector already threw a UsageError before anything ran, and it
4565
+ // never clears a receipt, because result-only never seals one.
4566
+ const selection = executionSummary.selectedTests.passed === executionSummary.selectedTests.selected &&
4567
+ executionSummary.selectedTests.selected > 0;
4568
+ const claimsProven = evaluated.blocking.length === 0 &&
4569
+ evaluated.verdicts.every((verdict) => verdict.verdict === 'satisfied' || verdict.verdict === 'waived');
4570
+ const runHonest = sealed.result.complete && !changedInputs && !snapshotUnavailable && expectedDigest !== null;
4571
+ if (!selection || !claimsProven || !runHonest)
4572
+ return 1;
4573
+ }
4574
+ else if (gateCode !== 0 || !sealed.result.complete || changedInputs || snapshotUnavailable || expectedDigest === null) {
4575
+ if (strictness.strictExitCode !== 0 && !options.resultOnly && !softened) {
1411
4576
  clearGateReceipt(stateDir);
4577
+ // A run that seals no receipt invalidates the re-seal chain with
4578
+ // it: the chain describes the parents of the receipt that is no
4579
+ // longer there, and its evidence was already overwritten by this
4580
+ // run's own. Leaving it behind would be read as a chain.
4581
+ clearResealChain(stateDir);
4582
+ // The retained parent evidence belongs to the receipt this run
4583
+ // just invalidated, exactly as the chain does: it is cleared here
4584
+ // and written again below, together with the run record that
4585
+ // replaces it.
4586
+ clearRetainedParentEvidence(stateDir);
4587
+ }
4588
+ // The run sealed no receipt; the evidence it DID produce is
4589
+ // retained as a run record, which only the test-only re-seal path
4590
+ // may read. It grants nothing on its own.
4591
+ wholeSuiteRunRecord();
4592
+ if (softened) {
4593
+ writeLine(io.stderr, `test-gates: ${strictnessSummaryLine(strictness)} — the gate exits 0 in mode '${strictness.mode}', ` +
4594
+ `strict mode would exit ${String(strictness.strictExitCode)}`);
4595
+ }
1412
4596
  return gateCode === 0 ? 1 : gateCode;
1413
4597
  }
1414
4598
  // The result-only selection uses either a private temporary state dir or
@@ -1416,20 +4600,23 @@ export async function runSupervisedTestGates(io, options) {
1416
4600
  // reads, writes, or clears the configured authoritative receipt.
1417
4601
  // Confirm the same candidate-tree drift check before returning a
1418
4602
  // descriptive pass.
1419
- const resultGitDir = resolveGitDir(io.cwd, io.env);
1420
- const resultTreeId = resultGitDir === null
1421
- ? null
1422
- : computeCandidateTreeId(resultGitDir, io.cwd, io.env, stateDir, 'record', runtimeReuseMounts, docsExclusions);
1423
- if (resultTreeId !== frozenTreeId) {
4603
+ if (resultTreeId !== testedTreeId) {
1424
4604
  writeLine(io.stderr, 'test-gates: the workspace changed during the run ' +
1425
- `(${frozenTreeId ?? 'unborn'} → ${resultTreeId ?? 'unborn'}); ` +
4605
+ `(${testedTreeId ?? 'unborn'} → ${resultTreeId ?? 'unborn'}); ` +
1426
4606
  'no result is reported for mixed bytes (fail closed)');
1427
4607
  return 1;
1428
4608
  }
1429
4609
  if (options.resultOnly) {
1430
- writeLine(io.stderr, 'selected result passed; this result is non-authoritative and did not create a gate receipt');
4610
+ // A named run always lands here: it reported its selection and
4611
+ // sealed nothing.
1431
4612
  return 0;
1432
4613
  }
4614
+ if (expectedDigest === null) {
4615
+ // Unreachable: the gate path above already returned 1 for an
4616
+ // unusable snapshot. Kept so the seal below never sees a null
4617
+ // input digest.
4618
+ return 1;
4619
+ }
1433
4620
  if (witnessVerifierKey === undefined) {
1434
4621
  // No verifier key: the receipt cannot be signed by the same
1435
4622
  // authority as witness records — never mint an unverifiable one.
@@ -1461,6 +4648,8 @@ export async function runSupervisedTestGates(io, options) {
1461
4648
  parentSha: frozenParentSha,
1462
4649
  trustedPolicyDigest: trustedPolicy,
1463
4650
  approvedPolicyDigest,
4651
+ receiptStage: config.enforcement?.receiptStage,
4652
+ engine: engineIdentity(),
1464
4653
  invocation: SUPERVISED_INVOCATION,
1465
4654
  selectionDigest,
1466
4655
  catalogDigest,
@@ -1470,6 +4659,37 @@ export async function runSupervisedTestGates(io, options) {
1470
4659
  ...(options.scope === 'changed'
1471
4660
  ? { scope: 'changed', coveredObligationFingerprints: coveredFingerprints }
1472
4661
  : {}),
4662
+ // Test-only re-seal bindings (additive): the parent this run
4663
+ // re-sealed from — a gate receipt or a run record, named by
4664
+ // `resealedFromKind` — how many outcomes it carried, how many
4665
+ // tests it re-ran, and the change set Gateforge itself computed.
4666
+ // CI recomputes every one of them from the two sealed trees.
4667
+ ...(preparedReseal === null
4668
+ ? {}
4669
+ : {
4670
+ ...(preparedReseal.parentKind === 'receipt'
4671
+ ? { carriedFrom: preparedReseal.parentSha, parentReceiptDigest: preparedReseal.parentDigest }
4672
+ : {}),
4673
+ resealedFrom: preparedReseal.parentDigest,
4674
+ resealedFromKind: preparedReseal.parentKind,
4675
+ changeClass: 'test-only',
4676
+ carriedTests: preparedReseal.carriedTests,
4677
+ rerunTests: plannedRows.length,
4678
+ changedPaths: preparedReseal.classification.changedPaths,
4679
+ // Which of those paths the owner's runtime-file declaration
4680
+ // hid, and the consumer recomputes the list from the same
4681
+ // declaration — a difference is EVIDENCE_STALE.
4682
+ ...((preparedReseal.classification.disregardedPaths ?? []).length > 0
4683
+ ? { resealDisregarded: preparedReseal.classification.disregardedPaths }
4684
+ : {}),
4685
+ // The graded evidence union — the carried parent records and
4686
+ // claims plus this run's own — bound by the receipt MAC, so a
4687
+ // consumer recomputes it and demands the state evidence equal
4688
+ // it.
4689
+ ...(carriedEvidenceDocumentsUnion === null
4690
+ ? {}
4691
+ : { carriedEvidenceDigest: carriedEvidenceDigestOf(carriedEvidenceDocumentsUnion) }),
4692
+ }),
1473
4693
  executionResultDigest: sealed.digest,
1474
4694
  evidenceAttestationDigest: liveAttestation === null ? null : sha256Canonical(liveAttestation),
1475
4695
  candidateTreeId,
@@ -1488,7 +4708,44 @@ export async function runSupervisedTestGates(io, options) {
1488
4708
  issuedAt: pipeline.now,
1489
4709
  });
1490
4710
  writeGateReceipt(stateDir, receipt);
4711
+ // A receipt supersedes the run record of the same run: it carries the
4712
+ // same evidence PLUS a verdict, so the record is dropped rather than
4713
+ // left behind as a stale parent (the re-seal's own copy of the parent
4714
+ // it consumed lives in the retained chain below).
4715
+ clearRunRecord(stateDir);
4716
+ // This receipt is now the parent, so the evidence copy a re-seal reads
4717
+ // is this run's own: written from the same envelope the receipt binds
4718
+ // by digest, and replacing whatever the previous parent left behind.
4719
+ retainParentEvidence();
4720
+ // The re-seal chain is additive run state: a re-sealed receipt keeps
4721
+ // its parent (receipt or run record, plus its execution result) and
4722
+ // the catalog its classification used, so a consumer can recompute
4723
+ // the re-seal with its own engine and key. Any other seal leaves no
4724
+ // chain behind.
4725
+ if (preparedReseal !== null && reSealParent !== null && catalog !== null) {
4726
+ writeResealChainHop(stateDir, {
4727
+ ...(reSealParent.receipt === null
4728
+ ? { runRecord: reSealParent.record, receipt: null }
4729
+ : { receipt: reSealParent.receipt, runRecord: null }),
4730
+ execution: reSealParent.execution,
4731
+ catalog,
4732
+ records: reSealParentEvidence?.records ?? [],
4733
+ claims: reSealParentEvidence?.claims ?? [],
4734
+ attestations: reSealParentEvidence?.attestations ?? [],
4735
+ });
4736
+ }
4737
+ else {
4738
+ clearResealChain(stateDir);
4739
+ }
4740
+ writeCandidateTreeEntries(stateDir, resultTreeSnapshot?.entries ?? []);
1491
4741
  writeLine(io.stderr, `receipt ${receipt.receiptId} sealed (complete run, evidence graded, inputs bound)`);
4742
+ if (preparedReseal !== null) {
4743
+ const disregarded = preparedReseal.classification.disregardedPaths ?? [];
4744
+ if (disregarded.length > 0)
4745
+ writeLine(io.stderr, `test-gates: ${resealDisregardNotice(disregarded)}`);
4746
+ writeLine(io.stderr, `only test files changed: re-ran ${String(plannedRows.length)} test(s), kept ${String(preparedReseal.carriedTests)} ` +
4747
+ `from the previous ${preparedReseal.parentKind === 'run-record' ? 'run' : 'receipt'}`);
4748
+ }
1492
4749
  return 0;
1493
4750
  }
1494
4751
  /** Runs the configured ADVISORY diagnostic suites as a separate step. */
@@ -1625,6 +4882,26 @@ function countUnclaimedObligations(stateDir, obligations) {
1625
4882
  }
1626
4883
  return obligations.filter((obligation) => !claimed.has(obligation.id)).length;
1627
4884
  }
4885
+ /**
4886
+ * Normalizes one runner-reported outcome onto the stream's vocabulary.
4887
+ *
4888
+ * A skipped test is a skip in every runner (`skipped`, `pending`); an
4889
+ * expected failure is still a non-passing test, and anything the
4890
+ * vocabulary does not know is reported as a failure — never as a pass.
4891
+ *
4892
+ * Args:
4893
+ * outcome: the status the runner adapter reported.
4894
+ *
4895
+ * Returns:
4896
+ * ProgressOutcome: the outcome the progress stream counts.
4897
+ */
4898
+ function progressOutcomeOf(outcome) {
4899
+ if (outcome === 'passed')
4900
+ return 'passed';
4901
+ if (outcome === 'skipped' || outcome === 'pending' || outcome === 'fixme')
4902
+ return 'skipped';
4903
+ return 'failed';
4904
+ }
1628
4905
  /** Builds the report counts from trusted execution and full-scope evaluation.
1629
4906
  *
1630
4907
  * Args:
@@ -1647,7 +4924,16 @@ function runExecutionSummaryOf(input) {
1647
4924
  const expectedFailures = finalOutcomes.filter((outcome) => outcome.status === 'failed' && outcome.expectedFailure).length;
1648
4925
  const selected = input.executionResult.planned.length;
1649
4926
  const blockingSelected = input.selectedVerdicts.filter((verdict) => verdict.verdict !== 'satisfied' && verdict.verdict !== 'waived').length;
1650
- const blockingRepository = input.repositoryVerdicts.filter((verdict) => verdict.verdict !== 'satisfied' && verdict.verdict !== 'waived').length;
4927
+ // The one definition, over both halves this run evaluated: the
4928
+ // graded surface (what the exit code blocks on) and the whole
4929
+ // repository (what the report describes).
4930
+ const debt = repositoryDebtOf({
4931
+ verdicts: input.repositoryVerdicts,
4932
+ findings: input.repositoryBlocking,
4933
+ gradedVerdicts: input.selectedVerdicts,
4934
+ gradedFindings: input.selectedBlocking,
4935
+ unclaimed: input.unclaimed,
4936
+ });
1651
4937
  return {
1652
4938
  scope: input.scope,
1653
4939
  mode: input.mode,
@@ -1666,12 +4952,9 @@ function runExecutionSummaryOf(input) {
1666
4952
  blockingEntries: input.selectedBlocking.length,
1667
4953
  waived: input.selectedVerdicts.filter((verdict) => verdict.verdict === 'waived').length,
1668
4954
  },
1669
- repositoryDebt: {
1670
- obligations: input.repositoryVerdicts.length,
1671
- blocking: blockingRepository + input.repositoryBlocking.length,
1672
- blockingEntries: input.repositoryBlocking.length,
1673
- unclaimed: input.unclaimed,
1674
- },
4955
+ // The one definition: the split is read back from what the
4956
+ // evaluator actually graded, never recomputed beside it.
4957
+ repositoryDebt: debt,
1675
4958
  };
1676
4959
  }
1677
4960
  /** A schema-valid empty catalog (used only when discovery itself failed). */
@@ -1716,7 +4999,13 @@ async function stopWitnessProcess(handle) {
1716
4999
  * verifierKey: the witness verifier key (attestation auth; never the
1717
5000
  * suite run token).
1718
5001
  * body: the validated current runId, fresh invocationId, and tested
1719
- * inputDigest from trusted caller memory.
5002
+ * inputDigest from trusted caller memory, plus the additive run
5003
+ * `options` (chaos / twin shapes) when this run asked for any.
5004
+ *
5005
+ * Returns:
5006
+ * AppliedWitnessOptions | null: the options the witness confirmed it
5007
+ * is applying, or null for a witness that does not echo them (an
5008
+ * older build) — never a guess.
1720
5009
  *
1721
5010
  * Throws:
1722
5011
  * Error: fail-closed when the witness refuses (used witness, changed
@@ -1746,8 +5035,14 @@ async function bindWitnessContext(witnessUrl, runToken, verifierKey, body) {
1746
5035
  body: canonicalJson(body),
1747
5036
  signal: controller.signal,
1748
5037
  });
1749
- if (response.ok)
1750
- return;
5038
+ if (response.ok) {
5039
+ // The `applied` echo is how the run learns whether this witness
5040
+ // UNDERSTOOD the options. A witness older than them answers
5041
+ // without it, and the caller must say so rather than report a
5042
+ // comparison — or a schedule — that never happened.
5043
+ const confirmed = (await response.json().catch(() => null));
5044
+ return isAppliedWitnessOptions(confirmed?.applied) ? confirmed.applied : null;
5045
+ }
1751
5046
  const status = response.status;
1752
5047
  let detail = '';
1753
5048
  try {
@@ -1770,6 +5065,144 @@ async function bindWitnessContext(witnessUrl, runToken, verifierKey, body) {
1770
5065
  clearTimeout(timer);
1771
5066
  }
1772
5067
  }
5068
+ /**
5069
+ * Builds the witness-side case assignments for this run: which compiled
5070
+ * behavior cases a given test may execute, keyed by the identity the
5071
+ * runner opens its session with (its own framework id, falling back to
5072
+ * the derived logical key exactly like the expected set does).
5073
+ *
5074
+ * The witness resolves `/behavior/execute` through this binding alone,
5075
+ * so it is supervisor-authenticated run input, never a suite-supplied
5076
+ * claim. A declaration whose test is absent from the current catalog
5077
+ * contributes no assignment (its test cannot open a session anyway);
5078
+ * a declaration without `caseIds` declares nothing.
5079
+ *
5080
+ * Args:
5081
+ * catalog: the current discovered test catalog.
5082
+ * sidecar: the validated `.gateforge/test-map.yml`, or null.
5083
+ *
5084
+ * Returns:
5085
+ * Record<string, string[]>: session test id → sorted case ids.
5086
+ */
5087
+ function behaviorCaseAssignments(catalog, sidecar) {
5088
+ if (sidecar === null)
5089
+ return {};
5090
+ const identityByKey = new Map();
5091
+ for (const row of catalog.entries) {
5092
+ // A catalog row without a runner-native identity is keyed by the
5093
+ // derived logical key, exactly like the registered expected set.
5094
+ const identity = row.parameterIdentity === null || row.parameterIdentity.length === 0
5095
+ ? row.logicalKey
5096
+ : row.parameterIdentity;
5097
+ identityByKey.set(row.logicalKey, identity);
5098
+ }
5099
+ const assignments = {};
5100
+ for (const entry of sidecar.tests) {
5101
+ if (entry.caseIds === undefined || entry.caseIds.length === 0)
5102
+ continue;
5103
+ const identity = identityByKey.get(entry.key);
5104
+ if (identity === undefined)
5105
+ continue;
5106
+ const merged = new Set(assignments[identity] ?? []);
5107
+ for (const caseId of entry.caseIds)
5108
+ merged.add(caseId);
5109
+ assignments[identity] = [...merged].sort(compareStrings);
5110
+ }
5111
+ return assignments;
5112
+ }
5113
+ /**
5114
+ * Binds the compiled behavior catalog to a wired witness (plan
5115
+ * 2026-09-19 §4.7): supervisor-authenticated
5116
+ * `POST /runs/behavior-catalog`, carrying the catalog, the case
5117
+ * assignments, the COMPLETE route inventory principal attribution needs,
5118
+ * and the engine-bundle authority-profile digest — all compiled by this
5119
+ * run, never read from the suite.
5120
+ *
5121
+ * Called only when a `behaviorPolicy` compiled at least one case: a
5122
+ * repository without one makes no call and its run is byte-identical.
5123
+ *
5124
+ * Args:
5125
+ * witnessUrl: the wired witness base URL.
5126
+ * runToken: the witness run token (outer auth gate).
5127
+ * verifierKey: the witness verifier key (supervisor capability).
5128
+ * catalog: this run's compiled behavior catalog.
5129
+ * assignments: session test id → allowed case ids.
5130
+ * routes: the complete derived `http.endpoint` inventory.
5131
+ * authorityProfileDigest: the engine bundle + trusted policy digest.
5132
+ *
5133
+ * Throws:
5134
+ * Error: fail closed when the witness refuses the registration or is
5135
+ * unreachable. Without a bound catalog every behavior obligation stays
5136
+ * `missing`, so a silent skip would be a lie; diagnostics name only
5137
+ * the failure class, never verifier material.
5138
+ */
5139
+ async function registerWitnessBehaviorCatalog(input) {
5140
+ if (input.routes.length === 0) {
5141
+ throw new Error('test-gates: the compiled behavior catalog cannot be bound — no http.endpoint route was ' +
5142
+ 'discovered and principal attribution has no any-endpoint fallback; no behavior case can execute without it');
5143
+ }
5144
+ let body;
5145
+ try {
5146
+ body = BehaviorCatalogRegistrationSchema.parse({
5147
+ catalog: input.catalog,
5148
+ assignments: input.assignments,
5149
+ routes: input.routes.map((route) => ({
5150
+ resourceId: route.resourceId,
5151
+ method: route.method,
5152
+ // Route shapes use `{}` wildcards (core pathMatchesShape), so a
5153
+ // graph path written with a named parameter (`:id`, `{id}`) is
5154
+ // registered in that grammar.
5155
+ canonicalPath: route.canonicalPath
5156
+ .split('/')
5157
+ .map((segment) => (/^:[^/]+$/.test(segment) || /^\{[^/{}]+\}$/.test(segment) ? '{}' : segment))
5158
+ .join('/'),
5159
+ })),
5160
+ authorityProfileDigest: input.authorityProfileDigest,
5161
+ });
5162
+ }
5163
+ catch (error) {
5164
+ const first = error.message.split('\n')[0] ?? 'unknown schema error';
5165
+ throw new Error(`test-gates: the compiled behavior catalog is not registrable (${first}); no behavior case can execute without it`);
5166
+ }
5167
+ const controller = new AbortController();
5168
+ const timer = setTimeout(() => controller.abort(), 5_000);
5169
+ try {
5170
+ const response = await fetch(`${input.witnessUrl}/runs/behavior-catalog`, {
5171
+ method: 'POST',
5172
+ headers: {
5173
+ 'x-gateforge-run': input.runToken,
5174
+ 'x-gateforge-verifier': input.verifierKey,
5175
+ 'content-type': 'application/json',
5176
+ accept: 'application/json',
5177
+ connection: 'close',
5178
+ },
5179
+ body: canonicalJson(body),
5180
+ signal: controller.signal,
5181
+ });
5182
+ if (response.ok)
5183
+ return;
5184
+ const status = response.status;
5185
+ let detail = '';
5186
+ try {
5187
+ const errorBody = (await response.json());
5188
+ if (typeof errorBody.error === 'string')
5189
+ detail = `: ${errorBody.error}`;
5190
+ }
5191
+ catch {
5192
+ detail = '';
5193
+ }
5194
+ throw new Error(`test-gates: witness ${input.witnessUrl} refused the behavior-catalog bind (HTTP ${String(status)})${detail}; ` +
5195
+ 'no behavior case can execute without it');
5196
+ }
5197
+ catch (error) {
5198
+ if (error instanceof Error && error.message.startsWith('test-gates: witness'))
5199
+ throw error;
5200
+ throw new Error(`test-gates: witness ${input.witnessUrl} behavior-catalog bind failed (transport): ${error.message}`);
5201
+ }
5202
+ finally {
5203
+ clearTimeout(timer);
5204
+ }
5205
+ }
1773
5206
  /**
1774
5207
  * Fetches the live v2 attestation from a still-running wired witness
1775
5208
  * (pin #7, GF-23, plan §11.3/§11.5). A wired witness appends its