clearotron 0.5.1 → 0.6.0-beta.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 (379) hide show
  1. package/.env.example +7 -7
  2. package/INSTALL.md +10 -10
  3. package/QUICKSTART.md +6 -6
  4. package/README.md +2 -2
  5. package/THIRD-PARTY-NOTICES.md +4 -4
  6. package/bin/README.md +2 -2
  7. package/bin/clearotron.mjs +1 -1
  8. package/bin/connect.mjs +1 -1
  9. package/bin/disconnect.mjs +1 -1
  10. package/bin/example.mjs +2 -2
  11. package/bin/grant.mjs +1 -1
  12. package/bin/onboard.mjs +78 -23
  13. package/bin/start.mjs +49 -18
  14. package/bin/update.mjs +13 -3
  15. package/build-info.json +2 -2
  16. package/docs/DELIVERY.md +1 -1
  17. package/docs/PORTAL.md +1 -1
  18. package/docs/RELEASES.md +1 -1
  19. package/docs/architecture/02-architecture.md +10 -2
  20. package/docs/architecture/03-run-lifecycle.md +6 -2
  21. package/docs/architecture/04-configuration-reference.md +3 -3
  22. package/docs/architecture/05-config-governance.md +5 -4
  23. package/docs/architecture/08-development-guide.md +4 -4
  24. package/docs/architecture/09-security-and-data.md +1 -1
  25. package/{driver/skills/clearance-search/SKILL.md → docs/architecture/retired-manuals/clearance-search-spine.md} +17 -30
  26. package/{driver/skills/clearance-search/templates/email/generic.md → docs/architecture/retired-manuals/email-generic.md} +1 -1
  27. package/{driver/skills/clearance-search → docs/architecture/retired-manuals}/template-formatting.md +3 -4
  28. package/docs/configuration.md +1 -1
  29. package/docs/decisions/0002-no-dark-functionality.md +5 -0
  30. package/driver/CHANGELOG.md +60 -0
  31. package/driver/README.md +11 -1
  32. package/driver/accepted-order.mjs +13 -5
  33. package/driver/attempt-rows.mjs +64 -0
  34. package/driver/attributed-span.mjs +1 -1
  35. package/driver/authority-trees.mjs +1 -1
  36. package/driver/best-draft.mjs +3 -3
  37. package/driver/blind-frame-record.mjs +2 -2
  38. package/driver/cancel.mjs +3 -2
  39. package/driver/carry-through.mjs +2 -2
  40. package/driver/citation-census.json +3 -3
  41. package/driver/clearance-variants-record.mjs +4 -10
  42. package/driver/common-law-coverage-status.mjs +3 -3
  43. package/driver/common-law-receipts.mjs +2 -2
  44. package/driver/compare.mjs +1 -1
  45. package/driver/config-inventory.mjs +6 -79
  46. package/driver/consumption-ledger.mjs +2 -1
  47. package/driver/contract-dictation-registry.mjs +5 -0
  48. package/driver/contract-e3-backlog.mjs +45 -66
  49. package/driver/contract-e3-baseline.json +16 -16
  50. package/driver/contract-vocabulary.mjs +8 -6
  51. package/driver/corrections-feedforward.mjs +3 -1
  52. package/driver/coverage-form-io.mjs +7 -8
  53. package/driver/coverage-tool.mjs +1 -1
  54. package/driver/declination-tool.mjs +2 -2
  55. package/driver/degraded-parts.mjs +9 -9
  56. package/driver/demo-container.mjs +5 -4
  57. package/driver/deploy-live-run-guard.mjs +19 -7
  58. package/driver/derived-state.mjs +2 -2
  59. package/driver/dev-portal.mjs +2 -1
  60. package/driver/dispatch-record.mjs +1 -1
  61. package/driver/disposition-tool.mjs +2 -1
  62. package/driver/doubt-closure-tool.mjs +2 -2
  63. package/driver/driver.config.mjs +35 -724
  64. package/driver/e2e-rounds.mjs +3 -4
  65. package/driver/engine/CONTRACT.md +3 -0
  66. package/driver/engine/README.md +2 -0
  67. package/driver/engine/anthropic-agent.mjs +8 -37
  68. package/driver/engine/auth.mjs +74 -0
  69. package/driver/engine/child-record.mjs +1 -1
  70. package/driver/engine/deny-authority-write.mjs +2 -2
  71. package/driver/engine/jx-turn.mjs +10 -2
  72. package/driver/engine/mcp/README.md +1 -1
  73. package/driver/engine/mcp/band-server.mjs +6 -6
  74. package/driver/engine/mcp/codex-config.mjs +1 -1
  75. package/driver/engine/mcp/declination-server.mjs +2 -3
  76. package/driver/engine/mcp/dispositions-server.mjs +3 -3
  77. package/driver/engine/mcp/gather-config.mjs +24 -19
  78. package/driver/engine/mcp/grid-provenance.mjs +1 -1
  79. package/driver/engine/mcp/held-answers.mjs +5 -5
  80. package/driver/engine/mcp/perplexity-server.mjs +16 -7
  81. package/driver/engine/mcp/recording-server.mjs +7 -6
  82. package/driver/engine/mcp/register-server.mjs +29 -0
  83. package/driver/engine/mcp/stdio-server.mjs +5 -5
  84. package/driver/engine/mcp/supplemental.mjs +9 -9
  85. package/driver/engine/openai-agent.mjs +5 -2
  86. package/driver/engine/registry.mjs +103 -0
  87. package/driver/engine/run-choices.mjs +162 -0
  88. package/driver/engine/stamps.mjs +35 -0
  89. package/driver/enqueue-schema.mjs +4 -4
  90. package/driver/envelope-settle.mjs +3 -2
  91. package/driver/feedback-issues.mjs +1 -1
  92. package/driver/feedback-mint.mjs +3 -2
  93. package/driver/feedback-store.mjs +3 -2
  94. package/driver/findings-model.mjs +1 -1
  95. package/driver/flag-snapshot.mjs +5 -4
  96. package/driver/floor-duty.mjs +3 -3
  97. package/driver/foreign-record-links.mjs +1 -1
  98. package/driver/frame-diff-record.mjs +2 -8
  99. package/driver/framework.mjs +1 -1
  100. package/driver/gate-metrics.mjs +10 -11
  101. package/driver/gateway.mjs +220 -839
  102. package/driver/goods-evidence.mjs +10 -6
  103. package/driver/jx-lanes.mjs +3 -3
  104. package/driver/jx-units.mjs +31 -37
  105. package/driver/jx.mjs +44 -59
  106. package/driver/knockout-assess-record.mjs +3 -3
  107. package/driver/knockout-caveats.mjs +21 -0
  108. package/driver/knockout-correction-record.mjs +58 -28
  109. package/driver/knockout-frame-record.mjs +2 -2
  110. package/driver/knockout-register-read.mjs +38 -21
  111. package/driver/knockout-register-record.mjs +5 -6
  112. package/driver/knockout-review-record.mjs +12 -11
  113. package/driver/ladder/model-gauge.mjs +88 -0
  114. package/driver/ladder/next-rung.mjs +296 -0
  115. package/driver/ladder/rescue.mjs +146 -0
  116. package/driver/ladder/stage-tools.mjs +57 -0
  117. package/driver/ladder/turn-failure.mjs +166 -0
  118. package/driver/log.mjs +2 -2
  119. package/driver/matter-frame-record.mjs +4 -4
  120. package/driver/methodology-witness.mjs +2 -2
  121. package/driver/narrative-refutation-record.mjs +145 -42
  122. package/driver/one-build-per-run.mjs +62 -0
  123. package/driver/outbox-backoff.mjs +4 -4
  124. package/driver/owner-screen.mjs +0 -10
  125. package/driver/owner-use-check.mjs +2 -28
  126. package/driver/package.json +1 -1
  127. package/driver/partial-payload-baseline.json +1 -1
  128. package/driver/parts-not-completed.mjs +1 -1
  129. package/driver/pipeline-knockout.mjs +1015 -1001
  130. package/driver/pipeline.mjs +511 -9265
  131. package/driver/placement-decisions.mjs +2 -2
  132. package/driver/placement-form-io.mjs +7 -9
  133. package/driver/placement-union.mjs +0 -6
  134. package/driver/plan-stability.mjs +7 -10
  135. package/driver/portal-acks.mjs +3 -2
  136. package/driver/portal-confirmation.mjs +48 -0
  137. package/driver/portal-families.mjs +3 -2
  138. package/driver/portal-local-auth.mjs +1 -2
  139. package/driver/portal-routes/README.md +24 -0
  140. package/driver/portal-routes/admin.mjs +425 -0
  141. package/driver/portal-routes/compose.mjs +66 -0
  142. package/driver/portal-routes/config.mjs +118 -0
  143. package/driver/portal-routes/connect.mjs +283 -0
  144. package/driver/portal-routes/feedback.mjs +178 -0
  145. package/driver/portal-routes/me.mjs +165 -0
  146. package/driver/portal-routes/queue.mjs +64 -0
  147. package/driver/portal-routes/report.mjs +106 -0
  148. package/driver/portal-routes/run.mjs +508 -0
  149. package/driver/portal-routes/runs.mjs +127 -0
  150. package/driver/portal-routes/usage.mjs +82 -0
  151. package/driver/portal-runs.mjs +588 -0
  152. package/driver/portal-service.mjs +78 -2592
  153. package/driver/portal-static.mjs +3 -1
  154. package/driver/predelivery-lint.mjs +92 -9
  155. package/driver/production-pool-guard.mjs +1 -1
  156. package/driver/profiles.mjs +5 -4
  157. package/driver/progress.mjs +29 -24
  158. package/driver/publish/README.md +10 -5
  159. package/driver/publish/archive-tags.mjs +3 -2
  160. package/driver/publish/demo-marking.mjs +2 -2
  161. package/driver/publish/index.mjs +215 -140
  162. package/driver/publish/knockout.mjs +153 -107
  163. package/driver/publish/office-record-links.mjs +22 -0
  164. package/driver/publish/parse.mjs +20 -5
  165. package/driver/publish/pool-admin.mjs +9 -3
  166. package/driver/publish/render.mjs +11 -3
  167. package/driver/publish/report-dates.mjs +3 -4
  168. package/driver/publish/report-registry.mjs +7 -10
  169. package/driver/publish/seed-pool.mjs +3 -2
  170. package/driver/publish/shell.mjs +106 -0
  171. package/driver/publish/templates/report.css +3 -1
  172. package/driver/queue-order.mjs +4 -3
  173. package/driver/record-carry.mjs +0 -9
  174. package/driver/record-discard.mjs +1 -4
  175. package/driver/record-fold.mjs +3 -3
  176. package/driver/record-goods.mjs +5 -5
  177. package/driver/reference-score.mjs +2 -3
  178. package/driver/register-capabilities.mjs +0 -6
  179. package/driver/register-count.mjs +3 -2
  180. package/driver/register-digest-record.mjs +7 -7
  181. package/driver/register-fixture-marker.mjs +3 -3
  182. package/driver/register-plan.mjs +2 -2
  183. package/driver/register-records.mjs +2 -2
  184. package/driver/register-taint.mjs +3 -3
  185. package/driver/register-unit-record.mjs +48 -9
  186. package/driver/register-unreachable.mjs +4 -3
  187. package/driver/registry-fidelity.mjs +79 -34
  188. package/driver/repair-composers.mjs +14 -9
  189. package/driver/repair-digest.mjs +4 -6
  190. package/driver/repair-scope.mjs +3 -3
  191. package/driver/repair-targets.mjs +24 -9
  192. package/driver/repairs.mjs +44 -58
  193. package/driver/replay-archive.mjs +7 -7
  194. package/driver/report-card-record.mjs +3 -3
  195. package/driver/report-overview-record.mjs +4 -4
  196. package/driver/research-answers.mjs +38 -6
  197. package/driver/research-checks.mjs +4 -4
  198. package/driver/result-noun-fields.mjs +28 -11
  199. package/driver/review-addresses.mjs +163 -0
  200. package/driver/rule-shape.mjs +1 -1
  201. package/driver/run-delivered.mjs +340 -0
  202. package/driver/run-economics.mjs +8 -26
  203. package/driver/run-failed.mjs +545 -0
  204. package/driver/run-integrity.mjs +1 -1
  205. package/driver/run-outcome.mjs +314 -0
  206. package/driver/run-park.mjs +23 -0
  207. package/driver/run-quote.mjs +32 -0
  208. package/driver/run-record.mjs +352 -0
  209. package/driver/run-requirements.mjs +22 -0
  210. package/driver/run-shell.mjs +55 -0
  211. package/driver/runner.mjs +71 -33
  212. package/driver/saved-register-pages.mjs +4 -4
  213. package/driver/score-redaction.mjs +2 -2
  214. package/driver/search-policy.mjs +12 -13
  215. package/driver/settle-stamp.mjs +4 -3
  216. package/driver/skeptic-record.mjs +2 -2
  217. package/driver/skeptic-search.mjs +1 -1
  218. package/driver/skills/README.md +7 -7
  219. package/driver/skills/blind-frame/SKILL.md +1 -2
  220. package/driver/skills/case-law-citation/SKILL.md +9 -37
  221. package/driver/skills/case-law-citation/sources/courtlistener.md +1 -3
  222. package/driver/skills/case-law-citation/sources/eurlex.md +8 -11
  223. package/driver/skills/case-law-citation/sources/legaldatahunter.md +1 -1
  224. package/driver/skills/clearance-common-law/SKILL.md +45 -111
  225. package/driver/skills/clearance-common-law/perplexity-prompts.md +7 -79
  226. package/driver/skills/clearance-register/SKILL.md +15 -33
  227. package/driver/skills/clearance-register/digest.md +31 -92
  228. package/driver/skills/clearance-register/providers/clarivate.md +2 -2
  229. package/driver/skills/clearance-register/providers/corsearch.md +5 -5
  230. package/driver/skills/clearance-register/providers/euipo.md +1 -2
  231. package/driver/skills/clearance-register/providers/free-tier.md +0 -19
  232. package/driver/skills/clearance-register/providers/signa.md +6 -25
  233. package/driver/skills/clearance-register/providers/uspto-local.md +0 -24
  234. package/driver/skills/clearance-register/register-recipes.md +8 -15
  235. package/driver/skills/clearance-register/status-rules.md +6 -24
  236. package/driver/skills/clearance-register/unit.md +11 -20
  237. package/driver/skills/clearance-search/delivery-contract.md +24 -120
  238. package/driver/skills/clearance-search/field-doctrine-pharma.md +1 -5
  239. package/driver/skills/clearance-search/firm-wide-reasoning.md +24 -43
  240. package/driver/skills/clearance-search/phase2-execution.md +29 -77
  241. package/driver/skills/clearance-search/report-prose.md +3 -4
  242. package/driver/skills/clearance-search/risk-framework-demo.md +1 -1
  243. package/driver/skills/clearance-search/risk-framework-triage.manifest.json +3 -3
  244. package/driver/skills/clearance-search/risk-framework-triage.md +7 -9
  245. package/driver/skills/clearance-search/risk-framework.manifest.json +1 -1
  246. package/driver/skills/clearance-search/risk-framework.md +1 -1
  247. package/driver/skills/clearance-search/synthesis-rules.md +30 -107
  248. package/driver/skills/clearance-search/worked-examples.md +5 -5
  249. package/driver/skills/clearance-variants/SKILL.md +46 -45
  250. package/driver/skills/clearance-variants/transliteration-scripts.md +4 -4
  251. package/driver/skills/frame-diff/SKILL.md +1 -1
  252. package/driver/skills/knockout-assess/SKILL.md +6 -14
  253. package/driver/skills/knockout-frame/SKILL.md +1 -1
  254. package/driver/skills/matter-frame/SKILL.md +7 -12
  255. package/driver/skills/matter-frame/watchlist-reference.md +1 -4
  256. package/driver/skills/narrative-refutation/SKILL.md +20 -30
  257. package/driver/skills/placement-inquiry/SKILL.md +8 -18
  258. package/driver/skills-store-provenance.mjs +1 -1
  259. package/driver/stage-context.mjs +32 -35
  260. package/driver/stage-freshness.mjs +127 -11
  261. package/driver/stages-knockout.mjs +49 -22
  262. package/driver/stages.mjs +88 -283
  263. package/driver/status-snapshot.mjs +2 -1
  264. package/driver/steps/correction-cycle.mjs +311 -0
  265. package/driver/steps/corrections.mjs +644 -0
  266. package/driver/steps/delivery.mjs +1287 -0
  267. package/driver/steps/frame-comparison.mjs +922 -0
  268. package/driver/steps/intake.mjs +84 -0
  269. package/driver/steps/open-run.mjs +419 -0
  270. package/driver/steps/overview-and-cards.mjs +899 -0
  271. package/driver/steps/placement-and-digest.mjs +23 -0
  272. package/driver/steps/register-sweep.mjs +1563 -0
  273. package/driver/steps/skeptic-and-follow-up.mjs +831 -0
  274. package/driver/steps/synthesis.mjs +261 -0
  275. package/driver/steps/verdict-gate.mjs +968 -0
  276. package/driver/suite-census.json +403 -91
  277. package/driver/surface-exit-verdict.mjs +0 -8
  278. package/driver/synthesis-record.mjs +72 -6
  279. package/driver/terminal-clamp.mjs +10 -0
  280. package/driver/tokens.mjs +8 -62
  281. package/driver/tool-calls.mjs +2 -2
  282. package/driver/unit-state-verdict.mjs +1 -1
  283. package/driver/usage-ledger.mjs +2 -1
  284. package/driver/verify-knockout.mjs +20 -35
  285. package/driver/verify.mjs +47 -36
  286. package/driver/web-grid.mjs +3 -4
  287. package/driver/whatif-memo-run.mjs +2 -2
  288. package/driver/whatif-queue.mjs +4 -3
  289. package/driver/withheld-families.mjs +14 -15
  290. package/driver/worker-heartbeat.mjs +3 -2
  291. package/driver/write-up-form.mjs +0 -3
  292. package/mcp-server/CHANGELOG.md +4 -0
  293. package/mcp-server/http-server.mjs +1 -1
  294. package/mcp-server/lib/brief.mjs +22 -4
  295. package/mcp-server/lib/events.mjs +2 -2
  296. package/mcp-server/lib/evidence.mjs +3 -2
  297. package/mcp-server/lib/findings.mjs +2 -1
  298. package/mcp-server/lib/knockout.mjs +9 -10
  299. package/mcp-server/lib/ops.mjs +9 -9
  300. package/mcp-server/lib/runs.mjs +9 -10
  301. package/mcp-server/lib/trace.mjs +1 -1
  302. package/mcp-server/lib/whatif.mjs +2 -3
  303. package/mcp-server/package.json +1 -1
  304. package/mcp-server/server.mjs +5 -5
  305. package/package.json +2 -1
  306. package/portal-ui/dist/assets/{index-fPqAU0sx.js → index-D5rkCjDc.js} +26 -14
  307. package/portal-ui/dist/index.html +1 -1
  308. package/portal-ui/package.json +3 -3
  309. package/providers/README.md +1 -1
  310. package/providers/_shared/answer-memory.mjs +4 -5
  311. package/providers/_shared/execute-plan.mjs +48 -1
  312. package/providers/_shared/records-from-search.mjs +46 -0
  313. package/providers/clarivate/README.md +2 -2
  314. package/providers/clarivate/src/adapter.js +147 -0
  315. package/providers/clarivate/src/core.js +1 -14
  316. package/{driver/engine/mcp/clarivate-server.mjs → providers/clarivate/src/mount.js} +5 -10
  317. package/providers/corsearch/README.md +3 -3
  318. package/providers/corsearch/src/adapter.js +80 -0
  319. package/providers/corsearch/src/core.js +14 -11
  320. package/{driver/engine/mcp/corsearch-server.mjs → providers/corsearch/src/mount.js} +5 -10
  321. package/providers/euipo/README.md +2 -2
  322. package/providers/euipo/src/adapter.js +85 -0
  323. package/providers/euipo/src/core.js +1 -1
  324. package/providers/euipo/src/euipo-client.js +1 -2
  325. package/{driver/engine/mcp/euipo-server.mjs → providers/euipo/src/mount.js} +5 -10
  326. package/providers/free-tier/README.md +2 -2
  327. package/providers/free-tier/src/adapter.js +127 -0
  328. package/{driver/engine/mcp/free-tier-server.mjs → providers/free-tier/src/mount.js} +5 -10
  329. package/providers/jx-subclass/coverage.mjs +1 -6
  330. package/providers/jx-subclass/score-truth.mjs +2 -1
  331. package/providers/oauth-mcp-bridge/CHANGELOG.md +4 -0
  332. package/providers/oauth-mcp-bridge/package.json +1 -1
  333. package/providers/perplexity/src/core.js +2 -2
  334. package/providers/signa/README.md +2 -2
  335. package/providers/signa/src/adapter.js +157 -0
  336. package/providers/signa/src/capabilities.js +0 -3
  337. package/providers/signa/src/core.js +2 -2
  338. package/{driver/engine/mcp/signa-server.mjs → providers/signa/src/mount.js} +7 -12
  339. package/providers/signa/src/offices.generated.js +17 -15
  340. package/providers/uspto-local/README.md +1 -1
  341. package/providers/uspto-local/bin/verify-index.mjs +1 -1
  342. package/providers/uspto-local/src/adapter.js +75 -0
  343. package/{driver/engine/mcp/uspto-local-server.mjs → providers/uspto-local/src/mount.js} +5 -10
  344. package/scripts/band-shape-probe.mjs +2 -2
  345. package/scripts/citation-line-check.mjs +7 -7
  346. package/scripts/compare.mjs +1 -1
  347. package/scripts/dead-names.mjs +2 -2
  348. package/scripts/e2e-first-time.mjs +19 -7
  349. package/scripts/e2e.mjs +13 -13
  350. package/scripts/engine-probe.mjs +1 -1
  351. package/scripts/env-audit.mjs +7 -4
  352. package/scripts/env-classify.mjs +5 -1
  353. package/scripts/feedback-mint.mjs +1 -1
  354. package/scripts/freeze-example-run.mjs +7 -7
  355. package/scripts/mint-suite-census.mjs +2 -2
  356. package/scripts/nightly-notice.mjs +1 -1
  357. package/scripts/release-cut-decision.mjs +7 -2
  358. package/scripts/release-note-required.mjs +26 -9
  359. package/scripts/release-notes-lint.mjs +3 -2
  360. package/scripts/release-version-pr-checks.mjs +1 -1
  361. package/scripts/settings-render-check.mjs +23 -3
  362. package/scripts/test-run.mjs +5 -5
  363. package/scripts/travelling-predicates.mjs +1 -1
  364. package/scripts/undeclared-field-census.mjs +1 -1
  365. package/scripts/unexecuted-asserts.mjs +1 -1
  366. package/scripts/verify-publishable.mjs +1 -1
  367. package/shared/client-door.mjs +1 -1
  368. package/shared/connect-clients.mjs +1 -1
  369. package/shared/connector-signin-probe.mjs +1 -1
  370. package/shared/env-aliases.mjs +1 -1
  371. package/shared/invocation.mjs +14 -2
  372. package/shared/names-in-force.mjs +2 -0
  373. package/shared/register-selection.mjs +2 -2
  374. package/shared/store-in-repo.mjs +3 -3
  375. package/shared/summary-blocks.mjs +0 -3
  376. package/shared/trigger-lane.mjs +1 -1
  377. package/shared/vacuous-pass.mjs +2 -2
  378. package/shared/verb-shim.mjs +4 -2
  379. package/node_modules/exceljs/README.md +0 -3023
@@ -0,0 +1,1563 @@
1
+ // SPDX-License-Identifier: AGPL-3.0-only
2
+ // Copyright 2026 Cordillera Sàrl. Additional terms under section 7 of the AGPL-3.0 apply — see ADDITIONAL-TERMS.md
3
+ //
4
+ // steps/register-sweep.mjs — the register and unregistered-use searches, their fan-in, and the recovery of what fell short.
5
+ //
6
+ // One phase of a run, moved out of pipelineInner unchanged. `helpers` are functions still held in pipeline.mjs, handed in
7
+ // because this module must not import that one back; each moves here when the other phases that share it have moved.
8
+ import { runRecordLogPath } from "../../providers/_shared/ledger-path.mjs";
9
+ import { recordSpan } from "../attributed-span.mjs";
10
+ import { recordStatusesFromFindings } from "../common-law-coverage-status.mjs";
11
+ import { GRID_HALVES, GRID_SEATS, MEANING_SEAT, balanceClosureCells, findCoverageLimitedCells, findDroppedConnotationQueries, findErroredConnotationQueries, findGridCandidateOmissions, findSimilarListingSignals, mergeCommonLawFindings, mergeGrids, partitionClosableCells } from "../common-law-receipts.mjs";
12
+ import { connotationObligations, parseDispositionForm, parsePrRiskResults, renderDispositionTable } from "../connotation-search.mjs";
13
+ import { NON_MATERIAL_AXES } from "../coverage-ledger.mjs";
14
+ import { undecidedCrossChecks, waitingCrossCheck, withoutWait } from "../cross-check-wait.mjs";
15
+ import { plainDeferralReason } from "../deferral-row.mjs";
16
+ import { formSidecarPath, outstandingRows, unionDispositionForm } from "../disposition-union.mjs";
17
+ import { config, envGateOn } from "../driver.config.mjs";
18
+ import { registerAdapter } from "../engine/run-choices.mjs"; // the run's register adapter, from ctx.register
19
+ import { readStickyGaps, receiptSettled, settleReceipt } from "../envelope-settle.mjs";
20
+ import { note, runLog } from "../log.mjs";
21
+ import { findCollapsedBands, quarantineUnknownStates, taintQuarantineCleanBlocks } from "../named-band.mjs";
22
+ import { readPartNotCompleted } from "../parts-not-completed.mjs";
23
+ import { gridBatchFor } from "../profiles.mjs";
24
+ import { countLaneCalls } from "../provider-usage.mjs";
25
+ import { atomicWrite, driverDir, readJson } from "../run-record.mjs";
26
+ import { foldSupplementalEntries, isProviderHardErrorReason, joinPlanToBands, mintSupplementalQid, partitionFoldDirectives, romanizedTermsFromPlan, screenThenCap } from "../register-plan.mjs";
27
+ import { readRegisterTaint } from "../register-taint.mjs";
28
+ import { repairFollowup } from "../repair-composers.mjs";
29
+ import { classifyFailureReason, createRepairLedger, fanInMissingEvidence } from "../repairs.mjs";
30
+ import { validators } from "../verify.mjs";
31
+ import { closureBlocksOf } from "../web-grid.mjs";
32
+ import { readWithheldFamilies, releasedFamilyQids } from "../withheld-families.mjs";
33
+ import { existsSync, readFileSync, renameSync, rmSync, writeFileSync } from "node:fs";
34
+ import { seedUnplannedBands } from "../register-unit-record.mjs";
35
+ import { join } from "node:path";
36
+
37
+ /**
38
+ * Which cross-checks this pass folds into the plan, and which the receipt keeps from an earlier pass. PURE.
39
+ *
40
+ * A run that enters the sweep again finds the cross-checks it minted before already in the plan. The fold
41
+ * passes over a qid the plan holds without adding or refusing it, so the screen alone keeps none of them,
42
+ * and the receipt was rewritten with no directives: the audit, the ask count and the demotion tripwire lost
43
+ * cross-checks that had run. A directive whose qid the plan holds is carried, as the earlier receipt
44
+ * recorded it where it did, and counts against the cap, so a later pass mints only what the first left
45
+ * room for. On a first pass the plan holds none, and the answer is the screen's.
46
+ */
47
+ export function crossChecksForThisPass(plan, candidates, candDirectives, prior, cap) {
48
+ const held = new Set((plan?.entries ?? []).map((e) => e?.qid));
49
+ const carried = new Map();
50
+ for (const d of [...(Array.isArray(prior?.directives) ? prior.directives : []), ...(candDirectives ?? [])])
51
+ if (held.has(d?.qid) && !carried.has(d.qid)) carried.set(d.qid, d);
52
+ return { ...screenThenCap(plan, candidates, Math.max(0, cap - carried.size)), carried: [...carried.values()] };
53
+ }
54
+
55
+ export async function runRegisterSweep({ P, agent, axes, ctx, job, opts, run, runCommonLaw }, helpers) {
56
+ const { CL_SUPP_TAGS, StageFailure, connotationRemedyToken, defaultConnotationReissuer, deriveNamedBand, foldSupplementalProposals, holdStickyGapsIn, inScopeClassList, isFallbackEligible, joinOptions, mergeRegisterBands, must, noteAdapter, noteChannelCoverageAtStageExit, readPlanExecution, readRegisterBands, recordConnotationAudit, remergeIfBandsMoved, resultsPerCellOf, runBatched, runSaturationProbeCodeSide, slicesUnitNeverReached, stage, taintDisposition, taintParkJudgmentArtifacts, takeSlicesOutOfTheBand, unfinishedUnitAsItStands, writePlanExecutionReceipt } = helpers;
57
+ // Step 2A/2B — fan-out (batched ≤ gatherConcurrency) then the code-side fan-in barrier.
58
+ // Property 1 (frame-omission design): the BLIND re-derivation runs as a sibling of the WHOLE gather,
59
+ // not as a gather member — it reads only the raw instruction (no tool calls), so under the turn cap it
60
+ // slots in as a gather unit frees and finishes inside the slowest gather member's wall (≈ zero added
61
+ // critical-path latency). NON-FATAL: a flake notes-and-skips (frame-diff then sees no blind model and
62
+ // is skipped) and never rejects the Promise.all that carries the $40 gather.
63
+ // A1 SPLIT: when armed (ctx.clHalfTerms — flag on + dictated spec + ≥2 terms + not a pre-split
64
+ // resume), the single common-law member becomes TWO concurrent half-grid members (the half id rides
65
+ // the member's axis field, exactly like a register unit's axis). Flag off / self-disarmed keeps the
66
+ // original single-member assembly VERBATIM below — that branch IS the rollback path.
67
+ const clSplit = Boolean(ctx.clHalfTerms);
68
+ // — RECORD THE CHOICE, HERE, where both paths converge. Not inside deriveGridSpec's arming
69
+ // block: that block does not execute at all on the spec-less path, which is exactly the path the
70
+ // 2026-08-11 codex R2 run took, and a record that only exists when the split arms cannot explain a
71
+ // run that did not split. `decided` is derived from ctx.clHalfTerms — the same value the assembly
72
+ // below branches on — so the file can never disagree with what the run actually did.
73
+ {
74
+ const d = ctx.clSplitDecision ?? { path: "unsplit", reason: "not-recorded", detail: "deriveGridSpec did not run on this path", flag: null, terms: null };
75
+ // The recorded reason and the assembly are derived from DIFFERENT things — the reason from which
76
+ // branch of deriveGridSpec ran, the path from ctx.clHalfTerms. A disagreement means the record is
77
+ // explaining a path the run did not take, which is worse than no record at all: it is a confident
78
+ // wrong answer to the exact question was opened to answer. Never silent.
79
+ const agrees = (d.path === "split") === clSplit;
80
+ const decision = { ...d, path: clSplit ? "split" : "unsplit",
81
+ members: clSplit ? GRID_SEATS.map((h) => `common-law-half:${h}`) : (runCommonLaw ? ["common-law"] : []),
82
+ ...(agrees ? {} : { reason: "selector-record-disagreement", recorded_reason: d.reason,
83
+ detail: `the run assembled the ${clSplit ? "split" : "unsplit"} path but deriveGridSpec recorded "${d.reason}" (${d.path}) — the selector and its record have diverged and the recorded reason cannot be trusted` }) };
84
+ atomicWrite(P.commonLawPath, JSON.stringify(decision, null, 2) + "\n");
85
+ runLog(run.runDir, { event: "common-law-path", path: decision.path, reason: decision.reason, terms: decision.terms, ...(agrees ? {} : { disagreement: true, recorded_reason: d.reason }) });
86
+ note(`common-law path: ${decision.path} — ${decision.detail}`);
87
+ // (3) — AND THEN STOP. A disagreement was recorded and the run carried on, which left the
88
+ // one artifact opened to answer "which path did this take" saying, in effect, "I do not know" —
89
+ // while every downstream common-law count was assembled anyway and delivered as if it did.
90
+ //
91
+ // ORDER IS THE WHOLE POINT: the write, the journal row and the note all run FIRST. A throw above
92
+ // them would kill the run with nothing on disk to diagnose from, which is the failure mode this
93
+ // record exists to prevent, arriving through the guard meant to enforce it.
94
+ //
95
+ // THIS CANNOT FIRE ON ANY PATH THE ENGINE HAS TODAY, and that is stated rather than glossed: both
96
+ // sides of `agrees` descend from the single deriveGridSpec(ctx) call ~30 lines above — every arm
97
+ // that records path "split" also sets ctx.clHalfTerms, and every arm that does not, does not — so
98
+ // they cannot disagree. The `?? { reason: "not-recorded" }` default has no live producer either
99
+ // (the only other ctx builder, reconstructCtx, feeds repairStale and the --experiment rig, and
100
+ // neither reaches this line). It buys a tripwire for the refactor that splits those two
101
+ // derivations, and nothing before then. Deterministic: a re-sample re-derives the identical
102
+ // divergence, so the retry ladder has nothing to offer it.
103
+ if (!agrees) throw new StageFailure("grid-spec",
104
+ `the run assembled the ${clSplit ? "split" : "unsplit"} path but deriveGridSpec recorded "${d.reason}" (${d.path}) — the selector and its record have diverged, so no downstream common-law count can be trusted`,
105
+ undefined, { failClass: "deterministic" });
106
+ }
107
+ const gather = clSplit
108
+ ? [...GRID_SEATS.map((h) => ({ name: "common-law-half", axis: h })), ...axes.map((a) => ({ name: "register-unit", axis: a }))]
109
+ : [...(runCommonLaw ? [{ name: "common-law" }] : []), ...axes.map((a) => ({ name: "register-unit", axis: a }))];
110
+ // The common-law member's result, BY NAME. It was read as gatherResults[0] in four places, which was
111
+ // only ever correct because the member is built first and always present — drop it for a register-only
112
+ // run and [0] silently becomes a register unit, and the grid-ledger pass below would then send a
113
+ // grid-ledger save followup addressed to the common-law session into it rather than skip (its guard is
114
+ // gridVariants × !skipped × no-ledger, and gridVariants comes from the manifest either way).
115
+ const clIndex = gather.findIndex((g) => g.name === "common-law");
116
+ const clMember = () => (clIndex >= 0 ? gatherResults[clIndex] : null);
117
+ // The plan-direct executor, resolved ONCE for the code-side saturation-probe unit here AND the
118
+ // fan-in repair kit below (same precedence: injected test executor > provider lane > null when
119
+ // dispatch is off / the provider has no adapter). See runSaturationProbeCodeSide for why the
120
+ // saturation-probe member bypasses the agent whenever this lane and a frozen plan exist — the
121
+ // agent member below stays the verbatim fallback (and the mock harness's default path).
122
+ // CLEAROTRON_PLAN_DISPATCH is a default-ON gate. It used to test `!== "off"` alone, so the `=0` idiom
123
+ // that governance documents for it — and that every sibling gate on that line honours — left the
124
+ // lane fully ARMED. envGateOn accepts both spellings rather than switching to a bare `!== "0"`:
125
+ // deployments and 15 test files already say "off", and breaking that would arm dispatch silently,
126
+ // which is the same bug in the other direction.
127
+ const planExec = opts.planExecutor
128
+ ?? (envGateOn("CLEAROTRON_PLAN_DISPATCH") && registerAdapter(ctx.register).executePlan
129
+ ? (args, c) => noteAdapter(c ?? ctx, registerAdapter(ctx.register)).executePlan(args, c) : null);
130
+ // Kill switch CLEAROTRON_SATPROBE_CODESIDE=0 (the inline `!== "0"` pattern): legacy mock harnesses
131
+ // opt out — their scenarios pre-date the code-side member and script the AGENT path (and an armed
132
+ // real executor lane would dial the provider from a test). Production default is ON.
133
+ const satProbeCodeSide = process.env.CLEAROTRON_SATPROBE_CODESIDE !== "0" && Boolean(planExec && ctx.registerPlan);
134
+ // An axis the frozen plan gives no work gets the honest empty band before its model unit runs (register-unit-record.mjs).
135
+ // The code-side saturation probe writes its own.
136
+ if (ctx.registerPlan) {
137
+ const seeded = seedUnplannedBands(P.runDir, ctx.registerPlan, axes.filter((a) => !(a === "saturation-probe" && satProbeCodeSide)));
138
+ if (seeded.length) runLog(run.runDir, { event: "unit-band-seeded-empty", axes: seeded });
139
+ }
140
+ // The units this run records as unfinished are taken as their bands stand (unfinishedUnitAsItStands, above).
141
+ const unfinishedUnits = new Set(readPartNotCompleted(run.runDir, "searches")?.unfinished_units ?? []);
142
+ const [gatherResults, blindRes] = await Promise.all([
143
+ runBatched(gather, config.gatherConcurrency, (g) =>
144
+ g.name === "register-unit" && unfinishedUnits.has(g.axis)
145
+ ? unfinishedUnitAsItStands({ ...ctx, axis: g.axis })
146
+ : g.name === "register-unit" && g.axis === "saturation-probe" && satProbeCodeSide
147
+ ? runSaturationProbeCodeSide({ ...ctx, axis: g.axis }, planExec)
148
+ : stage(g.name, { ...ctx, axis: g.axis })),
149
+ stage("blind-frame", ctx).catch((e) => ({ ok: false, fail: String(e?.message ?? e) })),
150
+ ]);
151
+ if (!clSplit && clMember()?.ok) recordStatusesFromFindings(P.commonLaw); if (!blindRes.ok) {
152
+ note(`blind-frame failed (non-fatal — no frame-diff/reopen this run): ${blindRes.fail}`);
153
+ runLog(run.runDir, { event: "blind-frame-skipped", reason: blindRes.fail });
154
+ }
155
+ // T1 (J1c) — terminal quarantine BEFORE the must barrier: after the stage's own retry
156
+ // ladder (which now carries a warm re-emit demand naming the fix), a run must never die on a
157
+ // model-authored VOCABULARY miss in the band. The driver repairs the band in code (qid-less
158
+ // unknown-state blocks → honest `incomplete` descriptors judgment reads like any crowd), then
159
+ // re-judges with the SAME stage validator; on a pass the member is recovered. A qid-stamped
160
+ // unknown state (tool bug) or any other defect falls through to must() unchanged.
161
+ for (let i = 0; i < gather.length; i++) {
162
+ const g = gather[i], r = gatherResults[i];
163
+ // register units only — under the A1 split the common-law halves ALSO carry an axis (the half id),
164
+ // and their quarantine lane is the dedicated half fan-in below, never the register band repair.
165
+ if (g.name !== "register-unit" || r?.ok || !/named_band_state_invalid/.test(String(r?.fail ?? ""))) continue;
166
+ const bandPath = P.registerBand(g.axis);
167
+ try {
168
+ const { blocks, quarantined } = quarantineUnknownStates(readFileSync(bandPath, "utf8"));
169
+ if (!quarantined.length) continue; // not a qid-less vocabulary miss — fail as before
170
+ writeFileSync(`${bandPath}.tmp`, JSON.stringify(blocks, null, 2) + "\n");
171
+ renameSync(`${bandPath}.tmp`, bandPath);
172
+ const v = validators.registerUnit(P.registerUnit(g.axis), readFileSync(P.registerUnit(g.axis), "utf8"));
173
+ if (!v.ok) { note(`register-unit ${g.axis}: band still invalid after quarantine (${v.reason}) — failing as before`); continue; }
174
+ runLog(run.runDir, { event: "named-band-state-quarantined", axis: g.axis, states: quarantined.map((q) => q.state), queries: quarantined.map((q) => q.query.slice(0, 60)) });
175
+ note(`register-unit ${g.axis}: quarantined ${quarantined.length} unknown-state judgment block(s) → incomplete descriptors (recovered; judgment weighs the descriptors)`);
176
+ gatherResults[i] = { ...r, ok: true, fail: null, bandQuarantined: true };
177
+ } catch (e) {
178
+ note(`register-unit ${g.axis}: band quarantine not applicable (${String(e.message).slice(0, 100)}) — failing as before`);
179
+ }
180
+ }
181
+ // ── A1 split fan-in step 1: half-failure quarantine (mirrors the band-quarantine above) ──────────
182
+ // ONE half failing on TRANSIENT INFRASTRUCTURE (isFallbackEligible — its retry ladder already ran
183
+ // out) must not kill the gather the other half completed: the merge below records every cell the
184
+ // failed half owned as an HONEST GAP against the FULL spec — never a thinner-but-valid ledger, every
185
+ // dictated cell stays accounted — and those gaps ride the existing coverage-closure pass (the error
186
+ // text deliberately reads non-mechanical, so they partition CLOSABLE and get the in-loop close
187
+ // attempt; whatever survives ships as the attempted-and-unreachable disclosure). CELLS only: the
188
+ // half's dictated CONNOTATION queries have no gap vocabulary, so the merge gate below runs a
189
+ // per-query identity join and fails TRANSIENT when any are unrecorded — a quarantine survives to
190
+ // the closure pass only when the failed half's meaning receipts made it into its ledger. A CONTENT failure
191
+ // (validator reject — e.g. a dropped dictated cell) and a both-halves failure fall through to must()
192
+ // unchanged: those are quality gates, and quarantining them would be the false-clean disease.
193
+ const clHalves = clSplit ? Object.fromEntries(GRID_SEATS.map((h, i) => {
194
+ const r = gatherResults[i];
195
+ return [h, { i, ok: !!r?.ok, skipped: !!r?.skipped, sessionKey: r?.sessionKey, fail: r?.fail ?? null, quarantined: false }];
196
+ })) : null;
197
+ if (clSplit) {
198
+ const failed = GRID_SEATS.filter((h) => !clHalves[h].ok);
199
+ if (failed.length === 1 && isFallbackEligible(clHalves[failed[0]].fail)) {
200
+ const h = failed[0];
201
+ clHalves[h].quarantined = true;
202
+ gatherResults[clHalves[h].i] = { ...gatherResults[clHalves[h].i], ok: true, fail: null, clHalfQuarantined: true };
203
+ note(`common-law-half:${h} failed on transient infrastructure (${clHalves[h].fail}) — quarantined: its cells merge as honest gaps and ride the coverage-closure pass`);
204
+ runLog(run.runDir, { event: "common-law-half-quarantined", half: h, fail: String(clHalves[h].fail).slice(0, 140) });
205
+ }
206
+ }
207
+ // The engine's own re-issue, spent at most once per run — the bound spans BOTH the half-stage
208
+ // hook below and the merge gate's disclosure, so a run never buys the same search twice.
209
+ let clConnotationReissueSpent = false;
210
+ // ── THE MEANING HALF FELL SHORT BY A SEARCH OR TWO: RE-ISSUE, THEN DELIVER ───────────────────
211
+ //
212
+ // This is where the clearance actually died. The half's own validator refuses when a dictated
213
+ // meaning search is missing from its receipts, and every attempt refused identically — eight of
214
+ // them — so the run was thrown away with fifty-nine of sixty searches done and recorded.
215
+ //
216
+ // Quarantine above cannot help here: that is for a half that failed wholesale on transient
217
+ // infrastructure, where re-running the half converges. This half SUCCEEDED at almost everything.
218
+ // So the engine re-issues the missing searches itself, through the same provider, and re-judges the
219
+ // half on its own artifact. If they landed, the half is simply valid and nothing is disclosed.
220
+ //
221
+ // If they did not, the half is accepted WITH THE SHORTFALL RECORDED — an honest gap per unfinished
222
+ // search, carrying its term, which the merge gate then discloses and the coverage row reads. That is
223
+ // the owner's ruling of 2026-09-17 and it is not the false-clean the gates guard: false-clean is
224
+ // silence, and this says on the client's own page which search did not complete.
225
+ if (clSplit && !clHalves[MEANING_SEAT].ok && /connotation_query_unrecorded/.test(String(clHalves[MEANING_SEAT].fail ?? ""))) {
226
+ const h = MEANING_SEAT;
227
+ let short = [];
228
+ try {
229
+ const spec = readJson(P.gridSpecHalf(h));
230
+ const halfLedger = readJson(P.commonLawGridHalf(h));
231
+ short = findDroppedConnotationQueries(spec, halfLedger);
232
+ if (short.length) {
233
+ runLog(run.runDir, { event: "connotation-reissue", half: h, count: short.length });
234
+ note(`the meaning half recorded all but ${short.length} of its dictated searches — the engine re-issues `
235
+ + `${short.length === 1 ? "it" : "them"} itself rather than asking for the sweep again`);
236
+ clConnotationReissueSpent = true;
237
+ const reissuer = opts.connotationReissuer ?? defaultConnotationReissuer;
238
+ const r = await reissuer(short, { spec, rawPath: driverDir(run.runDir, "web-results", `connotation-reissue-${h}-${Date.now()}.json`) });
239
+ runLog(run.runDir, { event: "connotation-reissue-result", ok: !!r?.ok,
240
+ recovered: Array.isArray(r?.rows) ? r.rows.length : 0,
241
+ cause: r?.ok ? null : String(r?.cause ?? "").slice(0, 160) });
242
+ const rows = (r?.ok && Array.isArray(r.rows)) ? r.rows : [];
243
+ halfLedger.extras = halfLedger.extras ?? {};
244
+ halfLedger.extras.pr_risk = [...(Array.isArray(halfLedger.extras.pr_risk) ? halfLedger.extras.pr_risk : []), ...rows];
245
+ const stillShort = findDroppedConnotationQueries(spec, halfLedger);
246
+ if (stillShort.length) {
247
+ halfLedger.gaps = Array.isArray(halfLedger.gaps) ? halfLedger.gaps : [];
248
+ for (const q of stillShort)
249
+ halfLedger.gaps.push({ term: q, platform: "connotation",
250
+ error: "the search did not complete after a re-ask and a re-issue by the engine" });
251
+ runLog(run.runDir, { event: "connotation-unfinished-disclosed", count: stillShort.length, half: h });
252
+ note(`${stillShort.length} dictated meaning quer${stillShort.length === 1 ? "y" : "ies"} did not complete — `
253
+ + "recorded as honest gaps and DISCLOSED on the coverage row; the run delivers the rest");
254
+ }
255
+ atomicWrite(P.commonLawGridHalf(h), JSON.stringify(halfLedger, null, 2) + "\n");
256
+ // The half is accepted on its re-judged artifact. Same shape as quarantine above: the stage is
257
+ // not re-run and the model is not asked again.
258
+ clHalves[h].ok = true;
259
+ gatherResults[clHalves[h].i] = { ...gatherResults[clHalves[h].i], ok: true, fail: null, clHalfShortfall: stillShort.length };
260
+ }
261
+ } catch (err) {
262
+ runLog(run.runDir, { event: "connotation-reissue-failed", error: String(err?.message ?? err).slice(0, 160) });
263
+ }
264
+ }
265
+ // A REGISTER UNIT THAT WROTE NO RESULT is the searches not completed, after every other member has been held to its
266
+ // own failure as before (unfinishedUnitAsItStands, above). A rate limit keeps its own path.
267
+ const unfinished = gather.map((g, i) => i).filter((i) => gather[i].name === "register-unit" && gather[i].axis
268
+ && !gatherResults[i]?.ok && !gatherResults[i]?.resetsAt && !existsSync(P.registerUnit(gather[i].axis)));
269
+ gather.forEach((g, i) => { if (!unfinished.includes(i)) must(gatherResults[i], g.name + (g.axis ? `:${g.axis}` : "")); });
270
+ if (unfinished.length) {
271
+ const axesOut = unfinished.map((i) => gather[i].axis), first = gatherResults[unfinished[0]];
272
+ throw Object.assign(new StageFailure(`register-unit:${axesOut[0]}`, first?.fail ?? "failed", undefined, { quantity: first?.quantity }),
273
+ { notCompletedPart: "searches", unfinishedUnits: axesOut,
274
+ excludedSlices: axesOut.flatMap((a) => slicesUnitNeverReached(P, ctx.registerPlan, a)) });
275
+ }
276
+ // winning session key per axis → a later escalation resumes the EXACT key the unit succeeded on.
277
+ // (register units only — a common-law half's axis is its half id, tracked in clHalves, never here.)
278
+ const unitKey = {};
279
+ gather.forEach((g, i) => { if (g.name === "register-unit" && g.axis) unitKey[g.axis] = gatherResults[i].sessionKey; });
280
+
281
+ // ── A1 split fan-in step 2: merge the half artifacts into the canonical pair ─────────────────────
282
+ // The two plugin-written half ledgers merge in CODE (mergeGrids — cells union by term|platform, gaps
283
+ // recomputed against the FULL canonical spec, extras.pr_risk concat+dedup) into the ONE canonical
284
+ // common-law-grid.json, and the half findings concatenate into the ONE canonical common-law-
285
+ // findings.md, so EVERYTHING downstream (fan-in barrier, receipts/connotation gates, closure,
286
+ // synthesis, replay) reads exactly the artifacts a single-member run would have written. Re-run after
287
+ // every routed half followup (closure / frame-reopen) — the half files stay the source of truth and
288
+ // the canonical pair is always derived, which also makes the merge resume-idempotent.
289
+ const mergeCommonLawArtifacts = !clSplit ? null : ({ discloseUnfinished = false } = {}) => { for (const h of GRID_HALVES) recordStatusesFromFindings(P.commonLawHalf(h), { half: h }); // each half's ledger statuses, recorded by code where the seat made no call (ruling 2026-10-01)
290
+ // Each half's coverage truth = its plugin-written main ledger FOLDED with any plugin-written
291
+ // supplementary sibling(s) the closure lane produced. Returns the batches as an ARRAY (mergeGrids'
292
+ // batchesOf flattens it, cells union across all of them); a missing/corrupt main leaves its cells to
293
+ // re-derive as gaps exactly as before. The supplementary siblings are existsSync-guarded so the
294
+ // FAN-IN merge (which runs BEFORE any supplementary exists) never throws (caveat 2). Only the plugin
295
+ // writes these files — never an agent — so a parse here is defensive, not a live failure mode.
296
+ const readHalfLedger = (h) => {
297
+ const batches = [];
298
+ try { batches.push(readJson(P.commonLawGridHalf(h))); } catch { /* main missing/corrupt → its cells re-derive as gaps */ }
299
+ for (const tag of CL_SUPP_TAGS) {
300
+ const sp = P.commonLawGridSupp(h, tag);
301
+ if (existsSync(sp)) { try { batches.push(readJson(sp)); } catch { /* a corrupt supp sibling contributes nothing; its cells stay gaps */ } }
302
+ }
303
+ return batches.length ? batches : null;
304
+ };
305
+ // GRID halves only: halfErrors attributes uncovered CELLS to the seat that owed them, and gaps are
306
+ // term x platform. The meaning seat owns no terms, so it can never be the owner of a gap — a
307
+ // quarantined meaning seat surfaces through the per-query identity join below instead, which is the
308
+ // gate that can actually see a missing meaning receipt.
309
+ const halfErrors = Object.fromEntries(GRID_HALVES.filter((h) => clHalves[h].quarantined)
310
+ .map((h) => [h, `half-${h} gather member did not complete: ${String(clHalves[h].fail).slice(0, 120)}`]));
311
+ const fullSpec = readJson(ctx.gridSpecPath);
312
+ // — three seats, two merges. mergeGrids returns the same {cells, extras, gaps} shape its
313
+ // batchesOf() accepts, so the meaning seat folds in by chaining rather than by widening a signature
314
+ // the guards are written against. It contributes no cells and no gaps — only its
315
+ // extras.pr_risk, which after this change IS the merged meaning receipt set, because both grid
316
+ // halves carry zero queries and the plugin's own hasConn gate writes them none.
317
+ const mergedGrid = mergeGrids(
318
+ mergeGrids(readHalfLedger("a"), readHalfLedger("b"), { spec: fullSpec, halfErrors }),
319
+ readHalfLedger(MEANING_SEAT), { spec: fullSpec, halfErrors });
320
+ atomicWrite(P.commonLawGrid, JSON.stringify(mergedGrid, null, 2) + "\n"); // B5 — the canonical ledger is never seen torn
321
+ // part 2 — the grid is on disk and the spec has been since dispatch, so plan-vs-executed is
322
+ // answerable HERE, roughly two hours before publish derives it. Reported, never gated.
323
+ noteChannelCoverageAtStageExit(P, mergedGrid);
324
+ // ── — CARRY THE STRUCTURED DISPOSITIONS THROUGH THE MERGE, AND RENDER THE PROSE FROM THEM ──
325
+ // Only CONNOTATION_HALF owns meaning queries, so in practice one half writes this file — but the
326
+ // union is over BOTH, because keying the merge on which half is supposed to own it is exactly the
327
+ // invariant that breaks silently when CONNOTATION_HALF is flipped (its own doc block calls that a
328
+ // wall-clock choice, correctness-neutral — it must stay one).
329
+ //
330
+ // Not carrying it is the shape: both halves pass, the canonical gate re-runs the PROSE join
331
+ // over a document whose dispositions live in structure, and the merge fails a run that was correct.
332
+ // — THE CANONICAL FORM IS THE UNION OF THE HALVES', OVER THE MERGED OBLIGATION SET. The rows
333
+ // are regenerated from the MERGED ledger, so the canonical form carries exactly what the canonical
334
+ // validator will judge — including any recurrence receipt that clears the floor only once both
335
+ // halves' queries are counted (the superadditive case CONNOTATION_HALF exists to make impossible,
336
+ // and which this would surface honestly rather than silently drop).
337
+ const mergedOb = connotationObligations(parsePrRiskResults(JSON.stringify(mergedGrid)));
338
+ const halfRows = [];
339
+ for (const h of GRID_SEATS) {
340
+ // B — the halves' rulings live in their ACCUMULATORS in `_driver/` (the tool's one copy); the
341
+ // seat-facing mirrors died with the form path and are written by nobody.
342
+ const dp = formSidecarPath(P.commonLawDispositionsHalf(h));
343
+ if (!existsSync(dp)) continue;
344
+ try { halfRows.push(...(parseDispositionForm(readFileSync(dp, "utf8")).rows ?? [])); }
345
+ catch { /* a half's unreadable form leaves its obligations undischarged — a finding, never a silent pass */ }
346
+ }
347
+ // Both halves, never only CONNOTATION_HALF: keying the merge on which half is SUPPOSED to own the
348
+ // sweep is exactly the invariant that breaks silently when that constant is flipped, and its own
349
+ // doc block calls the flip correctness-neutral. It must stay one.
350
+ // — THE HALVES ARRIVE THROUGH THE PRIOR CHANNEL, NOT THE SEAT ONE, AND THE PARK IS WHY.
351
+ //
352
+ // This used to be `({ rows: [] }, { rows: halfRows }, …)`: empty prior, halves fed as the seat's
353
+ // submission. It cost a clearance. `unionDispositionForm` reconstructs a park from exactly two
354
+ // places — `s.obstacle`, a LIVE submission field that is deliberately never persisted into a form,
355
+ // or `p.parked` from the prior. Handed a persisted form on the seat side with an empty prior, both
356
+ // miss, and the else branch clears `parked`, `parked_kind`, `parked_reason` and `parked_refusals`.
357
+ // A row the seat had correctly declared unquotable arrived at the canonical validator as a ruled
358
+ // row still owing a quote, `isRuled` refused it, and the run died deterministic with no recovery.
359
+ // Any park erases this way, not only the declared kind — an exhausted park at the bound vanished
360
+ // identically from the day the park shipped.
361
+ //
362
+ // NOT FIXED BY READING `s.parked`, and that is the binding constraint rather than a preference: the
363
+ // seat must not be able to park a row by asserting it in a submission. Every widening of what the
364
+ // seat side may set is a widening of what a model can claim about its own work.
365
+ //
366
+ // The prior channel is the TRUSTED one and already carries everything needed. Half forms are
367
+ // driver-written, `seatFields(p, row)` carries their rulings by the same `pOk` path, and
368
+ // syncDispositionForm() in gateway.mjs already unions this exact shape — prior-only, `{ rows: null }` submitted — on
369
+ // every attempt. So this is that mode, not a new one.
370
+ //
371
+ // ONE METRIC MOVES, deliberately: with no submission, `carried` counts every ruled row, because
372
+ // "rows this attempt's own submission would not have carried" is all of them when there is no
373
+ // submission. Same at the gateway call, for the same reason.
374
+ const merged = mergedOb.queries.length
375
+ ? unionDispositionForm({ rows: halfRows }, { rows: null }, mergedOb, { generatedFrom: "common-law-grid.json" })
376
+ : null;
377
+ if (merged) {
378
+ const json = JSON.stringify(merged.form, null, 2) + "\n";
379
+ // ONE copy: the canonical ACCUMULATOR in `_driver/`. The canonical validator reads exactly this —
380
+ // it is the era stamp the arm keys on, and the copy no seat can delete. The seat-facing mirror
381
+ // (and the preserve-the-submission write that guarded it) died with the form path: no seat ever
382
+ // writes at the canonical dispositions path, so there is no submission to preserve and no second
383
+ // copy to keep in step.
384
+ atomicWrite(formSidecarPath(P.commonLawDispositions), json);
385
+ }
386
+ // The rendered table is DRIVER-RENDERED from the form, with the receipt titles and URLs taken
387
+ // from the tool-written ledger — so the document gains a complete table that no model had to
388
+ // transcribe, and the seats' own narrative and Findings ride through the concatenation untouched.
389
+ const dispositionTable = merged ? renderDispositionTable(merged.form.rows, mergedOb) : "";
390
+ atomicWrite(P.commonLaw, mergeCommonLawFindings(GRID_SEATS.map((h) => ({
391
+ half: h,
392
+ content: existsSync(P.commonLawHalf(h)) ? readFileSync(P.commonLawHalf(h), "utf8") : null,
393
+ error: halfErrors[h] ?? null,
394
+ }))) + (dispositionTable ? `\n${dispositionTable}` : ""));
395
+ runLog(run.runDir, { event: "common-law-merged", cells: mergedGrid.cells.length, gaps: mergedGrid.gaps.length,
396
+ pr_risk: Array.isArray(mergedGrid.extras?.pr_risk) ? mergedGrid.extras.pr_risk.length : 0 });
397
+ // CONVERGE (2026-07-13): the SAME canonical gate runs on EVERY re-merge — the fan-in below AND the
398
+ // reopen/closure supplementary re-merges (which used to re-derive the canonical pair with NO
399
+ // connotation re-check, laundering a supplementary fold past the gate the fan-in enforces). Reusing
400
+ // the fan-in gate here (never a new cycle) guarantees a re-merge can never ship a merged pair the
401
+ // unsplit path would have rejected.
402
+ // The canonical validator over the MERGED artifacts is the same gate a single-member run passes at
403
+ // its stage boundary (full-spec exact join, platform identity, the connotation receipt) — run it in
404
+ // code so the split can never ship a merged pair the unsplit path would have rejected.
405
+ const anyQuarantined = GRID_SEATS.some((h) => clHalves[h].quarantined);
406
+ const v = validators.commonLaw(P.commonLaw, readFileSync(P.commonLaw, "utf8"));
407
+ // — THE CLASS IS DERIVED FROM WHAT THE VALIDATOR SAID, AND IT USED TO BE DECIDED BEFORE IT
408
+ // SPOKE. This was `anyQuarantined ? "transient" : "deterministic"`, computed two lines ABOVE the
409
+ // call, so `v.reason` never reached the classification and EVERY unquarantined merge failure was
410
+ // deterministic — parkBudget 0, no recovery — whatever had actually gone wrong. Two of two
411
+ // clearances died that way in one round, and the proof the class was wrong came from production:
412
+ // `connotation_call_partial` RECOVERED at a half hours earlier on the same engine family and
413
+ // killed a run at the merge, same token, because only one of the two paths asks.
414
+ //
415
+ // Quarantine stays an input and keeps its own answer: a quarantined half is re-run fresh by the
416
+ // park loop, which is a fact about the RUN and not about the reason. Everything else goes through
417
+ // the same router the rest of the engine uses, so the merge stops being the one seat that answers
418
+ // from its own state.
419
+ //
420
+ // Most validator reasons land on `unknown` — the regexes name weather and defects, not validator
421
+ // tokens — which is ONE park, not a free retry loop, and the same treatment the dropped-query
422
+ // branch below already gives an explained failure. A genuine dead end still terminates; it does so
423
+ // after one dictated repair instead of before it.
424
+ const clFailClass = anyQuarantined ? "transient" : classifyFailureReason(v.reason);
425
+ // — the sentence and the payload are separate fields. `quantity` is stamped from the
426
+ // validator's own count, because taking the census out of the message would otherwise blind the
427
+ // convergence ledger (see StageFailure's `detail`).
428
+ if (!v.ok) throw new StageFailure("common-law", "merged half-grids failed the canonical validator", undefined,
429
+ { failClass: clFailClass, detail: v.reason, quantity: v.quantity });
430
+ // CONNOTATION completeness — the validator above cannot carry this under the split: its
431
+ // connotation gate is COUNT-based (any one recorded query passes it), so a quarantined half's
432
+ // dictated meaning queries would vanish silently — never re-routed, nowhere disclosed — while the
433
+ // surviving half's receipts keep the count positive: the exact gang-slang-near-miss false-clean
434
+ // class the gate exists to prevent. The per-query identity join closes that hole: every dictated
435
+ // query must be recorded in the merged extras.pr_risk[], or the merge gate fails.
436
+ //
437
+ // (The previous note here said a dropped query is "never a gap row (gaps are term×platform only)".
438
+ // That is not true and it was the stated justification for the failClass below: mergeGrids' non-spec
439
+ // union branch re-adds any gap whose platform is not in the spec, so an honestly-thrown connotation
440
+ // query DOES arrive as `{ term: <query>, platform: "connotation", error }`. We were discarding the
441
+ // one signal that distinguishes weather from a defect.)
442
+ //
443
+ // HOW MANY ATTEMPTS THE FAILURE GETS, and why it is not one number:
444
+ // quarantined half → transient — the park loop re-runs that half fresh, the surviving half's
445
+ // artifacts are kept, and the re-merge converges.
446
+ // both halves ok, query THREW and said so
447
+ // → unknown — one park. Most likely one web request failing inside a plugin
448
+ // that otherwise completed; worth exactly one retry. If it throws
449
+ // again the run still dies, which is correct.
450
+ // both halves ok, query VANISHED → deterministic — no receipt, no gap row, nothing: the plugin's
451
+ // own per-query contract was not honoured. Retrying a defect
452
+ // buys nothing, and this is the original reasoning, intact.
453
+ //
454
+ // What does NOT change: an errored query still FAILS this gate. A meaning check that did not
455
+ // complete cannot back a clean reputational read, and counting it as searched to keep the run alive
456
+ // would launder a real hole into a clean receipt — a worse defect than the one being fixed. The old
457
+ // behaviour was zero retries after full spend, with a re-run that failed identically; the new
458
+ // behaviour is one retry, then the same honest death.
459
+ const dropped = findDroppedConnotationQueries(fullSpec, mergedGrid);
460
+ if (dropped.length && discloseUnfinished) {
461
+ // ── THE LAST STEP OF THE OWNER'S RULING: a run that completed 59 of 60 dictated searches
462
+ // DELIVERS, and says on the client's own page that it was partial and for which term.
463
+ //
464
+ // This is NOT the false-clean the note below guards against, and the difference is the whole
465
+ // reason it is allowed here. False-clean is SILENCE — a hole counted as searched, nobody able to
466
+ // see what was not done. This records each unfinished query as an honest gap carrying its own
467
+ // term, which is the vocabulary the note above says dictated queries did not have, and that gap
468
+ // is what the coverage row reads. A reader is told the investigation was partial and which term
469
+ // did not complete.
470
+ //
471
+ // It is reached ONLY after the bounded attempts are spent: the model's single routed remedy and
472
+ // the engine's own re-issue of the search. On the first pass this branch does not exist — the
473
+ // gate throws exactly as before and the park loop gets its retries. Disclosure is the last
474
+ // resort, never the first answer.
475
+ const errored = findErroredConnotationQueries(fullSpec, mergedGrid);
476
+ const explained = new Set(errored.map((e) => e.query));
477
+ const gaps = Array.isArray(mergedGrid.gaps) ? mergedGrid.gaps : (mergedGrid.gaps = []);
478
+ for (const q of dropped) {
479
+ if (explained.has(q)) continue; // the provider already said why; its row stands
480
+ gaps.push({ term: q, platform: "connotation",
481
+ error: "the search did not complete after a re-ask and a re-issue by the engine" });
482
+ }
483
+ // THE CANONICAL LEDGER IS WRITTEN ABOVE, BEFORE THIS GATE RUNS, so mutating the merged object
484
+ // here reaches nothing: the report reads the file. Re-write it with the gaps in place, or the
485
+ // disclosure exists only in memory and the coverage row has nothing to read — which is the
486
+ // silent half of the very defect this branch exists to prevent.
487
+ atomicWrite(P.commonLawGrid, JSON.stringify(mergedGrid, null, 2) + "\n");
488
+ runLog(run.runDir, { event: "connotation-unfinished-disclosed", count: dropped.length,
489
+ explained: errored.length, terms: dropped.length });
490
+ note(`${dropped.length} dictated meaning quer${dropped.length === 1 ? "y" : "ies"} did not complete after `
491
+ + "the bounded attempts — recorded as honest gaps and DISCLOSED on the coverage row; the run delivers");
492
+ return { mergedGrid, fullSpec, connotationUnfinished: dropped.slice() };
493
+ }
494
+ if (dropped.length) {
495
+ const errored = findErroredConnotationQueries(fullSpec, mergedGrid);
496
+ const allExplained = errored.length === dropped.length;
497
+ const dropClass = anyQuarantined ? clFailClass : (allExplained ? "unknown" : "deterministic");
498
+ const detail = allExplained
499
+ ? `threw and were recorded as gaps (${errored.map((e) => `${e.query}: ${e.error}`).join("; ").slice(0, 160)})`
500
+ : `never executed, and a count-based connotation gate cannot see it (${dropped.join("; ").slice(0, 160)})`;
501
+ // — same split: the count is part of the sentence (a reader can act on "3 queries"), the
502
+ // queries themselves are the payload. `quantity` is the drop count, which is what converges.
503
+ throw new StageFailure("common-law",
504
+ `merged half-grids dropped ${dropped.length} dictated connotation quer${dropped.length === 1 ? "y" : "ies"}`,
505
+ undefined, { failClass: dropClass, detail, quantity: dropped.length });
506
+ }
507
+ return { mergedGrid, fullSpec };
508
+ };
509
+ // ── P2-C (§8b leg 2) — the merge-gate connotation failure gets ONE routed model turn before it may
510
+ // be terminal (2026-07-31 review round). With both halves completed (no quarantine), a merged doc
511
+ // failing connotation_no_ruling / connotation_form_damaged is a DOC defect — a clean bottom
512
+ // line in one half over receipts recorded in a half that never wrote its rows — at seats whose warm
513
+ // sessions are still open. mergeCommonLawArtifacts throws it failClass "deterministic", and
514
+ // decideRecovery gives deterministic failures parkBudget 0 ("never parked at all"), so without this
515
+ // channel the FIRST such run dies .failed at the merge after a full paid gather while gateway.mjs's
516
+ // connotation correction hints are never shown to any model. Remedy: route a followup to each usable
517
+ // half whose OWN recorded receipts are among the violations (the routed-half-followup channel — the
518
+ // closure/frame-reopen precedent), carrying the exact correction hint; each half's re-emit is
519
+ // re-judged by validators.commonLawHalf, then ONE re-merge decides. Bounded to a single remedy round
520
+ // per run — a re-merge that still fails throws the same honest death (the original reasoning stands:
521
+ // retrying a defect buys nothing; this is one dictated repair, not a retry). Quarantined-half shapes
522
+ // keep their transient park path untouched (the remedy never runs for them).
523
+ let clConnotationRemedySpent = false;
524
+ /**
525
+ * THE ENGINE'S OWN ATTEMPT, THEN DELIVERY WITH THE GAP DISCLOSED.
526
+ *
527
+ * Reached only after the model has had its single routed repair turn. The engine re-issues the
528
+ * missing searches itself through the same provider, appends whatever comes back to the half's own
529
+ * ledger, and re-merges. If the searches are there now, the run is simply clean and nothing is
530
+ * disclosed. If they are still missing, the run DELIVERS and the coverage row says the investigation
531
+ * was partial and which term did not complete.
532
+ *
533
+ * A clearance that completed 59 of 60 dictated searches used to throw the whole report away. The
534
+ * failure it is replacing is not a quality gate doing its job: the work was done, one search of
535
+ * sixty did not land, and the client lost everything including the 59.
536
+ */
537
+ const reissueThenDisclose = async (e) => {
538
+ if (!clConnotationReissueSpent) {
539
+ clConnotationReissueSpent = true;
540
+ let missing = [];
541
+ try {
542
+ const spec = readJson(P.gridSpecHalf(MEANING_SEAT));
543
+ const merged = readJson(P.commonLawGrid);
544
+ missing = findDroppedConnotationQueries(spec, merged);
545
+ if (missing.length) {
546
+ runLog(run.runDir, { event: "connotation-reissue", count: missing.length });
547
+ note(`${missing.length} dictated meaning quer${missing.length === 1 ? "y" : "ies"} missing after the `
548
+ + "model's one repair turn — the engine re-issues them itself through the same tool");
549
+ const reissuer = opts.connotationReissuer ?? defaultConnotationReissuer;
550
+ const r = await reissuer(missing, { spec, rawPath: driverDir(run.runDir, "web-results", `connotation-reissue-${Date.now()}.json`) });
551
+ runLog(run.runDir, { event: "connotation-reissue-result", ok: !!r?.ok,
552
+ recovered: Array.isArray(r?.rows) ? r.rows.length : 0,
553
+ cause: r?.ok ? null : String(r?.cause ?? "").slice(0, 160) });
554
+ if (r?.ok && r.rows?.length) {
555
+ // Append into the half's OWN ledger, so the ordinary re-merge picks them up and nothing
556
+ // downstream needs to know this call happened.
557
+ const half = readJson(P.commonLawGridHalf(MEANING_SEAT));
558
+ half.extras = half.extras ?? {};
559
+ half.extras.pr_risk = [...(Array.isArray(half.extras.pr_risk) ? half.extras.pr_risk : []), ...r.rows];
560
+ atomicWrite(P.commonLawGridHalf(MEANING_SEAT), JSON.stringify(half, null, 2) + "\n");
561
+ }
562
+ }
563
+ } catch (err) {
564
+ // Never fatal: a re-issue that cannot even be attempted leaves the run exactly where it was,
565
+ // and the disclosure below is what the ruling actually guarantees.
566
+ runLog(run.runDir, { event: "connotation-reissue-failed", error: String(err?.message ?? err).slice(0, 160) });
567
+ }
568
+ try { return mergeCommonLawArtifacts(); } catch { /* still short — disclose below */ }
569
+ }
570
+ return mergeCommonLawArtifacts({ discloseUnfinished: true });
571
+ };
572
+ const mergeWithConnotationRemedy = !clSplit ? null : async () => {
573
+ try { return mergeCommonLawArtifacts(); }
574
+ catch (e) {
575
+ // — `quote_unbound` joins the two here or the remedy channel does not open for it: a merged
576
+ // doc failing ONLY on a quote would throw "deterministic", get parkBudget 0, and die at the merge
577
+ // after a full paid gather with no model ever shown the correction hint. Same defect class as the
578
+ // one this channel was built for, and the token that describes it is the newest one.
579
+ // — THE TOKEN IS READ FROM THE DETAIL AS WELL AS THE MESSAGE, AND WITHOUT THAT THIS WHOLE
580
+ // CHANNEL WAS DEAD. It matched `e.message` alone. StageFailure builds that as `${stage}: ${reason}`,
581
+ // and moved the open-set payload OUT of `reason` into `detail` so a renderer could show the
582
+ // sentence and hide the payload — so from that split onward the message read
583
+ // "common-law: merged half-grids failed the canonical validator" and carried no token at all.
584
+ // `!tok` was therefore true on EVERY merge-validator failure: this remedy re-threw before it
585
+ // opened, and the run died on a token whose own error text carried the recovery instruction.
586
+ // Measured on the two failures that prompted this — token in `e.message`: null; in `e.detail`:
587
+ // `connotation_quote_unbound:quote_unbound=3;…` and `connotation_call_partial:2 rows still
588
+ // outstanding`.
589
+ //
590
+ // A converted field takes its guards QUIET, not red, and a recovery path is a reader too. The
591
+ // message half is kept rather than replaced: an archived or re-thrown failure that still carries
592
+ // the token inline must keep opening this channel.
593
+ const tok = connotationRemedyToken(e);
594
+ const anyQuarantined = GRID_SEATS.some((h) => clHalves[h].quarantined);
595
+ // A quarantined half keeps its transient park path: that half is re-run whole and the re-merge
596
+ // converges, so there is nothing here to disclose yet.
597
+ // THE DROPPED-QUERY FAILURE CARRIES NO FORM TOKEN, and matching on the form tokens alone is why
598
+ // this channel never opened for it: `connotationRemedyToken` reads the connotation FORM
599
+ // vocabulary, and "merged half-grids dropped N dictated connotation queries" is not in it. The
600
+ // run therefore died at the merge with the recovery path sitting unused beside it.
601
+ const droppedQueries = /dropped \d+ dictated connotation quer/i.test(String(e?.message ?? ""));
602
+ if (anyQuarantined) throw e;
603
+ if (droppedQueries) return await reissueThenDisclose(e);
604
+ if (!tok) throw e;
605
+ // ── ONE RE-ASK OF THE MODEL, THEN THE ENGINE TAKES OVER ──────────────────────────────────
606
+ // The loop stops being a loop. The model gets exactly one routed repair turn; after that the
607
+ // engine re-issues the search itself and, failing that, the run delivers with the gap disclosed.
608
+ // Before this, a second arrival here re-threw and the clearance died after a full paid gather.
609
+ if (clConnotationRemedySpent) return await reissueThenDisclose(e);
610
+ clConnotationRemedySpent = true;
611
+ runLog(run.runDir, { event: "connotation-remedy", detail: tok.slice(0, 200) });
612
+ // — WHICH HALVES OWE ROWS, READ FROM THE FORM. This used to re-derive the violation set here,
613
+ // a SECOND derivation of what the gate had just computed — and one that ran without the seats'
614
+ // rulings passed in, so it read structurally-discharged obligations as violations and returned a
615
+ // SUPERSET of the halves that actually owed anything. The canonical form already carries every row
616
+ // and every ruling; an outstanding row's own queries name the halves to route to.
617
+ let needy = new Set();
618
+ try {
619
+ const mergedOb = connotationObligations(parsePrRiskResults(readFileSync(P.commonLawGrid, "utf8")));
620
+ // B — the canonical rulings live in the ACCUMULATOR (the merge's one write); the seat-facing
621
+ // mirror died with the form path.
622
+ const form = parseDispositionForm(readFileSync(formSidecarPath(P.commonLawDispositions), "utf8")).rows;
623
+ for (const row of outstandingRows({ rows: form }, mergedOb))
624
+ for (const q of (row.kind === "recurrence" ? (row.queries ?? []) : [row.query])) if (q) needy.add(q);
625
+ } catch { /* unreadable merged pair or no form — fall through; the re-merge below re-throws honestly */ }
626
+ const usable = (h) => Boolean(clHalves[h].sessionKey && !clHalves[h].quarantined);
627
+ // — ONE seat owns the whole sweep, so the remedy has exactly one address. Routing over the
628
+ // grid halves would send a form-repair turn into two seats that were never given a meaning query
629
+ // and hold no form to open — a message with no work in it, twice, on the critical path.
630
+ await runBatched([MEANING_SEAT], config.gatherConcurrency, async (h) => {
631
+ if (!usable(h)) return;
632
+ let owned = [];
633
+ try { owned = parsePrRiskResults(readFileSync(P.commonLawGridHalf(h), "utf8")).filter((e2) => e2.results.length); }
634
+ catch { /* no seat ledger → nothing owed here */ }
635
+ if (!owned.some((e2) => needy.has(e2.query))) return;
636
+ // B — THE REPAIR IS A TOOL CALL, and the tail must order exactly that. A tail ordering
637
+ // targeted edits to any file would be the two halves of one message disagreeing about where
638
+ // the work lands — the routing gap closed, kept closed under the typed transport.
639
+ const followup = repairFollowup("common-law-half:connotation-remedy", { findingsFile: P.commonLawHalf(h), gridSpecPath: P.gridSpecHalf(h), tok });
640
+ const r = await stage("common-law-half", { ...ctx, axis: h }, { force: true, followup, sessionKey: clHalves[h].sessionKey, trigger: "connotation-remedy" });
641
+ if (!r.ok) note(`connotation remedy (half ${h}) failed mechanically (${r.fail}) — the re-merge below decides`);
642
+ });
643
+ try { return mergeCommonLawArtifacts(); }
644
+ catch (e2) { return await reissueThenDisclose(e2); }
645
+ }
646
+ };
647
+ if (clSplit) await mergeWithConnotationRemedy();
648
+ recordConnotationAudit(run, P);
649
+ // ── repair-first (2026-07-05): the plan-direct-execute repair kit for the fan-in gates below. The
650
+ // provider adapter re-runs dictated slices as pure code at the gate (no agent turn, no gateway lane);
651
+ // the tool's qid-ownership merge preserves untargeted/judgment blocks. Tests inject opts.planExecutor
652
+ // (or set CLEAROTRON_PLAN_DISPATCH=off) so the offline mock never dials the live provider. Budgets live in
653
+ // the persistent repair ledger (_driver/repairs.json); the epoch (plan_version:recoveryAttempts)
654
+ // re-arms them when the input legitimately changed (a plan extension, a fresh recovery attempt).
655
+ // (planExec itself is resolved once, above the gather — the code-side saturation-probe unit shares it.)
656
+ const repairLedger = ctx.repairLedger ?? (ctx.repairLedger = createRepairLedger(run.runDir, { log: (o) => runLog(run.runDir, o) }));
657
+ const repairEpoch = (() => {
658
+ const att = (() => { try { return Number(readJson(join(run.runDir, "status.json")).recoveryAttempts) || 0; } catch { return 0; } })();
659
+ return `${ctx.registerPlan?.plan_version ?? 0}:${att}`;
660
+ })();
661
+ const fanInRepairs = [];
662
+ const dispatchPlanQids = async (a, qids, repairId, max = 1) => {
663
+ if (!planExec || !ctx.registerPlan) return null;
664
+ // A qid this run has accepted as a capability gap is never sent to the provider again, under any plan
665
+ // version (envelope-settle.mjs stickyGapsAfter). A whole-axis dispatch becomes the axis's other qids;
666
+ // the executor's qid-ownership merge keeps the gap's own block as it stands.
667
+ const sticky = readStickyGaps(P);
668
+ if (sticky.size) {
669
+ const wanted = qids?.length ? qids : (ctx.registerPlan.entries ?? []).filter((e) => e.axis === a).map((e) => e.qid);
670
+ const held = wanted.filter((q) => sticky.has(q));
671
+ if (held.length) {
672
+ runLog(run.runDir, { event: "plan-qids-sticky-gap", axis: a, qids: held, action: repairId });
673
+ qids = wanted.filter((q) => !sticky.has(q));
674
+ if (!qids.length) return null;
675
+ }
676
+ }
677
+ if (!repairLedger.canAttempt(repairId, a, { max, epoch: repairEpoch })) return null;
678
+ note(`register-unit ${a}: ${repairId} — direct executor dispatch (code, no agent turn) for ${qids?.length ?? "all"} dictated slice(s)`);
679
+ let outcome;
680
+ // — the clock starts at the DISPATCH, not at the bookkeeping after it. These calls sit
681
+ // between stages, so on the D8 measurement their time landed in "outside any stage": 220s of one
682
+ // 6m45s seam was three of them, against 1.1s of driver compute in the same window.
683
+ const dispatchStartedMs = Date.now();
684
+ try {
685
+ // The envelope close's own dispatch is the one rung that asks a question that timed out at the gateway again
686
+ // (execute-plan.mjs, timedOutBefore); every other dispatch leaves its timeout standing.
687
+ const r = await planExec({ planPath: P.registerPlan, axis: a, outputPath: P.registerBand(a), ...(qids?.length ? { qids } : {}) },
688
+ { agentId: agent, sessionKey: `clearance-${run.slug}-${run.codename}-register-unit-${a}`, recordLog: runRecordLogPath(run.runDir),
689
+ ...(repairId === "early-envelope-close" ? { reaskTimedOut: true } : {}) });
690
+ outcome = r?.ok ? "ok" : `failed: ${String(r?.cause ?? "unknown").slice(0, 140)}`;
691
+ } catch (err) { outcome = `threw: ${String(err?.message ?? err).slice(0, 140)}`; }
692
+ // — MEASURE WHETHER THE HOLE CLOSED, not whether the phone was answered. `outcome` is the
693
+ // executor call returning; on a delivered run all five of these read "ok" while the deferred set
694
+ // they were repairing grew 4 → 7. The bands are already on disk at this point, so the answer costs
695
+ // one read: of the qids we ASKED for, how many now own a band block that is not an error?
696
+ // Best-effort by construction — a repair that worked must never be reported as failed because the
697
+ // measurement threw, so an unreadable band yields "unmeasured" rather than a zero, which would be
698
+ // a confident wrong value of exactly the kind this issue is about.
699
+ let effect;
700
+ try {
701
+ if (qids?.length) {
702
+ // `readRegisterBands` directly, not the `readBands` helper further down: that one is declared
703
+ // in an inner block and is not in this closure's scope. Only this axis's band: the executor writes no
704
+ // other, and every qid it was sent is this axis's.
705
+ const landed = new Set();
706
+ for (const arr of Object.values(readRegisterBands(P, [a]) ?? {}))
707
+ for (const b of arr ?? []) if (b && typeof b.qid === "string" && b.qid && b.error !== true) landed.add(b.qid);
708
+ effect = { asked: qids.length, closed: qids.filter((q) => landed.has(q)).length };
709
+ }
710
+ } catch { effect = undefined; }
711
+ const dispatchEndedMs = Date.now();
712
+ repairLedger.record(repairId, a, outcome, { epoch: repairEpoch, effect, max, durationMs: dispatchEndedMs - dispatchStartedMs });
713
+ // …and the same span where the decomposition can see it. `register-repair` is the stage label it
714
+ // will print, because that instrument takes the label from the filename.
715
+ recordSpan(run.runDir, "register-repair", { startedMs: dispatchStartedMs, endedMs: dispatchEndedMs },
716
+ { repair: repairId, target: a, outcome: String(outcome), asked: effect?.asked ?? null, closed: effect?.closed ?? null });
717
+ if (effect && effect.closed < effect.asked)
718
+ note(`register-unit ${a}: ${repairId} dispatched ${outcome} but closed ${effect.closed} of ${effect.asked} slice(s) — the call returning is not the hole closing`);
719
+ fanInRepairs.push({ repair: repairId, target: a, outcome, effect: effect ?? null });
720
+ return outcome;
721
+ };
722
+ // barrier: every expected file present + valid. "Expected" is what the FROZEN POLICY dictated —
723
+ // a register-only run has no common-law member, so demanding its findings file here would fail
724
+ // every such run at the barrier. The list must never be narrowed for any other reason: this is
725
+ // the gate that stops a report shipping over an artifact a stage was supposed to write and did not.
726
+ for (const f of [...(runCommonLaw ? [P.commonLaw] : []), ...axes.map((a) => P.registerUnit(a))]) {
727
+ if (!existsSync(f)) throw new StageFailure("fan-in", `missing ${f}`);
728
+ }
729
+ // THE SLICES A CHECK COULD NOT PROVE RAN, ONCE ITS RECOVERY WAS SPENT: each is taken out of its axis's band and
730
+ // delivered as an open row, before the band's checks and the plan join read the band. The checks below name the
731
+ // slices they fail on, and the run-level catch records them (parts-not-completed.mjs).
732
+ const searchesOpen = readPartNotCompleted(run.runDir, "searches");
733
+ if (Array.isArray(searchesOpen?.slices) && searchesOpen.slices.length) {
734
+ const taken = takeSlicesOutOfTheBand(P, searchesOpen.slices);
735
+ runLog(run.runDir, { event: "searches-not-completed-delivery", slices: searchesOpen.slices.length, taken: taken.length,
736
+ reasons: [...new Set(searchesOpen.slices.map((s) => s.reason))] });
737
+ note(`register: ${searchesOpen.slices.length} slice(s) a check could not prove ran are taken out of the band and delivered as open rows`);
738
+ }
739
+ // judgment-relocation LINCHPIN (2026-06-24): the load-bearing funnel artifact is the COMPLETE NAMED BAND
740
+ // (register-units/<axis>-band.json) — the real material that crosses the lifted firewall. A unit that RAN
741
+ // THIS process (unitKey[a] set) MUST have written it; a missing band would merge to empty and let a clean
742
+ // ship over an UN-searched band (the firewall silently failing — the exact disease). Hard-require it for
743
+ // freshly-run axes, as a TECHNICAL fan-in failure (retryable), never a silent pass. A resume PAST gather
744
+ // (unitKey unset for an axis) stays lenient — deriveNamedBand handles a legacy/archived band-less run.
745
+ // T3 (H3) — the resume-past-gather leniency is TIGHTENED: post- every unit writes a band
746
+ // (the executor writes even error blocks), so on a resumed run where ANY band file exists, an axis
747
+ // with none is a coverage hole, not a legacy artifact. Only a ZERO-band run (true pre-band legacy /
748
+ // archived) keeps the lenient path. copper-spire's shipping path was exactly fail → manual resume →
749
+ // resumed-past leniency → degrade-with-note → ship.
750
+ const anyBands = axes.some((x) => existsSync(P.registerBand(x)));
751
+ const unprovenBands = []; // every axis whose band the ledger cannot evidence, failed on together below
752
+ const collapsedSlices = []; // every axis's qid-stamped slices that claimed hits and carried no record, likewise
753
+ for (const a of axes) {
754
+ if ((unitKey[a] || anyBands) && !existsSync(P.registerBand(a)))
755
+ throw new StageFailure("fan-in", `missing named band for axis "${a}" — the funnel produced no complete band (a clean can never ship over an unsearched band)`, undefined, { detail: `${P.registerBand(a)}${unitKey[a] ? "" : " — resumed-past axis on a run that carries bands: a hole, not legacy"}` });
756
+ // FIX backstop: a COLLAPSED slice (enumerated, total_hits>0, ZERO records) is the firewall silently
757
+ // failing in the other direction — a clean shipping over a dangerous slice that WAS searched but lost.
758
+ // Terminal immediately for freshly-run axes (the validator ladder above already gave the slice a re-run).
759
+ // Fresh-axes-only (unitKey set) → never runs in replay, so no historical-verdict flip from the backstop;
760
+ // the deterministic, floor-safe validators.registerUnit gate carries replay.
761
+ if (unitKey[a] && existsSync(P.registerBand(a))) {
762
+ const readCollapsed = () => { try { return findCollapsedBands(readFileSync(P.registerBand(a), "utf8")); } catch { return []; /* parse defect handled at the stage validator */ } };
763
+ let collapsed = readCollapsed();
764
+ // Repair-first A2: a collapsed DICTATED slice (qid-stamped) gets ONE direct re-execution — the
765
+ // tool rewrites that slice's block from a fresh enumeration, no agent turn. Judgment (qid-less)
766
+ // collapsed slices already had their re-run via the validator ladder — they stay terminal.
767
+ const collapsedQids = collapsed.map((x) => x.qid).filter(Boolean);
768
+ if (collapsedQids.length && (await dispatchPlanQids(a, collapsedQids, "collapsed-reexecute")) === "ok") collapsed = readCollapsed();
769
+ // The collapsed slices are the searches not completed, failed on with every axis's below. One with no qid is named by
770
+ // its query, and its block becomes a deferred block on that query.
771
+ if (collapsed.length) collapsedSlices.push({ axis: a, collapsed });
772
+ }
773
+ // ── band-truth gate (2026-07-14, teal-foundry): the band must be EVIDENCED, not just well-formed ──
774
+ // A qid-stamped band whose unit lane logged ZERO real provider calls was AUTHORED, not executed —
775
+ // the exact fabrication that shipped 07-06 (ashen-causeway), 07-07 (teal-lattice, a CLEAR) and
776
+ // 07-13 (teal-foundry): the model skipped its one register_execute_plan call and hand-wrote
777
+ // plausible blocks. Forged qids satisfy every content gate, and the plan-execution receipt derives
778
+ // from the band itself — so the judge here is the provider call LEDGER, code-written at the plugin
779
+ // chokepoint, outside the model's reach. Repair-first: ONE direct re-execution rebuilds the band
780
+ // from the frozen plan (real calls, real data — the qid-ownership merge overwrites every forged
781
+ // dictated block); fail-closed only when that too cannot be evidenced. Scoped to fresh axes
782
+ // (unitKey — same as the collapsed gate; a resumed skip recovers the winning lane key, so resumed
783
+ // forged runs are caught too) with dictated entries and a qid-carrying band. A null count = the
784
+ // ledger file is absent (hermetic tests, fresh installs) — the gate cannot judge and skips.
785
+ // Kill switch CLEAROTRON_BAND_TRUTH_GATE=0 (the inline `!== "0"` pattern): hermetic test harnesses
786
+ // opt out (their runs never touch the provider, so the production ledger can never evidence them);
787
+ // production default is ON.
788
+ if (process.env.CLEAROTRON_BAND_TRUTH_GATE !== "0"
789
+ && unitKey[a] && existsSync(P.registerBand(a)) && (ctx.registerPlan?.entries ?? []).some((e) => e?.axis === a)) {
790
+ const laneKey = `clearance-${run.slug}-${run.codename}-register-unit-${a}`;
791
+ // A slice taken out of the band, or one the provider could not express, is a deferred block that made no call.
792
+ const qidBlocks = (() => {
793
+ try { const b = readJson(P.registerBand(a)); return Array.isArray(b) ? b.filter((x) => x && typeof x === "object" && x.qid && !(x.error === true && x.deferred === true)) : []; }
794
+ catch { return []; /* parse defects are the stage validator's problem, not this gate's */ }
795
+ })();
796
+ const bandHasQids = qidBlocks.length > 0;
797
+ if (bandHasQids && countLaneCalls(laneKey) === 0) {
798
+ note(`register-unit ${a}: band carries qid blocks but its lane logged ZERO provider calls — authored, not executed; direct re-execution from the frozen plan`);
799
+ runLog(run.runDir, { event: "band-truth-gate", axis: a, lane: laneKey, calls: 0 });
800
+ const outcome = await dispatchPlanQids(a, null, "unverified-band-reexecute");
801
+ const callsNow = countLaneCalls(laneKey);
802
+ if (outcome === "ok" || (callsNow ?? 0) > 0) {
803
+ runLog(run.runDir, { event: "band-truth-rebuilt", axis: a, outcome, calls: callsNow ?? 0 });
804
+ note(`register-unit ${a}: band re-executed from the frozen plan (dispatch ${outcome ?? "unavailable"}, ${callsNow ?? 0} ledger call(s)) — fan-in continues over executor data`);
805
+ } else {
806
+ unprovenBands.push({ axis: a, laneKey, reexecution: outcome, qids: qidBlocks.map((x) => x.qid) });
807
+ }
808
+ }
809
+ }
810
+ }
811
+ // THE SLICES THE BAND'S CHECKS COULD NOT PROVE RAN, failed on together, so one park takes every axis's. They are the
812
+ // searches not completed: once this is terminal they are taken out of the band and delivered as open rows, each with
813
+ // its shipped reason. A band no ledger call evidences reads "nothing in the run's own record confirms it was
814
+ // searched"; a slice that claimed hits and carried no record reads "it could not be completed this run". A slice that
815
+ // is both keeps the first.
816
+ const notCompleted = [
817
+ ...unprovenBands.flatMap((u) => u.qids.map((qid) => ({ axis: u.axis, qid, reason: plainDeferralReason("not-verified-closed") }))),
818
+ ...collapsedSlices.flatMap((c) => c.collapsed.map((x) => (x.qid ? { axis: c.axis, qid: x.qid, reason: plainDeferralReason("collapsed-slice") }
819
+ : { axis: c.axis, query: String(x.query ?? ""), reason: plainDeferralReason("collapsed-slice") }))),
820
+ ];
821
+ if (unprovenBands.length) {
822
+ const [first] = unprovenBands, more = unprovenBands.length - 1;
823
+ throw Object.assign(new StageFailure("fan-in", `fabricated named band for ${more ? `${unprovenBands.length} axes` : `axis "${first.axis}"`} — qid-stamped blocks, ZERO provider calls in the ledger, re-execution not evidenced (a clean can never ship over an unexecuted band)`,
824
+ undefined, { failClass: "deterministic", repairs: fanInRepairs,
825
+ detail: `${P.registerBand(first.axis)} — lane "${first.laneKey}", re-execution ${first.reexecution ?? "no executor lane"}${more ? `; ${more} more axis(es): ${unprovenBands.slice(1).map((u) => u.axis).join(", ")}` : ""}` }),
826
+ { notCompletedPart: "searches", excludedSlices: notCompleted });
827
+ }
828
+ if (collapsedSlices.length) {
829
+ const [{ axis: a, collapsed }] = collapsedSlices;
830
+ const n = collapsedSlices.reduce((k, c) => k + c.collapsed.length, 0);
831
+ throw Object.assign(new StageFailure("fan-in", `collapsed named band for axis "${a}" — ${n} enumerated slice(s) claimed hits but carried ZERO records into the band (a clean can never ship over a collapsed slice)`,
832
+ undefined, { failClass: "deterministic", repairs: fanInRepairs,
833
+ detail: `${P.registerBand(a)} — ${collapsed.slice(0, 6).map((x) => `${(x.query || "slice").slice(0, 40)}~${x.total_hits}`).join("; ")}${collapsedSlices.length > 1 ? `; and on ${collapsedSlices.length - 1} more axis(es)` : ""}` }),
834
+ { notCompletedPart: "searches", excludedSlices: notCompleted });
835
+ }
836
+
837
+ // ── timeout-taint chain (copper-lattice 2026-07-08): unfinished ⇒ deferred ⇒ recover ⇒ converge ──────
838
+ // A register-unit pass SIGKILLed at the wall leaves partial band writes the merge preserves; the
839
+ // same-stage retry then "succeeds" by validating the poisoned band — the false 0/clean never THREW, so
840
+ // nothing recovered it. The chain, per tainted axis (register-taint.mjs reads the per-attempt jsonl —
841
+ // durable across --resume):
842
+ // T0 quarantine floor — every qid-less enumerated-with-zero-records block becomes an honest
843
+ // `incomplete` descriptor marked `(taint)` (never-silent-clean holds even if every re-run fails);
844
+ // T0.5 deterministic repair of the dictated half — one whole-axis execute_plan re-dispatch;
845
+ // T1 ONE fresh in-loop re-run (fresh session, never warm — doc-44: never warm-resume a killed
846
+ // session; the envelope, a warm resume, stays the second net); attempt-1-clean supersedes.
847
+ // Still tainted on a MATERIAL axis → pre-synthesis: rename the tainted artifacts (so the resume
848
+ // genuinely re-executes, not skip-validates) and THROW transient — the run-level park loop re-runs and
849
+ // converges, repeat-signature → the honest failure notice. Post-synthesis (narrative locked): DISCLOSE —
850
+ // `taint:<axis>` joins escalation-state failed[] (client export withheld) and the ledger relabel
851
+ // (loadCoverageLedger → applyTaintDeferred) + registerGap clamp carry the verdict. NO KILL SWITCH:
852
+ // it had one, nothing ever set it — not a deployment, not CI, not the config store, not a test —
853
+ // so the off-path was never exercised by anything and is gone. The block stays a block because
854
+ // what it declares must not leak into the scope around it.
855
+ {
856
+ const taint0 = readRegisterTaint(run.runDir, axes);
857
+ const taintedNow = axes.filter((a) => taint0[a]?.tainted);
858
+ if (taintedNow.length) {
859
+ const recoveryAttempts = (() => { try { return Number(readJson(join(run.runDir, "status.json")).recoveryAttempts) || 0; } catch { return 0; } })();
860
+ // The axes whose recovery is spent: the searches record lists them, and each is read as it stands and disclosed.
861
+ const disclosedAxes = new Set(Array.isArray(searchesOpen?.disclosed_axes) ? searchesOpen.disclosed_axes : []);
862
+ const axesRec = {};
863
+ const digestLocked = existsSync(P.narrative); // synthesis done — the audit spine is locked; disclose, never mutate under it
864
+ for (const a of taintedNow) {
865
+ const repairs = [];
866
+ let quarantined = 0;
867
+ // T0 — quarantine floor (unconditional, idempotent, code-only)
868
+ try {
869
+ if (existsSync(P.registerBand(a))) {
870
+ const q = taintQuarantineCleanBlocks(readFileSync(P.registerBand(a), "utf8"));
871
+ if (q.quarantined.length) {
872
+ writeFileSync(`${P.registerBand(a)}.tmp`, JSON.stringify(q.blocks, null, 2) + "\n");
873
+ renameSync(`${P.registerBand(a)}.tmp`, P.registerBand(a));
874
+ quarantined = q.quarantined.length;
875
+ note(`register-unit ${a}: taint-quarantined ${quarantined} self-reported-clean judgment block(s) → incomplete descriptors`);
876
+ runLog(run.runDir, { event: "taint-quarantine", axis: a, blocks: quarantined });
877
+ }
878
+ }
879
+ } catch (e) { note(`register-unit ${a}: taint quarantine not applicable (${String(e.message).slice(0, 100)})`); }
880
+ // T0.5 — deterministic re-execution of the dictated half (repair-ledger bounded). Not for an axis the searches
881
+ // record discloses: its recovery is spent, and its band is read as the last pass left it.
882
+ const dispatched = disclosedAxes.has(a) ? null : await dispatchPlanQids(a, null, "taint-dispatch");
883
+ if (dispatched) repairs.push(`taint-dispatch:${dispatched}`);
884
+ // T1 — ONE fresh in-loop re-run, pre-synthesis only (a fresh full pass on the stage's one model)
885
+ // — held until the real result is in hand; see the push below the taint re-read.
886
+ let taintRerunDispatch = null;
887
+ // — ONE ceiling, named once and read by BOTH ends. A literal repeated at the record site is a
888
+ // second statement of the same rule, and two ends stating the same rule is how they drift apart.
889
+ const taintRerunMax = 1;
890
+ if (!digestLocked && !disclosedAxes.has(a) && repairLedger.canAttempt("taint-rerun", a, { max: taintRerunMax, epoch: repairEpoch })) {
891
+ note(`register-unit ${a}: taint-rerun — one fresh re-run (fresh session; a killed session is never warm-resumed)`);
892
+ const r = await stage("register-unit", { ...ctx, axis: a },
893
+ { force: true, trigger: "taint-rerun", sessionKey: `clearance-${run.slug}-${run.codename}-register-unit-${a}-taint-rerun-${recoveryAttempts}` });
894
+ repairLedger.record("taint-rerun", a, r.ok ? "ok" : `failed: ${String(r.fail ?? "unknown").slice(0, 100)}`, { epoch: repairEpoch, max: taintRerunMax });
895
+ repairs.push(`taint-rerun:${r.ok ? "ok" : `failed: ${String(r.fail ?? "unknown").slice(0, 60)}`}`);
896
+ if (r.ok && r.sessionKey) unitKey[a] = r.sessionKey;
897
+ taintRerunDispatch = r.ok ? "ok" : `failed: ${String(r.fail ?? "unknown").slice(0, 100)}`;
898
+ }
899
+ const after = readRegisterTaint(run.runDir, [a])[a];
900
+ // ── — `outcome` SAID THE CALL RETURNED, AND THE ROW REACHES A FAILURE PACKET ───────────
901
+ //
902
+ // `r.ok` is whether the re-run CALL came back, not whether the taint cleared — and this row
903
+ // travels as `repairs:` on a StageFailure, so a reader of that packet saw `outcome: "ok"` for an
904
+ // axis still tainted. The same shape found on `repair-attempted.outcome`.
905
+ //
906
+ // `outcome` KEEPS ITS MEANING rather than being renamed: `repairs.mjs` documents
907
+ // `axisOutcome` as "the AXIS's repair-attempt outcome", and `fanInMissingEvidence` uses it to say
908
+ // what a repair HIT when a slice landed nothing of its own. That reading is correct and consumed
909
+ // correctly; renaming would churn a documented vocabulary across two producers, a map and a
910
+ // parameter, to fix a field that is not the one lying.
911
+ //
912
+ // So the row gains the result as a SIBLING — the other remedy — and the push moves below the
913
+ // taint re-read so there IS a result to state. `cleared` is the same fact `axesRec[a].status`
914
+ // records two lines down, from this same read.
915
+ if (taintRerunDispatch !== null) {
916
+ fanInRepairs.push({ repair: "taint-rerun", target: a, outcome: taintRerunDispatch,
917
+ cleared: !after?.tainted });
918
+ }
919
+ axesRec[a] = {
920
+ status: after?.tainted ? "active" : "resolved",
921
+ evidence: (after?.tainted ? after.evidence : taint0[a].evidence).slice(0, 8),
922
+ quarantinedBlocks: quarantined,
923
+ repairs,
924
+ ...(after?.tainted ? {} : { resolvedBy: "taint-rerun", resolvedAt: new Date().toISOString() }),
925
+ };
926
+ }
927
+ try {
928
+ const tp = P.registerTaint;
929
+ writeFileSync(`${tp}.tmp`, JSON.stringify({ schema_version: 1, ts: new Date().toISOString(), axes: axesRec }, null, 2) + "\n");
930
+ renameSync(`${tp}.tmp`, tp);
931
+ } catch (e) { note(`register-taint receipt write failed (non-fatal): ${String(e.message).slice(0, 80)}`); }
932
+ const stillTainted = Object.entries(axesRec)
933
+ .filter(([a, v]) => v.status === "active" && !NON_MATERIAL_AXES.includes(String(a).toLowerCase()))
934
+ .map(([a]) => a);
935
+ // Disclosed: every axis once synthesis is done, and an axis the searches record lists once its recovery is spent.
936
+ // Parked: the rest, while the run can still re-run them.
937
+ const { disclose: toDisclose, park: toPark } = taintDisposition(stillTainted, { digestLocked, disclosedAxes });
938
+ if (toDisclose.length) {
939
+ // DISCLOSE — the sanctioned lever once synthesis is done, and once an axis's recovery is spent: the client
940
+ // export is withheld until the search is re-run to closure (the same class as a failed escalation/envelope),
941
+ // the internal report ships CONDITIONAL via the ledger relabel + registerGap clamp.
942
+ try {
943
+ const escPath = P.escalationState;
944
+ let esc = {}; try { esc = readJson(escPath); } catch { /* fresh */ }
945
+ const failed = Array.isArray(esc.failed) ? esc.failed : [];
946
+ for (const a of toDisclose) if (!failed.includes(`taint:${a}`)) failed.push(`taint:${a}`);
947
+ atomicWrite(escPath, JSON.stringify({ ...esc, ts: new Date().toISOString(), failed }, null, 2) + "\n"); // B5 — the client-gate reads this: never truncated
948
+ } catch (e) { note(`taint disclose: escalation-state append failed (${String(e.message).slice(0, 80)})`); }
949
+ // Receipt status → "disclosed": the LEDGER keeps treating the axis as a gap (deferred → clamp +
950
+ // client-gate withhold) but the digest validator stays quiet — a locked narrative is never
951
+ // forced into a rewrite loop (see register-taint.mjs status contract).
952
+ try {
953
+ const tp = P.registerTaint;
954
+ const rec = readJson(tp);
955
+ for (const a of toDisclose) if (rec?.axes?.[a]) rec.axes[a] = { ...rec.axes[a], status: "disclosed" };
956
+ writeFileSync(`${tp}.tmp`, JSON.stringify(rec, null, 2) + "\n"); renameSync(`${tp}.tmp`, tp);
957
+ } catch (e) { note(`register-taint receipt disclose update failed (non-fatal): ${String(e.message).slice(0, 80)}`); }
958
+ runLog(run.runDir, { event: "taint-disclose", axes: toDisclose });
959
+ note(`timeout-taint on ${toDisclose.join(", ")} ${digestLocked ? "past the locked audit spine" : "with its recovery spent"} — disclosed: client export withheld, verdict clamps CONDITIONAL (internal report still ships)`);
960
+ }
961
+ if (toPark.length) {
962
+ // PARK — the converging outer net. Rename (never delete — forensics) so stageOnce's
963
+ // exists-and-validates skip MISSES and the resume genuinely re-executes the tainted units;
964
+ // drop the plan-execution receipt so the re-join runs over the fresh bands; a digest already
965
+ // derived from tainted material is renamed too, else its skip would ship stale rows. The renames ride the
966
+ // failure: once its recovery is spent, the run-level catch puts them back and the axes are disclosed instead.
967
+ const undoRenames = [];
968
+ const parkRename = (f) => {
969
+ try { if (existsSync(f)) { renameSync(f, `${f}.tainted-${recoveryAttempts}`); undoRenames.push({ from: f, to: `${f}.tainted-${recoveryAttempts}` }); } }
970
+ catch { /* best-effort */ }
971
+ };
972
+ for (const a of toPark) for (const f of [P.registerUnit(a), P.registerBand(a)]) parkRename(f);
973
+ try { if (existsSync(P.planExecution)) rmSync(P.planExecution); } catch { /* best-effort */ }
974
+ for (const f of taintParkJudgmentArtifacts(P, run.runDir)) parkRename(f);
975
+ runLog(run.runDir, { event: "taint-park", axes: toPark, attempt: recoveryAttempts });
976
+ throw Object.assign(new StageFailure(`register-unit:${toPark[0]}`,
977
+ `register slice timeout-tainted and unrecovered — an unfinished pass cannot ship self-reported clean (axes: ${toPark.join(", ")})`,
978
+ undefined, { failClass: "transient", repairs: fanInRepairs }),
979
+ { notCompletedPart: "searches", taintedAxes: toPark, undoRenames });
980
+ }
981
+ }
982
+ }
983
+
984
+ // judgment-relocation (2026-06-23): MERGE the per-axis COMPLETE NAMED BANDS into one (register-named-band.json)
985
+ // so the lifted firewall carries the real material into Layer B (placement / digest / synthesis read it as a
986
+ // declared stage input). T3: a band that survived the recovery ladder still malformed FAILS the run
987
+ // inside deriveNamedBand — judgment must never reason over receipts it cannot read. Re-run on every
988
+ // re-enumeration pass below.
989
+ // Repair-first A3: before that terminal, a malformed DICTATED axis gets ONE whole-axis direct
990
+ // re-execution — the tool's merge rewrites every dictated block (fresh-writes over an unparseable
991
+ // file, trading unsalvageable qid-less judgment blocks for a readable dictated band). Only THIS
992
+ // fan-in call carries the repair; later deriveNamedBand calls re-merge post-repair bands.
993
+ try { deriveNamedBand(ctx); }
994
+ catch (e) {
995
+ if (!(e instanceof StageFailure) || !ctx.registerPlan || !planExec) throw e;
996
+ const { invalid } = mergeRegisterBands(P, axes);
997
+ const planAxes = new Set(ctx.registerPlan.entries.map((x) => x.axis));
998
+ const targets = invalid.map((x) => x.axis).filter((x) => planAxes.has(x));
999
+ let repaired = false;
1000
+ for (const a of targets) if ((await dispatchPlanQids(a, null, "band-reexecute")) === "ok") repaired = true;
1001
+ if (!repaired) throw e;
1002
+ deriveNamedBand(ctx); // still malformed → throws for real this time
1003
+ }
1004
+
1005
+ // ── common-law → register cross-check (copper-lattice recovery net #3) ───────────────────────────
1006
+ // Option-D Triggers 1/4 (phase2-execution.md) as CODE: a common-law hit carrying the
1007
+ // "Similar listing(s) found" receipt (or an <x>-of-record owner in a findings block) mints
1008
+ // deterministic register queries — an owner-field sweep per extracted owner, a contains sweep per
1009
+ // owner-less mark — folded into the frozen plan as qid'd entries (plan_version bump). The join
1010
+ // below then sees them MISSING and the plan-direct-execute dispatch runs them as pure code; they
1011
+ // land qid-stamped in the primary-sweep band, skeleton-tracked and receipt-durable. Bounded at the
1012
+ // Option-D cap (10, ranked verified-use-with-URL > owner > term-only), overflow LOGGED never
1013
+ // silent; deterministic qids make the fold resume-idempotent. NEVER-KILL: a parse miss degrades to
1014
+ // a logged skip. Receipt: _driver/register-xcheck.json (the demotion tripwire's substrate).
1015
+ if (ctx.registerPlan) {
1016
+ try {
1017
+ const receiptPath = P.registerXcheck;
1018
+ const prior = existsSync(receiptPath) ? readJson(receiptPath) : null;
1019
+ const signals = findSimilarListingSignals(readFileSync(P.commonLaw, "utf8"));
1020
+ const ranked = [
1021
+ ...signals.filter((s) => s.owner && s.url),
1022
+ ...signals.filter((s) => s.owner && !s.url),
1023
+ ...signals.filter((s) => !s.owner),
1024
+ ];
1025
+ const inScope = inScopeClassList(job, ctx.profile).map(Number).filter(Number.isFinite);
1026
+ const XCHECK_CAP = 10;
1027
+ const candidates = [], candDirectives = [], overflow = [];
1028
+ const seen = new Set();
1029
+ const mintedQids = new Set(); // qid uniqueness inside the lane — the fold below dedupes on it
1030
+ for (const s of ranked) {
1031
+ const term = (s.owner ?? s.markText ?? s.term ?? "").trim();
1032
+ if (!term || !inScope.length) continue;
1033
+ const key = `${s.owner ? "owner" : "mark"}:${term.toLowerCase()}`;
1034
+ if (seen.has(key)) continue;
1035
+ seen.add(key);
1036
+ // IDENTITY, NOT A DISPLAY SLUG — AND ON BOTH ROW TYPES. `kebab()` NFKD-decomposes and turns
1037
+ // every combining mark into a hyphen, so distinct katakana marks minted ONE qid and
1038
+ // foldSupplementalEntries, which dedupes on qid, dropped the rest with nothing in refused[]
1039
+ // and nothing on the receipt: marks nobody searched, and nothing saying so.
1040
+ //
1041
+ // The owner side is fixed with it, deliberately. The exemption below withholds the ROMANISATION
1042
+ // from owner rows — a term rule, about what goes out in the query. A qid is an identity and
1043
+ // decides whether a row survives at all, so a colliding owner qid drops a distinct owner into
1044
+ // the substrate findUncrossCheckedDemotions then reads as if it were whole.
1045
+ //
1046
+ // THE NET IS A SECOND DEFECT, not a precaution. termIdentity falls back to the fingerprint only
1047
+ // when the Latin fold is EMPTY, so a Latin term returns its long fold and this site truncates at
1048
+ // 40 — two ordinary corporate names sharing a 40-character prefix collide today. Two classes,
1049
+ // two changes. Latin qids that do not collide are byte-unchanged, so no existing entry moves.
1050
+ const qid = mintSupplementalQid({ prefix: s.owner ? "xcheck-owner" : "xcheck-mark", term, used: mintedQids });
1051
+ // — CARRY THE ROMANISATION THE PLAN ALREADY HOLDS. This lane mints outside
1052
+ // the compiler's push(), so its entries never met romanStamp: a non-Latin term arrived bare and
1053
+ // was refused by the capability gap while the same plan held its romanisation on the entries
1054
+ // that answered it. An owner row is exempt — an owner NAME is not mark text and the executor
1055
+ // drops the carrier on an owner query, exactly as romanStamp itself decides.
1056
+ candidates.push(waitingCrossCheck({ qid, axis: "primary-sweep", predicate: s.owner ? "owner" : "default", term, nice_classes: inScope.map(String), regions: [], ...(s.owner ? {} : (() => { const r = romanizedTermsFromPlan(ctx.registerPlan, term); return r ? { romanizedTerms: r } : {}; })()), expected_kind: "enumerate" }));
1057
+ candDirectives.push({ qid, owner: s.owner ?? null, markText: s.markText ?? null, source: { term: s.term ?? null, platform: s.platform ?? null, url: s.url ?? null } });
1058
+ }
1059
+ // — THIS IS THE LANE THAT KILLED R2b. `findSimilarListingSignals` takes a negative-results
1060
+ // matrix row's first cell VERBATIM (the finding arm strips `[*_\`]`, the matrix arm strips
1061
+ // nothing), so a grouping HEADING in that table became `{predicate:"default", term:"**Core
1062
+ // (BIOVELTRIN, …, etc.)**"}` and folded into a plan the freeze lint had already passed. The
1063
+ // screen is inside foldSupplementalEntries; here the refused rows are moved out of directives[]
1064
+ // and into the receipt's own refused[], where the ask ledger renders them as OPEN asks. Owner
1065
+ // rows are exempt from the term rules, so findUncrossCheckedDemotions keeps its whole substrate.
1066
+ // ── — THE CAP COUNTS QUERIES, NOT CANDIDATES ────────────────────────────
1067
+ //
1068
+ // The cap used to fill from the raw candidate list while the duplicate screen ran AFTER it, so
1069
+ // an entry the fold was going to refuse still consumed a slot, and a genuinely new term behind
1070
+ // it was logged "assess manually" instead of being searched.
1071
+ //
1072
+ // AND THE COLLISION IS THE EXPECTED CASE, not an ordering accident. The terms most likely to be
1073
+ // refused as duplicates are the mark itself and its nearest forms — exactly what the common-law
1074
+ // pass surfaces FIRST, so they arrive at the front of `ranked` and take the earliest slots.
1075
+ // Measured on a live run: cap 10, six directives kept, FOUR slots spent on entries this very
1076
+ // fold then discarded, and six real terms pushed out behind them.
1077
+ //
1078
+ // SCREEN FIRST, THEN COUNT. The fold is pure — it derives its sets from `plan.entries` on each
1079
+ // call and returns a NEW plan rather than mutating one — so probing with the full candidate
1080
+ // list costs nothing, and it is what makes the batch-internal dedup visible before the cap is
1081
+ // spent. The fold's refusal logic is untouched: it is right about every row it refuses, and
1082
+ // only the ORDER of screening and counting moves.
1083
+ const screened = crossChecksForThisPass(ctx.registerPlan, candidates, candDirectives, prior, XCHECK_CAP);
1084
+ const entries = screened.entries;
1085
+ // Overflow now holds GENUINE excess only: a term is over-cap because ten real queries were
1086
+ // minted ahead of it, never because a slot was burned on a row nobody dispatched.
1087
+ for (const e of screened.overflow)
1088
+ overflow.push({ term: e.term, reason: `cap ${XCHECK_CAP} reached — assess manually` });
1089
+ const folded = foldSupplementalEntries(ctx.registerPlan, entries); // PURE — safe above the guard
1090
+ const entryQids = new Set(entries.map((e) => e.qid));
1091
+ const kept = [...screened.carried, ...partitionFoldDirectives(candDirectives.filter((d) => entryQids.has(d.qid)), folded.refused).kept];
1092
+ // The refusals are still RECORDED, across the WHOLE candidate list. They render as asks a reader
1093
+ // adjudicates, and screening further down the list must not quietly drop the disclosure for rows
1094
+ // the cap never reached — a fix that searched more while disclosing less would be a bad trade.
1095
+ const { refused: refusedDirectives } = partitionFoldDirectives(candDirectives, screened.refused);
1096
+ // Computed over the KEPT set, so the resume guard below compares like with like on every attempt.
1097
+ const dirKey = kept.map((d) => d.qid).sort().join(",");
1098
+ const priorKey = Array.isArray(prior?.directives) ? prior.directives.map((d) => d.qid).sort().join(",") : null;
1099
+ if (candidates.length && dirKey !== priorKey) {
1100
+ const { plan, added } = folded;
1101
+ if (added.length) {
1102
+ writeFileSync(`${P.registerPlan}.tmp`, JSON.stringify(plan, null, 2) + "\n");
1103
+ renameSync(`${P.registerPlan}.tmp`, P.registerPlan);
1104
+ ctx.registerPlan = plan; // run-local only — no slug-store write-back (clearances run once; senior lawyer 2026-07-10)
1105
+ runLog(run.runDir, { event: "register-xcheck", minted: added.length, overflow: overflow.length });
1106
+ note(`common-law→register cross-check: ${added.length} register quer${added.length === 1 ? "y" : "ies"} minted (cap ${XCHECK_CAP}${overflow.length ? `, ${overflow.length} over-cap logged` : ""})`);
1107
+ }
1108
+ }
1109
+ if (refusedDirectives.length) {
1110
+ runLog(run.runDir, { event: "register-xcheck-refused", refused: refusedDirectives.length,
1111
+ qids: refusedDirectives.map((d) => d.qid).slice(0, 6) });
1112
+ note(`common-law→register cross-check: ${refusedDirectives.length} signal(s) REFUSED as un-searchable terms — recorded in _driver/register-xcheck.json refused[], never dispatched`);
1113
+ }
1114
+ // THE CROSS-CHECKS WAIT FOR THE READING STEP (cross-check-wait.mjs). Minted after it decided its plan,
1115
+ // they are put to it once more, in its own session. Whatever it leaves undecided — all of them when
1116
+ // that session cannot be asked — runs as code, as before the wait, and the receipt says so.
1117
+ let decided = prior?.decided ?? null;
1118
+ const waiting = undecidedCrossChecks(ctx.registerPlan, { released: releasedFamilyQids(run.runDir), withheld: readWithheldFamilies(run.runDir) });
1119
+ if (waiting.length) {
1120
+ const axis = "primary-sweep";
1121
+ let asked = false;
1122
+ // A follow-up that throws is one that could not be asked: the questions must still run below.
1123
+ if (unitKey[axis]) try {
1124
+ const byQid = new Map(ctx.registerPlan.entries.map((e) => [e.qid, e]));
1125
+ const from = new Map([...(Array.isArray(prior?.directives) ? prior.directives : []), ...kept].map((d) => [d.qid, d.source?.url ?? null]));
1126
+ const followup = repairFollowup("register-unit:xcheck-decide", { axis, registerPlan: P.registerPlan, bandPath: P.registerBand(axis), entries: waiting.map((q) => ({ ...byQid.get(q), from: from.get(q) ?? null })),
1127
+ job: ctx.job, profile: ctx.profile, supplementalLane: !!ctx.registerPlan?.contract?.supplemental_lane });
1128
+ const r = await stage("register-unit", { ...ctx, axis }, { force: true, followup, sessionKey: unitKey[axis], trigger: "xcheck-decide" });
1129
+ asked = r?.ok === true;
1130
+ remergeIfBandsMoved(ctx, "xcheck-decide");
1131
+ } catch (e) { runLog(run.runDir, { event: "register-xcheck-decide-failed", fail: String(e?.message ?? e).slice(0, 160) }); }
1132
+ const released = releasedFamilyQids(run.runDir), withheld = readWithheldFamilies(run.runDir);
1133
+ const ran = undecidedCrossChecks(ctx.registerPlan, { released, withheld });
1134
+ if (ran.length) {
1135
+ const plan = withoutWait(ctx.registerPlan, ran);
1136
+ writeFileSync(`${P.registerPlan}.tmp`, JSON.stringify(plan, null, 2) + "\n");
1137
+ renameSync(`${P.registerPlan}.tmp`, P.registerPlan);
1138
+ ctx.registerPlan = plan;
1139
+ note(`common-law→register cross-check: ${ran.length} quer${ran.length === 1 ? "y" : "ies"} the reading step did not decide`
1140
+ + `${asked ? "" : " (its session could not be asked)"} run as code, as before the wait`);
1141
+ }
1142
+ decided = { asked, released: waiting.filter((q) => released.has(q)), withheld: waiting.filter((q) => withheld[q]), ran_undecided: ran };
1143
+ runLog(run.runDir, { event: "register-xcheck-decided", ...decided });
1144
+ }
1145
+ writeFileSync(`${receiptPath}.tmp`, JSON.stringify({ schema_version: 1, ts: new Date().toISOString(), cap: XCHECK_CAP, directives: kept, overflow, ...(refusedDirectives.length ? { refused: refusedDirectives } : {}), ...(decided ? { decided } : {}) }, null, 2) + "\n");
1146
+ renameSync(`${receiptPath}.tmp`, receiptPath);
1147
+ } catch (e) {
1148
+ note(`common-law→register cross-check skipped (${String(e.message).slice(0, 100)}) — never-kill`);
1149
+ }
1150
+ }
1151
+
1152
+ // WS2 (B3) — the plan⇄band IDENTITY JOIN (plan mode only; legacy runs have no plan and skip).
1153
+ // Every guard-active plan entry must own a band block carrying its qid. A missing qid gets ONE
1154
+ // targeted followup on the owning axis's winning key dictating exactly the unexecuted entries;
1155
+ // whatever is still missing is a StageFailure — a clean can never ship over a slice the PLAN dictated
1156
+ // and nothing ran (the F2/F3 seam). The receipt (_driver/plan-execution.json, incl. the code-derived
1157
+ // coverage skeleton) is what the digest ledger gate and the refutation plan-audit read.
1158
+ if (ctx.registerPlan) {
1159
+ // copper-lattice re-route: fold the propose-tool's per-axis supplemental plans BEFORE the join —
1160
+ // a folded qid with no band block joins MISSING and rides the same dispatch/followup/StageFailure
1161
+ // ladder as a dictated entry (plan_version growth also invalidates a stale clean receipt below).
1162
+ foldSupplementalProposals(ctx);
1163
+ const readBands = () => readRegisterBands(P, axes);
1164
+ const writeExecution = (joinRes) => writePlanExecutionReceipt(ctx, joinRes);
1165
+ // ── Settle the receipt's deferrals HERE, before anything expensive reads them ──────────────────
1166
+ // On the R2 evidence run the receipt recorded three refused slices at 11:47:26 and the envelope
1167
+ // decided about them at 12:31:22 — with placement (626s), a digest attempt GUARANTEED to fail its
1168
+ // coverage_clean_deferred validator (810s), its retry (697s) and the skeptic (335s) in between.
1169
+ // made that decision read the deferral's own reason instead of the clock; this makes it happen
1170
+ // before the work that depends on it. Zero model turns: the only close mechanism here is the code
1171
+ // executor, and nothing in this lane consults a deadline (see envelope-settle.mjs).
1172
+ const settleEnvelopeAtReceipt = async (source) => {
1173
+ const receipt = readPlanExecution(ctx);
1174
+ if (!receipt) return null;
1175
+ // A suspect deferral is nearly always an executor MIS-STAMP (deterministic refusals go to
1176
+ // `deferred`, transients to `missing`, and the fan-in ladder above already closed-or-killed
1177
+ // `missing`). One budgeted attempt each, through the same repair ledger every other lane uses —
1178
+ // so a mis-stamp cannot quietly become permanent, and a real gap costs one executor call.
1179
+ const doc = await settleReceipt({
1180
+ P, plan: ctx.registerPlan, receipt,
1181
+ dispatch: planExec ? async (axis, qids) => {
1182
+ runLog(run.runDir, { event: "plan-qids-deferred-suspect", axis, qids, action: "early-envelope-close" });
1183
+ await dispatchPlanQids(axis, qids, "early-envelope-close", 2);
1184
+ } : null,
1185
+ rejoin: planExec ? async () => {
1186
+ writeExecution(joinPlanToBands(ctx.registerPlan, readBands(), joinOptions(ctx)));
1187
+ deriveNamedBand(ctx); // a close landed band blocks — re-merge so Layer B reads them
1188
+ return readPlanExecution(ctx);
1189
+ } : null,
1190
+ });
1191
+ runLog(run.runDir, { event: "envelope-decision-early", source, deferred: (receipt.deferred ?? []).length,
1192
+ accepted: doc.accepted.length, closed: doc.closed.length, close_failed: doc.close_failed.length });
1193
+ if (doc.accepted.length)
1194
+ note(`register plan: ${doc.accepted.length} deferred slice(s) ACCEPTED as provider capability gaps before placement — `
1195
+ + `they are disclosed, never retried, and no stage will be asked to close them: `
1196
+ + doc.accepted.slice(0, 3).map((a2) => a2.qid).join(", "));
1197
+ return doc;
1198
+ };
1199
+ // Hung on ctx so a downstream guard settles through the SAME lane, executor included. Without this
1200
+ // the guard would still settle (settleReceipt works dispatch-less), but a mis-stamped deferral it
1201
+ // met would be recorded ended without ever being tried.
1202
+ ctx.settleEnvelope = settleEnvelopeAtReceipt;
1203
+ // A CLEAN execution receipt for THIS plan version is durable: judgment-lane band re-emits
1204
+ // (escalation / frame-reopen warm re-runs) happen AFTER the join and may not carry the qid
1205
+ // stamps forward — the receipt, written at the moment of execution, remains the truth of
1206
+ // what Phase A ran. Re-join only when no clean receipt exists for this version (fresh runs)
1207
+ // or the plan grew (extension bumps plan_version → the new entries must execute + re-join).
1208
+ let priorReceipt = null;
1209
+ try { priorReceipt = readJson(P.planExecution); } catch { /* none yet */ }
1210
+ if (priorReceipt && priorReceipt.plan_version === ctx.registerPlan.plan_version
1211
+ && Array.isArray(priorReceipt.missing) && priorReceipt.missing.length === 0) {
1212
+ ctx.planExecution = priorReceipt;
1213
+ runLog(run.runDir, { event: "plan-execution", reused: true, executed: priorReceipt.executed?.length ?? 0 });
1214
+ // The seam a resume sails through. On the evidence run the 15:47:37 resume reused a clean receipt
1215
+ // and then re-decided the envelope from scratch an hour later — because the decision had only ever
1216
+ // been a log line. Settling here is idempotent and makes the decision durable.
1217
+ if (!receiptSettled(P, priorReceipt).settled) await settleEnvelopeAtReceipt("receipt-reuse");
1218
+ } else {
1219
+ // A qid this run has accepted as a capability gap does not ride the ladder again. It leaves `missing`
1220
+ // for `deferred` with the reason it was accepted under, before any dispatch or followup reads the
1221
+ // join, so neither the direct executor nor the plan-join followup re-dictates it.
1222
+ const holdStickyGaps = (j) => {
1223
+ const held = holdStickyGapsIn(j, readStickyGaps(P));
1224
+ if (held !== j) runLog(run.runDir, { event: "plan-qids-sticky-gap", qids: j.missing.filter((q) => !held.missing.includes(q)), action: "held-from-missing" });
1225
+ return held;
1226
+ };
1227
+ let joinRes = holdStickyGaps(joinPlanToBands(ctx.registerPlan, readBands(), joinOptions(ctx)));
1228
+ const missingEntriesByAxis = () => {
1229
+ const byQid = new Map(ctx.registerPlan.entries.map((e) => [e.qid, e]));
1230
+ const m = new Map();
1231
+ for (const qid of joinRes.missing) {
1232
+ const e = byQid.get(qid);
1233
+ if (!m.has(e.axis)) m.set(e.axis, []);
1234
+ m.get(e.axis).push(e);
1235
+ }
1236
+ return m;
1237
+ };
1238
+ // ── repair-first A1 (2026-07-05): code first, agent second, throw with evidence third. The
1239
+ // direct executor dispatch closes missing dictated slices in seconds with no agent turn (the
1240
+ // Open Country class: two 414-killed form slices burned 3 parks + an LLM followup that
1241
+ // re-derived the same failure). The LLM followup below survives as the FALLBACK for providers
1242
+ // without an executePlan adapter, or a dispatch that itself failed at the transport level.
1243
+ if (joinRes.missing.length && planExec) {
1244
+ for (const [a, entries] of missingEntriesByAxis()) {
1245
+ const qids = entries.map((e) => e.qid);
1246
+ runLog(run.runDir, { event: "plan-qids-missing", axis: a, qids, action: "plan-direct-execute" });
1247
+ await dispatchPlanQids(a, qids, "plan-direct-execute", 2);
1248
+ }
1249
+ joinRes = holdStickyGaps(joinPlanToBands(ctx.registerPlan, readBands(), joinOptions(ctx)));
1250
+ if (!joinRes.missing.length) deriveNamedBand(ctx); // dispatch landed blocks — re-merge so Layer B reads them
1251
+ }
1252
+ if (joinRes.missing.length) {
1253
+ for (const [a, entries] of missingEntriesByAxis()) {
1254
+ if (!unitKey[a]) {
1255
+ // T1 (J6): a resumed-past axis has no live session, but register_execute_plan needs
1256
+ // no session context — ONE fresh tool-only call converts the transient into recovery. The
1257
+ // plan-unexecuted StageFailure below still holds the line for a genuine hole.
1258
+ runLog(run.runDir, { event: "plan-qids-missing", axis: a, qids: entries.map((e) => e.qid), action: "fresh-execute-plan" });
1259
+ note(`register-unit ${a}: ${entries.length} dictated plan entr${entries.length === 1 ? "y" : "ies"} unexecuted on a resumed-past axis — one fresh execute_plan-only call`);
1260
+ const freshMsg = repairFollowup("register-unit:plan-join-fresh", { axis: a, registerPlan: P.registerPlan, bandPath: P.registerBand(a), entries });
1261
+ const rf = await stage("register-unit", { ...ctx, axis: a }, { force: true, freshMessage: freshMsg, sessionKey: `clearance-${ctx.run.slug}-${ctx.run.codename}-register-unit-${a}-plan-join-fresh`, trigger: "plan-join-fresh" });
1262
+ if (!rf.ok) note(`register-unit ${a}: fresh execute_plan call failed (${rf.fail}) — the plan-unexecuted StageFailure below holds the line`);
1263
+ continue;
1264
+ }
1265
+ runLog(run.runDir, { event: "plan-qids-missing", axis: a, qids: entries.map((e) => e.qid), action: "warm-followup" });
1266
+ note(`register-unit ${a}: ${entries.length} dictated plan entr${entries.length === 1 ? "y" : "ies"} unexecuted — one followup`);
1267
+ const followup = repairFollowup("register-unit:plan-join", { axis: a, registerPlan: P.registerPlan, bandPath: P.registerBand(a), entries });
1268
+ // Repair-first: the followup's own failure no longer hard-throws here (the old
1269
+ // register-unit:<axis>(plan-join) must()) — the fan-in throw below is the single authority,
1270
+ // carrying the per-slice provider evidence and the honest failClass.
1271
+ const wf = await stage("register-unit", { ...ctx, axis: a }, { force: true, followup, sessionKey: unitKey[a], trigger: "plan-join" });
1272
+ if (!wf.ok) note(`register-unit ${a}: plan-join followup failed (${wf.fail}) — the plan-unexecuted StageFailure below holds the line`);
1273
+ }
1274
+ joinRes = holdStickyGaps(joinPlanToBands(ctx.registerPlan, readBands(), joinOptions(ctx)));
1275
+ deriveNamedBand(ctx); // the followup appended band blocks — re-merge so Layer B reads them
1276
+ }
1277
+ const skeleton = writeExecution(joinRes);
1278
+ // — the RECEIPT is the authority, not the local join. writeExecution may have moved a
1279
+ // ladder-spent, provider-hard-errored qid from `missing` to `deferred`; reading its own write back
1280
+ // is what makes the throw below agree with the file every downstream gate reads. Taking the
1281
+ // conversion at the writer and forgetting it here would throw over a slice the receipt discloses.
1282
+ if (ctx.planExecution) joinRes = { ...joinRes, missing: ctx.planExecution.missing ?? [], deferred: ctx.planExecution.deferred ?? [] };
1283
+ // A DEFERRED slice is a capability gap the active provider cannot close (register-plan.mjs
1284
+ // joinPlanToBands): re-running it would produce the identical refusal, so it is NOT missing and
1285
+ // must not ride the ladder into the StageFailure below. It is also NOT executed — the coverage
1286
+ // skeleton marks the axis `deferred` and findUnexecutedCleanClaims refuses a `confirmed-clean`
1287
+ // claim over it, so the gap is disclosed rather than closed. Loud in the log and the note, never a
1288
+ // silent narrowing.
1289
+ // The rows are excluded here and announced by their own note: they are NOT slices the provider
1290
+ // cannot express — it accepted them and then failed — and one note claiming both would make the
1291
+ // run's own record of WHY a territory went unsearched wrong.
1292
+ // And the slices a check could not prove ran, taken out of the band (searchesOpen above): announced on their own.
1293
+ const takenOut = new Set((Array.isArray(searchesOpen?.slices) ? searchesOpen.slices : []).map((s) => s.qid));
1294
+ const capabilityDeferred = (joinRes.deferred ?? []).filter((d) => !isProviderHardErrorReason(d.reason) && !takenOut.has(d.qid));
1295
+ if (capabilityDeferred.length) {
1296
+ runLog(run.runDir, { event: "plan-qids-deferred", count: capabilityDeferred.length,
1297
+ qids: capabilityDeferred.slice(0, 8).map((d) => d.qid) });
1298
+ note(`register plan: ${capabilityDeferred.length} dictated slice(s) DEFERRED — the active register provider cannot express them, `
1299
+ + `so they were never searched and cannot be read as clean: ${capabilityDeferred.slice(0, 3).map((d) => `${d.qid} ← ${String(d.reason).slice(0, 120)}`).join("; ")}`);
1300
+ }
1301
+ // — THE CENSUS IS RECORDED BEFORE THE THROW, NOT AFTER IT. The `plan-execution` runLog below
1302
+ // carries `unplanned`, and it sat two lines past the throw: on every run that PARKED here — the only
1303
+ // runs anyone diagnoses — the number was computed and discarded. `missing` and `unplanned` together
1304
+ // are the fingerprint that separates this park's two causes (see the evidence block below), so the
1305
+ // one row that could tell them apart was unreachable on exactly the path that needed it. Same class
1306
+ // as /: the data existed, the reporting did not.
1307
+ // ONE read of the bands for the census, the error quotes and the landed counts. Reading them twice
1308
+ // would let the census and the classification disagree about the same files, and the whole point of
1309
+ // both is that they are the record of one moment.
1310
+ const bands = readBands() ?? {};
1311
+ const landedByAxis = new Map();
1312
+ for (const [axis, blocks] of Object.entries(bands))
1313
+ landedByAxis.set(axis, (blocks ?? []).filter((b) => b && typeof b.qid === "string" && b.qid).length);
1314
+ runLog(run.runDir, { event: "plan-execution-census", executed: joinRes.executed.length, missing: joinRes.missing.length,
1315
+ skipped: joinRes.skipped.length, deferred: (joinRes.deferred ?? []).length, unplanned: joinRes.unplanned.length,
1316
+ unplannedQids: joinRes.unplanned.slice(0, 8).map((u) => u.qid),
1317
+ landed: [...landedByAxis].map(([a, n]) => `${a}:${n}`) });
1318
+ if (joinRes.missing.length) {
1319
+ // The old throw was a lie of omission ("own no band block") — the provider's VERBATIM error for
1320
+ // each missing slice sits in the band's error blocks. Quote it, so the terminal diagnosis (and
1321
+ // the recovery classifier) see the actual cause: teal-causeway's three parks never surfaced the
1322
+ // HTTP 414 that was in the band file the whole time.
1323
+ const errByQid = new Map();
1324
+ for (const bandBlocks of Object.values(bands)) for (const b of bandBlocks) if (b && b.qid && b.error && b.reason) errByQid.set(b.qid, String(b.reason));
1325
+ const axisOutcome = new Map(fanInRepairs.map((r) => [r.target, r.outcome]));
1326
+ const byQid = new Map(ctx.registerPlan.entries.map((e) => [e.qid, e]));
1327
+ // — the decision is `fanInMissingEvidence` in repairs.mjs, next to TRANSIENT_RE and
1328
+ // DETERMINISTIC_RE. It reads per-slice evidence and falls back to the axis's repair outcome ONLY
1329
+ // when that axis landed no qid-stamped block at all; see its comment for why the old unconditional
1330
+ // fallback inverted the signal. The detail sentence and the failClass come out of the same pass.
1331
+ const { rows, failClass } = fanInMissingEvidence(joinRes.missing, {
1332
+ ownError: errByQid, axisOutcome, landedByAxis, axisOf: (qid) => byQid.get(qid)?.axis,
1333
+ });
1334
+ const detail = rows.slice(0, 6).map((r) => {
1335
+ // The quote is always shown; what CHANGES is whether it is presented as this slice's cause.
1336
+ // An axis outcome on an axis that landed other blocks is context — a repair was tried and this
1337
+ // is what it hit — and saying so is the difference between informing a reader and misleading
1338
+ // the ladder. The 414 that teal-causeway lost still reaches the terminal either way.
1339
+ if (r.source === "axis-context") return `${r.qid} ← no error of its own; axis "${r.axis}" repair hit: ${r.quote.slice(0, 140)} (axis landed other blocks — context, not this slice's cause)`;
1340
+ if (r.quote) return `${r.qid} ← ${r.quote.slice(0, 160)}`;
1341
+ return `${r.qid} ← no error block and no repair outcome — nothing ran this slice`;
1342
+ });
1343
+ // Once their recovery is spent, these are the searches not completed: each is added to its axis's band as the
1344
+ // executor's deferred block and delivered as an open row, reading that it was planned and never reached the
1345
+ // register (parts-not-completed.mjs).
1346
+ throw Object.assign(new StageFailure("fan-in", `register plan unexecuted after direct dispatch + followup — ${joinRes.missing.length} dictated qid(s) own no band block: ${detail.join("; ")}${joinRes.missing.length > 6 ? " …" : ""} (a clean can never ship over a slice the plan dictated and nothing ran)`, undefined,
1347
+ // `quantity` is the missing count — what CONVERGES across attempts (5 → 3 → 1 is a run closing
1348
+ // on the hole; 5 → 5 → 5 is one that has stopped). repairs.mjs progressQuantity cannot read it
1349
+ // out of this prose: its census table is an allowlist and this template is not in it, so the
1350
+ // ladder has been reading `unknown` here and a converging run looked plateaued.
1351
+ { failClass, repairs: fanInRepairs, quantity: joinRes.missing.length }),
1352
+ { notCompletedPart: "searches", excludedSlices: joinRes.missing.map((qid) => ({ axis: byQid.get(qid)?.axis, qid, reason: plainDeferralReason("slice-not-landed") }))
1353
+ .filter((x) => x.axis) });
1354
+ }
1355
+ runLog(run.runDir, { event: "plan-execution", executed: joinRes.executed.length, skipped: joinRes.skipped.length, unplanned: joinRes.unplanned.length,
1356
+ awaiting: joinRes.awaiting?.length ?? 0, asked: joinRes.asked?.length ?? 0,
1357
+ axes: skeleton.map((s) => `${s.axis}:${s.state}`) });
1358
+ // Decide the deferrals now — before placement-inquiry, which on the evidence run started one second
1359
+ // after this point on inputs the run had just recorded as unfinished.
1360
+ await settleEnvelopeAtReceipt("fan-in");
1361
+ }
1362
+ }
1363
+
1364
+ // Machine-receipts contract gate (post-mortem §1b): a FRESH common-law run under a dictated key list
1365
+ // must save the grid stdout JSON (the validator already exact-joins it when present). A resumed run
1366
+ // that skipped the stage is exempt (archived/pre-machine-receipts artifacts are legacy by design).
1367
+ // One followup on the winning session asks for just the save; still missing ⇒ the run fails —
1368
+ // a new run silently on the legacy prose path would be the inference disease growing back.
1369
+ // A1 split: this lane is single-member only BY CONSTRUCTION — each half validator is ledger-or-fail
1370
+ // (its spec sidecar always dictates the grid), and mergeCommonLawArtifacts just wrote the canonical
1371
+ // ledger in code (a quarantined half's cells are already accounted as gaps), so under the split a
1372
+ // missing canonical ledger cannot reach here.
1373
+ if (!clSplit) {
1374
+ const cl = clMember();
1375
+ if (cl && ctx.gridVariants?.length && !cl.skipped && !existsSync(P.commonLawGrid)) {
1376
+ runLog(run.runDir, { event: "grid-ledger-missing", action: "warm-followup" });
1377
+ note("common-law: grid ledger missing after a fresh run — one warm save-followup");
1378
+ const followup = ctx.gridSpecPath
1379
+ ? repairFollowup("common-law:grid-ledger", { gridLedger: P.commonLawGrid, gridSpecPath: ctx.gridSpecPath })
1380
+ : repairFollowup("common-law:grid-ledger-no-spec", { gridLedger: P.commonLawGrid });
1381
+ must(await stage("common-law", ctx, { force: true, followup, sessionKey: cl.sessionKey, trigger: "grid-ledger" }), "common-law(grid-ledger)");
1382
+ if (!existsSync(P.commonLawGrid)) throw new StageFailure("common-law", "grid ledger never saved (machine-receipts contract)");
1383
+ runLog(run.runDir, { event: "grid-ledger-saved", recovered: true });
1384
+ }
1385
+ }
1386
+
1387
+ // ── V4-4: coverage closure — a gap the machine can close itself never ships as a recommendation ──
1388
+ // At the point the run consumes the common-law findings on its way to synthesis (fresh, resumed, or
1389
+ // skipped — V4-1 semantics: this operates on the FILE, not on session events). Coverage-limited cells
1390
+ // not exempted by a mechanical-error gap/ledger entry get ONE corrective followup on the stage's
1391
+ // winning session, dictating exactly the missing variant×platform cells (batched at the profile-
1392
+ // derived ceiling, the convention). Whatever survives ships as a GENUINE attempted-and-unreachable front-matter
1393
+ // note with a priced offer — never as a "commission a re-run" recommendation (the S&I line-154
1394
+ // failure: the system knew the 91 missing cells, could close them for ~$0.12, and told the lawyer to
1395
+ // commission the work instead). The receipt (_driver/coverage-closure.json) is also the narrative
1396
+ // validator's conditional substrate. Idempotent across resumes: a receipt whose requested set equals
1397
+ // the current closable set means the pass already ran — don't re-spend; keep the note.
1398
+ // Cell source: the machine grid ledger's gaps when present (the substrate — each gap carries
1399
+ // the program's own error string), else the sanctioned prose vocabulary (inherited/legacy artifacts).
1400
+ // Register-only skips the pass entirely: with no grid there are no cells to close, and the fallback
1401
+ // prose path would read a common-law findings file that was never written.
1402
+ if (runCommonLaw) {
1403
+ // P2-A candidate-cardinality CENSUS (review problems 1 + 9) — the ONLY arm: how many hit cells
1404
+ // were received by a zero-candidates "No results" receipt. Advisory by construction, because
1405
+ // `candidates[]` is raw unjudged web-search output and relevance is the model's judgment; the
1406
+ // first cut gated on it and failed the delivered evidence run 221×. Asserted every run (0 is a
1407
+ // real answer, per the house rule) so drift in receipt vocabulary is watchable without a
1408
+ // brittle prose gate deciding deliveries. Matrix COMPLETENESS stays hard-gated in verify.mjs.
1409
+ try {
1410
+ if (existsSync(P.commonLawGrid) && existsSync(P.commonLaw)) {
1411
+ const om = findGridCandidateOmissions(readFileSync(P.commonLawGrid, "utf8"), readFileSync(P.commonLaw, "utf8"));
1412
+ runLog(run.runDir, { event: "common-law-candidates", denied: om.denied.length,
1413
+ sample: om.denied.slice(0, 3).map((v) => `${v.term}×${v.platform}(${v.candidates})`) });
1414
+ if (om.denied.length) note(`common-law candidates: ${om.denied.length} hit cell(s) received by a "No results" row (advisory census — relevance is the model's judgment; the honest form is "No similar listings (N candidates reviewed)")`);
1415
+ }
1416
+ } catch (e) { note(`common-law candidate census skipped (${String(e?.message ?? e).slice(0, 80)}) — never-kill`); }
1417
+ const closureReceiptPath = P.coverageClosure;
1418
+ const cellsOf = () => {
1419
+ const txt = readFileSync(P.commonLaw, "utf8");
1420
+ let cells;
1421
+ try {
1422
+ const ledgerRaw = existsSync(P.commonLawGrid) ? readFileSync(P.commonLawGrid, "utf8") : null;
1423
+ cells = findCoverageLimitedCells(txt, ledgerRaw);
1424
+ } catch { cells = findCoverageLimitedCells(txt); } // unparseable ledger → prose fallback (the stage validator owns that failure)
1425
+ return partitionClosableCells(txt, cells);
1426
+ };
1427
+ let { exempt, closable } = cellsOf();
1428
+ const cellKey = (c) => `${c.variant} × ${c.platform}`;
1429
+ // A CHANNEL THE FRAME-DIFF NAMED IS NOT FOLDED IN HERE. It is disclosed as an open row, never swept (the
1430
+ // frame-reopen above defers it as a channel never swept), so this pass closes grid cells and nothing else.
1431
+ // The signature keeps its second slot, empty, so a receipt written for the same cells still matches.
1432
+ const priorReceipt = existsSync(closureReceiptPath) ? readJson(closureReceiptPath) : null;
1433
+ const closureSig = JSON.stringify([closable.map(cellKey).sort(), []]);
1434
+ const alreadyAttempted = priorReceipt && (priorReceipt.sig === closureSig ||
1435
+ // back-compat: a pre-doc-35 receipt keyed only on the cell set
1436
+ (priorReceipt.sig == null &&
1437
+ JSON.stringify((priorReceipt.requested ?? []).map(cellKey).sort()) === JSON.stringify(closable.map(cellKey).sort())));
1438
+ // SIZED BY THE CELLS A CLOSURE GRID RUNS, as the main grid is (gridBatchFor): its spec carries only the
1439
+ // platforms of the cells it closes.
1440
+ const closureBatch = (cells) => gridBatchFor(ctx.profile, new Set(cells.map((c) => c.platform)).size);
1441
+ if (closable.length && !alreadyAttempted) {
1442
+ const requested = closable;
1443
+ const variants = [...new Set(closable.map((c) => c.variant))];
1444
+ const batchSize = closureBatch(closable);
1445
+ const batches = Math.max(1, Math.ceil(variants.length / batchSize));
1446
+ const gridCalls = batches; // grid call(s) (tokens-only: no $ estimate)
1447
+ note(`coverage closure: ${closable.length} machine-closable cell(s) — one supplementary grid pass (${gridCalls} grid call(s))`);
1448
+ // Fix-1: the driver DICTATES a supplementary grid SPEC for a set of closable cells (a subset of the
1449
+ // canonical grid) and the PLUGIN writes the ledger from the API response — never an agent hand-append
1450
+ // (the grid_ledger_unparseable class). Connotation is OMITTED (caveat 4): meaning was swept in the
1451
+ // main gather and the identity join (findDroppedConnotationQueries) lives at the canonical fan-in,
1452
+ // which ran already — a supp spec must never re-run it. The driver folds the plugin-written ledger in
1453
+ // code below (mergeGrids: union cells, extras.pr_risk survives, gaps recomputed against the full spec).
1454
+ const buildSuppSpec = (cells, half) => {
1455
+ const spec = {
1456
+ terms: [...new Set(cells.map((c) => c.variant))],
1457
+ platforms: [...new Set(cells.map((c) => c.platform))],
1458
+ // A grid the frame decided is blocks, so its gaps are too: re-running them as one product would
1459
+ // ask cells the grid never dictated. One product still reads exactly as before.
1460
+ ...closureBlocksOf(cells),
1461
+ output_path: P.commonLawGridSupp(half, "closure"),
1462
+ batch: batchSize,
1463
+ ledger_required: true,
1464
+ ...(half ? { half } : {}),
1465
+ ...resultsPerCellOf(ctx.searchPolicy),
1466
+ };
1467
+ atomicWrite(P.gridSpecSupp(half, "closure"), JSON.stringify(spec, null, 2) + "\n");
1468
+ return spec;
1469
+ };
1470
+ if (!clSplit) {
1471
+ const suppSpec = closable.length ? buildSuppSpec(closable, null) : null;
1472
+ const followup = repairFollowup("common-law:coverage-closure", { findingsFile: P.commonLaw, suppSpec, suppSpecPath: P.gridSpecSupp(null, "closure"), closable, cellKey });
1473
+ const r = await stage("common-law", ctx, { force: true, followup, sessionKey: clMember()?.sessionKey, trigger: "coverage-closure" });
1474
+ if (!r.ok) note(`coverage closure pass failed mechanically (${r.fail}) — surviving cells ship as the genuine limitation`);
1475
+ // Fold AFTER the stage returns ok (caveat 3): the stage re-validated the UNCHANGED canonical ledger
1476
+ // (the plugin never touched it — it wrote only the supp), so grid_ledger_unparseable is structurally
1477
+ // impossible on this lane. Now union the plugin-written supp into the canonical in code. The full spec
1478
+ // is read from the stable _driver/grid-spec.json (resume-safe — ctx.gridSpecPath may be null on a
1479
+ // resume where the gather-spec block did not re-run). A missing supp/spec/canonical skips the fold:
1480
+ // the closable cells then stay plugin-recorded gaps → closable → ship as an honest limitation (never
1481
+ // silently closed). mergeGrids is union-only, so a re-fold on resume is idempotent.
1482
+ if (r.ok && suppSpec) {
1483
+ const specPath = ctx.gridSpecPath || P.gridSpec; // — the declared path, not a second literal
1484
+ if (existsSync(suppSpec.output_path) && existsSync(P.commonLawGrid) && existsSync(specPath)) {
1485
+ try {
1486
+ const fullSpec = readJson(specPath);
1487
+ const merged = mergeGrids(readJson(P.commonLawGrid), readJson(suppSpec.output_path), { spec: fullSpec });
1488
+ atomicWrite(P.commonLawGrid, JSON.stringify(merged, null, 2) + "\n"); // B5 — the canonical ledger is never seen torn
1489
+ runLog(run.runDir, { event: "common-law-supp-folded", lane: "coverage-closure", cells: merged.cells.length, gaps: merged.gaps.length });
1490
+ } catch (e) { note(`coverage closure: supplementary fold skipped (${String(e.message).slice(0, 80)}) — closable cells stay disclosed gaps`); }
1491
+ }
1492
+ }
1493
+ } else {
1494
+ // A1 SPLIT — followup ROUTING: each closable cell goes to the half-session that OWNS its term
1495
+ // (the deterministic partition, via ctx.clHalfTerms); a cell whose owner half has no usable
1496
+ // session this process (quarantined) re-routes to the OTHER live half — any live common-law
1497
+ // session can run a dictated supplementary cell, and the merge unions by term|platform
1498
+ // regardless of which half's ledger carries it. Every followup targets the HALF artifacts (the
1499
+ // halves stay the source of truth); the code re-merge below refreshes the canonical pair before
1500
+ // cellsOf() re-reads it.
1501
+ const usable = (h) => Boolean(clHalves[h].sessionKey && !clHalves[h].quarantined);
1502
+ // item 25 — the closure set is partitioned EVENLY at dispatch, not routed through halfOfTerm.
1503
+ //
1504
+ // halfOfTerm is right for the FRESH gather: it is a pure function of the term, every followup
1505
+ // finds its work by asking it, and the two halves come out 1.4x apart. It is wrong here. The
1506
+ // reopen re-runs a SUBSET chosen by what failed, and that subset does not respect the term
1507
+ // partition at all — on the evidence run one half drew 857s of closure work and the other 100s,
1508
+ // because the closable cells happened to belong to one side.
1509
+ //
1510
+ // So the reopen partitions what it is actually re-running, deterministically (sorted by cell
1511
+ // key, dealt round-robin), and records the partition. halfOfTerm is untouched and nothing
1512
+ // durable is written: a followup can still find its work because it DICTATES its cells by name.
1513
+ // This is the balance the N-worker queue was proposed for, without spending the pure partition
1514
+ // every followup depends on.
1515
+ const usableHalves = GRID_HALVES.filter(usable);
1516
+ const bal = balanceClosureCells(closable, usableHalves, cellKey);
1517
+ const cellJobs = Object.fromEntries(GRID_HALVES.map((h) => [h, bal.assigned[h] ?? []]));
1518
+ for (const cell of bal.unassigned)
1519
+ note(`coverage closure: no usable common-law half-session for ${cellKey(cell)} — ships as the genuine limitation`);
1520
+ if (closable.length)
1521
+ runLog(run.runDir, { event: "closure-partition", cells: closable.length,
1522
+ per_half: Object.fromEntries(GRID_HALVES.map((h) => [h, cellJobs[h].length])),
1523
+ unassigned: bal.unassigned.length });
1524
+ // CONCURRENCY (2026-07-13): the two half followups run CONCURRENTLY on their OWN half keys,
1525
+ // each a fresh session (the same runBatched fan-out that dispatched the half gather members) — the halves are
1526
+ // independent, so serializing them only doubled the closure wall.
1527
+ await runBatched(GRID_HALVES, config.gatherConcurrency, async (h) => {
1528
+ const cells = cellJobs[h];
1529
+ if (!cells.length) return;
1530
+ const suppSpec = buildSuppSpec(cells, h);
1531
+ const followup = repairFollowup("common-law-half:coverage-closure", { findingsFile: P.commonLawHalf(h), gridSpecPath: P.gridSpecHalf(h), suppSpec, suppSpecPath: P.gridSpecSupp(h, "closure"), cells, cellKey });
1532
+ const r = await stage("common-law-half", { ...ctx, axis: h }, { force: true, followup, sessionKey: clHalves[h].sessionKey, trigger: "coverage-closure" });
1533
+ if (!r.ok) note(`coverage closure pass (half ${h}) failed mechanically (${r.fail}) — surviving cells ship as the genuine limitation`);
1534
+ });
1535
+ // The plugin wrote each half's supplementary ledger; the extended readHalfLedger folds it with the
1536
+ // UNCHANGED main half ledger (both plugin-written) into the canonical pair — fold-after-stage, so the
1537
+ // stage re-validated the untouched main ledger and grid_ledger_unparseable is impossible on this lane.
1538
+ // (Through the connotation-remedy wrapper: a closure re-emit that dropped the disposition rows gets
1539
+ // its one routed repair here too, if the fan-in round did not already spend it.)
1540
+ await mergeWithConnotationRemedy(); // the halves changed — re-derive the canonical pair before re-reading
1541
+ }
1542
+ ({ exempt, closable } = cellsOf());
1543
+ const receipt = { ts: new Date().toISOString(), requested: requested, sig: closureSig,
1544
+ closed: requested.length - closable.length, remaining: closable, exempt, gridCalls };
1545
+ writeFileSync(closureReceiptPath, JSON.stringify(receipt, null, 2) + "\n");
1546
+ runLog(run.runDir, { event: "coverage-closure", requested: requested.length,
1547
+ closed: receipt.closed, remaining: closable.length, exempt: exempt.length, gridCalls });
1548
+ } else if (closable.length || exempt.length) {
1549
+ runLog(run.runDir, { event: "coverage-closure", requested: 0, closed: 0,
1550
+ remaining: closable.length, exempt: exempt.length, gridCalls: 0,
1551
+ reason: alreadyAttempted ? "already attempted this gap set" : "all gaps exempt (mechanical failures)" });
1552
+ }
1553
+ if (closable.length || exempt.length) {
1554
+ // Tokens-only (owner directive 2026-07-11): the offer names the work (grid calls), never a $ figure.
1555
+ const batchesLeft = Math.max(1, Math.ceil([...new Set(closable.map((c) => c.variant))].length / closureBatch(closable)));
1556
+ const offer = ` — closable on instruction (${batchesLeft} supplementary grid call(s))`;
1557
+ ctx.coverageNote = `marketplace cells not executed: ${[...closable, ...exempt].map(cellKey).join("; ")}` +
1558
+ (closable.length ? ` — attempted in-loop and still unreachable${offer}` : "") +
1559
+ (exempt.length ? ` (${exempt.length} cell(s) behind a mechanical platform failure — see the Coverage ledger)` : "");
1560
+ }
1561
+ }
1562
+ return { planExec, unitKey, dispatchPlanQids };
1563
+ }