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
@@ -11,39 +11,29 @@
11
11
  // What this lane deliberately does NOT have, by design:
12
12
  // - no register machinery, no grid, no coverage ledger — the sweep is ONE broad question per mark,
13
13
  // and one narrow one on the name in use in the client's field, as the frame words it;
14
- // - no UNCONDITIONAL auto-recovery ladder. Since this lane has a CLASS-AWARE one:
15
- // a knockout re-run costs ~$2, so a park is bought only where a fresh sample is the plausible
16
- // remedy — TRANSIENT gets the ladder, UNKNOWN exactly one park, DETERMINISTIC and FACTUAL get NONE,
17
- // every designed refusal gets none, and a signature that already parked is terminal at once.
18
- // Everything else goes terminal with the standard failure packet exactly as before (rate-limits
19
- // still postpone via pipeline()'s outer catch — we re-throw StageFailure).
14
+ // - no failure path of its own. A failure takes the clearance's (run-failed.mjs): the same class-aware
15
+ // recovery ladder — TRANSIENT gets the ladder, UNKNOWN exactly one park, DETERMINISTIC and FACTUAL get
16
+ // NONE, every designed refusal gets none, and a signature that already parked is terminal at once —
17
+ // the same park, stop and failure records, and the same notice. Rate limits still postpone via
18
+ // pipeline()'s outer catch.
20
19
  // A THROW SITE THAT KNOWS ITS OWN CLASS MUST STAMP IT (`failClass`, see StageFailure). Unstamped,
21
20
  // the ladder can only guess from the reason text, and the guess for anything the regexes do not
22
21
  // recognise is UNKNOWN — which buys a park. Every throw in this file was written while the lane had
23
- // no ladder and stamping was therefore free to skip; that is no longer true;
24
- //
25
- // A NOTE ON THE ISSUE NUMBER, BECAUSE THE HISTORY AND THE SOURCE DISAGREE AND ONLY ONE CAN BE FIXED.
26
- // The commit that landed this ladder says "". That is the WRONG issue — 1886 is
27
- // about doctrine resolution and has nothing to do with this lane. The work was authorised against the
28
- // plan of record, 1889, which lists it by name. The commit message cannot be edited once pushed and
29
- // history is not rewritten to tidy a citation, so the wrong number stands in the log forever; the
30
- // references in this file are corrected and this comment is the reconciliation. A reader who greps the
31
- // history for 1886 and lands here is in the right place and the number that brought them is not.
32
- import { readFileSync, writeFileSync, existsSync, mkdirSync, appendFileSync, rmSync, renameSync } from "node:fs";
33
- import { join, dirname } from "node:path";
22
+ // no ladder and stamping was therefore free to skip; that is no longer true.
23
+ import { atomicWrite, paths } from "./run-record.mjs";
24
+ import { readFileSync, writeFileSync, existsSync, mkdirSync, appendFileSync, rmSync, renameSync, readdirSync } from "node:fs";
25
+ import { join, dirname, basename } from "node:path";
26
+ import { createHash } from "node:crypto";
27
+ import { diffFingerprint, fingerprint, readStamp, writeFingerprint } from "./stage-freshness.mjs"; // a stage reuses its output only while what it read is unchanged
34
28
  import { driverDir, ensureDriverDir } from "../shared/driver-dir.mjs"; // — one definition of where `_driver/` is
35
29
  import { fileURLToPath } from "node:url";
36
30
 
37
31
  import { runStage } from "./gateway.mjs";
38
- import { config, RESEARCH_PROVIDERS, REGISTER_PROVIDER, activeProvider, missingCredentials } from "./driver.config.mjs";
39
- import { StageFailure, buildFailurePacket, stageWallFields, terminalReasonFields, isDesignedRefusal } from "./pipeline.mjs"; // — the wall fields the spine already carries
40
- import {
41
- REFUSAL_TERMINAL_KIND, // — the terminal kind that is not a failure
42
- // — the clearance lane's recovery DECISION, reused rather than restated. The
43
- // ladder's class-awareness, its repeat-signature backstop and its lane accounting are one
44
- // implementation; a second copy here would be a second thing to keep true.
45
- decideRecovery, failureSignature, classifyFailureReason, countRecoveryLanes, weatherCeilingFor,
46
- } from "./repairs.mjs";
32
+ import { config, RESEARCH_PROVIDERS, REGISTER_PROVIDER, missingCredentials } from "./driver.config.mjs";
33
+ import { registerAdapter as adapterForRegister } from "./engine/run-choices.mjs"; // the run's register adapter, from ctx.register
34
+ import { StageFailure, stageWallFields } from "./run-outcome.mjs"; // — the wall fields the spine already carries
35
+ import { endTheDeliveredRun, runShell } from "./run-shell.mjs"; // — the runner and the delivered ending both products share
36
+ import { logTurnaroundReconciliation } from "./run-quote.mjs";
47
37
  import { RunCancelled, assertNotCancelledBeforePublish, isCancelled, readCancel } from "./cancel.mjs"; // stop-by-user: never the failure lane below
48
38
  import { loadFrameworkManifest, parseFrameworkManifest, frameworkFor, DEFAULT_FRAMEWORK } from "./framework.mjs";
49
39
  import { attachFrameworkMethod, methodPathFor, FROZEN_METHOD_FILE } from "./framework-method.mjs";
@@ -51,40 +41,40 @@ import { KO_STAGES, KO_STEPS, KO_STEP_REGISTER_COUNT, koSteps, koPaths, kebab, k
51
41
  import { kebabCollisions, reportIdentityFor, CAPABILITY_SKIPPED_CAUSE, CAPABILITY_SKIPPED_NOTE } from "./search-policy.mjs";
52
42
  import { countPreflight, countRegisterHits, countedMarks, resolveCountExecutor } from "./register-count.mjs";
53
43
  import { recordsPreflight, listedMarks } from "./register-records.mjs";
54
- import { knockoutQuestionPlan, knockoutBandPath, knockoutBandBlocks, knockoutProposals, knockoutRecordsDoc, knockoutAxis, openingQid, questionPlanPath,
44
+ import { knockoutQuestionPlan, knockoutBandPath, knockoutBandBlocks, knockoutProposals, knockoutRecordsDoc, knockoutAxis, questionPlanPath,
55
45
  readingTableLines, appendQuestionReceipts, resolveQuestionExecutor, writeFixtureMarker, addedClassQuestions, formsOfName, formQid, countRowsOf, foldFormCounts, unfoldFormCounts, withCitedFilings, withHeldGoods } from "./knockout-register-read.mjs";
56
46
  import { capabilitiesFor } from "./register-capabilities.mjs";
57
47
  // — the ONE binding of the office split to this box's env, shared with the plan lane.
58
48
  import { registerUnavailableOffices } from "./register-unreachable.mjs";
59
49
  import { runRecordLogPath } from "../providers/_shared/ledger-path.mjs"; // — this run's record log
60
- import { beginAnswerMemory, endAnswerMemory } from "../providers/_shared/answer-memory.mjs";
61
- import { validators as koValidators, validateMergedFindings, worstBand, registerSurfacedFilings, raterCaveats, SURVIVOR_BOUNDARY_RE, REGISTER_LANE_FILE, PERMITTED_SOURCES } from "./verify-knockout.mjs";
50
+ import { beginAnswerMemory } from "../providers/_shared/answer-memory.mjs";
51
+ import { validateMergedFindings, worstBand, registerSurfacedFilings, raterCaveats, SURVIVOR_BOUNDARY_RE, REGISTER_LANE_FILE, PERMITTED_SOURCES } from "./verify-knockout.mjs";
62
52
  import { KNOCKOUT_CARD_ORDER } from "./findings-model.mjs";
63
53
  import { reviewDispatch, applyKnockoutReview, knockoutReviewFile, rewritesThatSurvive } from "./knockout-review-record.mjs";
64
- import { correctionAnswers, correctionOutcomes, correctionWork, correctionWorkPath, keepChunkBases, knockoutCorrectionFile, movedOutsideScope, readCorrectionWork, restoreChunkBases, rollBackName, sameFinding } from "./knockout-correction-record.mjs";
54
+ import { chunkBasePath, correctionAnswers, correctionOutcomes, correctionWork, correctionWorkPath, keepChunkBases, knockoutCorrectionFile, movedOutsideScope, readCorrectionWork, restoreChunkBases, rollBackName, sameFinding } from "./knockout-correction-record.mjs";
65
55
  import { knockoutAssessSourceDefects } from "./knockout-assess-record.mjs";
66
56
  import { correctionsAppliedTable, unresolvedFlags } from "./corrections-feedforward.mjs";
67
57
  import { settledKnockoutReading } from "./knockout-register-record.mjs";
68
58
  import { stripNextStepSections } from "./knockout-next-step.mjs";
69
- import { publishKnockout, composeKnockoutEmail } from "./publish/knockout.mjs";
70
- import { writeRunStatus, readRunStatus, rollupStatus, atomicWrite, identitySeed } from "./progress.mjs"; // — the identity seed is shared; the stepper is not
59
+ import { publishKnockout, composeKnockoutEmail, knockoutName } from "./publish/knockout.mjs";
60
+ import { writeRunStatus, readRunStatus, rollupStatus, identitySeed, recordTransition, resumeRecord } from "./progress.mjs"; // — the identity seed is shared; the stepper is not
71
61
  import { batchMarkName } from "./mark-name.mjs";
72
62
  import { runLog, note, outputMeta } from "./log.mjs";
73
- import { defaultTerritoryState } from "./effective-scope.mjs"; // the stored-defaults reading — one producer, shared with the clearance lane
63
+ import { defaultTerritoryState } from "./effective-scope.mjs";
64
+ import { keepsInstructedScope } from "./accepted-order.mjs"; // a resume rebuilt from status keeps the scope its order wrote, as a clearance does // the stored-defaults reading — one producer, shared with the clearance lane
74
65
  import { whatsappRouting } from "./stages.mjs";
75
- import { writeOutboxPacket } from "./outbox.mjs";
76
66
  import { rollupTokens, stampTokenRollup } from "./tokens.mjs";
77
67
  import { recordRunConsumption } from "./consumption-ledger.mjs";
78
- import { writeSettleStamp } from "./settle-stamp.mjs"; // — the pool copy's own terminal state
79
- import { stopReason } from "../shared/stop-reason.mjs"; //
80
68
  // The scoped owner lookup a promoted register filing is owed. Bounded, deduplicated
81
69
  // per owner, and structurally unable to withhold a report.
82
- import { ownersOwedACheck, runOwnerChecks } from "./owner-use-check.mjs";
70
+ import { composeOwnerQuery, ownerPayloadFile, ownersOwedACheck, runOwnerChecks } from "./owner-use-check.mjs";
71
+ import { isResearchAnswer } from "./research-answers.mjs";
83
72
 
84
73
  const DRIVER_DIR = dirname(fileURLToPath(import.meta.url));
85
74
  export const TRIAGE_FRAMEWORK = "skills/clearance-search/risk-framework-triage.md";
86
75
 
87
- // sentinel/archive mirror pipeline.mjs's private helpers (cross-referenced there) — byte-faithful.
76
+ // sentinel and archive are this lane's own. The clearance's archive (pipeline.mjs) also settles any pending what-if
77
+ // before it moves the run; this one does not.
88
78
  const sentinel = (runDir, name, obj) => atomicWrite(join(runDir, name), JSON.stringify({ ts: new Date().toISOString(), ...obj }, null, 2) + "\n");
89
79
  function archive(run) {
90
80
  try { mkdirSync(dirname(run.archiveDir), { recursive: true }); renameSync(run.runDir, run.archiveDir); return run.archiveDir; }
@@ -92,17 +82,20 @@ function archive(run) {
92
82
  }
93
83
  // Steps are addressed BY LABEL: Depth 2 inserts a step, so every index after the frame shifts. The
94
84
  // run's own step list is frozen on ctx at dispatch (ctx.koSteps).
85
+ // `currentStep` is the step the run is in now, as a clearance records it; this stepper only moves forward, so it is
86
+ // the step fields in the clearance's shape.
95
87
  const koStep = (ctx, label, extra = {}) => {
96
88
  const steps = ctx.koSteps ?? KO_STEPS;
97
89
  const i = steps.indexOf(label);
98
- writeRunStatus(ctx, { stepIndex: i, stepLabel: label, stepN: i + 1, stepTotal: steps.length, ...extra });
90
+ writeRunStatus(ctx, { stepIndex: i, stepLabel: label, stepN: i + 1, stepTotal: steps.length,
91
+ currentStep: { index: i, label, n: i + 1, total: steps.length }, ...extra });
99
92
  };
100
93
 
101
94
  // ── framework freeze (knockout flavour): the customer's OWN framework when configured, else the house
102
95
  // TRIAGE ladder (NOT the clearance Generic default — a knockout rates at triage grain). Same freeze
103
96
  // doctrine as attachFramework: minted once, read verbatim on resume, corrupt = loud.
104
97
  function attachKnockoutFramework(ctx) {
105
- const sidecarPath = driverDir(ctx.paths.runDir, "framework.json");
98
+ const sidecarPath = paths(ctx.paths.runDir).framework;
106
99
  // ── THE DECK'S PATH, RESOLVED ONCE AND ON BOTH PATHS ────────────────────────
107
100
  //
108
101
  // The assess stage is served the DECK now, not only the manifest — `framework.mjs` states the rule
@@ -123,7 +116,7 @@ function attachKnockoutFramework(ctx) {
123
116
  if (raw != null) {
124
117
  try { ctx.framework = parseFrameworkManifest(raw); }
125
118
  catch (e) { throw new Error(`_driver/framework.json is corrupt (${e.message}) — investigate; the frozen framework is never silently re-derived`); }
126
- readBackLadder(ctx, sidecarPath, { minted: false });
119
+ readBackLadder(sidecarPath);
127
120
  // The method is read back with the manifest it was frozen beside, never loaded fresh on a resume.
128
121
  ctx.frameworkMethod = attachFrameworkMethod({ frozenPath: driverDir(ctx.paths.runDir, FROZEN_METHOD_FILE),
129
122
  resolve: (rel) => config.resolveSkillPath(rel), fwPath, manifest: ctx.framework, minted: false });
@@ -141,7 +134,7 @@ function attachKnockoutFramework(ctx) {
141
134
  atomicWrite(sidecarPath, JSON.stringify(manifest, null, 2) + "\n");
142
135
  runLog(ctx.paths.runDir, { event: "framework", key: manifest.framework_key, custom: fwPath !== TRIAGE_FRAMEWORK, lane: "knockout", bands: manifest.bands.map((b) => b.label).join("/"),
143
136
  method: ctx.frameworkMethod ? methodPathFor(fwPath) : null });
144
- readBackLadder(ctx, sidecarPath, { minted: true });
137
+ readBackLadder(sidecarPath);
145
138
  }
146
139
 
147
140
  // ── — READ THE LADDER BACK THE WAY ITS CONSUMER READS IT, AT THE ONE MOMENT IT IS FREE ─────────
@@ -157,31 +150,16 @@ function attachKnockoutFramework(ctx) {
157
150
  // not travel — check-what-enforces, not what declares. Checking here costs no model call: this runs before
158
151
  // any assess dispatch.
159
152
  //
160
- // TWO DISPOSITIONS, because it is not the same fault in both directions:
161
- // MINTED — the driver wrote the file itself, moments ago, from a manifest it had already parsed. If it
162
- // cannot read its own ladder back, the driver is contradicting itself and nothing downstream is
163
- // trustworthy. Hard fail, before a paid turn.
164
- // PRE-EXISTING (a resume, or an archived run replayed) — those bytes predate this process and may
165
- // predate this shape. its own "not claimed" names exactly this risk: a replay turning red is how
166
- // this fix would go wrong. So it is LOUD and it does not stop the run.
167
- export function readBackLadder(ctx, sidecarPath, { minted }) { // exported for its test: both dispositions are driven directly
153
+ // ONE DISPOSITION. The driver wrote the file from a manifest it had already parsed: on this pass when it froze
154
+ // the framework, or on an earlier pass of the same build when this is a resume, since a run started on another
155
+ // build is not resumed. If it cannot read its own ladder back, the driver is contradicting itself and nothing
156
+ // downstream is trustworthy. Hard fail, before a paid turn.
157
+ export function readBackLadder(sidecarPath) { // exported for its test
168
158
  let bands = null;
169
159
  try { bands = JSON.parse(readFileSync(sidecarPath, "utf8"))?.bands; } catch { /* handled below */ }
170
160
  const ladder = Array.isArray(bands) ? bands.map((b) => String(b?.label ?? "")).filter(Boolean) : [];
171
161
  if (ladder.length) return;
172
- const detail = `${sidecarPath} does not read back as a band ladder, so knockoutAssessChunk's three band checks would pass every rating unchecked`;
173
- if (minted) throw new Error(`knockout_ladder_unreadable: ${detail} — the driver wrote this file itself from a parsed manifest, so this is a driver fault and no seat can fix it`);
174
- // THE RECORDING CANNOT BE WHAT STOPS THE RUN. `runLog` → appendLine() in log.mjs (:11) does an unguarded
175
- // mkdirSync + appendFileSync: on EACCES or a full disk it THROWS. Everywhere else in the driver that is
176
- // the accepted behaviour, but not here — this branch exists precisely to keep a pre-existing run alive,
177
- // and a throw out of it would take down the run it is written to spare, for a reason unrelated to
178
- // frameworks. The note still fires either way: stderr is the one sink that does not touch the disk.
179
- try {
180
- runLog(ctx.paths.runDir, { event: "knockout-ladder-unreadable", path: sidecarPath, lane: "knockout", minted: false });
181
- } catch (e) {
182
- note(`knockout-ladder-unreadable could not be written to run.jsonl (${String(e?.message ?? e).slice(0, 80)}) — the finding below still stands`);
183
- }
184
- note(`_driver/framework.json does not read back as a band ladder — the knockout band checks will not constrain this run's ratings. The file predates this process, so the run continues; investigate before trusting its bands.`);
162
+ throw new Error(`knockout_ladder_unreadable: ${sidecarPath} does not read back as a band ladder, so knockoutAssessChunk's three band checks would pass every rating unchecked — the driver wrote this file itself from a parsed manifest, so this is a driver fault and no seat can fix it`);
185
163
  }
186
164
 
187
165
  // ── koStage: the slim lane's stage runner — skip-if-output-valid (the stageOnce pattern), one
@@ -204,7 +182,15 @@ export function readBackLadder(ctx, sidecarPath, { minted }) { // exported for
204
182
  */
205
183
  async function knockoutReviewingPass({ ctx, run, K, merged, plan, chunks, composeRecord }) {
206
184
  // A ROUND ALREADY BEGUN GOES ON FROM WHERE IT STOOD: a resumed run must not check a half-corrected record as a first look.
207
- const begun = readCorrectionWork(run.runDir);
185
+ // Unless the record it was begun on is gone: a chunk rated again on this pass, or a change in what the first review
186
+ // read, leaves its defects about a rating the run no longer holds. That round is set aside and the record is read afresh.
187
+ let begun = readCorrectionWork(run.runDir);
188
+ const obsolete = begun ? reviewRoundObsolete({ ctx, run, K }) : null;
189
+ if (obsolete) {
190
+ setAsideTheRound(run.runDir, begun, ctx.koRated ?? new Set(), obsolete);
191
+ merged = composeRecord();
192
+ begun = null;
193
+ }
208
194
  if (begun?.stoodDown) return merged;
209
195
  if (begun) return correctAndRecheck({ ctx, run, K, plan, chunks, composeRecord, work: begun, firstReview: readJsonOrNull(knockoutReviewFile(run.runDir)), merged });
210
196
  // A SOURCE THE RATING LOST STAYS OPEN: leaving a reference out does not support the claim it stood behind. It goes to the correction
@@ -214,7 +200,7 @@ async function knockoutReviewingPass({ ctx, run, K, merged, plan, chunks, compos
214
200
  const sourceAnswered = chunks.flatMap((_, c) => knockoutAssessSourceDefects(run.runDir, c)).filter((x) => x.state === "answered");
215
201
  const keepOpen = () => {
216
202
  if (!sourceDefects.length && !sourceAnswered.length) return;
217
- atomicWrite(driverDir(run.runDir, "knockout-corrections.json"), JSON.stringify({ defects: sourceDefects, outcomes: [], recheck: "not-run",
203
+ atomicWrite(paths(run.runDir).knockoutCorrections, JSON.stringify({ defects: sourceDefects, outcomes: [], recheck: "not-run",
218
204
  open: [...sourceDefects.map((x) => ({ kind: x.kind, mark: x.mark, problem: x.problem, state: "not-corrected" })),
219
205
  ...sourceAnswered.map((x) => ({ kind: "source", mark: x.mark, problem: sourceProblem(x), state: "not-rechecked" }))] }, null, 2) + "\n");
220
206
  };
@@ -268,6 +254,43 @@ async function knockoutReviewingPass({ ctx, run, K, merged, plan, chunks, compos
268
254
  return doc;
269
255
  }
270
256
 
257
+ /**
258
+ * Is the review round this run began still about the record it holds? Not when a chunk was rated again on this pass, or
259
+ * when anything the first review read has changed other than the record and its message, which the round's own
260
+ * corrections change. With no record of what the first review read, its freshness is unknown, so the round is not kept.
261
+ * Returns why it is obsolete, or null.
262
+ */
263
+ function reviewRoundObsolete({ ctx, run, K }) {
264
+ if (ctx.koRated?.size) return { why: "a chunk was rated again on this pass", chunks: [...ctx.koRated] };
265
+ const stamp = readStamp(run.runDir, "knockout-review");
266
+ if (!Array.isArray(stamp?.inputs) || !stamp.inputs.length) return { why: "no record of what the first review read" };
267
+ const notTheRoundsOwn = (e) => e.path !== K.findings && e.path !== "value:message";
268
+ const now = koReadsNow(KO_STAGES["knockout-review"], K, "knockout-review", "", ctx);
269
+ const d = diffFingerprint(stamp.inputs.filter(notTheRoundsOwn), now.filter(notTheRoundsOwn));
270
+ return d.stale ? { why: "what the first review read has changed", changed: d.changed } : null;
271
+ }
272
+
273
+ /**
274
+ * Set an obsolete review round aside, kept: each chunk it corrected goes back to its rating, except one rated again on
275
+ * this pass, which keeps its new rating; then the round's work, chunk bases, corrections and reviews move under
276
+ * `_driver/knockout-review-set-aside/`, so the next round keeps its own bases and its reviews run afresh.
277
+ */
278
+ function setAsideTheRound(runDir, work, rated, why) {
279
+ const touched = chunksOf(work);
280
+ restoreChunkBases(runDir, touched.filter((c) => !rated.has(c)));
281
+ const dest = driverDir(runDir, "knockout-review-set-aside", new Date().toISOString().replace(/[:.]/g, "-"));
282
+ mkdirSync(dest, { recursive: true });
283
+ const moved = [];
284
+ for (const f of [correctionWorkPath(runDir), paths(runDir).knockoutCorrections, knockoutReviewFile(runDir, 0), knockoutReviewFile(runDir, 1),
285
+ ...touched.flatMap((c) => [chunkBasePath(runDir, c), knockoutCorrectionFile(runDir, c)])]) {
286
+ if (!existsSync(f)) continue;
287
+ renameSync(f, join(dest, basename(f)));
288
+ moved.push(basename(f));
289
+ }
290
+ runLog(runDir, { event: "knockout-review-round-set-aside", ...why, moved });
291
+ note(`reviewing pass: the round begun on the earlier rating is set aside (${why.why}); the record is read afresh`);
292
+ }
293
+
271
294
  /** What the check compares: the source left out and the claim as it stood, beside the record it reads. */
272
295
  export const sourceAnswerLine = (d) => `- "${d.mark}", finding "${d.name}"${d.removed ? ", since removed" : ""}: it cited "${d.cited}". The claim then: ${JSON.stringify(d.was?.net ?? "")}, on the ground ${JSON.stringify(d.was?.basis ?? "")}.`;
273
296
 
@@ -301,13 +324,13 @@ async function correctAndRecheck({ ctx, run, K, plan, chunks, composeRecord, wor
301
324
  const correctedNames = [...new Set(work.defects.map((x) => x.mark))];
302
325
  const log = (outcome, detail = {}) => runLog(run.runDir, { event: "knockout-review", outcome, material: work.defects.length, marks: correctedNames.length, ...detail });
303
326
  const asOpen = (defects, state, reason = null) => defects.map((x) => ({ kind: x.kind, mark: x.mark, problem: x.problem, state, ...(reason ? { reason } : {}) }));
304
- const keepRecord = (record) => { try { atomicWrite(driverDir(run.runDir, "knockout-corrections.json"), JSON.stringify(record, null, 2) + "\n"); } catch (e) { note(`corrections record not kept (non-fatal): ${String(e?.message ?? e).slice(0, 160)}`); } };
327
+ const keepRecord = (record) => { try { atomicWrite(paths(run.runDir).knockoutCorrections, JSON.stringify(record, null, 2) + "\n"); } catch (e) { note(`corrections record not kept (non-fatal): ${String(e?.message ?? e).slice(0, 160)}`); } };
305
328
  const failed = [];
306
329
  for (const c of touched) {
307
330
  try {
308
331
  await koStage("knockout-correct", ctx, { chunkNo: c, msgCtx: { work, chunkMarks: chunks[c], framework: ctx.framework, frameworkMethod: ctx.frameworkMethod ?? null } });
309
332
  } catch (e) {
310
- if (e instanceof StageFailure && e.resetsAt) throw e;
333
+ if (e instanceof StageFailure && (e.rateLimited || e.resetsAt)) throw e;
311
334
  failed.push({ chunk: c, reason: String(e?.message ?? e).slice(0, 200) });
312
335
  }
313
336
  }
@@ -338,29 +361,38 @@ async function correctAndRecheck({ ctx, run, K, plan, chunks, composeRecord, wor
338
361
  }
339
362
  if (!corrected) return standDown("correction-refused-by-the-merged-gate", { reason: gateCause });
340
363
  }
364
+ // A CHANGE OUTSIDE THE DEFECTS IS RECORDED AND RECHECKED, as a clearance records it (design ruling, 2026-11-10: the
365
+ // Knockout corrects the clearance's way). It no longer stands the correction down: each moved name is kept with its
366
+ // before and after, and the recheck reads it. A comparison that could not be made sends the recheck to the whole batch.
341
367
  const outside = movedOutsideScope(work, corrected);
342
- if (outside.marks.length || outside.blocks.length) return standDown("correction-moved-what-no-defect-named", { outside });
368
+ const movedNames = [...new Set([...outside.marks, ...outside.blocks])];
343
369
 
344
- // THE FIRST PASS'S REWRITES STILL STAND WHERE NO DEFECT REOPENED THE LINE. The second pass reads the record with them on it.
370
+ // THE FIRST PASS'S REWRITES STILL STAND ONLY ON A NAME THE CORRECTION DID NOT CHANGE. A rewrite on a changed name was
371
+ // written against the record as rated, and laid over the change it would put back the words the change replaced. With no
372
+ // comparison, no name is known to be unchanged. The second pass reads the record with the survivors on it, as it ships.
345
373
  let doc = corrected;
346
- const { doc: rewritten, receipt } = applyKnockoutReview(corrected, rewritesThatSurvive(firstReview, correctedNames));
374
+ const survivors = rewritesThatSurvive(firstReview, outside.complete ? [...new Set([...correctedNames, ...movedNames])] : null);
375
+ const rewritesRetired = (firstReview?.rewrites?.length ?? 0) - survivors.rewrites.length;
376
+ const { doc: rewritten, receipt } = applyKnockoutReview(corrected, survivors);
347
377
  if (validateMergedFindings(run.runDir, rewritten, plan).ok) { doc = rewritten; atomicWrite(K.findings, JSON.stringify(doc, null, 2) + "\n"); }
348
378
 
349
379
  const answers = correctionAnswers(run.runDir, touched);
350
380
  const outcomes = correctionOutcomes(work, doc, answers);
351
381
  const unresolved = unresolvedFlags(outcomes).map((r) => r.n);
352
382
  const notAnswered = work.defects.filter((x) => outcomes.find((o) => o.n === x.n)?.outcome === "not-answered");
353
- const held = { defects: work.defects, outcomes, failedChunks: failed, rolledBack, ...(gateCause ? { gateCause } : {}) };
383
+ const held = { defects: work.defects, outcomes, failedChunks: failed, rolledBack, ...(gateCause ? { gateCause } : {}),
384
+ movedOutsideDefects: outside.moved, comparisonComplete: outside.complete, rewritesRetired };
354
385
 
355
386
  const d = reviewDispatch(doc, plan);
356
387
  try {
357
- await koStage("knockout-review", ctx, { chunkNo: 1, msgCtx: { ...d.msgCtx, recheckTable: correctionsAppliedTable(outcomes) } });
388
+ await koStage("knockout-review", ctx, { chunkNo: 1, msgCtx: { ...d.msgCtx, recheckTable: correctionsAppliedTable(outcomes),
389
+ movedNames, comparisonComplete: outside.complete } });
358
390
  } catch (e) {
359
- if (e instanceof StageFailure && e.resetsAt) throw e;
391
+ if (e instanceof StageFailure && (e.rateLimited || e.resetsAt)) throw e;
360
392
  // NOBODY READ THE CORRECTED RECORD, so nothing here can call a defect answered.
361
393
  const reason = String(e?.message ?? e).slice(0, 200);
362
394
  keepRecord({ ...held, recheck: "failed", failure: reason, open: asOpen(work.defects, "not-rechecked", "recheck-failed") });
363
- log("recheck-failed", { applied: receipt.applied, unresolved: unresolved.length, reason });
395
+ log("recheck-failed", { applied: receipt.applied, unresolved: unresolved.length, reason, movedOutsideDefects: movedNames.length, comparisonComplete: outside.complete });
364
396
  return doc;
365
397
  }
366
398
  const second = readJsonOrNull(knockoutReviewFile(run.runDir, 1));
@@ -369,10 +401,120 @@ async function correctAndRecheck({ ctx, run, K, plan, chunks, composeRecord, wor
369
401
  keepRecord({ ...held, recheck: "ran", open });
370
402
  const again = applyKnockoutReview(doc, second ?? {});
371
403
  if (validateMergedFindings(run.runDir, again.doc, plan).ok) { doc = again.doc; atomicWrite(K.findings, JSON.stringify(doc, null, 2) + "\n"); }
372
- log("corrected", { applied: receipt.applied + again.receipt.applied, unresolved: unresolved.length, open: open.length, failedChunks: failed.length, rolledBack: rolledBack.length });
404
+ log("corrected", { applied: receipt.applied + again.receipt.applied, unresolved: unresolved.length, open: open.length, failedChunks: failed.length, rolledBack: rolledBack.length,
405
+ movedOutsideDefects: movedNames.length, comparisonComplete: outside.complete });
373
406
  return doc;
374
407
  }
375
408
 
409
+ // ── WHAT A STAGE READ, AND WHETHER ITS OUTPUT STILL STANDS ON IT ────────────────────────────────────────────────
410
+ //
411
+ // A Knockout stage reuses its output only while what it read is unchanged, through the clearance's own stamps
412
+ // (stage-freshness.mjs). It records what it read as it starts (`koReadsNow`, from `reads` in KO_STAGES), and the record
413
+ // is written once the stage has run, so it says what the output was based on. On a resume a changed input runs the
414
+ // stage again, with a `stage-stale` row naming what changed.
415
+ //
416
+ // AN OUTPUT WITH NO RECORD IS NOT REUSED. Its freshness is unknown. A clearance reads a missing stamp as fresh, for runs
417
+ // that predate its stamps; a Knockout has no such runs to keep, because a run from an earlier build is no longer
418
+ // resumed, so reuse here needs the record. (A record that could not be written costs that stage one more run.)
419
+
420
+ /** The files a folder holds now, as paths, sorted. A folder that cannot be read holds none. */
421
+ function filesIn(dir) {
422
+ try { return readdirSync(dir, { withFileTypes: true }).filter((e) => e.isFile()).map((e) => join(dir, e.name)).sort(); } catch { return []; }
423
+ }
424
+
425
+ // THE REGISTER'S FILES ARE TAKEN AGAIN ON EVERY PASS, and each pass stamps them with when it took them. Measured on two
426
+ // passes over one run with nothing changed, these differ in four places and nowhere else: the counts' and the
427
+ // records' `takenAt`, a reused count's `reused` mark on its name, and each owner check's `ts` and `took_ms`. So these
428
+ // three files are compared on what they say with exactly those four places set aside, through the freshness module's
429
+ // projection, and the whole-file sha is still recorded beside it. Nothing else is set aside, at any depth: a count,
430
+ // a filing, an owner or what an owner check found that changed is still a change.
431
+ const WHEN_IT_WAS_TAKEN = {
432
+ "register-counts.json": ({ takenAt: _takenAt, ...doc }) => ({ ...doc, ...(Array.isArray(doc.marks) ? { marks: doc.marks.map((m) => {
433
+ if (!m || typeof m !== "object" || Array.isArray(m)) return m;
434
+ const { reused: _reused, ...rest } = m;
435
+ return rest;
436
+ }) } : {}) }),
437
+ "register-records.json": ({ takenAt: _takenAt, ...doc }) => doc,
438
+ "owner-checks.json": (doc) => ({ ...doc, ...(Array.isArray(doc.checks) ? { checks: doc.checks.map((c) => {
439
+ if (!c || typeof c !== "object" || Array.isArray(c)) return c;
440
+ const { ts: _ts, took_ms: _tookMs, ...rest } = c;
441
+ return rest;
442
+ }) } : {}) }),
443
+ };
444
+ /** What a retaken register file says, without when it was taken, as a short sha. null for any other file, or one that does not parse. */
445
+ export function whatItSays(_label, absPath) { // @internal
446
+ const without = WHEN_IT_WAS_TAKEN[basename(String(absPath ?? ""))];
447
+ if (!without) return null;
448
+ try {
449
+ const doc = JSON.parse(readFileSync(absPath, "utf8"));
450
+ if (!doc || typeof doc !== "object" || Array.isArray(doc)) return null;
451
+ return createHash("sha256").update(JSON.stringify(without(doc))).digest("hex").slice(0, 12);
452
+ } catch { return null; }
453
+ }
454
+
455
+ /**
456
+ * What stage `def` reads, as a fingerprint taken now: its files, the files its folders hold, its message, and, for a
457
+ * stage that rates, the framework deck the model is sent to. null when it declares none.
458
+ *
459
+ * THE DECK IS THE FILE THE MODEL READS. Its message names the deck by path, and the model reads it from whichever
460
+ * layer is in force: the deployment's private instructions first, then the shipped tree (`config.resolveSkillPath`,
461
+ * the same resolver the framework freeze uses). So the deck is recorded as that file's content, and which file is in
462
+ * force is recorded beside it: an edited private deck, or a private deck added or removed, is a change. The method
463
+ * is frozen with the run (`framework-method.json`) and declared with the frozen rules.
464
+ */
465
+ export function koReadsNow(def, K, label, message, ctx = null) { // @internal
466
+ const r = def?.reads?.(K) ?? null;
467
+ if (!r) return null;
468
+ const dirs = r.dirs ?? [];
469
+ const files = [...(r.files ?? []), ...dirs.flatMap(filesIn)];
470
+ const values = Object.fromEntries(dirs.map((d) => [`files under ${basename(d)}`, filesIn(d).map((p) => basename(p)).join("\n")]));
471
+ if (r.message) values.message = String(message ?? "");
472
+ if (r.deck && ctx?.frameworkPath) {
473
+ const deck = config.resolveSkillPath(ctx.frameworkPath);
474
+ files.push(deck);
475
+ values["deck in force"] = deck;
476
+ }
477
+ return fingerprint(files, { label, values, project: whatItSays });
478
+ }
479
+
480
+ /** Does the output of `label` still stand on what it read? PURE but for one read of its record. */
481
+ export function koStaleness(runDir, label, now) { // @internal
482
+ const stamp = readStamp(runDir, label);
483
+ if (!Array.isArray(stamp?.inputs) || !stamp.inputs.length) return { stale: true, reason: "no record of the inputs it was produced from", changed: [] };
484
+ const d = diffFingerprint(stamp.inputs, now);
485
+ return d.stale ? { stale: true, reason: "an input changed since it ran", changed: d.changed } : { stale: false, changed: [] };
486
+ }
487
+
488
+ /**
489
+ * Which owner checks this run already holds an answer to, and which it must still ask. PURE but for reads of the
490
+ * answers' own files.
491
+ *
492
+ * AN OWNER CHECK IS PAID FOR, AND ITS ANSWER DOES NOT CHANGE WITHIN THE RUN (2026-11-11), as a register answer does
493
+ * not. So a resume asks again only what the run holds no answer to. A held row answers an owed check only when it is
494
+ * the same question: the same name, owner, filings and classes, the same words put to the provider at the same depth,
495
+ * and an answer whose payload is still under research/ beside it. Anything else is unfinished work and is asked: a
496
+ * failed check, a check with no row, a row whose payload is gone, and an owner or filing that changed. A changed
497
+ * owner does not inherit another owner's answer. A held row is returned as it was written, its time and its sources
498
+ * included, so what the rating reads is the evidence the run paid for.
499
+ */
500
+ export function heldOwnerChecks(priorRows, owed, { runDir, preset }) { // @internal
501
+ const sameSet = (a, b) => Array.isArray(a) && Array.isArray(b) && a.length === b.length
502
+ && [...a].map(String).sort().join("\u0000") === [...b].map(String).sort().join("\u0000");
503
+ const rows = Array.isArray(priorRows) ? priorRows : [];
504
+ const held = new Map();
505
+ const ask = [];
506
+ owed.forEach((o, i) => {
507
+ const payloadFile = ownerPayloadFile(o);
508
+ const row = rows.find((r) => r?.ok === true && r.mark === o.mark && r.owner === o.owner
509
+ && sameSet(r.recordIds, o.recordIds) && sameSet(r.classes, o.classes)
510
+ && r.query === composeOwnerQuery(o) && r.preset === preset && r.payloadFile === payloadFile);
511
+ let answer = null;
512
+ try { answer = row ? readFileSync(join(runDir, "research", payloadFile), "utf8") : null; } catch { answer = null; }
513
+ if (row && isResearchAnswer(answer)) held.set(i, row); else ask.push(o);
514
+ });
515
+ return { held, ask };
516
+ }
517
+
376
518
  async function koStage(name, ctx, { chunkNo = null, msgCtx = {} } = {}) {
377
519
  // — the stage's own start, captured before ANY work: before the existsSync, before the validator
378
520
  // read, before the message composition. states why on the spine — capture it after the await and
@@ -384,22 +526,29 @@ async function koStage(name, ctx, { chunkNo = null, msgCtx = {} } = {}) {
384
526
  const out = def.out(K, chunkNo ?? undefined);
385
527
  const label = chunkNo != null ? `${name}#${chunkNo}` : name;
386
528
  const model = process.env.CLEAROTRON_KNOCKOUT_MODEL || def.model;
529
+ const message = def.message({ ...ctx, K, chunkNo, ...msgCtx });
530
+ const readsNow = koReadsNow(def, K, label, message, ctx);
387
531
  if (existsSync(out)) {
388
532
  const v = def.validate(out, readFileSync(out, "utf8"));
389
- if (v.ok) {
533
+ const fresh = v.ok && readsNow ? koStaleness(ctx.paths.runDir, label, readsNow) : { stale: false, changed: [] };
534
+ if (v.ok && !fresh.stale) {
390
535
  // Was `{event:"stage-skip"}`, which nothing read: mcp-server/lib/events.mjs classifies `stage` and
391
536
  // `skip` and dropped this lane on the floor, so a knockout run's stages were invisible in get_run
392
537
  // while the clearance spine's were not. Renamed rather than duplicated — no legacy path, and the
393
538
  // grep that found its only reader found none.
394
539
  runLog(ctx.paths.runDir, { event: "skip", stage: label, lane: "knockout", trigger: "skip", ok: true,
395
540
  model, output: outputMeta(out), ...stageWallFields(tDispatch) });
541
+ recordTransition(ctx, name); // as a clearance's stage records it: the stage the run is at, on a resume too
396
542
  return { ok: true, skipped: true };
397
543
  }
398
- runLog(ctx.paths.runDir, { event: "stage-stale", stage: label, reason: v.reason });
544
+ runLog(ctx.paths.runDir, { event: "stage-stale", stage: label, reason: v.ok ? fresh.reason : v.reason, ...(fresh.changed.length ? { changed: fresh.changed } : {}) });
399
545
  }
546
+ // The run is in this stage from the moment it dispatches, as a clearance's stage records it. The bare name, so a
547
+ // batch's chunks are one stage. No Knockout stage has a step on the clearance's stepper, so this moves no step.
548
+ recordTransition(ctx, name);
400
549
  const r = await runStage(label, {
401
550
  agent: ctx.agent,
402
- message: def.message({ ...ctx, K, chunkNo, ...msgCtx }),
551
+ message,
403
552
  model, thinking: def.thinking,
404
553
  sessionKey: `clearance-${ctx.run.slug}-${ctx.run.codename}-${label}`,
405
554
  timeoutSec: def.timeoutSec, stallSec: def.stallSec,
@@ -418,6 +567,10 @@ async function koStage(name, ctx, { chunkNo = null, msgCtx = {} } = {}) {
418
567
  modelSelector: model, // — what re-spawns the writer, beside what ran
419
568
  output: outputMeta(out), outputWritten: r.wrote ?? null, ...stageWallFields(tDispatch) });
420
569
  if (!r.ok) throw new StageFailure(label, r.fail ?? "failed", r.resetsAt);
570
+ if (readsNow) writeFingerprint(ctx.paths.runDir, label, readsNow);
571
+ // A chunk rated again on this pass makes any review round begun on the old rating obsolete (knockoutReviewingPass).
572
+ if (name === "knockout-assess") (ctx.koRated ??= new Set()).add(chunkNo);
573
+ recordTransition(ctx, name);
421
574
  return r;
422
575
  }
423
576
 
@@ -432,9 +585,10 @@ async function koStage(name, ctx, { chunkNo = null, msgCtx = {} } = {}) {
432
585
  // with the failure on it, and nothing more is fetched: listing each smaller count is no recovery. A rate limit is not
433
586
  // that failure: it parks and resumes as every stage's does, and the resume reuses each answer held.
434
587
  async function readTheRegister({ ctx, job, K, run, agent, markRows, plan, counts, countExec, opts }) {
588
+ const register = ctx.register ?? REGISTER_PROVIDER; // the run's register (ctx.register), the machine's where none is named
435
589
  const names = markRows.map((m) => ({ name: String(m.name), classes: Array.isArray(m.classes) ? m.classes : null }));
436
590
  const exec = resolveQuestionExecutor({
437
- lister: opts?.recordLister ?? null, adapter: activeProvider(),
591
+ lister: opts?.recordLister ?? null, adapter: adapterForRegister(ctx.register),
438
592
  agentId: agent, sessionKey: `clearance-${run.slug}-${run.codename}`, recordLog: runRecordLogPath(run.runDir),
439
593
  // A fixture run never reaches a live register: if the counts ran on fixtures this lane may not either.
440
594
  offline: countExec.source.startsWith("fixtures:"),
@@ -446,16 +600,16 @@ async function readTheRegister({ ctx, job, K, run, agent, markRows, plan, counts
446
600
  : recordsPreflight({ capabilities: ctx.registerCaps, hasAdapter: exec.source !== "none" });
447
601
  if (refusal) {
448
602
  atomicWrite(K.registerRecords, JSON.stringify({
449
- schema: 2, provider: REGISTER_PROVIDER, providerLabel: ctx.registerCaps?.label ?? REGISTER_PROVIDER,
603
+ schema: 2, provider: register, providerLabel: ctx.registerCaps?.label ?? register,
450
604
  takenAt: new Date().toISOString(), unavailable: refusal, marks: [],
451
605
  }, null, 2) + "\n");
452
606
  note(`register filings not listed: ${refusal}`);
453
- runLog(run.runDir, { event: "knockout-register-records-refused", provider: REGISTER_PROVIDER, reason: refusal });
607
+ runLog(run.runDir, { event: "knockout-register-records-refused", provider: register, reason: refusal });
454
608
  return null;
455
609
  }
456
610
  const unreachable = exec.source === "provider" ? (ctx.registerUnreachable ?? []) : [];
457
611
  const scope = { marks: names, classes: job.classes ?? null, jurisdictions: job.jurisdictions ?? null, capabilities: ctx.registerCaps, unreachable };
458
- const build = (reading) => knockoutRecordsDoc({ ...scope, provider: REGISTER_PROVIDER, counts, reading, framedMarks: plan.marks,
612
+ const build = (reading) => knockoutRecordsDoc({ ...scope, provider: register, counts, reading, framedMarks: plan.marks,
459
613
  readBlocks: (name) => knockoutBandBlocks(run.runDir, name), readProposals: (name) => knockoutProposals(run.runDir, name) });
460
614
  try {
461
615
  if (exec.fixtureDir) writeFixtureMarker(run.runDir, exec.fixtureDir);
@@ -463,7 +617,7 @@ async function readTheRegister({ ctx, job, K, run, agent, markRows, plan, counts
463
617
  mkdirSync(join(run.runDir, "register-units"), { recursive: true });
464
618
  } catch (e) {
465
619
  note(`register filings listing failed (non-fatal): ${e.message}`);
466
- runLog(run.runDir, { event: "knockout-register-records-failed", provider: REGISTER_PROVIDER, cause: String(e?.message ?? e).slice(0, 300) });
620
+ runLog(run.runDir, { event: "knockout-register-records-failed", provider: register, cause: String(e?.message ?? e).slice(0, 300) });
467
621
  return null;
468
622
  }
469
623
 
@@ -484,13 +638,13 @@ async function readTheRegister({ ctx, job, K, run, agent, markRows, plan, counts
484
638
  const inScope = [...new Set(names.flatMap((m) => m.classes ?? []).concat(Array.isArray(job.classes) ? job.classes : []))].join(", ") || null;
485
639
  await koStage("knockout-register-read", ctx, { msgCtx: {
486
640
  readingLines: readingTableLines({ marks: names, counts, classes: job.classes ?? null, framedMarks: plan.marks, runDir: run.runDir }),
487
- providerDoc: activeProvider()?.skillDoc ?? null, inScope,
641
+ providerDoc: adapterForRegister(ctx.register)?.skillDoc ?? null, inScope,
488
642
  } });
489
643
  reading = JSON.parse(readFileSync(K.registerReading, "utf8"));
490
644
  runLog(run.runDir, { event: "knockout-register-read", names: reading.marks?.length ?? 0 });
491
645
  }
492
646
  } catch (e) {
493
- if (e instanceof StageFailure && e.resetsAt) throw e;
647
+ if (e instanceof StageFailure && (e.rateLimited || e.resetsAt)) throw e;
494
648
  note(`register reading step did not finish (non-fatal): ${String(e?.message ?? e).slice(0, 200)}`);
495
649
  runLog(run.runDir, { event: "knockout-register-read-failed", cause: String(e?.message ?? e).slice(0, 300) });
496
650
  reading = settledKnockoutReading(run.runDir);
@@ -498,14 +652,14 @@ async function readTheRegister({ ctx, job, K, run, agent, markRows, plan, counts
498
652
  try {
499
653
  const doc = withHeldGoods(build(reading), run.runDir, { runPrefix: `clearance-${run.slug}-${run.codename}` });
500
654
  atomicWrite(K.registerRecords, JSON.stringify(doc, null, 2) + "\n");
501
- appendQuestionReceipts(K.countLedger, doc, { provider: REGISTER_PROVIDER });
502
- runLog(run.runDir, { event: "knockout-register-records", provider: REGISTER_PROVIDER, executor: exec.source,
655
+ appendQuestionReceipts(K.countLedger, doc, { provider: register });
656
+ runLog(run.runDir, { event: "knockout-register-records", provider: register, executor: exec.source,
503
657
  marks: doc.marks.length, listed: listedMarks(doc), records: doc.marks.reduce((n, m) => n + m.records.length, 0),
504
658
  questions: doc.marks.reduce((n, m) => n + m.terms.filter((t) => t.qid?.startsWith("supp:")).length, 0), reading: reading ? "finished" : "not-finished" });
505
659
  return doc;
506
660
  } catch (e) {
507
661
  note(`register filings listing failed (non-fatal): ${e.message}`);
508
- runLog(run.runDir, { event: "knockout-register-records-failed", provider: REGISTER_PROVIDER, cause: String(e?.message ?? e).slice(0, 300) });
662
+ runLog(run.runDir, { event: "knockout-register-records-failed", provider: register, cause: String(e?.message ?? e).slice(0, 300) });
509
663
  return null;
510
664
  }
511
665
  }
@@ -636,940 +790,800 @@ export function removeNextStepSections(runDir, marks) {
636
790
  return out;
637
791
  }
638
792
 
639
- // ── — the knockout lane's recovery park ───────────────────────────────────────
640
- //
641
- // EXPORTED so it can be armed directly. The clearance lane's equivalent is inline in a 6,000-line catch
642
- // and is reachable only by driving a whole pipeline; that is why its class-awareness has no focused arm
643
- // and why this one does.
644
- //
645
- // Returns the runner's park result, or NULL to mean "no park was bought — carry on to the terminal".
646
- // Null is the answer on every path that is not a park, including a failure to read the run's own status:
647
- // a park bought on an unreadable history could re-buy a signature that already parked, which is the one
648
- // thing `decideRecovery`'s backstop exists to stop.
649
- export function knockoutRecoveryPark({ ctx, run, e, reason, failedStage, note = () => {} }) {
650
- if (!run?.runDir) return null;
651
- let snapshot = {};
652
- try { snapshot = JSON.parse(readFileSync(join(run.runDir, "status.json"), "utf8")) ?? {}; } catch { snapshot = {}; }
653
- const priorAttempts = Number(snapshot.recoveryAttempts) || 0;
654
- const history = Array.isArray(snapshot.recoveryHistory) ? snapshot.recoveryHistory : [];
655
- // No early return for recoveryMax === 0: decideRecovery already refuses on its own ceiling
656
- // (laneAttempts < laneCeiling is false at 0), and a guard that cannot fail is a guard that looks
657
- // load-bearing and is not. Proved by planting its removal — nothing red. Letting the decision run
658
- // also means a deployment with the ladder OFF still records "recovery-classified", so the journal
659
- // says the ladder was consulted and declined rather than saying nothing at all.
660
- const recoveryMax = Math.max(0, Number(process.env.CLEAROTRON_RECOVERY_MAX ?? 3));
661
-
662
- const failSig = failureSignature(failedStage, reason,
663
- { codes: e instanceof StageFailure ? e.reasonCodes : undefined });
664
- const failClass = (e instanceof StageFailure && e.failClass) || classifyFailureReason(String(reason));
665
- const laneCounts = countRecoveryLanes(history, { total: priorAttempts });
666
- const weatherCeiling = weatherCeilingFor(recoveryMax);
667
- const decision = decideRecovery({
668
- failClass, sig: failSig.sig, reason: String(reason), history, priorAttempts,
669
- recoveryMax, hasRunDir: true, runCeiling: recoveryMax, weatherCeiling,
670
- weatherAttempts: laneCounts.weather, defectAttempts: laneCounts.defect,
671
- });
672
- try {
673
- runLog(run.runDir, { event: "recovery-classified", lane: "knockout", sig: failSig.sig,
674
- class: failClass, stage: failedStage, recoverable: decision.recoverable,
675
- parkBudget: decision.parkBudget, repeat: decision.repeat, recoveryLane: decision.lane });
676
- } catch { /* observability must never mask the failure being handled */ }
677
- if (!decision.recoverable) return null;
678
-
679
- const RECOVERY_BACKOFF_MIN = [2, 15, 60]; // attempt N resumes after BACKOFF[N-1] minutes (last repeats)
680
- const attempt = priorAttempts + 1;
681
- const backoffMin = RECOVERY_BACKOFF_MIN[Math.min(decision.sigAttempts, RECOVERY_BACKOFF_MIN.length - 1)];
682
- const recoveryResumesAt = new Date(Date.now() + backoffMin * 60000).toISOString();
683
- const lane = decision.lane;
684
- const recoveryLanes = {
685
- weather: { attempts: laneCounts.weather + (lane === "weather" ? 1 : 0), ceiling: weatherCeiling },
686
- defect: { attempts: laneCounts.defect + (lane === "defect" ? 1 : 0), ceiling: recoveryMax },
687
- };
688
- note(`[knockout] RECOVERABLE failure in ${run.codename} at ${failedStage} — parking for AUTO-RECOVERY, `
689
- + `${lane === "weather" ? "upstream weather" : "defect"} attempt ${attempt}/${recoveryMax}, resumes ${recoveryResumesAt}`);
690
- // `.postponed` and NO `.failed`: the marker IS the difference between a parked run and a dead one,
691
- // and writing both would leave a run the runner resumes and a reader reads as failed.
692
- try {
693
- sentinel(run.runDir, ".postponed", { kind: "recovery", lane: "knockout", recoveryResumesAt,
694
- postponedAt: new Date().toISOString(), stage: failedStage });
695
- } catch { /* best-effort — status.json below is the durable record */ }
696
- try {
697
- writeRunStatus(ctx, { state: "recovering", recoveryAttempts: attempt, recoveryMax, failedStage,
698
- ...terminalReasonFields(reason), recoveryResumesAt, resetsAt: null,
699
- recoveryLane: lane, recoveryLanes, lane: "knockout",
700
- recoveryHistory: [...history, { sig: failSig.sig, class: failClass, stage: failedStage,
701
- lane, at: new Date().toISOString(), quantity: decision.progress?.quantity ?? null }] });
702
- } catch { /* best-effort */ }
703
- try { runLog(run.runDir, { event: "recovery-parked", lane: "knockout", attempt, of: recoveryMax,
704
- sig: failSig.sig, recoveryResumesAt, recoveryLane: lane }); } catch { /* best-effort */ }
705
- try { recordRunConsumption(ctx, { phase: "recovery-park", tokens: stampTokenRollup(run.runDir, "recovery-park") }); }
706
- catch { /* best-effort */ }
707
- try { rollupStatus(run.studioRoot); } catch { /* best-effort */ }
708
- // `resetsAt` is the runner's due-clock contract (parkPostponed / postponedDueAt), not a status surface.
709
- return { ok: false, postponed: true, recovery: true, attempt, resetsAt: recoveryResumesAt,
710
- codename: run.codename, runDir: run.runDir, failedStage, lane: "knockout" };
711
- }
793
+ // What the failure path takes from this product. A failure whose error names no stage is named "knockout", the stage the
794
+ // notice then names; a stop names its stage with "(knockout)" after it, as the staff read it in the stop reason.
795
+ export const KNOCKOUT_ENDING = Object.freeze({ unnamedStage: "knockout", stopStage: (stage) => `${stage} (knockout)`, logTag: "knockout" });
712
796
 
713
797
  export async function knockoutInner(ctx, job, opts = {}) {
714
798
  const { run, agent, paths: P } = ctx;
799
+ const register = ctx.register ?? REGISTER_PROVIDER; // the run's register (ctx.register), the machine's where none is named
715
800
  const K = ctx.K = koPaths(run.runDir);
716
801
  const policy = ctx.searchPolicy;
717
802
  const runId = `${run.slug}-${run.date}-${run.codename}`; // same shape as clearance (seedRunStatus) — one format across every consumer
718
- try {
719
- // ── — IDENTITY IS SEEDED BEFORE ANYTHING CAN REFUSE ──────────────────────────────────────────
720
- //
721
- // `ref` is the ONLY field round discovery matches on — e2e-rounds.mjs coerces a run's status `ref`
722
- // to a string and tests the prefix, and nothing else is consulted. (Phrased without the
723
- // "key: <quoted token>" shape on purpose: gitleaks' generic-api-key rule fires on it in prose.) And
724
- // `findRunsByRef`'s own docstring says it keys on status.json rather than meta.json *"so that failed
725
- // runs stay discoverable"* — meta.json is written at publish time, so discovery by it finds every run
726
- // that succeeded and not one that failed. The intent was written down; the guarantee was not
727
- // implemented.
728
- //
729
- // A run that dies before the full seat-flow seed below wrote status.json from the FAILURE writer, with
730
- // no `ref` — so `findRunsByRef` never saw it, `roundSettlement` got `runStates 0` + `markers 0`, and
731
- // the round settled to "unknown" forever. Re-reading it re-stamps unknown. Measured: one round
732
- // permanently unclosable, its run dir on disk the whole time with a complete diagnosis in it, while
733
- // the operator was told the evidence "may have been torn down".
734
- //
735
- // TWO PREFLIGHTS REACHED THE FAILURE WRITER BEFORE THE SEED, not one. The register-count refusal
736
- // below is the one that produced the specimen; a PERPLEXITY_API_KEY refusal above it was the same
737
- // orphan by a different door. Fixing either call site alone would have left the other, which is why
738
- // the identity goes HERE — above every refusal — rather than into a refusal's own writer.
739
- // THE SECOND DOOR IS GONE ( acceptance 6 made it a skip), and that does not make this
740
- // placement redundant: it is what keeps the next refusal added above the seed from re-orphaning its
741
- // run. Moving this stamp down into the surviving refusal's writer would rebuild the bug.
742
- //
743
- // Merged, not replaced: `writeRunStatus` merges, so the full seed further down still writes the step
744
- // flow, the mark names and everything else. This carries the fields that answer "which run and which
745
- // round is this", and nothing that would claim progress it has not made.
746
- //
747
- // `startedAt` now backfills HERE rather than at the failure, which is more honest and is the
748
- // documented first-write-wins behaviour (A3, progress.mjs) rather than a change to it.
749
- writeRunStatus(ctx, {
750
- schema: 1, id: job.id, runId, slug: run.slug, codename: run.codename,
751
- date: run.date, agent, forwarder: job.forwarder, ref: job.ref ?? null,
752
- state: "running", lane: "knockout",
753
- // — and the PROCESS and BUILD identity for the same reason the run
754
- // identity is here: a knockout refused in preflight is exactly the run whose record nobody can
755
- // otherwise attribute, and it is the one most likely to be asked about. Found by the derived
756
- // guard (driver/test/both-lanes-seed-identity.test.mjs), not by the issue, which named only the
757
- // seed further down.
758
- ...identitySeed(),
759
- }, null, { critical: true }); // door B — this write's failure is the one that must not be silent
803
+ // A Knockout's own steps, in order, run by run-shell.mjs. A value one step hands a later one is held here, between
804
+ // them. The last step returns the delivered run; a failure in any step ends through run-failed.mjs.
805
+ let sweep, probeWanted, countExec, markRows, markNames, STEPS, plan, planMarks, registerCounts, degraded, recovered, chunks, composeRecord, merged, overall, published;
806
+ return await runShell({ P, agent, ctx, job, run }, { ending: KNOCKOUT_ENDING, helpers: { sentinel }, steps: [
807
+ { name: "open", run: async () => {
808
+ // ── — IDENTITY IS SEEDED BEFORE ANYTHING CAN REFUSE ──────────────────────────────────────────
809
+ //
810
+ // `ref` is the ONLY field round discovery matches on — e2e-rounds.mjs coerces a run's status `ref`
811
+ // to a string and tests the prefix, and nothing else is consulted. (Phrased without the
812
+ // "key: <quoted token>" shape on purpose: gitleaks' generic-api-key rule fires on it in prose.) And
813
+ // `findRunsByRef`'s own docstring says it keys on status.json rather than meta.json *"so that failed
814
+ // runs stay discoverable"* — meta.json is written at publish time, so discovery by it finds every run
815
+ // that succeeded and not one that failed. The intent was written down; the guarantee was not
816
+ // implemented.
817
+ //
818
+ // A run that dies before the full seat-flow seed below wrote status.json from the FAILURE writer, with
819
+ // no `ref` — so `findRunsByRef` never saw it, `roundSettlement` got `runStates 0` + `markers 0`, and
820
+ // the round settled to "unknown" forever. Re-reading it re-stamps unknown. Measured: one round
821
+ // permanently unclosable, its run dir on disk the whole time with a complete diagnosis in it, while
822
+ // the operator was told the evidence "may have been torn down".
823
+ //
824
+ // TWO PREFLIGHTS REACHED THE FAILURE WRITER BEFORE THE SEED, not one. The register-count refusal
825
+ // below is the one that produced the specimen; a PERPLEXITY_API_KEY refusal above it was the same
826
+ // orphan by a different door. Fixing either call site alone would have left the other, which is why
827
+ // the identity goes HERE — above every refusal — rather than into a refusal's own writer.
828
+ // THE SECOND DOOR IS GONE ( acceptance 6 made it a skip), and that does not make this
829
+ // placement redundant: it is what keeps the next refusal added above the seed from re-orphaning its
830
+ // run. Moving this stamp down into the surviving refusal's writer would rebuild the bug.
831
+ //
832
+ // Merged, not replaced: `writeRunStatus` merges, so the full seed further down still writes the step
833
+ // flow, the mark names and everything else. This carries the fields that answer "which run and which
834
+ // round is this", and nothing that would claim progress it has not made.
835
+ //
836
+ // `startedAt` now backfills HERE rather than at the failure, which is more honest and is the
837
+ // documented first-write-wins behaviour (A3, progress.mjs) rather than a change to it.
838
+ //
839
+ // WHICH PASS THIS IS, here and only here, as a clearance's seed records it (resumeRecord): a fresh run
840
+ // is attempt 1, and a resume records its clock and counts itself. Here because a pass refused in
841
+ // preflight is still a pass; only here because a second seed reading the count back would count twice.
842
+ writeRunStatus(ctx, {
843
+ schema: 1, id: job.id, runId, slug: run.slug, codename: run.codename,
844
+ date: run.date, agent, forwarder: job.forwarder, ref: job.ref ?? null,
845
+ state: "running", lane: "knockout",
846
+ ...resumeRecord(run.runDir, ctx.stateReset),
847
+ // — and the PROCESS and BUILD identity for the same reason the run
848
+ // identity is here: a knockout refused in preflight is exactly the run whose record nobody can
849
+ // otherwise attribute, and it is the one most likely to be asked about. Found by the derived
850
+ // guard (driver/test/both-lanes-seed-identity.test.mjs), not by the issue, which named only the
851
+ // seed further down.
852
+ ...identitySeed(),
853
+ }, null, { critical: true }); // door B — this write's failure is the one that must not be silent
760
854
 
761
- mkdirSync(K.researchDir, { recursive: true });
762
- attachKnockoutFramework(ctx);
855
+ mkdirSync(K.researchDir, { recursive: true });
856
+ attachKnockoutFramework(ctx);
763
857
 
764
- // Lane preflight (the doc-27 discipline, knockout flavour). This USED TO REFUSE the whole screen
765
- // when the live sweep had no credential. It no longer does ( acceptance 6): the resolver
766
- // returns a SKIP instead, the sweep is never attempted, and the screen delivers its register half
767
- // with the missing half disclosed. The reason the refusal existed is preserved, not discarded —
768
- // "the cred-guard degrades every mark per-call and the batch dies all-failed only AFTER the paid
769
- // frame turn" is exactly what a skip prevents, and prevents earlier than a throw did.
770
- // (pipelineInner's register preflight is skipped for this lane — knockout has no register machinery.)
771
- const sweep = resolveSweepExecutor(opts);
858
+ // Lane preflight (the doc-27 discipline, knockout flavour). This USED TO REFUSE the whole screen
859
+ // when the live sweep had no credential. It no longer does ( acceptance 6): the resolver
860
+ // returns a SKIP instead, the sweep is never attempted, and the screen delivers its register half
861
+ // with the missing half disclosed. The reason the refusal existed is preserved, not discarded —
862
+ // "the cred-guard degrades every mark per-call and the batch dies all-failed only AFTER the paid
863
+ // frame turn" is exactly what a skip prevents, and prevents earlier than a throw did.
864
+ // (pipelineInner's register preflight is skipped for this lane — knockout has no register machinery.)
865
+ sweep = resolveSweepExecutor(opts);
772
866
 
773
- // Depth 2 preflight — the SAME discipline, for the register count. Both refusals it can return
774
- // are structural (a provider that cannot count; a territory scope it cannot express), so they are
775
- // settled here, once, before the paid frame turn — never twenty identical per-mark failures and a
776
- // published report with an empty column where the product should have been.
777
- const probeWanted = Boolean(policy.components?.registerProbe);
778
- // THE RECORD THAT THIS RUN HAS NO REGISTER COMPONENT, so a later step reads a skip from what ran, and never from a missing file.
779
- if (!probeWanted) atomicWrite(driverDir(run.runDir, REGISTER_LANE_FILE), JSON.stringify({ skipped: true }) + "\n");
780
- let countExec = { count: null, source: "none" };
781
- if (probeWanted) {
782
- // — NO REGISTER SET IS A REFUSAL TOO, stamped like the count refusal below. `activeProvider()`
783
- // throws a plain Error when CLEAROTRON_DATABASE is unset; unstamped, the ladder guessed "unknown"
784
- // from its prose and parked the run to retry a setting no wait can supply, with the reason only
785
- // in status.json. The remedy is the deployment, so it ends here, refused, before any spend.
786
- let registerAdapter;
787
- try { registerAdapter = activeProvider(); }
788
- catch (e) {
789
- throw new StageFailure("knockout-register-count", e.message, null, { refusal: true, failClass: "deterministic" });
790
- }
791
- const caps = capabilitiesFor(REGISTER_PROVIDER);
792
- countExec = resolveCountExecutor({
793
- counter: opts?.countExecutor ?? null, adapter: registerAdapter,
794
- agentId: agent, sessionKey: `clearance-${run.slug}-${run.codename}`,
795
- recordLog: runRecordLogPath(run.runDir),
796
- // FROM THE JOB, not the environment. Whether this run calls a real register
797
- // is a fact about the run, so it arrives with the run and lands on its record.
798
- fixtureDir: job?.registerFixtures?.counts ?? null,
799
- });
800
- // EVERY required variable. `Boolean(process.env[credEnv])` here was a half-check: it
801
- // reported "credential present" for a euipo instance holding the id and no secret, and would
802
- // have done the same for a free-tier instance holding one member of two. fixed the
803
- // same bug in preflightCredentials and left this site; one predicate now serves both.
804
- //
805
- // Computed ONCE and passed BOTH ways: the boolean decides, the names go into the sentence.
806
- // Recomputing inside the refusal string would be a second read of the environment between the
807
- // decision and the message, which is how a refusal comes to name a variable that is set.
808
- const missing = countExec.source === "provider" ? missingCredentials(registerAdapter) : [];
809
- // — the offices this box cannot reach, COMPUTED ONCE for both Depth 2 lanes and for the
810
- // refusal below, for the same reason `missing` is computed once above: a second read of the
811
- // environment between the decision and the message is how a refusal comes to name a variable
812
- // that is set, and here it would also let the count lane and the record lane narrow to different
813
- // scopes on the same run.
814
- //
815
- // ONLY when the counter is the real provider. On fixtures or an injected counter the offices this
816
- // deployment can reach are not what the lane is talking to, and splitting on them would defer a
817
- // register the fixture holds — a $0 lane reporting a gap it does not have (the shape a
818
- // sibling defect had, and the reason `missing` carries the same guard).
819
- const unreachable = countExec.source === "provider" ? registerUnavailableOffices(caps) : [];
820
- ctx.registerUnreachable = unreachable;
821
- const refusal = countPreflight({
822
- capabilities: caps, jurisdictions: job.jurisdictions ?? null,
823
- hasAdapter: countExec.source !== "none",
824
- credentialPresent: missing.length === 0,
825
- missing, unreachable,
826
- });
827
- // — A REFUSAL, STAMPED AS ONE. Every arm countPreflight can return is the product declining
828
- // an ORDER against THIS DEPLOYMENT before a single token is bought: a provider that cannot count,
829
- // a credential this box does not hold, a territory the provider does not cover, a register it
830
- // covers and this install cannot reach. None of them is the engine breaking, and no retry moves
831
- // any of them — the remedy is always the order or the deployment. Recorded unstamped, correct
832
- // product behaviour landed in the failure channel and the failure counts stopped meaning anything.
833
- //
834
- // `failClass: "deterministic"` says the same thing to the OTHER reader: repairs.mjs's ladder. It
835
- // was stamped when this lane had no ladder for it to reach — "so the fact travels with the throw
836
- // rather than being re-guessed from prose by whichever catch the throw ends up in." That catch is
837
- // now this lane's own, the stamp is LIVE, and it is what buys this refusal
838
- // zero parks without the ladder having to read a word of the prose.
839
- if (refusal) throw new StageFailure("knockout-register-count", refusal, null,
840
- { refusal: true, failClass: "deterministic" });
841
- ctx.registerCaps = caps;
842
- if (unreachable.length)
843
- note(`register offices unreachable on this deployment: ${unreachable.map((u) => `${u.office} (${u.memberId}: ${u.missing.join(" + ")} unset)`).join(", ")} — the lane counts and lists the rest and discloses these on every mark`);
844
- }
867
+ // Depth 2 preflight — the SAME discipline, for the register count. Both refusals it can return
868
+ // are structural (a provider that cannot count; a territory scope it cannot express), so they are
869
+ // settled here, once, before the paid frame turn — never twenty identical per-mark failures and a
870
+ // published report with an empty column where the product should have been.
871
+ probeWanted = Boolean(policy.components?.registerProbe);
872
+ // THE RECORD THAT THIS RUN HAS NO REGISTER COMPONENT, so a later step reads a skip from what ran, and never from a missing file.
873
+ if (!probeWanted) atomicWrite(driverDir(run.runDir, REGISTER_LANE_FILE), JSON.stringify({ skipped: true }) + "\n");
874
+ countExec = { count: null, source: "none" };
875
+ if (probeWanted) {
876
+ // — NO REGISTER SET IS A REFUSAL TOO, stamped like the count refusal below. `activeProvider()`
877
+ // throws a plain Error when CLEAROTRON_DATABASE is unset; unstamped, the ladder guessed "unknown"
878
+ // from its prose and parked the run to retry a setting no wait can supply, with the reason only
879
+ // in status.json. The remedy is the deployment, so it ends here, refused, before any spend.
880
+ let registerAdapter;
881
+ try { registerAdapter = adapterForRegister(ctx.register); }
882
+ catch (e) {
883
+ throw new StageFailure("knockout-register-count", e.message, null, { refusal: true, failClass: "deterministic" });
884
+ }
885
+ const caps = capabilitiesFor(register);
886
+ countExec = resolveCountExecutor({
887
+ counter: opts?.countExecutor ?? null, adapter: registerAdapter,
888
+ agentId: agent, sessionKey: `clearance-${run.slug}-${run.codename}`,
889
+ recordLog: runRecordLogPath(run.runDir),
890
+ // FROM THE JOB, not the environment. Whether this run calls a real register
891
+ // is a fact about the run, so it arrives with the run and lands on its record.
892
+ fixtureDir: job?.registerFixtures?.counts ?? null,
893
+ });
894
+ // EVERY required variable. `Boolean(process.env[credEnv])` here was a half-check: it
895
+ // reported "credential present" for a euipo instance holding the id and no secret, and would
896
+ // have done the same for a free-tier instance holding one member of two. fixed the
897
+ // same bug in preflightCredentials and left this site; one predicate now serves both.
898
+ //
899
+ // Computed ONCE and passed BOTH ways: the boolean decides, the names go into the sentence.
900
+ // Recomputing inside the refusal string would be a second read of the environment between the
901
+ // decision and the message, which is how a refusal comes to name a variable that is set.
902
+ const missing = countExec.source === "provider" ? missingCredentials(registerAdapter) : [];
903
+ // — the offices this box cannot reach, COMPUTED ONCE for both Depth 2 lanes and for the
904
+ // refusal below, for the same reason `missing` is computed once above: a second read of the
905
+ // environment between the decision and the message is how a refusal comes to name a variable
906
+ // that is set, and here it would also let the count lane and the record lane narrow to different
907
+ // scopes on the same run.
908
+ //
909
+ // ONLY when the counter is the real provider. On fixtures or an injected counter the offices this
910
+ // deployment can reach are not what the lane is talking to, and splitting on them would defer a
911
+ // register the fixture holds — a $0 lane reporting a gap it does not have (the shape a
912
+ // sibling defect had, and the reason `missing` carries the same guard).
913
+ const unreachable = countExec.source === "provider" ? registerUnavailableOffices(caps) : [];
914
+ ctx.registerUnreachable = unreachable;
915
+ const refusal = countPreflight({
916
+ capabilities: caps, jurisdictions: job.jurisdictions ?? null,
917
+ hasAdapter: countExec.source !== "none",
918
+ credentialPresent: missing.length === 0,
919
+ missing, unreachable,
920
+ });
921
+ // — A REFUSAL, STAMPED AS ONE. Every arm countPreflight can return is the product declining
922
+ // an ORDER against THIS DEPLOYMENT before a single token is bought: a provider that cannot count,
923
+ // a credential this box does not hold, a territory the provider does not cover, a register it
924
+ // covers and this install cannot reach. None of them is the engine breaking, and no retry moves
925
+ // any of them — the remedy is always the order or the deployment. Recorded unstamped, correct
926
+ // product behaviour landed in the failure channel and the failure counts stopped meaning anything.
927
+ //
928
+ // `failClass: "deterministic"` says the same thing to the OTHER reader: repairs.mjs's ladder. It
929
+ // was stamped when this lane had no ladder for it to reach — "so the fact travels with the throw
930
+ // rather than being re-guessed from prose by whichever catch the throw ends up in." That catch is
931
+ // now this lane's own, the stamp is LIVE, and it is what buys this refusal
932
+ // zero parks without the ladder having to read a word of the prose.
933
+ if (refusal) throw new StageFailure("knockout-register-count", refusal, null,
934
+ { refusal: true, failClass: "deterministic" });
935
+ ctx.registerCaps = caps;
936
+ if (unreachable.length)
937
+ note(`register offices unreachable on this deployment: ${unreachable.map((u) => `${u.office} (${u.memberId}: ${u.missing.join(" + ")} unset)`).join(", ")} — the lane counts and lists the rest and discloses these on every mark`);
938
+ }
845
939
 
846
- // intake artifacts + the code-authoritative instructed scope (mirrors pipelineInner's blocks —
847
- // dispatch happens before them, so this lane writes its own; the frame validator reads THIS file).
848
- try {
849
- if (job.rawRequest) writeFileSync(P.inboundRequest, String(job.rawRequest));
850
- if (job.brief) writeFileSync(P.confirmationBrief, String(job.brief));
851
- } catch (e) { note(`intake artifact write failed (non-fatal): ${e.message}`); }
852
- const markRows = Array.isArray(job.marks)
853
- ? job.marks.map((m) => (typeof m === "string" ? { name: m } : m)).filter((m) => m?.name)
854
- : [job.markName ?? job.name].filter(Boolean).map((name) => ({ name }));
855
- const markNames = markRows.map((m) => String(m.name));
856
- // research artifacts key on kebab(name) — a collision would silently share one payload between two
857
- // marks (validateJob clarifies this at intake; this guard covers direct dispatch).
858
- const koll = kebabCollisions(markNames);
859
- // `failClass: "factual"` — stamped because gave this lane a ladder that would
860
- // otherwise GUESS. The reason text matches neither classifier regex, so the guess is UNKNOWN, and
861
- // UNKNOWN buys one park: a ~$2 re-run of a job whose two mark names collide exactly as they did
862
- // before, ending in the identical throw two minutes later. FACTUAL rather than DETERMINISTIC on the
863
- // doctrine repairs.mjs states — deterministic means the repairs already ran and retry is futile;
864
- // factual means no retry can answer it because the answer is a person's. This throw's own remedy
865
- // sentence says which one it is: reword or drop one and re-enqueue. Both classes buy zero parks, so
866
- // the choice changes no behaviour — it changes the terminal kind the operator reads.
867
- if (koll.length)
868
- throw new StageFailure("knockout-scope", `marks ${koll.map(([a, b]) => `"${a}"/"${b}"`).join(", ")} collide to the same research key — reword or drop one and re-enqueue`, null,
869
- { failClass: "factual" });
870
- try {
871
- writeFileSync(K.instructedScope, JSON.stringify({
872
- marks: markNames, classes: job.classes ?? null, jurisdictions: job.jurisdictions ?? null,
873
- goods: job.goods ?? null, customer: job.customer ?? null,
874
- // per-mark detail (classes/ref from the request, e.g. the cockpit's "NAME [9, 42]" rows) — the
875
- // frame reads THIS file, so without it those classes silently vanished (review 2026-07-17)
876
- marksDetailed: markRows.map((m) => ({ name: String(m.name), ...(Array.isArray(m.classes) && m.classes.length ? { classes: m.classes } : {}), ...(m.ref ? { ref: m.ref } : {}) })),
877
- }, null, 2) + "\n");
878
- } catch (e) { note(`instructed-scope write failed (non-fatal): ${e.message}`); }
879
- // The stored defaults the engine cannot search — the clearance lane's record, on this lane too. A
880
- // knockout reads the same account profile and dropped the same entries in the same silence.
881
- try {
882
- const dts = defaultTerritoryState(ctx.profile);
883
- // two records of one fact, so each has its own try: a fault in one must not take the other
884
- try { if (dts.unrecognized.length) runLog(run.runDir, { event: "default-territory-unrecognized", count: dts.unrecognized.length, entries: dts.unrecognized, lane: "knockout" }); } catch (e) { note(`default-territory-unrecognized log failed (non-fatal): ${e.message}`); }
885
- writeFileSync(K.defaultTerritories, JSON.stringify({
886
- profileKey: ctx.profile?.profileKey ?? null,
887
- searchable: dts.kept,
888
- unrecognized: dts.unrecognized,
889
- }, null, 2) + "\n");
890
- } catch (e) { note(`default-territories write failed (non-fatal): ${e.message}`); }
940
+ // intake artifacts + the code-authoritative instructed scope (mirrors pipelineInner's blocks —
941
+ // dispatch happens before them, so this lane writes its own; the frame validator reads THIS file).
942
+ try {
943
+ if (job.rawRequest) writeFileSync(P.inboundRequest, String(job.rawRequest));
944
+ if (job.brief) writeFileSync(P.confirmationBrief, String(job.brief));
945
+ } catch (e) { note(`intake artifact write failed (non-fatal): ${e.message}`); }
946
+ // A RESUME REBUILT FROM STATUS KEEPS THE SCOPE ITS ORDER WROTE, as a clearance does (keepsInstructedScope). The
947
+ // rebuilt job knows the names and not each name's own classes or reference; the scope on disk does, and the
948
+ // count and the register reading ask with each name's own classes. So the names come from that scope.
949
+ let keptScope = null;
950
+ if (keepsInstructedScope({ jobRebuiltFromStatus: opts.jobRebuiltFromStatus === true, scopeOnDisk: existsSync(K.instructedScope) })) {
951
+ try { keptScope = JSON.parse(readFileSync(K.instructedScope, "utf8")); } catch { keptScope = null; }
952
+ if (!Array.isArray(keptScope?.marksDetailed) || !keptScope.marksDetailed.some((m) => m?.name)) keptScope = null;
953
+ }
954
+ markRows = keptScope
955
+ ? keptScope.marksDetailed.filter((m) => m?.name)
956
+ : Array.isArray(job.marks)
957
+ ? job.marks.map((m) => (typeof m === "string" ? { name: m } : m)).filter((m) => m?.name)
958
+ : [job.markName ?? job.name].filter(Boolean).map((name) => ({ name }));
959
+ markNames = markRows.map((m) => String(m.name));
960
+ // research artifacts key on kebab(name) — a collision would silently share one payload between two
961
+ // marks (validateJob clarifies this at intake; this guard covers direct dispatch).
962
+ const koll = kebabCollisions(markNames);
963
+ // `failClass: "factual"` — stamped because gave this lane a ladder that would
964
+ // otherwise GUESS. The reason text matches neither classifier regex, so the guess is UNKNOWN, and
965
+ // UNKNOWN buys one park: a ~$2 re-run of a job whose two mark names collide exactly as they did
966
+ // before, ending in the identical throw two minutes later. FACTUAL rather than DETERMINISTIC on the
967
+ // doctrine repairs.mjs states — deterministic means the repairs already ran and retry is futile;
968
+ // factual means no retry can answer it because the answer is a person's. This throw's own remedy
969
+ // sentence says which one it is: reword or drop one and re-enqueue. Both classes buy zero parks, so
970
+ // the choice changes no behaviour — it changes the terminal kind the operator reads.
971
+ if (koll.length)
972
+ throw new StageFailure("knockout-scope", `marks ${koll.map(([a, b]) => `"${a}"/"${b}"`).join(", ")} collide to the same research key — reword or drop one and re-enqueue`, null,
973
+ { failClass: "factual" });
974
+ if (keptScope) note(`instructed scope kept as the order wrote it: this resume's job was rebuilt from status`);
975
+ else try {
976
+ writeFileSync(K.instructedScope, JSON.stringify({
977
+ marks: markNames, classes: job.classes ?? null, jurisdictions: job.jurisdictions ?? null,
978
+ goods: job.goods ?? null, customer: job.customer ?? null,
979
+ // per-mark detail (classes/ref from the request, e.g. the cockpit's "NAME [9, 42]" rows) — the
980
+ // frame reads THIS file, so without it those classes silently vanished (review 2026-07-17)
981
+ marksDetailed: markRows.map((m) => ({ name: String(m.name), ...(Array.isArray(m.classes) && m.classes.length ? { classes: m.classes } : {}), ...(m.ref ? { ref: m.ref } : {}) })),
982
+ }, null, 2) + "\n");
983
+ } catch (e) { note(`instructed-scope write failed (non-fatal): ${e.message}`); }
984
+ // The stored defaults the engine cannot search — the clearance lane's record, on this lane too. A
985
+ // knockout reads the same account profile and dropped the same entries in the same silence.
986
+ try {
987
+ const dts = defaultTerritoryState(ctx.profile);
988
+ // two records of one fact, so each has its own try: a fault in one must not take the other
989
+ try { if (dts.unrecognized.length) runLog(run.runDir, { event: "default-territory-unrecognized", count: dts.unrecognized.length, entries: dts.unrecognized, lane: "knockout" }); } catch (e) { note(`default-territory-unrecognized log failed (non-fatal): ${e.message}`); }
990
+ writeFileSync(K.defaultTerritories, JSON.stringify({
991
+ profileKey: ctx.profile?.profileKey ?? null,
992
+ searchable: dts.kept,
993
+ unrecognized: dts.unrecognized,
994
+ }, null, 2) + "\n");
995
+ } catch (e) { note(`default-territories write failed (non-fatal): ${e.message}`); }
891
996
 
892
- // status seed — knockout's OWN step flow (never seedRunStatus's clearance stepper). Depth 2
893
- // walks one more step than a plain knockout, so the list is resolved once and frozen on ctx.
894
- const STEPS = ctx.koSteps = koSteps({ registerProbe: probeWanted });
895
- writeRunStatus(ctx, {
896
- schema: 1, id: job.id, runId, slug: run.slug, codename: run.codename,
897
- date: run.date, agent, forwarder: job.forwarder, ref: job.ref ?? null,
898
- // ONE SPELLING (progress.mjs batchMarkName). This line composed "IRONWHISK (+2 marks)" while the
899
- // publisher composed "IRONWHISK +2 more" for the SAME batch, so a run changed its name at delivery
900
- // and the browser — which threads reads on the name string — listed a batch's live face and its own
901
- // delivered face as two different marks. It also read "(+1 marks)" on every two-mark batch: the
902
- // same unguarded plural the publisher's title carried until.
903
- markName: batchMarkName(markNames),
904
- // THE NAMES THEMSELVES, so a surface can count them. status.json carried a mark STRING and nothing
905
- // countable, so the portal's live row sent `marks: []` and the Result screen — which reads that
906
- // array as a name count — told the customer a three-name batch had "0 names" for the whole run.
907
- // Bands stay off: a live batch has not been rated, and inventing one is the opposite failure.
908
- marks: markNames.map((name) => ({ name })),
909
- classes: job.classes ?? null, state: "running", lane: "knockout", stageLabel: policy.stageLabel,
910
- // — WHO IS RUNNING THIS AND WHICH BUILD. This lane opts out of the
911
- // clearance STEPPER (see the step list above) and used to lose the identity fields with it, so no
912
- // knockout run could be attributed to a commit by its own status.json and none was ever eligible
913
- // for reconcile-runs' exact liveness test. The stepper and the identity are separate calls now.
914
- ...identitySeed(),
915
- stepIndex: 0, stepLabel: STEPS[0], stepN: 1, stepTotal: STEPS.length,
916
- review: null, url: null, failedStage: null, reason: null, deliveredAt: null,
917
- // A5/A3: a re-run of a previously-terminal knockout may reopen the state ONLY because the resume
918
- // guard cleared the sentinel (ctx.stateReset threads that authority); startedAt is no longer
919
- // seeded anywhere — writeRunStatus backfills it first-write-wins.
920
- ...(ctx.stateReset ? { __stateReset: true } : {}),
921
- });
922
- rollupStatus(run.studioRoot);
923
- // THE SIGNA RUN MEMORY'S ATTEMPT (providers/_shared/answer-memory.mjs): whatever an earlier attempt
924
- // held is dropped, so a re-run asks the register again, and the mode is fixed for this attempt.
925
- ctx.answerMemory = beginAnswerMemory(run.runDir, REGISTER_PROVIDER);
926
- if (ctx.answerMemory.applies)
927
- runLog(run.runDir, { event: "answer-memory", mode: ctx.answerMemory.mode, ...(ctx.answerMemory.unknown ? { unrecognised: ctx.answerMemory.unknown } : {}) });
928
- if (ctx.answerMemory.unknown) note(`answer memory: ${ctx.answerMemory.switch}="${ctx.answerMemory.unknown}" is not off, watch or on, so this register's default applies (${ctx.answerMemory.mode})`);
929
- note(`=== KNOCKOUT batch (${policy.stageLabel}) — ${markNames.length} mark(s), framework ${ctx.framework.framework_key} ===`);
997
+ // status seed — knockout's OWN step flow (never seedRunStatus's clearance stepper). Depth 2
998
+ // walks one more step than a plain knockout, so the list is resolved once and frozen on ctx.
999
+ STEPS = ctx.koSteps = koSteps({ registerProbe: probeWanted });
1000
+ writeRunStatus(ctx, {
1001
+ schema: 1, id: job.id, runId, slug: run.slug, codename: run.codename,
1002
+ date: run.date, agent, forwarder: job.forwarder, ref: job.ref ?? null,
1003
+ // ONE SPELLING (progress.mjs batchMarkName). This line composed "IRONWHISK (+2 marks)" while the
1004
+ // publisher composed "IRONWHISK +2 more" for the SAME batch, so a run changed its name at delivery
1005
+ // and the browser — which threads reads on the name string — listed a batch's live face and its own
1006
+ // delivered face as two different marks. It also read "(+1 marks)" on every two-mark batch: the
1007
+ // same unguarded plural the publisher's title carried until.
1008
+ markName: batchMarkName(markNames),
1009
+ // THE NAMES THEMSELVES, so a surface can count them. status.json carried a mark STRING and nothing
1010
+ // countable, so the portal's live row sent `marks: []` and the Result screen — which reads that
1011
+ // array as a name count — told the customer a three-name batch had "0 names" for the whole run.
1012
+ // Bands stay off: a live batch has not been rated, and inventing one is the opposite failure.
1013
+ marks: markNames.map((name) => ({ name })),
1014
+ classes: job.classes ?? null, state: "running", lane: "knockout", stageLabel: policy.stageLabel,
1015
+ // — WHO IS RUNNING THIS AND WHICH BUILD. This lane opts out of the
1016
+ // clearance STEPPER (see the step list above) and used to lose the identity fields with it, so no
1017
+ // knockout run could be attributed to a commit by its own status.json and none was ever eligible
1018
+ // for reconcile-runs' exact liveness test. The stepper and the identity are separate calls now.
1019
+ ...identitySeed(),
1020
+ stepIndex: 0, stepLabel: STEPS[0], stepN: 1, stepTotal: STEPS.length,
1021
+ review: null, url: null, failedStage: null, reason: null, deliveredAt: null,
1022
+ // A5/A3: a re-run of a previously-terminal knockout may reopen the state ONLY because the resume
1023
+ // guard cleared the sentinel (ctx.stateReset threads that authority); startedAt is no longer
1024
+ // seeded anywhere — writeRunStatus backfills it first-write-wins.
1025
+ ...(ctx.stateReset ? { __stateReset: true } : {}),
1026
+ });
1027
+ rollupStatus(run.studioRoot);
1028
+ // THE SIGNA RUN MEMORY'S ATTEMPT (providers/_shared/answer-memory.mjs): whatever an earlier attempt
1029
+ // held is dropped, so a re-run asks the register again, and the mode is fixed for this attempt.
1030
+ ctx.answerMemory = beginAnswerMemory(run.runDir, register);
1031
+ if (ctx.answerMemory.applies)
1032
+ runLog(run.runDir, { event: "answer-memory", mode: ctx.answerMemory.mode, ...(ctx.answerMemory.unknown ? { unrecognised: ctx.answerMemory.unknown } : {}) });
1033
+ if (ctx.answerMemory.unknown) note(`answer memory: ${ctx.answerMemory.switch}="${ctx.answerMemory.unknown}" is not off, watch or on, so this register's default applies (${ctx.answerMemory.mode})`);
1034
+ note(`=== KNOCKOUT batch (${policy.stageLabel}) — ${markNames.length} mark(s), framework ${ctx.framework.framework_key} ===`);
1035
+ } },
1036
+ { name: "frame", run: async () => {
1037
+ // 1 — frame
1038
+ await koStage("knockout-frame", ctx);
1039
+ plan = JSON.parse(readFileSync(K.plan, "utf8"));
1040
+ planMarks = plan.marks;
1041
+ } },
1042
+ { name: "evidence", run: async () => {
1043
+ // THE WEB SWEEP NEEDS ONLY THE PLAN. Where the register is counted it starts once the counts have passed their check, and runs beside
1044
+ // the register reading and its owner checks; elsewhere it starts here. The rating waits for both, and a branch that fails waits for the
1045
+ // other to settle, so nothing is left running.
1046
+ const sweepMarks = async () => {
1047
+ koStep(ctx, "Sweeping marks");
1048
+ // WHEN THE SWEEP STARTED, for the minutes recorded against the owner's bar after it. The sweep's own
1049
+ // wall clock, not the sum of the marks' — they run side by side, so a sum would report minutes nobody
1050
+ // waited. Epoch, never a formatted time.
1051
+ const sweepStartedAt = Date.now();
1052
+ const { grid, source } = sweep;
1053
+ const { preset, reasoning } = KNOCKOUT_WEB;
1054
+ // step 3 — was a knob; no environment ever set it. The `Number.isFinite` guard beside it went
1055
+ // with the read: a constant cannot be typo'd, which is the hazard that guard existed for.
1056
+ const concurrency = 3;
1057
+ let callNo = 0;
1058
+ const degraded = new Map();
1059
+ const outaged = new Set(); // the subset of `degraded` whose cause was a 429/5xx — see the all-failed branch
1060
+ const recovered = []; // previously-degraded marks whose re-sweep succeeded — their stale assess chunks must be invalidated
1061
+ if (sweep.skipped) {
1062
+ // acceptance 6 — NOT ATTEMPTED. No executor is called, so nothing is billed, nothing can
1063
+ // 429, and no `.failed` sentinel is written: there is no failure here to record, and writing one
1064
+ // would tell a resumed run that a sweep was tried.
1065
+ //
1066
+ // Every mark takes the named cause, and that is the ENTIRE downstream wiring. The assess stage
1067
+ // already reads it (stages-knockout.mjs renders "(DEGRADED: … — apply the null-results doctrine,
1068
+ // never inflate)"), verify-knockout.mjs already REFUSES a row that holds no payload and does not
1069
+ // carry degraded:true plus a manual-verification note, and the renderers already print it. The
1070
+ // null-results doctrine carries this case; it needed no new path, only a cause.
1071
+ for (const m of planMarks) degraded.set(m.name, CAPABILITY_SKIPPED_CAUSE[sweep.skipped] ?? sweep.skipped);
1072
+ runLog(run.runDir, { event: "knockout-sweep-skipped", marks: planMarks.length, executor: source, cause: sweep.skipped });
1073
+ note(`knockout sweep: not run (${sweep.skipped}) — the screen delivers its register half and discloses the rest`);
1074
+ } else {
1075
+ runLog(run.runDir, { event: "knockout-sweep-start", marks: planMarks.length, executor: source, preset, reasoning: reasoning.effort, resultsPerCell: KNOCKOUT_WEB.resultsPerCell, concurrency });
1076
+ await runBatched(planMarks, concurrency, async (m) => {
1077
+ const out = K.research(kebab(m.name));
1078
+ if (existsSync(out)) return; // per-mark resume: only missing payloads re-sweep
1079
+ const hadFailed = existsSync(out + ".failed");
1080
+ const spec = knockoutGridSpec(m, plan.batch, { outputPath: out });
1081
+ const started = Date.now();
1082
+ const n = ++callNo;
1083
+ // ONE MORE CALL WHEN THE PROGRAM, NOT THE PROVIDER, FAILED. The search program is written by the
1084
+ // provider's model each call, and the clearance grid's own guidance retries once when it did not run
1085
+ // or printed something unreadable. A provider outage is not retried here: the provider call retried
1086
+ // a 429 or 5xx already, and the all-failed branch below parks the batch on it.
1087
+ let r = null, attempts = 0;
1088
+ const raw = []; // every attempt's, in order: a retried call's first answer is evidence too
1089
+ if (!spec.terms.length || !spec.platforms.length) {
1090
+ r = { ok: false, cause: "the plan names no spellings or no places for this mark" };
1091
+ } else {
1092
+ while (attempts < 2) {
1093
+ attempts++;
1094
+ try { r = await grid(spec, { mark: m.name, preset, reasoning }); }
1095
+ catch (e) { r = { ok: false, cause: `executor threw: ${String(e?.message ?? e).slice(0, 200)}` }; }
1096
+ if (Array.isArray(r?.raw) && r.raw.length) raw.push({ attempt: attempts, items: r.raw });
1097
+ if (r?.ok || r?.outage === true || !/^grid: /.test(String(r?.cause ?? ""))) break;
1098
+ }
1099
+ }
1100
+ // THE RAW RESULTS ARE KEPT, whether the call answered or not: what the provider returned is the only
1101
+ // record of which pages a search reached, and the ledger keeps only what each cell asked for.
1102
+ if (raw.length) {
1103
+ try {
1104
+ mkdirSync(dirname(K.webResults(kebab(m.name))), { recursive: true });
1105
+ writeFileSync(K.webResults(kebab(m.name)), JSON.stringify({ mark: m.name, callNo: n, attempts: raw }, null, 1) + "\n");
1106
+ } catch { /* the ledger below is the receipt; a raw-results write never fails a mark */ }
1107
+ }
1108
+ const row = {
1109
+ ts: new Date().toISOString(), mark: m.name, callNo: n, preset, reasoning: reasoning.effort, executor: source,
1110
+ spellings: spec.terms, places: spec.platforms, ...(spec.use ? { use: spec.use } : {}), resultsPerCell: spec.results_per_cell,
1111
+ cells: r?.requested ?? spec.terms.length * spec.platforms.length,
1112
+ // The mark's whole wall time, both attempts when there were two: what the client waited for.
1113
+ present: r?.present ?? 0, attempts, took_ms: Date.now() - started,
1114
+ bytes: r?.bytes ?? (r?.ledgerJson ? Buffer.byteLength(r.ledgerJson) : 0),
1115
+ ok: Boolean(r?.ok && r?.ledgerJson), ...(r?.ok && r?.ledgerJson ? {} : { cause: String(r?.cause ?? "unknown").slice(0, 300) }),
1116
+ };
1117
+ try { appendFileSync(K.sweepLedger, JSON.stringify(row) + "\n"); } catch { /* receipts best-effort, never fatal */ }
1118
+ if (row.ok) {
1119
+ // THE LEDGER IS THE PAYLOAD. The rating step reads it as it came back: every cell, the listings
1120
+ // each search returned, and any search that could not run. It is data, with no words of ours in it.
1121
+ writeFileSync(out, r.ledgerJson + "\n");
1122
+ if (hadFailed) {
1123
+ try { rmSync(out + ".failed"); } catch { /* best-effort */ }
1124
+ recovered.push(m.name);
1125
+ }
1126
+ } else {
1127
+ degraded.set(m.name, row.cause);
1128
+ if (r?.outage === true) outaged.add(m.name);
1129
+ writeFileSync(out + ".failed", `research failed: ${row.cause}\n`);
1130
+ }
1131
+ });
1132
+ if (degraded.size >= planMarks.length) {
1133
+ // EVERY mark failed. Whether that ends the batch or pauses it depends on why, and until now it
1134
+ // always ended it: the throw carried a prose reason, and StageFailure sets `rateLimited` by an EXACT
1135
+ // string match on `reason === "rate_limited"`, so `rateLimited` was false, the lane's own catch wrote
1136
+ // .failed immediately, so the run reported a hard failure for a provider hiccup. When this was
1137
+ // written the rate-limit re-throw through pipeline()'s outer catch was the lane's ONLY escape
1138
+ // hatch and this path could not reach it. added a second one — the class-aware
1139
+ // ladder in the catch below — and an outage-shaped reason classifies TRANSIENT there, so this
1140
+ // block is no longer the difference between a park and a dead run. It stays because it is the
1141
+ // BETTER answer: `rate_limited` postpones on the provider's own clock through the outer catch,
1142
+ // where the ladder would spend a recovery attempt to learn the same thing.
1143
+ //
1144
+ // ALL of them must be outage-shaped, not merely one. A batch where two marks hit a 429 and one hit a
1145
+ // bad key is a broken configuration wearing an outage's clothes; parking it would auto-resume
1146
+ // forever and bury the real error. Anything mixed, anything unexplained, stays terminal.
1147
+ //
1148
+ // resetsAt is null: the provider does not surface Retry-After through this path, and runner.mjs's
1149
+ // postponedDueAt already applies the default backoff for a null. Better an honest null than a
1150
+ // fabricated deadline.
1151
+ if (outaged.size >= planMarks.length) {
1152
+ note(`knockout sweep: all ${planMarks.length} research calls failed with an outage-shaped status — postponing rather than failing the batch`);
1153
+ runLog(run.runDir, { event: "knockout-sweep-outage", marks: planMarks.length, executor: source });
1154
+ throw new StageFailure("knockout-sweep", "rate_limited", null);
1155
+ }
1156
+ throw new StageFailure("knockout-sweep", `all ${planMarks.length} research calls failed (executor ${source}) — nothing to assess`, null);
1157
+ }
1158
+ if (degraded.size) note(`knockout sweep: ${degraded.size}/${planMarks.length} mark(s) degraded — the batch continues (null-results doctrine)`);
1159
+ // ── WHAT THE SWEEP COST, BESIDE THE BAR (ruling 570) ─────────────────────────────────────────────
1160
+ //
1161
+ // The frame chooses each name's places with no cap, so the only way to know what a knockout costs is
1162
+ // to record it. Cells come from the RECEIPTS ON DISK rather than the loop's own variables: a resumed
1163
+ // run's earlier marks are in the ledger and not in this process, and the ledger is what a reader has
1164
+ // afterwards. The bar is recorded, not applied — nothing above or below this line reads it.
1165
+ try {
1166
+ const rows = readFileSync(K.sweepLedger, "utf8").split("\n").filter(Boolean).map((l) => { try { return JSON.parse(l); } catch { return null; } }).filter(Boolean);
1167
+ const cells = rows.reduce((n, r) => n + (Number.isFinite(r?.cells) ? r.cells : 0), 0);
1168
+ const places = rows.reduce((n, r) => Math.max(n, Array.isArray(r?.places) ? r.places.length : 0), 0);
1169
+ // THE SWEEP'S OWN ELAPSED TIME, UNDER A NAME THAT SAYS SO, and the bar is no longer asserted here.
1170
+ // The bar is about the RUN (ruling 591) and this span is one stage of it: both knockouts of
1171
+ // 2026-09-26 recorded `overBar: false` at 0.6 and 0.8 minutes while the runs took 14.4 minutes
1172
+ // wall, which e2e scored as over. A bar recorded against the wrong quantity is worse than an
1173
+ // unrecorded one, because the field's name says it answered the question. It is recorded at
1174
+ // delivery instead, where the run's own start is readable.
1175
+ const sweepMinutes = Number(((Date.now() - sweepStartedAt) / 60000).toFixed(1));
1176
+ runLog(run.runDir, { event: "knockout-sweep-total", marks: planMarks.length, calls: rows.length,
1177
+ cells, mostPlacesForOneName: places, sweepMinutes });
1178
+ note(`knockout sweep: ${cells} cell(s) across ${rows.length} call(s) in ${sweepMinutes} min`);
1179
+ } catch { /* the receipts are the record; a summary that could not be read never fails a sweep */ }
1180
+ }
1181
+ return { degraded, recovered };
1182
+ };
1183
+ let sweepRun = null;
1184
+ // HANDLED FROM THE START. A sweep that fails while the register is still being read rejects with nothing awaiting it yet, and
1185
+ // an unhandled rejection ends the process with no status written. The reading's `finally` and the await below take its failure.
1186
+ const startSweep = () => {
1187
+ if (!sweepRun) { sweepRun = sweepMarks(); sweepRun.catch(() => {}); }
1188
+ return sweepRun;
1189
+ };
930
1190
 
931
- // 1 — frame
932
- await koStage("knockout-frame", ctx);
933
- const plan = JSON.parse(readFileSync(K.plan, "utf8"));
934
- const planMarks = plan.marks;
1191
+ // 1.5 — STAGE 0.5: the register hit-counts. Pure code — no stage, no model, no turn. It runs
1192
+ // BEFORE the sweep because it is the cheap deterministic question and the client sees its answer
1193
+ // first; it runs after the frame only so the batch's shape is settled and a frame failure costs
1194
+ // nothing at the register. Its own inputs come from the REQUEST, not from the plan (below).
1195
+ registerCounts = null;
1196
+ if (probeWanted) {
1197
+ koStep(ctx, KO_STEP_REGISTER_COUNT);
1198
+ ensureDriverDir(run.runDir);
1199
+ // ── THE OWNER LOOKUP, ONCE THE LISTING HAS NAMED THE OWNER AND A COUNT HAS LANDED ──────────────
1200
+ //
1201
+ // Run after the count gate below, whichever lane went first. A batch where not one mark got a
1202
+ // number stops at that gate; on a register that lists first the lookups used to run before it,
1203
+ // research calls the batch paid for and then threw away.
1204
+ const checkOwners = async (recDoc) => {
1205
+ if (!recDoc) return;
1206
+ // On the run that produced the issue, the owner's name was on disk 48 seconds before the sweep
1207
+ // started and no pass ever searched it: every sweep keys on the TERM, and nothing re-swept on an
1208
+ // OWNER once the register named one. The assessment then inferred what the owner sold from the
1209
+ // owner's name, and deferred the real answer to a document the run did not hold.
1210
+ //
1211
+ // Bounded to promoted filings and deduplicated per owner — on the issue's own run that is ONE
1212
+ // extra query. Never throws: a failure produces rows saying the lookup did not answer, and the
1213
+ // run publishes (ruling A, 2026-09-07).
1214
+ try {
1215
+ const owed = ownersOwedACheck(recDoc);
1216
+ if (owed.length) {
1217
+ // A resume asks only the checks the run holds no answer to (heldOwnerChecks).
1218
+ let prior = [];
1219
+ try { prior = JSON.parse(readFileSync(K.ownerChecks, "utf8")).checks ?? []; } catch { /* first pass */ }
1220
+ const { held, ask } = heldOwnerChecks(prior, owed, { runDir: run.runDir, preset: KNOCKOUT_WEB.questionPreset });
1221
+ const asked = ask.length ? await runOwnerChecks({
1222
+ owners: ask, exec: sweep.exec, runDir: run.runDir, ledgerPath: K.ownerCheckLedger,
1223
+ rawDir: paths(run.runDir).webResults, preset: KNOCKOUT_WEB.questionPreset,
1224
+ concurrency: 3, // step 3 — the same constant as the sibling calls above
1225
+ }) : [];
1226
+ const answers = new Map(ask.map((o, j) => [o, asked[j]]));
1227
+ const checks = owed.map((o, i) => held.get(i) ?? answers.get(o));
1228
+ atomicWrite(K.ownerChecks, JSON.stringify({ schema: 1, checks }, null, 2) + "\n");
1229
+ runLog(run.runDir, {
1230
+ event: "knockout-owner-checks", owners: owed.length,
1231
+ answered: checks.filter((c) => c.ok).length,
1232
+ // The count is logged because the ruling is about COST: one promoted filing on the
1233
+ // issue's run means one query. A number climbing here is the bound having widened.
1234
+ unanswered: checks.filter((c) => !c.ok).length,
1235
+ // Answers the run already held, so asked nothing for: `asked` is what this pass paid for.
1236
+ reused: held.size, asked: ask.length,
1237
+ });
1238
+ } else {
1239
+ runLog(run.runDir, { event: "knockout-owner-checks", owners: 0, answered: 0, unanswered: 0,
1240
+ detail: "no promoted filing names a proprietor to search" });
1241
+ }
1242
+ } catch (e) {
1243
+ // Structural only — runOwnerChecks itself never throws. Non-fatal by the same rule as the
1244
+ // listing above: a report is never withheld for a check that could not run.
1245
+ note(`owner use-check failed (non-fatal): ${e.message}`);
1246
+ runLog(run.runDir, { event: "knockout-owner-checks-failed", cause: String(e?.message ?? e).slice(0, 300) });
1247
+ }
1248
+ };
935
1249
 
936
- // THE WEB SWEEP NEEDS ONLY THE PLAN. Where the register is counted it starts once the counts have passed their check, and runs beside
937
- // the register reading and its owner checks; elsewhere it starts here. The rating waits for both, and a branch that fails waits for the
938
- // other to settle, so nothing is left running.
939
- const sweepMarks = async () => {
940
- koStep(ctx, "Sweeping marks");
941
- // WHEN THE SWEEP STARTED, for the minutes recorded against the owner's bar after it. The sweep's own
942
- // wall clock, not the sum of the marks' — they run side by side, so a sum would report minutes nobody
943
- // waited. Epoch, never a formatted time.
944
- const sweepStartedAt = Date.now();
945
- const { grid, source } = sweep;
946
- const { preset, reasoning } = KNOCKOUT_WEB;
947
- // step 3 — was a knob; no environment ever set it. The `Number.isFinite` guard beside it went
948
- // with the read: a constant cannot be typo'd, which is the hazard that guard existed for.
949
- const concurrency = 3;
950
- let callNo = 0;
951
- const degraded = new Map();
952
- const outaged = new Set(); // the subset of `degraded` whose cause was a 429/5xx — see the all-failed branch
953
- const recovered = []; // previously-degraded marks whose re-sweep succeeded — their stale assess chunks must be invalidated
954
- if (sweep.skipped) {
955
- // acceptance 6 — NOT ATTEMPTED. No executor is called, so nothing is billed, nothing can
956
- // 429, and no `.failed` sentinel is written: there is no failure here to record, and writing one
957
- // would tell a resumed run that a sweep was tried.
958
- //
959
- // Every mark takes the named cause, and that is the ENTIRE downstream wiring. The assess stage
960
- // already reads it (stages-knockout.mjs renders "(DEGRADED: … — apply the null-results doctrine,
961
- // never inflate)"), verify-knockout.mjs already REFUSES a row that holds no payload and does not
962
- // carry degraded:true plus a manual-verification note, and the renderers already print it. The
963
- // null-results doctrine carries this case; it needed no new path, only a cause.
964
- for (const m of planMarks) degraded.set(m.name, CAPABILITY_SKIPPED_CAUSE[sweep.skipped] ?? sweep.skipped);
965
- runLog(run.runDir, { event: "knockout-sweep-skipped", marks: planMarks.length, executor: source, cause: sweep.skipped });
966
- note(`knockout sweep: not run (${sweep.skipped}) — the screen delivers its register half and discloses the rest`);
967
- } else {
968
- runLog(run.runDir, { event: "knockout-sweep-start", marks: planMarks.length, executor: source, preset, reasoning: reasoning.effort, resultsPerCell: KNOCKOUT_WEB.resultsPerCell, concurrency });
969
- await runBatched(planMarks, concurrency, async (m) => {
970
- const out = K.research(kebab(m.name));
971
- if (existsSync(out)) return; // per-mark resume: only missing payloads re-sweep
972
- const hadFailed = existsSync(out + ".failed");
973
- const spec = knockoutGridSpec(m, plan.batch, { outputPath: out });
974
- const started = Date.now();
975
- const n = ++callNo;
976
- // ONE MORE CALL WHEN THE PROGRAM, NOT THE PROVIDER, FAILED. The search program is written by the
977
- // provider's model each call, and the clearance grid's own guidance retries once when it did not run
978
- // or printed something unreadable. A provider outage is not retried here: the provider call retried
979
- // a 429 or 5xx already, and the all-failed branch below parks the batch on it.
980
- let r = null, attempts = 0;
981
- const raw = []; // every attempt's, in order: a retried call's first answer is evidence too
982
- if (!spec.terms.length || !spec.platforms.length) {
983
- r = { ok: false, cause: "the plan names no spellings or no places for this mark" };
984
- } else {
985
- while (attempts < 2) {
986
- attempts++;
987
- try { r = await grid(spec, { mark: m.name, preset, reasoning }); }
988
- catch (e) { r = { ok: false, cause: `executor threw: ${String(e?.message ?? e).slice(0, 200)}` }; }
989
- if (Array.isArray(r?.raw) && r.raw.length) raw.push({ attempt: attempts, items: r.raw });
990
- if (r?.ok || r?.outage === true || !/^grid: /.test(String(r?.cause ?? ""))) break;
1250
+ // resume: a settled prior sidecar is reused cell by cell, so a re-run never re-bills a count that
1251
+ // already landed — including across a build that ADDED a predicate, where only the new column is
1252
+ // bought (register-count.mjs cellSettled).
1253
+ let prior = null;
1254
+ try { prior = unfoldFormCounts(JSON.parse(readFileSync(K.registerCounts, "utf8"))); } catch { /* first attempt */ }
1255
+ const counted0 = await countRegisterHits({
1256
+ // Scope comes from the REQUEST (markRows / job.classes), never from the frame's plan. The plan
1257
+ // is a model output, and its per-mark classes may carry the frame's own belt-and-braces
1258
+ // inference — fine for shaping a research prompt, wrong for a figure the client reads as
1259
+ // "filings in my classes". The names are identical either way (the frame validator enforces
1260
+ // one row per instructed mark, verbatim), so this is a scope decision, not a set difference.
1261
+ marks: countRowsOf(markRows.map((m) => ({ name: String(m.name), classes: Array.isArray(m.classes) ? m.classes : null })), plan.marks),
1262
+ classes: job.classes ?? null, jurisdictions: job.jurisdictions ?? null,
1263
+ provider: register, capabilities: ctx.registerCaps,
1264
+ counter: countExec.count, ledgerPath: K.countLedger, prior,
1265
+ joinForms: countExec.source === "provider" && ctx.registerCaps?.exactFormsCountAsOne === true,
1266
+ unreachable: ctx.registerUnreachable ?? [], // — computed once at preflight, above
1267
+ concurrency: 3, // step 3 — was a knob; no environment ever set it
1268
+ // The close-variation fan-out's ceiling. A deployment may buy FEWER forms per mark than the code
1269
+ // cap — on Corsearch each form is a billable search — and may not buy more: variantForms clamps
1270
+ // to VARIANT_CAP, so this knob can only ever narrow. Unset ⇒ the code cap, which is the answer
1271
+ // for every deployment that has not thought about it.
1272
+ ...(process.env.CLEAROTRON_KNOCKOUT_VARIANT_CAP ? { variantCap: Number(process.env.CLEAROTRON_KNOCKOUT_VARIANT_CAP) } : {}),
1273
+ });
1274
+ // A name given in several written forms is counted as each, and reads as one row from here on.
1275
+ const doc = foldFormCounts(counted0, markRows.map((m) => ({ name: String(m.name) })), plan.marks);
1276
+ const counted = countedMarks(doc);
1277
+ // Not one mark got a number. The count IS this product — a batch published now would be a plain
1278
+ // knockout wearing a Depth 2 label and price, which is the silent substitution the whole
1279
+ // search-policy registry exists to forbid. Terminal, with the provider's own reason on it.
1280
+ if (!counted) {
1281
+ // The record's cause where a count kept one apart from the reader's line, so the operator reads what to fix.
1282
+ const first = doc.marks?.[0]?.counts?.[Object.keys(doc.marks[0].counts)[0]];
1283
+ const why = first?.cause ?? first?.unavailable ?? "no reason recorded";
1284
+ throw new StageFailure("knockout-register-count",
1285
+ `no register count could be taken for any of the ${planMarks.length} mark(s) via ${register} (executor ${countExec.source}) — first cause: ${String(why).slice(0, 200)}`, null);
991
1286
  }
1287
+ atomicWrite(K.registerCounts, JSON.stringify(doc, null, 2) + "\n");
1288
+ registerCounts = doc;
1289
+ runLog(run.runDir, { event: "knockout-register-counts", provider: register, executor: countExec.source, marks: doc.marks.length, counted, regions: doc.scope.regions ?? "worldwide" });
1290
+ if (counted < doc.marks.length) note(`register counts: ${doc.marks.length - counted}/${doc.marks.length} mark(s) unavailable — the batch continues (they publish as "not available", never as zero)`);
1291
+
1292
+ const sweeping = startSweep();
1293
+ try { await checkOwners(await readTheRegister({ ctx, job, K, run, agent, markRows, plan, counts: doc, countExec, opts })); }
1294
+ finally { await sweeping.catch(() => {}); }
992
1295
  }
993
- // THE RAW RESULTS ARE KEPT, whether the call answered or not: what the provider returned is the only
994
- // record of which pages a search reached, and the ledger keeps only what each cell asked for.
995
- if (raw.length) {
996
- try {
997
- mkdirSync(dirname(K.webResults(kebab(m.name))), { recursive: true });
998
- writeFileSync(K.webResults(kebab(m.name)), JSON.stringify({ mark: m.name, callNo: n, attempts: raw }, null, 1) + "\n");
999
- } catch { /* the ledger below is the receipt; a raw-results write never fails a mark */ }
1296
+
1297
+ // 2 — the sweep: ONE grid call per mark, receipted, through the clearance grid's own program path.
1298
+ // Every spelling the frame named for the mark is searched once on every place it named for the batch,
1299
+ // and every result is kept, with no summary (stages-knockout.mjs, KNOCKOUT_WEB). A mark whose call
1300
+ // fails is degraded on its own; the rest of the batch goes on.
1301
+ ({ degraded, recovered } = await startSweep());
1302
+ } },
1303
+ { name: "assess", run: async () => {
1304
+ // 3 — assess (chunked ≤8/turn; merged + gated in code). DEGRADED per the DISK truth (payload
1305
+ // presence), never the in-memory Map alone — resume-proof: a prior attempt's degrades count too.
1306
+ // A STOP ASKED FOR WHILE THE TWO RESEARCH BRANCHES RAN ends the run here, with both settled and their work kept: the rating does
1307
+ // not start, and the status does not name it as begun. The turn boundary would refuse its first turn anyway.
1308
+ if (isCancelled(run.runDir)) throw new RunCancelled("knockout-assess", readCancel(run.runDir));
1309
+ koStep(ctx, "Knockout assessment");
1310
+ const chunkRows = planMarks.map((m) => {
1311
+ const has = existsSync(K.research(kebab(m.name)));
1312
+ return { name: m.name, degraded: has ? null : (degraded.get(m.name) ?? "research unavailable (prior attempt)") };
1313
+ });
1314
+ chunks = koChunks(chunkRows);
1315
+ // the assignment sidecar — the per-chunk validator joins each chunk's marks against THIS (membership
1316
+ // is enforced in code, not prompted); deterministic from the frozen plan, so a resume re-mints equal.
1317
+ atomicWrite(paths(run.runDir).knockoutChunks,
1318
+ JSON.stringify({ schema: 1, chunks: chunks.map((ch) => ch.map((m) => m.name)) }, null, 2) + "\n");
1319
+ // a recovered mark's evidence changed — its prior assess chunk is STALE by construction; drop it so
1320
+ // the stage re-runs (otherwise the re-sweep was billed for nothing and the fresh payload never read).
1321
+ if (recovered.length) {
1322
+ for (let c = 0; c < chunks.length; c++) {
1323
+ if (chunks[c].some((m) => recovered.includes(m.name)) && existsSync(K.assessChunk(c))) {
1324
+ try { rmSync(K.assessChunk(c)); runLog(run.runDir, { event: "knockout-assess-invalidated", chunk: c, recovered: chunks[c].filter((m) => recovered.includes(m.name)).map((m) => m.name) }); } catch { /* best-effort */ }
1325
+ }
1326
+ }
1000
1327
  }
1001
- const row = {
1002
- ts: new Date().toISOString(), mark: m.name, callNo: n, preset, reasoning: reasoning.effort, executor: source,
1003
- spellings: spec.terms, places: spec.platforms, ...(spec.use ? { use: spec.use } : {}), resultsPerCell: spec.results_per_cell,
1004
- cells: r?.requested ?? spec.terms.length * spec.platforms.length,
1005
- // The mark's whole wall time, both attempts when there were two: what the client waited for.
1006
- present: r?.present ?? 0, attempts, took_ms: Date.now() - started,
1007
- bytes: r?.bytes ?? (r?.ledgerJson ? Buffer.byteLength(r.ledgerJson) : 0),
1008
- ok: Boolean(r?.ok && r?.ledgerJson), ...(r?.ok && r?.ledgerJson ? {} : { cause: String(r?.cause ?? "unknown").slice(0, 300) }),
1009
- };
1010
- try { appendFileSync(K.sweepLedger, JSON.stringify(row) + "\n"); } catch { /* receipts best-effort, never fatal */ }
1011
- if (row.ok) {
1012
- // THE LEDGER IS THE PAYLOAD. The rating step reads it as it came back: every cell, the listings
1013
- // each search returned, and any search that could not run. It is data, with no words of ours in it.
1014
- writeFileSync(out, r.ledgerJson + "\n");
1015
- if (hadFailed) {
1016
- try { rmSync(out + ".failed"); } catch { /* best-effort */ }
1017
- recovered.push(m.name);
1328
+ for (let c = 0; c < chunks.length; c++) {
1329
+ await koStage("knockout-assess", ctx, { chunkNo: c, msgCtx: { chunkMarks: chunks[c], chunkTotal: chunks.length, framework: ctx.framework, frameworkMethod: ctx.frameworkMethod ?? null } });
1330
+ }
1331
+ // ONE COMPOSITION, for the rated batch and for a corrected one: the chunks read, the summary joined, the engine's caveats,
1332
+ // the merged gate and the write. A correction that took a shorter road would reach a client through a lighter gate.
1333
+ composeRecord = () => {
1334
+ // cardOrder records how this run's page lists a name's cards, so a delivered report re-renders as it was delivered.
1335
+ const merged = { schema_version: 1, framework: null, batch: null, cardOrder: KNOCKOUT_CARD_ORDER, marks: [] };
1336
+ const summaries = [];
1337
+ for (let c = 0; c < chunks.length; c++) {
1338
+ const chunkPath = K.assessChunk(c);
1339
+ const part = JSON.parse(readFileSync(chunkPath, "utf8"));
1340
+ if (c === 0) { merged.framework = part.framework ?? { source: ctx.framework.framework_key, ladder: ctx.framework.bands.map((b) => b.label) }; merged.batch = part.batch ?? null; }
1341
+ if (typeof part.chunkSummary === "string" && part.chunkSummary.trim()) summaries.push(part.chunkSummary.trim());
1342
+ merged.marks.push(...(part.marks ?? []));
1018
1343
  }
1344
+ if (!merged.batch) merged.batch = { productContext: plan.batch.productContext, standardCaveats: [] };
1345
+ // the WHOLE-batch executive summary = the per-chunk summaries, composed in code (every chunk's
1346
+ // validator required one, so no mark's chunk is silently absent — review 2026-07-17)
1347
+ merged.batch.executiveSummary = summaries.join("\n\n");
1348
+ // ── THE PENDING-REGISTER CAVEAT, CONDITIONAL SINCE RF-10 v3 ────────────────
1349
+ //
1350
+ // "Ratings reflect our common law assessment. Register analysis may adjust ratings in either
1351
+ // direction." This is a CODE DEFAULT that fires when the model supplied no caveat of its own, and
1352
+ // turned it from dormant into the thing that ships.
1353
+ //
1354
+ // BEFORE: a rule in the knockout-assess manual ordered the seat to write that caveat, so the array
1355
+ // arrived non-empty and this default almost never fired. THAT RULE IS RETIRED IN THIS SAME BRANCH —
1356
+ // the seat is no longer told to write it — so the array now arrives EMPTY and this line injects the
1357
+ // sentence unconditionally. Retiring the rule in the doctrine while leaving its default in the code
1358
+ // did not remove the caveat; it made it fire on every run.
1359
+ //
1360
+ // And it is FALSE on the runs it now fires on. The rater is handed this run's fetched register
1361
+ // filings and weighs them, so "register analysis may adjust ratings" describes work that already
1362
+ // happened. RF-10 v3 (synthesis-rules.md): when register analysis ran AND surfaced live filings,
1363
+ // drop the caveat and cite the register evidence directly; where it did not run, it stands and is
1364
+ // the honest thing to say.
1365
+ //
1366
+ // THE DRIVER'S READ, off the run. A seat that could assert whether the register ran could waive its
1367
+ // own caveat. Records present AND non-empty: a file that exists with nothing in it is a register
1368
+ // that surfaced no filings, which is exactly the case the caveat is still true for.
1369
+ // — ONE DERIVATION, shared with the verifier. This was a private copy, and the
1370
+ // lint that checks the result did not have it: it required the caveat unconditionally while this
1371
+ // injected it conditionally, so any run where the seat supplied its own caveats failed by
1372
+ // construction. Two predicates that must agree forever is how they stop agreeing.
1373
+ // — THE SAME DERIVATION THE LINT USES. This counted the array, blanks included, so
1374
+ // `["", " "]` read as "the rater supplied two" here and as "supplied none" in the verifier. The lint
1375
+ // could not see the disagreement because the survivor sentence below silenced it entirely.
1376
+ if (raterCaveats(merged.batch.standardCaveats).length === 0 && !registerSurfacedFilings(K.registerRecords)) {
1377
+ merged.batch.standardCaveats = ["Ratings reflect our common law assessment. Register analysis may adjust ratings in either direction."];
1378
+ }
1379
+ if (!Array.isArray(merged.batch.standardCaveats)) merged.batch.standardCaveats = [];
1380
+ // ── the survivor sentence, in CODE ( fix 3) ────────────────────────────────────────────────────
1381
+ //
1382
+ // A mark this lane did not knock out is a SURVIVOR. It is not clear, and the document must not be
1383
+ // readable as though it were: the knockout screens, the clearance enumerates, and the whole distance
1384
+ // between them is the work that has not happened yet. Two runs on two matters delivered "Medium,
1385
+ // complete" while missing almost every mark the lawyer named, because a screen cannot know what it
1386
+ // did not look for — so the boundary of the screen is stated by the engine rather than left to the
1387
+ // assessing model, which is the one party that cannot see it.
1388
+ //
1389
+ // APPENDED, never prepended: publish/knockout.mjs's email takes standardCaveats[0], so leading with
1390
+ // this would silently replace the standing caveat in the requester's inbox.
1391
+ const survivorNote = survivorBoundaryNote(policy);
1392
+ if (!merged.batch.standardCaveats.some((c) => SURVIVOR_BOUNDARY_RE.test(String(c))))
1393
+ merged.batch.standardCaveats.push(survivorNote);
1394
+ // ── the skipped-capability sentence, in CODE, for the survivor sentence's own reason ──────
1395
+ //
1396
+ // The per-mark degrade above already reaches the client on every row. This is the RUN-level fact
1397
+ // underneath twenty identical rows: not "research was unavailable for this name" twenty times, but
1398
+ // one capability that never ran on this deployment. The assessing model cannot state it — it is
1399
+ // told a mark is degraded, never why the whole screen is — so the engine states it, exactly as it
1400
+ // states the survivor boundary two lines up.
1401
+ //
1402
+ // APPENDED, never prepended, for the same reason the survivor note is: publish/knockout.mjs's email
1403
+ // takes standardCaveats[0], and leading with this would silently replace the standing caveat in the
1404
+ // requester's inbox.
1405
+ const skippedNote = sweep.skipped ? CAPABILITY_SKIPPED_NOTE[sweep.skipped] : null;
1406
+ if (skippedNote && !merged.batch.standardCaveats.some((c) => String(c) === skippedNote))
1407
+ merged.batch.standardCaveats.push(skippedNote);
1408
+ // The merged gate now also validates the TYPED findings and receipts their citations, and it
1409
+ // NORMALISES as it validates — each finding's band comes back in the frozen deck's own casing — so
1410
+ // it runs BEFORE the artifact is written, not after. The counts are logged because a receipts pass
1411
+ // over zero citations is a different fact from a receipts pass, and only the count can tell them
1412
+ // apart afterwards.
1413
+ // BEFORE THE GATE AND THE WRITE, so the record on disk is the record that ships, and the reviewing
1414
+ // pass never addresses a line inside a section that is about to go.
1415
+ removeNextStepSections(run.runDir, merged.marks);
1416
+ const mv = validateMergedFindings(run.runDir, merged, plan);
1417
+ if (!mv.ok) throw new StageFailure("knockout-assess", `merged findings failed the lint: ${mv.failures.join("; ")}`, null);
1418
+ runLog(run.runDir, { event: "knockout-receipts", ...mv.receipts });
1419
+ atomicWrite(K.findings, JSON.stringify(merged, null, 2) + "\n");
1420
+ return merged;
1421
+ };
1422
+ // Reassigned by the reviewing pass, which returns a REWRITTEN record rather than editing this one:
1423
+ // the original has to survive intact as the thing that ships if the pass cannot finish cleanly.
1424
+ merged = composeRecord();
1425
+ } },
1426
+ { name: "review", run: async () => {
1427
+ // ── THE REVIEWING PASS, AFTER THE RECORD IS ON DISK AND BEFORE ANYTHING READS IT ─────────────────
1428
+ //
1429
+ // ORDER MATTERS THREE WAYS. The record is written FIRST so the stage's validator has something to
1430
+ // join every address against — an address that names no line is refused while the seat can still
1431
+ // send a repair turn, rather than reported as unresolved after the stage was declared good. It also
1432
+ // means a run that dies inside the pass has already left a complete, valid, deliverable record: the
1433
+ // rated one, unrewritten, which is exactly what shipped before this stage existed. And the rewritten
1434
+ // record goes back through `validateMergedFindings` before it replaces that one, so nothing reaches
1435
+ // a client that has not been through the same gate.
1436
+ //
1437
+ // NO NEW STEP LABEL. `stepTotal` is derived from `koSteps()`, so adding one would renumber the
1438
+ // progress screen a client watches for a pass that takes a minute. It runs inside "Knockout
1439
+ // assessment", which is what it is part of.
1440
+ merged = await knockoutReviewingPass({ ctx, run, K, merged, plan, chunks, composeRecord });
1441
+ try { writeFileSync(K.assessment, String(merged.batch.executiveSummary ?? "")); } catch { /* prose mirror, best-effort */ }
1442
+ } },
1443
+ { name: "publish", run: async () => {
1444
+ // 4 — publish (report + workbook + meta + index)
1445
+ //
1446
+ // PUBLISHED ONCE, as a clearance is. The publish result is recorded in `.published`, and a resume that finds the
1447
+ // record delivers what was published rather than publishing again: a run stopped between the publish and its
1448
+ // delivery record would otherwise put a second copy in the pool. The record carries everything the delivery
1449
+ // below reads, so the resumed delivery is the one the first pass would have sent.
1450
+ overall = worstBand(ctx.framework, merged.marks);
1451
+ if (existsSync(join(run.runDir, ".published"))) {
1452
+ const { ts: _publishedAt, ...stored } = JSON.parse(readFileSync(join(run.runDir, ".published"), "utf8"));
1453
+ published = stored;
1454
+ koStep(ctx, "Report & publish");
1455
+ note(`publish skip — already published → ${published.url}`);
1019
1456
  } else {
1020
- degraded.set(m.name, row.cause);
1021
- if (r?.outage === true) outaged.add(m.name);
1022
- writeFileSync(out + ".failed", `research failed: ${row.cause}\n`);
1457
+ // THE LAST READ OF THE STOP FLAG. Everything above dispatches through the gateway, which reads it
1458
+ // before a turn — so on this lane, where publication follows the final stage directly, a stop
1459
+ // pressed during that stage was never seen and the report went out anyway.
1460
+ assertNotCancelledBeforePublish(run.runDir, "knockout");
1461
+ // PAST THE LAST STOPPABLE POINT, RECORDED WHERE IT BECOMES TRUE. The read above is the final one, so
1462
+ // from this line on a stop cannot prevent delivery — and the screen must stop promising it will.
1463
+ // Written here rather than derived on the screen from a step number: "Report & publish" is step 4 of
1464
+ // 5 on this lane, not the last, so any arithmetic over stepN would name the wrong step and go stale
1465
+ // the day a lane's list changes.
1466
+ writeRunStatus(ctx, { stoppable: false });
1467
+ koStep(ctx, "Report & publish");
1468
+ // A set-aside filing the rating cites moves up with the carried ones, so the report has its row.
1469
+ try {
1470
+ const held = JSON.parse(readFileSync(K.registerRecords, "utf8"));
1471
+ const moved = withCitedFilings(held, merged);
1472
+ if (moved !== held) atomicWrite(K.registerRecords, JSON.stringify(moved, null, 2) + "\n");
1473
+ } catch { /* no record on this run, or none readable: publish says which */ }
1474
+ published = await publishKnockout({
1475
+ runId, codename: run.codename, runDir: run.runDir,
1476
+ findings: merged, plan, framework: ctx.framework, overall,
1477
+ poolRoot: config.poolRoot,
1478
+ // THE FALLBACK HERE COULD NOT FIRE, AND COULD NOT HAVE HELPED IF IT HAD. It read
1479
+ // `config.poolUrl ?? envFrom(process.env, "CLEAROTRON_REPORTS_URL") ?? null`. Two things were wrong
1480
+ // with it and both were invisible: the getter returns "" when the variable is unset, and `??` only
1481
+ // falls through on null or undefined — so the second operand was unreachable — and that second
1482
+ // operand read the same `process.env` the getter had just read, so reaching it would have returned
1483
+ // the same empty answer. A reader saw a safety net twice over where there was none.
1484
+ //
1485
+ // `|| null` instead, which says the one true thing: no base URL configured, so no link. That is the
1486
+ // state `reportUrlFor` already handles by returning null per report rather than an empty string, and
1487
+ // a null link is what the delivery packet is specified to carry when no pool URL is set.
1488
+ poolUrl: config.poolUrl || null,
1489
+ customerKey: ctx.profile?.profileKey ?? "generic",
1490
+ // — the frozen profile's delivery overlay decides the confidentiality marking, exactly as it
1491
+ // does on the clearance lane. Absent (an unbound run, or a profile silent on the field) is the
1492
+ // NO-OPINION state and gets the plain default; only an explicit `privileged:false` suppresses it.
1493
+ delivery: ctx.profile?.delivery,
1494
+ searchPolicy: policy, tokens: (() => { try { return rollupTokens(run.runDir).total; } catch { return null; } })(),
1495
+ registerCounts,
1496
+ });
1497
+ sentinel(run.runDir, ".published", published);
1498
+ runLog(run.runDir, { event: "knockout-published", url: published.url, reports: published.reports.map((r) => ({ mark: r.mark, url: r.url })), overall, marks: merged.marks.length });
1023
1499
  }
1024
- });
1025
- if (degraded.size >= planMarks.length) {
1026
- // EVERY mark failed. Whether that ends the batch or pauses it depends on why, and until now it
1027
- // always ended it: the throw carried a prose reason, and StageFailure sets `rateLimited` by an EXACT
1028
- // string match on `reason === "rate_limited"`, so `rateLimited` was false, the lane's own catch wrote
1029
- // .failed immediately, so the run reported a hard failure for a provider hiccup. When this was
1030
- // written the rate-limit re-throw through pipeline()'s outer catch was the lane's ONLY escape
1031
- // hatch and this path could not reach it. added a second one — the class-aware
1032
- // ladder in the catch below — and an outage-shaped reason classifies TRANSIENT there, so this
1033
- // block is no longer the difference between a park and a dead run. It stays because it is the
1034
- // BETTER answer: `rate_limited` postpones on the provider's own clock through the outer catch,
1035
- // where the ladder would spend a recovery attempt to learn the same thing.
1500
+ // The knockout lane put its token total in the PUBLISHED ARTIFACT but never stamped the run itself,
1501
+ // so `status.json.tokens` was empty for every Stage-0 run however it ended (fixed 2026-07-28) — and
1502
+ // a Stage-0 run appeared in no account-level consumption view at all.
1503
+ recordRunConsumption(ctx, { phase: "delivered", tokens: stampTokenRollup(run.runDir, "delivered") });
1504
+ } },
1505
+ { name: "deliver", run: async () => {
1506
+ // 5 — delivery handoff, to the clearance's packet contract (run-delivered.mjs)
1507
+ koStep(ctx, "Sending to you");
1508
+ // qcFlags: the projected predelivery-lint lines publishKnockout just computed and recorded — the
1509
+ // cover note enumerates exactly what the workbook does (A10, extended to this lane 2026-07-31).
1510
+ // They are FLAGS: the packet, the state and the send below are byte-identical with or without them.
1511
+ // The product's name, from the run's frozen policy, for the email's first line and its subject alike.
1512
+ const productName = knockoutName(policy);
1513
+ const emailHtml = composeKnockoutEmail({ findings: merged, framework: ctx.framework, overall, reports: published.reports, auditUrl: published.auditUrl, job, registerCounts, qcFlags: published.qcFlags, productName });
1514
+ writeFileSync(K.emailBody, emailHtml);
1515
+ const nMarks = merged.marks.length;
1516
+ const refTag = job.ref ? ` (${job.ref})` : "";
1517
+ const packet = {
1518
+ runId, agent,
1519
+ forwarder: job.forwarder, forwarderEmail: job.forwarderEmail, msgId: job.msgId,
1520
+ conversationId: job.conversationId ?? null,
1521
+ subject: `${[productName, job.ref ?? markNames[0] ?? "batch"].filter(Boolean).join(" — ")} (${nMarks} mark${nMarks === 1 ? "" : "s"})`,
1522
+ emailBodyHtml: emailHtml,
1523
+ // THE SAME ROUTING AS THE CLEARANCE PACKET (part b). This read
1524
+ // `AGENT_WHATSAPP[agent]`, and every user of a deployment shares one agent id, so every knockout
1525
+ // completion paged the operator and told the person who ordered it nothing. The clearance packet
1526
+ // was moved off that and this one was not, which is the half that shipped: one call site fixed,
1527
+ // two existing. Where no number is held the packet now SAYS so in `whatsappToReason` rather than
1528
+ // substituting the operator silently.
1529
+ //
1530
+ // The failure notice (run-failed.mjs, buildFailurePacket) routes the same way. It used to keep `AGENT_WHATSAPP[agent]` as an
1531
+ // operational page, but the courier relays it to the requester, who is owed it as they are owed a report, and the
1532
+ // operator keeps the page as the copy beside it.
1533
+ ...whatsappRouting(job, agent),
1534
+ // ONE LINE, N LINKS. This said "Report: <one url>" and on a batch that url is now null, which would
1535
+ // have read "Report: null" — the fail-visible shape doing its job, and still not a line to send. A
1536
+ // batch names every report it produced, in the order the names were ordered.
1537
+ whatsappText: `✅ Knockout screen${refTag} of ${nMarks} mark(s) is done — ${nMarks === 1 ? "rating" : "highest rating"} ${overall}. `
1538
+ + (published.reports.length === 1
1539
+ ? `Report: ${published.reports[0].url}`
1540
+ : `Reports: ${published.reports.map((r) => `${r.mark} ${r.url}`).join(" · ")}`),
1541
+ // `url` is the run's single report, and NULL for a batch — publishKnockout's own rule, carried
1542
+ // through rather than papered over. `reports` is where a batch's documents are, and docs/DELIVERY.md
1543
+ // says so: an integrator that only knows `url` gets null on a batch and fails visibly, instead of
1544
+ // mailing the first of eight names as though it were the answer.
1545
+ url: published.url, reports: published.reports.map((r) => ({ mark: r.mark, url: r.url })),
1546
+ verdict: overall, markName: batchMarkName(markNames),
1547
+ };
1548
+ try { rmSync(join(run.runDir, ".sent")); } catch { /* none */ }
1549
+ try { rmSync(paths(run.runDir).sendReceipts, { force: true }); } catch { /* none */ }
1550
+ try { rmSync(paths(run.runDir).failure); } catch { /* none */ }
1551
+ writeFileSync(paths(run.runDir).delivery, JSON.stringify(packet, null, 2) + "\n");
1552
+ try {
1553
+ mkdirSync(config.outboxDir, { recursive: true });
1554
+ writeFileSync(join(config.outboxDir, `${packet.runId}.pending`), `${agent}\n`);
1555
+ } catch (e) { note(`delivery: outbox marker write skipped (${String(e.message).slice(0, 100)})`); }
1556
+ const deliveredAt = new Date().toISOString();
1557
+ // ── THE TEN-MINUTE BAR, AGAINST THE RUN (ruling 591) ────────────────────────────────────────────
1036
1558
  //
1037
- // ALL of them must be outage-shaped, not merely one. A batch where two marks hit a 429 and one hit a
1038
- // bad key is a broken configuration wearing an outage's clothes; parking it would auto-resume
1039
- // forever and bury the real error. Anything mixed, anything unexplained, stays terminal.
1559
+ // Recorded here because this is the first point at which the run's own span is known: `startedAt` is
1560
+ // in the run's status and `deliveredAt` is the line above. It used to be recorded at the web sweep,
1561
+ // against the sweep's own elapsed time, so both knockouts of 2026-09-26 stated `overBar: false` at
1562
+ // 0.6 and 0.8 minutes while their runs took 14.4 minutes wall — the number beside the bar was not the
1563
+ // number the bar is about.
1040
1564
  //
1041
- // resetsAt is null: the provider does not surface Retry-After through this path, and runner.mjs's
1042
- // postponedDueAt already applies the default backoff for a null. Better an honest null than a
1043
- // fabricated deadline.
1044
- if (outaged.size >= planMarks.length) {
1045
- note(`knockout sweep: all ${planMarks.length} research calls failed with an outage-shaped status — postponing rather than failing the batch`);
1046
- runLog(run.runDir, { event: "knockout-sweep-outage", marks: planMarks.length, executor: source });
1047
- throw new StageFailure("knockout-sweep", "rate_limited", null);
1048
- }
1049
- throw new StageFailure("knockout-sweep", `all ${planMarks.length} research calls failed (executor ${source}) — nothing to assess`, null);
1050
- }
1051
- if (degraded.size) note(`knockout sweep: ${degraded.size}/${planMarks.length} mark(s) degraded — the batch continues (null-results doctrine)`);
1052
- // ── WHAT THE SWEEP COST, BESIDE THE BAR (ruling 570) ─────────────────────────────────────────────
1053
- //
1054
- // The frame chooses each name's places with no cap, so the only way to know what a knockout costs is
1055
- // to record it. Cells come from the RECEIPTS ON DISK rather than the loop's own variables: a resumed
1056
- // run's earlier marks are in the ledger and not in this process, and the ledger is what a reader has
1057
- // afterwards. The bar is recorded, not applied — nothing above or below this line reads it.
1058
- try {
1059
- const rows = readFileSync(K.sweepLedger, "utf8").split("\n").filter(Boolean).map((l) => { try { return JSON.parse(l); } catch { return null; } }).filter(Boolean);
1060
- const cells = rows.reduce((n, r) => n + (Number.isFinite(r?.cells) ? r.cells : 0), 0);
1061
- const places = rows.reduce((n, r) => Math.max(n, Array.isArray(r?.places) ? r.places.length : 0), 0);
1062
- // THE SWEEP'S OWN ELAPSED TIME, UNDER A NAME THAT SAYS SO, and the bar is no longer asserted here.
1063
- // The bar is about the RUN (ruling 591) and this span is one stage of it: both knockouts of
1064
- // 2026-09-26 recorded `overBar: false` at 0.6 and 0.8 minutes while the runs took 14.4 minutes
1065
- // wall, which e2e scored as over. A bar recorded against the wrong quantity is worse than an
1066
- // unrecorded one, because the field's name says it answered the question. It is recorded at
1067
- // delivery instead, where the run's own start is readable.
1068
- const sweepMinutes = Number(((Date.now() - sweepStartedAt) / 60000).toFixed(1));
1069
- runLog(run.runDir, { event: "knockout-sweep-total", marks: planMarks.length, calls: rows.length,
1070
- cells, mostPlacesForOneName: places, sweepMinutes });
1071
- note(`knockout sweep: ${cells} cell(s) across ${rows.length} call(s) in ${sweepMinutes} min`);
1072
- } catch { /* the receipts are the record; a summary that could not be read never fails a sweep */ }
1073
- }
1074
- return { degraded, recovered };
1075
- };
1076
- let sweepRun = null;
1077
- // HANDLED FROM THE START. A sweep that fails while the register is still being read rejects with nothing awaiting it yet, and
1078
- // an unhandled rejection ends the process with no status written. The reading's `finally` and the await below take its failure.
1079
- const startSweep = () => {
1080
- if (!sweepRun) { sweepRun = sweepMarks(); sweepRun.catch(() => {}); }
1081
- return sweepRun;
1082
- };
1083
-
1084
- // 1.5 — STAGE 0.5: the register hit-counts. Pure code — no stage, no model, no turn. It runs
1085
- // BEFORE the sweep because it is the cheap deterministic question and the client sees its answer
1086
- // first; it runs after the frame only so the batch's shape is settled and a frame failure costs
1087
- // nothing at the register. Its own inputs come from the REQUEST, not from the plan (below).
1088
- let registerCounts = null;
1089
- if (probeWanted) {
1090
- koStep(ctx, KO_STEP_REGISTER_COUNT);
1091
- ensureDriverDir(run.runDir);
1092
- // ── THE OWNER LOOKUP, ONCE THE LISTING HAS NAMED THE OWNER AND A COUNT HAS LANDED ──────────────
1093
- //
1094
- // Run after the count gate below, whichever lane went first. A batch where not one mark got a
1095
- // number stops at that gate; on a register that lists first the lookups used to run before it,
1096
- // research calls the batch paid for and then threw away.
1097
- const checkOwners = async (recDoc) => {
1098
- if (!recDoc) return;
1099
- // On the run that produced the issue, the owner's name was on disk 48 seconds before the sweep
1100
- // started and no pass ever searched it: every sweep keys on the TERM, and nothing re-swept on an
1101
- // OWNER once the register named one. The assessment then inferred what the owner sold from the
1102
- // owner's name, and deferred the real answer to a document the run did not hold.
1565
+ // RECORDED, NEVER APPLIED, exactly as before: nothing reads `overBar` and nothing about this run
1566
+ // changes on it.
1103
1567
  //
1104
- // Bounded to promoted filings and deduplicated per owner — on the issue's own run that is ONE
1105
- // extra query. Never throws: a failure produces rows saying the lookup did not answer, and the
1106
- // run publishes (ruling A, 2026-09-07).
1568
+ // AND AN UNREADABLE START SAYS SO RATHER THAN VANISHING. `readRunStatus` answers `{}` when it cannot
1569
+ // read, and a bar quietly omitted because a file was unreadable is an absence that reads as "not
1570
+ // over". So the event always carries the field, and names the reason when it has no span.
1107
1571
  try {
1108
- const owed = ownersOwedACheck(recDoc);
1109
- if (owed.length) {
1110
- const checks = await runOwnerChecks({
1111
- owners: owed, exec: sweep.exec, runDir: run.runDir, ledgerPath: K.ownerCheckLedger,
1112
- rawDir: driverDir(run.runDir, "web-results"), preset: KNOCKOUT_WEB.questionPreset,
1113
- concurrency: 3, // step 3 — the same constant as the sibling calls above
1114
- });
1115
- atomicWrite(K.ownerChecks, JSON.stringify({ schema: 1, checks }, null, 2) + "\n");
1116
- runLog(run.runDir, {
1117
- event: "knockout-owner-checks", owners: owed.length,
1118
- answered: checks.filter((c) => c.ok).length,
1119
- // The count is logged because the ruling is about COST: one promoted filing on the
1120
- // issue's run means one query. A number climbing here is the bound having widened.
1121
- unanswered: checks.filter((c) => !c.ok).length,
1122
- });
1123
- } else {
1124
- runLog(run.runDir, { event: "knockout-owner-checks", owners: 0, answered: 0, unanswered: 0,
1125
- detail: "no promoted filing names a proprietor to search" });
1126
- }
1127
- } catch (e) {
1128
- // Structural only — runOwnerChecks itself never throws. Non-fatal by the same rule as the
1129
- // listing above: a report is never withheld for a check that could not run.
1130
- note(`owner use-check failed (non-fatal): ${e.message}`);
1131
- runLog(run.runDir, { event: "knockout-owner-checks-failed", cause: String(e?.message ?? e).slice(0, 300) });
1132
- }
1133
- };
1134
-
1135
- // resume: a settled prior sidecar is reused cell by cell, so a re-run never re-bills a count that
1136
- // already landed — including across a build that ADDED a predicate, where only the new column is
1137
- // bought (register-count.mjs cellSettled).
1138
- let prior = null;
1139
- try { prior = unfoldFormCounts(JSON.parse(readFileSync(K.registerCounts, "utf8"))); } catch { /* first attempt */ }
1140
- const counted0 = await countRegisterHits({
1141
- // Scope comes from the REQUEST (markRows / job.classes), never from the frame's plan. The plan
1142
- // is a model output, and its per-mark classes may carry the frame's own belt-and-braces
1143
- // inference — fine for shaping a research prompt, wrong for a figure the client reads as
1144
- // "filings in my classes". The names are identical either way (the frame validator enforces
1145
- // one row per instructed mark, verbatim), so this is a scope decision, not a set difference.
1146
- marks: countRowsOf(markRows.map((m) => ({ name: String(m.name), classes: Array.isArray(m.classes) ? m.classes : null })), plan.marks),
1147
- classes: job.classes ?? null, jurisdictions: job.jurisdictions ?? null,
1148
- provider: REGISTER_PROVIDER, capabilities: ctx.registerCaps,
1149
- counter: countExec.count, ledgerPath: K.countLedger, prior,
1150
- joinForms: countExec.source === "provider" && ctx.registerCaps?.exactFormsCountAsOne === true,
1151
- unreachable: ctx.registerUnreachable ?? [], // — computed once at preflight, above
1152
- concurrency: 3, // step 3 — was a knob; no environment ever set it
1153
- // The close-variation fan-out's ceiling. A deployment may buy FEWER forms per mark than the code
1154
- // cap — on Corsearch each form is a billable search — and may not buy more: variantForms clamps
1155
- // to VARIANT_CAP, so this knob can only ever narrow. Unset ⇒ the code cap, which is the answer
1156
- // for every deployment that has not thought about it.
1157
- ...(process.env.CLEAROTRON_KNOCKOUT_VARIANT_CAP ? { variantCap: Number(process.env.CLEAROTRON_KNOCKOUT_VARIANT_CAP) } : {}),
1158
- });
1159
- // A name given in several written forms is counted as each, and reads as one row from here on.
1160
- const doc = foldFormCounts(counted0, markRows.map((m) => ({ name: String(m.name) })), plan.marks);
1161
- const counted = countedMarks(doc);
1162
- // Not one mark got a number. The count IS this product — a batch published now would be a plain
1163
- // knockout wearing a Depth 2 label and price, which is the silent substitution the whole
1164
- // search-policy registry exists to forbid. Terminal, with the provider's own reason on it.
1165
- if (!counted) {
1166
- // The record's cause where a count kept one apart from the reader's line, so the operator reads what to fix.
1167
- const first = doc.marks?.[0]?.counts?.[Object.keys(doc.marks[0].counts)[0]];
1168
- const why = first?.cause ?? first?.unavailable ?? "no reason recorded";
1169
- throw new StageFailure("knockout-register-count",
1170
- `no register count could be taken for any of the ${planMarks.length} mark(s) via ${REGISTER_PROVIDER} (executor ${countExec.source}) — first cause: ${String(why).slice(0, 200)}`, null);
1171
- }
1172
- atomicWrite(K.registerCounts, JSON.stringify(doc, null, 2) + "\n");
1173
- registerCounts = doc;
1174
- runLog(run.runDir, { event: "knockout-register-counts", provider: REGISTER_PROVIDER, executor: countExec.source, marks: doc.marks.length, counted, regions: doc.scope.regions ?? "worldwide" });
1175
- if (counted < doc.marks.length) note(`register counts: ${doc.marks.length - counted}/${doc.marks.length} mark(s) unavailable — the batch continues (they publish as "not available", never as zero)`);
1176
-
1177
- const sweeping = startSweep();
1178
- try { await checkOwners(await readTheRegister({ ctx, job, K, run, agent, markRows, plan, counts: doc, countExec, opts })); }
1179
- finally { await sweeping.catch(() => {}); }
1180
- }
1181
-
1182
- // 2 — the sweep: ONE grid call per mark, receipted, through the clearance grid's own program path.
1183
- // Every spelling the frame named for the mark is searched once on every place it named for the batch,
1184
- // and every result is kept, with no summary (stages-knockout.mjs, KNOCKOUT_WEB). A mark whose call
1185
- // fails is degraded on its own; the rest of the batch goes on.
1186
- const { degraded, recovered } = await startSweep();
1187
-
1188
- // 3 — assess (chunked ≤8/turn; merged + gated in code). DEGRADED per the DISK truth (payload
1189
- // presence), never the in-memory Map alone — resume-proof: a prior attempt's degrades count too.
1190
- // A STOP ASKED FOR WHILE THE TWO RESEARCH BRANCHES RAN ends the run here, with both settled and their work kept: the rating does
1191
- // not start, and the status does not name it as begun. The turn boundary would refuse its first turn anyway.
1192
- if (isCancelled(run.runDir)) throw new RunCancelled("knockout-assess", readCancel(run.runDir));
1193
- koStep(ctx, "Knockout assessment");
1194
- const chunkRows = planMarks.map((m) => {
1195
- const has = existsSync(K.research(kebab(m.name)));
1196
- return { name: m.name, degraded: has ? null : (degraded.get(m.name) ?? "research unavailable (prior attempt)") };
1197
- });
1198
- const chunks = koChunks(chunkRows);
1199
- // the assignment sidecar — the per-chunk validator joins each chunk's marks against THIS (membership
1200
- // is enforced in code, not prompted); deterministic from the frozen plan, so a resume re-mints equal.
1201
- atomicWrite(driverDir(run.runDir, "knockout-chunks.json"),
1202
- JSON.stringify({ schema: 1, chunks: chunks.map((ch) => ch.map((m) => m.name)) }, null, 2) + "\n");
1203
- // a recovered mark's evidence changed — its prior assess chunk is STALE by construction; drop it so
1204
- // the stage re-runs (otherwise the re-sweep was billed for nothing and the fresh payload never read).
1205
- if (recovered.length) {
1206
- for (let c = 0; c < chunks.length; c++) {
1207
- // Both locations: a stale chunk left at the pre-relocation path must be invalidated too, or a
1208
- // resumed run reads the STALE one through the fallback below and the re-sweep is billed for nothing.
1209
- if (chunks[c].some((m) => recovered.includes(m.name)) && (existsSync(K.assessChunk(c)) || existsSync(K.assessChunkLegacy(c)))) {
1210
- try { for (const f of [K.assessChunk(c), K.assessChunkLegacy(c)]) if (existsSync(f)) rmSync(f); runLog(run.runDir, { event: "knockout-assess-invalidated", chunk: c, recovered: chunks[c].filter((m) => recovered.includes(m.name)).map((m) => m.name) }); } catch { /* best-effort */ }
1211
- }
1212
- }
1213
- }
1214
- for (let c = 0; c < chunks.length; c++) {
1215
- await koStage("knockout-assess", ctx, { chunkNo: c, msgCtx: { chunkMarks: chunks[c], chunkTotal: chunks.length, framework: ctx.framework, frameworkMethod: ctx.frameworkMethod ?? null } });
1216
- }
1217
- // ONE COMPOSITION, for the rated batch and for a corrected one: the chunks read, the summary joined, the engine's caveats,
1218
- // the merged gate and the write. A correction that took a shorter road would reach a client through a lighter gate.
1219
- const composeRecord = () => {
1220
- // cardOrder records how this run's page lists a name's cards, so a delivered report re-renders as it was delivered.
1221
- const merged = { schema_version: 1, framework: null, batch: null, cardOrder: KNOCKOUT_CARD_ORDER, marks: [] };
1222
- const summaries = [];
1223
- for (let c = 0; c < chunks.length; c++) {
1224
- // READ prefers the new location and falls back to the pre-relocation one, so a run whose chunks
1225
- // were written before the move (or through the Bash bypass closed) resumes without paying for
1226
- // a re-dispatch. Nothing writes the legacy path any more — see stages-knockout.mjs.
1227
- const chunkPath = existsSync(K.assessChunk(c)) ? K.assessChunk(c) : K.assessChunkLegacy(c);
1228
- const part = JSON.parse(readFileSync(chunkPath, "utf8"));
1229
- if (c === 0) { merged.framework = part.framework ?? { source: ctx.framework.framework_key, ladder: ctx.framework.bands.map((b) => b.label) }; merged.batch = part.batch ?? null; }
1230
- if (typeof part.chunkSummary === "string" && part.chunkSummary.trim()) summaries.push(part.chunkSummary.trim());
1231
- merged.marks.push(...(part.marks ?? []));
1232
- }
1233
- if (!merged.batch) merged.batch = { productContext: plan.batch.productContext, standardCaveats: [] };
1234
- // the WHOLE-batch executive summary = the per-chunk summaries, composed in code (every chunk's
1235
- // validator required one, so no mark's chunk is silently absent — review 2026-07-17)
1236
- merged.batch.executiveSummary = summaries.join("\n\n");
1237
- // ── THE PENDING-REGISTER CAVEAT, CONDITIONAL SINCE RF-10 v3 ────────────────
1238
- //
1239
- // "Ratings reflect our common law assessment. Register analysis may adjust ratings in either
1240
- // direction." This is a CODE DEFAULT that fires when the model supplied no caveat of its own, and
1241
- // turned it from dormant into the thing that ships.
1242
- //
1243
- // BEFORE: a rule in the knockout-assess manual ordered the seat to write that caveat, so the array
1244
- // arrived non-empty and this default almost never fired. THAT RULE IS RETIRED IN THIS SAME BRANCH —
1245
- // the seat is no longer told to write it — so the array now arrives EMPTY and this line injects the
1246
- // sentence unconditionally. Retiring the rule in the doctrine while leaving its default in the code
1247
- // did not remove the caveat; it made it fire on every run.
1248
- //
1249
- // And it is FALSE on the runs it now fires on. The rater is handed this run's fetched register
1250
- // filings and weighs them, so "register analysis may adjust ratings" describes work that already
1251
- // happened. RF-10 v3 (synthesis-rules.md): when register analysis ran AND surfaced live filings,
1252
- // drop the caveat and cite the register evidence directly; where it did not run, it stands and is
1253
- // the honest thing to say.
1254
- //
1255
- // THE DRIVER'S READ, off the run. A seat that could assert whether the register ran could waive its
1256
- // own caveat. Records present AND non-empty: a file that exists with nothing in it is a register
1257
- // that surfaced no filings, which is exactly the case the caveat is still true for.
1258
- // — ONE DERIVATION, shared with the verifier. This was a private copy, and the
1259
- // lint that checks the result did not have it: it required the caveat unconditionally while this
1260
- // injected it conditionally, so any run where the seat supplied its own caveats failed by
1261
- // construction. Two predicates that must agree forever is how they stop agreeing.
1262
- // — THE SAME DERIVATION THE LINT USES. This counted the array, blanks included, so
1263
- // `["", " "]` read as "the rater supplied two" here and as "supplied none" in the verifier. The lint
1264
- // could not see the disagreement because the survivor sentence below silenced it entirely.
1265
- if (raterCaveats(merged.batch.standardCaveats).length === 0 && !registerSurfacedFilings(K.registerRecords)) {
1266
- merged.batch.standardCaveats = ["Ratings reflect our common law assessment. Register analysis may adjust ratings in either direction."];
1267
- }
1268
- if (!Array.isArray(merged.batch.standardCaveats)) merged.batch.standardCaveats = [];
1269
- // ── the survivor sentence, in CODE ( fix 3) ────────────────────────────────────────────────────
1270
- //
1271
- // A mark this lane did not knock out is a SURVIVOR. It is not clear, and the document must not be
1272
- // readable as though it were: the knockout screens, the clearance enumerates, and the whole distance
1273
- // between them is the work that has not happened yet. Two runs on two matters delivered "Medium,
1274
- // complete" while missing almost every mark the lawyer named, because a screen cannot know what it
1275
- // did not look for — so the boundary of the screen is stated by the engine rather than left to the
1276
- // assessing model, which is the one party that cannot see it.
1277
- //
1278
- // APPENDED, never prepended: publish/knockout.mjs's email takes standardCaveats[0], so leading with
1279
- // this would silently replace the standing caveat in the requester's inbox.
1280
- const survivorNote = survivorBoundaryNote(policy);
1281
- if (!merged.batch.standardCaveats.some((c) => SURVIVOR_BOUNDARY_RE.test(String(c))))
1282
- merged.batch.standardCaveats.push(survivorNote);
1283
- // ── the skipped-capability sentence, in CODE, for the survivor sentence's own reason ──────
1284
- //
1285
- // The per-mark degrade above already reaches the client on every row. This is the RUN-level fact
1286
- // underneath twenty identical rows: not "research was unavailable for this name" twenty times, but
1287
- // one capability that never ran on this deployment. The assessing model cannot state it — it is
1288
- // told a mark is degraded, never why the whole screen is — so the engine states it, exactly as it
1289
- // states the survivor boundary two lines up.
1290
- //
1291
- // APPENDED, never prepended, for the same reason the survivor note is: publish/knockout.mjs's email
1292
- // takes standardCaveats[0], and leading with this would silently replace the standing caveat in the
1293
- // requester's inbox.
1294
- const skippedNote = sweep.skipped ? CAPABILITY_SKIPPED_NOTE[sweep.skipped] : null;
1295
- if (skippedNote && !merged.batch.standardCaveats.some((c) => String(c) === skippedNote))
1296
- merged.batch.standardCaveats.push(skippedNote);
1297
- // The merged gate now also validates the TYPED findings and receipts their citations, and it
1298
- // NORMALISES as it validates — each finding's band comes back in the frozen deck's own casing — so
1299
- // it runs BEFORE the artifact is written, not after. The counts are logged because a receipts pass
1300
- // over zero citations is a different fact from a receipts pass, and only the count can tell them
1301
- // apart afterwards.
1302
- // BEFORE THE GATE AND THE WRITE, so the record on disk is the record that ships, and the reviewing
1303
- // pass never addresses a line inside a section that is about to go.
1304
- removeNextStepSections(run.runDir, merged.marks);
1305
- const mv = validateMergedFindings(run.runDir, merged, plan);
1306
- if (!mv.ok) throw new StageFailure("knockout-assess", `merged findings failed the lint: ${mv.failures.join("; ")}`, null);
1307
- runLog(run.runDir, { event: "knockout-receipts", ...mv.receipts });
1308
- atomicWrite(K.findings, JSON.stringify(merged, null, 2) + "\n");
1309
- return merged;
1310
- };
1311
- // `let`, because the reviewing pass below returns a REWRITTEN record rather than editing this one:
1312
- // the original has to survive intact as the thing that ships if the pass cannot finish cleanly.
1313
- let merged = composeRecord();
1314
- // ── THE REVIEWING PASS, AFTER THE RECORD IS ON DISK AND BEFORE ANYTHING READS IT ─────────────────
1315
- //
1316
- // ORDER MATTERS THREE WAYS. The record is written FIRST so the stage's validator has something to
1317
- // join every address against — an address that names no line is refused while the seat can still
1318
- // send a repair turn, rather than reported as unresolved after the stage was declared good. It also
1319
- // means a run that dies inside the pass has already left a complete, valid, deliverable record: the
1320
- // rated one, unrewritten, which is exactly what shipped before this stage existed. And the rewritten
1321
- // record goes back through `validateMergedFindings` before it replaces that one, so nothing reaches
1322
- // a client that has not been through the same gate.
1323
- //
1324
- // NO NEW STEP LABEL. `stepTotal` is derived from `koSteps()`, so adding one would renumber the
1325
- // progress screen a client watches for a pass that takes a minute. It runs inside "Knockout
1326
- // assessment", which is what it is part of.
1327
- merged = await knockoutReviewingPass({ ctx, run, K, merged, plan, chunks, composeRecord });
1328
- try { writeFileSync(K.assessment, String(merged.batch.executiveSummary ?? "")); } catch { /* prose mirror, best-effort */ }
1329
-
1330
- // 4 — publish (report + workbook + meta + index)
1331
- //
1332
- // THE LAST READ OF THE STOP FLAG. Everything above dispatches through the gateway, which reads it
1333
- // before a turn — so on this lane, where publication follows the final stage directly, a stop
1334
- // pressed during that stage was never seen and the report went out anyway.
1335
- assertNotCancelledBeforePublish(run.runDir, "knockout");
1336
- // PAST THE LAST STOPPABLE POINT, RECORDED WHERE IT BECOMES TRUE. The read above is the final one, so
1337
- // from this line on a stop cannot prevent delivery — and the screen must stop promising it will.
1338
- // Written here rather than derived on the screen from a step number: "Report & publish" is step 4 of
1339
- // 5 on this lane, not the last, so any arithmetic over stepN would name the wrong step and go stale
1340
- // the day a lane's list changes.
1341
- writeRunStatus(ctx, { stoppable: false });
1342
- koStep(ctx, "Report & publish");
1343
- const overall = worstBand(ctx.framework, merged.marks);
1344
- // A set-aside filing the rating cites moves up with the carried ones, so the report has its row.
1345
- try {
1346
- const held = JSON.parse(readFileSync(K.registerRecords, "utf8"));
1347
- const moved = withCitedFilings(held, merged);
1348
- if (moved !== held) atomicWrite(K.registerRecords, JSON.stringify(moved, null, 2) + "\n");
1349
- } catch { /* no record on this run, or none readable: publish says which */ }
1350
- const published = await publishKnockout({
1351
- runId, codename: run.codename, runDir: run.runDir,
1352
- findings: merged, plan, framework: ctx.framework, overall,
1353
- poolRoot: config.poolRoot,
1354
- // THE FALLBACK HERE COULD NOT FIRE, AND COULD NOT HAVE HELPED IF IT HAD. It read
1355
- // `config.poolUrl ?? envFrom(process.env, "CLEAROTRON_REPORTS_URL") ?? null`. Two things were wrong
1356
- // with it and both were invisible: the getter returns "" when the variable is unset, and `??` only
1357
- // falls through on null or undefined — so the second operand was unreachable — and that second
1358
- // operand read the same `process.env` the getter had just read, so reaching it would have returned
1359
- // the same empty answer. A reader saw a safety net twice over where there was none.
1360
- //
1361
- // `|| null` instead, which says the one true thing: no base URL configured, so no link. That is the
1362
- // state `reportUrlFor` already handles by returning null per report rather than an empty string, and
1363
- // a null link is what the delivery packet is specified to carry when no pool URL is set.
1364
- poolUrl: config.poolUrl || null,
1365
- customerKey: ctx.profile?.profileKey ?? "generic",
1366
- // — the frozen profile's delivery overlay decides the confidentiality marking, exactly as it
1367
- // does on the clearance lane. Absent (an unbound run, or a profile silent on the field) is the
1368
- // NO-OPINION state and gets the plain default; only an explicit `privileged:false` suppresses it.
1369
- delivery: ctx.profile?.delivery,
1370
- searchPolicy: policy, tokens: (() => { try { return rollupTokens(run.runDir).total; } catch { return null; } })(),
1371
- registerCounts,
1372
- });
1373
- runLog(run.runDir, { event: "knockout-published", url: published.url, reports: published.reports.map((r) => ({ mark: r.mark, url: r.url })), overall, marks: merged.marks.length });
1374
- // The knockout lane put its token total in the PUBLISHED ARTIFACT but never stamped the run itself,
1375
- // so `status.json.tokens` was empty for every Stage-0 run however it ended (fixed 2026-07-28) — and
1376
- // a Stage-0 run appeared in no account-level consumption view at all.
1377
- recordRunConsumption(ctx, { phase: "delivered", tokens: stampTokenRollup(run.runDir, "delivered") });
1378
-
1379
- // 5 — delivery handoff (byte-faithful to pipelineInner's packet contract; cross-ref pipeline.mjs)
1380
- koStep(ctx, "Sending to you");
1381
- // qcFlags: the projected predelivery-lint lines publishKnockout just computed and recorded — the
1382
- // cover note enumerates exactly what the workbook does (A10, extended to this lane 2026-07-31).
1383
- // They are FLAGS: the packet, the state and the send below are byte-identical with or without them.
1384
- const emailHtml = composeKnockoutEmail({ findings: merged, framework: ctx.framework, overall, reports: published.reports, auditUrl: published.auditUrl, job, registerCounts, qcFlags: published.qcFlags });
1385
- writeFileSync(K.emailBody, emailHtml);
1386
- const nMarks = merged.marks.length;
1387
- const refTag = job.ref ? ` (${job.ref})` : "";
1388
- const packet = {
1389
- runId, agent,
1390
- forwarder: job.forwarder, forwarderEmail: job.forwarderEmail, msgId: job.msgId,
1391
- conversationId: job.conversationId ?? null,
1392
- subject: `Knockout trademark review — ${job.ref ?? markNames[0] ?? "batch"} (${nMarks} mark${nMarks === 1 ? "" : "s"})`,
1393
- emailBodyHtml: emailHtml,
1394
- // THE SAME ROUTING AS THE CLEARANCE PACKET (part b). This read
1395
- // `AGENT_WHATSAPP[agent]`, and every user of a deployment shares one agent id, so every knockout
1396
- // completion paged the operator and told the person who ordered it nothing. The clearance packet
1397
- // was moved off that and this one was not, which is the half that shipped: one call site fixed,
1398
- // two existing. Where no number is held the packet now SAYS so in `whatsappToReason` rather than
1399
- // substituting the operator silently.
1400
- //
1401
- // The failure notice below routes the same way (buildFailurePacket). It used to keep `AGENT_WHATSAPP[agent]` as an
1402
- // operational page, but the courier relays it to the requester, who is owed it as they are owed a report, and the
1403
- // operator keeps the page as the copy beside it.
1404
- ...whatsappRouting(job, agent),
1405
- // ONE LINE, N LINKS. This said "Report: <one url>" and on a batch that url is now null, which would
1406
- // have read "Report: null" — the fail-visible shape doing its job, and still not a line to send. A
1407
- // batch names every report it produced, in the order the names were ordered.
1408
- whatsappText: `✅ Knockout screen${refTag} of ${nMarks} mark(s) is done — ${nMarks === 1 ? "rating" : "highest rating"} ${overall}. `
1409
- + (published.reports.length === 1
1410
- ? `Report: ${published.reports[0].url}`
1411
- : `Reports: ${published.reports.map((r) => `${r.mark} ${r.url}`).join(" · ")}`),
1412
- // `url` is the run's single report, and NULL for a batch — publishKnockout's own rule, carried
1413
- // through rather than papered over. `reports` is where a batch's documents are, and docs/DELIVERY.md
1414
- // says so: an integrator that only knows `url` gets null on a batch and fails visibly, instead of
1415
- // mailing the first of eight names as though it were the answer.
1416
- url: published.url, reports: published.reports.map((r) => ({ mark: r.mark, url: r.url })),
1417
- verdict: overall, markName: batchMarkName(markNames),
1418
- };
1419
- try { rmSync(join(run.runDir, ".sent")); } catch { /* none */ }
1420
- try { rmSync(driverDir(run.runDir, "send-receipts.json"), { force: true }); } catch { /* none */ }
1421
- try { rmSync(driverDir(run.runDir, "failure.json")); } catch { /* none */ }
1422
- writeFileSync(driverDir(run.runDir, "delivery.json"), JSON.stringify(packet, null, 2) + "\n");
1423
- try {
1424
- mkdirSync(config.outboxDir, { recursive: true });
1425
- writeFileSync(join(config.outboxDir, `${packet.runId}.pending`), `${agent}\n`);
1426
- } catch (e) { note(`delivery: outbox marker write skipped (${String(e.message).slice(0, 100)})`); }
1427
- const deliveredAt = new Date().toISOString();
1428
- // ── THE TEN-MINUTE BAR, AGAINST THE RUN (ruling 591) ────────────────────────────────────────────
1429
- //
1430
- // Recorded here because this is the first point at which the run's own span is known: `startedAt` is
1431
- // in the run's status and `deliveredAt` is the line above. It used to be recorded at the web sweep,
1432
- // against the sweep's own elapsed time, so both knockouts of 2026-09-26 stated `overBar: false` at
1433
- // 0.6 and 0.8 minutes while their runs took 14.4 minutes wall — the number beside the bar was not the
1434
- // number the bar is about.
1435
- //
1436
- // RECORDED, NEVER APPLIED, exactly as before: nothing reads `overBar` and nothing about this run
1437
- // changes on it.
1438
- //
1439
- // AND AN UNREADABLE START SAYS SO RATHER THAN VANISHING. `readRunStatus` answers `{}` when it cannot
1440
- // read, and a bar quietly omitted because a file was unreadable is an absence that reads as "not
1441
- // over". So the event always carries the field, and names the reason when it has no span.
1442
- try {
1443
- const verdict = knockoutBarVerdict({ startedAt: readRunStatus(run.runDir)?.startedAt, deliveredAt });
1444
- runLog(run.runDir, { event: "knockout-run-total", barMinutes: KNOCKOUT_MINUTES_BAR, ...verdict });
1445
- } catch { /* the bar is a record, never a gate: a summary that could not be written never fails a delivery */ }
1446
- // `tier` beside `verdict` — the same band word under the name the clearance lane records it by, so a
1447
- // reader of either lane's status finds the rating in one place. `verdict` stays as it was.
1448
- writeRunStatus(ctx, { state: "delivered", tier: overall, statement: published.statement, url: published.url, reports: published.reports.map((r) => ({ mark: r.mark, url: r.url })), deliveredAt, sendPending: true, stepIndex: STEPS.length - 1, stepLabel: STEPS[STEPS.length - 1], stepN: STEPS.length, stepTotal: STEPS.length });
1449
- // — the knockout lane's pool copy learns its terminal state the same way,
1450
- // for the same reason: publish returns the pool dir, and `state: "delivered"` is decided after it
1451
- // returns. Same seam, same best-effort contract, no lane-specific exception to write down.
1452
- const stamp = writeSettleStamp(published.poolRunDir, { state: "delivered", tier: overall, deliveredAt, runId: published.runId ?? run.runId, lane: "knockout" });
1453
- if (!stamp.written) note(`delivery: settle stamp not written (${stamp.reason})`);
1454
- endAnswerMemory(run.runDir); // the held answers do not travel into the archive
1455
- const archived = archive(run);
1456
- rollupStatus(run.studioRoot);
1457
- sentinel(archived ?? run.runDir, ".delivered", { verdict: overall, url: published.url, reports: published.reports.map((r) => ({ mark: r.mark, url: r.url })), notified: "pending", sendPending: true, archived, lane: "knockout" });
1458
- note(`=== KNOCKOUT DELIVERED (${nMarks} marks, worst ${overall}) → ${published.reports.map((r) => r.url).join(", ") || "no report URL (pool URL unset)"}${archived ? ` — archived → ${archived}` : ""} ===\n`);
1459
- return { ok: true, verdict: overall, url: published.url, reports: published.reports, runDir: archived ?? run.runDir };
1460
- } catch (e) {
1461
- // rate-limit rides to pipeline()'s postpone catch (the shared park+auto-resume lane)
1462
- if (e instanceof StageFailure && e.rateLimited) throw e;
1463
- // STOPPED BY THE USER — terminal, and it must not take the failure lane below: that lane pushes
1464
- // "❌ … FAILED at …" to the customer over the outbox, and someone who pressed Stop must never be
1465
- // told their search broke. Same shape as the clearance lane's cancel terminal (pipeline.mjs).
1466
- if (e instanceof RunCancelled) {
1467
- note(`[knockout] STOPPED ${run?.codename ?? "run"} at ${e.stage} by user request${e.requestedAt ? ` (asked ${e.requestedAt})` : ""} — terminal, nothing delivered`);
1468
- try { sentinel(run.runDir, ".cancelled", { stage: e.stage, requestedAt: e.requestedAt, via: e.via, lane: "knockout" }); } catch { /* best-effort */ }
1469
- try { runLog(run.runDir, { event: "cancelled", stage: e.stage, lane: "knockout" }); } catch { /* best-effort */ }
1470
- try { recordRunConsumption(ctx, { phase: "cancelled", tokens: stampTokenRollup(run.runDir, "cancelled") }); } catch { /* best-effort */ }
1471
- // — the same builder the clearance lane uses; `lane` is carried because a knockout stop and a
1472
- // clearance stop at the same stage name are different runs.
1473
- writeRunStatus(ctx, { state: "cancelled", failedStage: e.stage,
1474
- reason: stopReason({ stage: `${e.stage} (knockout)`, via: e.via, requestedAt: e.requestedAt }) });
1475
- try { rollupStatus(run.studioRoot); } catch { /* best-effort */ }
1476
- return { ok: false, cancelled: true, failedStage: e.stage, codename: run?.codename ?? null, runDir: run.runDir };
1477
- }
1478
- // ── — THE RECOVERY LADDER THIS LANE NEVER HAD ─────────────────────────────
1479
- //
1480
- // The line that stood here said "NO recovery ladder (a knockout re-run is ~$2)", and the comment
1481
- // below it went further: "There is no recovery machinery on this lane to keep it away from."
1482
- // So ANY validator exhaustion ended the run — dead until a human noticed — which is the exact shape
1483
- // the clearance lane fixed after the VENZY bake: an in-stage ladder exhausted on model vocabulary
1484
- // misses, terminal, and a fresh resume converges with high probability.
1485
- //
1486
- // WHY THE PRICE OBJECTION DOES NOT SURVIVE CLASS-AWARENESS. `decideRecovery` buys a park only where
1487
- // a fresh re-sample is the plausible remedy: TRANSIENT gets the ladder, UNKNOWN gets exactly one
1488
- // park, DETERMINISTIC and FACTUAL get NONE — their repairs already ran at the point of defect, so a
1489
- // re-sample re-derives the same failure. And a signature that already parked once is terminal
1490
- // immediately whatever the class guess said. At ~$2 a re-run the worst case for the common case is
1491
- // one extra run, and the failures that would have burned it are exactly the ones that buy nothing.
1492
- //
1493
- // A DESIGNED REFUSAL BUYS NOTHING, AND THAT IS THE EXISTING BEHAVIOUR PRESERVED, NOT A NEW RULE.
1494
- // countPreflight's refusals, a kebab collision — anything `isDesignedRefusal` already marks — is the
1495
- // PRODUCT answering before model work began, not the engine breaking. Re-sampling a refusal re-earns
1496
- // the same refusal and spends money to do it. The check is FIRST, ahead of every artifact below.
1497
- const reason = e instanceof StageFailure ? e.reason : String(e?.stack ?? e);
1498
- const failedStage = e?.stage ?? "knockout";
1499
- const terminalKind = isDesignedRefusal(e) ? REFUSAL_TERMINAL_KIND : null;
1500
- if (!terminalKind) {
1501
- const parked = knockoutRecoveryPark({ ctx, run, e, reason, failedStage, note });
1502
- // A park writes `.postponed` and NO `.failed`; the runner's `res.postponed` branch re-dispatches
1503
- // it, and `pipeline()` re-enters THIS lane by policy, so a knockout park can never resume as a
1504
- // clearance run. Verified structurally: pipeline.mjs dispatches on `searchPolicy.pipeline`.
1505
- if (parked) return parked;
1506
- }
1507
- // terminal — the ladder above declined to buy a park: .failed + the standard failure packet
1508
- // — WAS THIS THE PRODUCT REFUSING, OR THE ENGINE BREAKING? Asked once, here, and carried into
1509
- // every record this block writes. Null on an ordinary failure, so nothing about an ordinary failure
1510
- // changes shape. That other half — a designed refusal must never reach recovery machinery — was
1511
- // satisfied by construction while the lane had none. It is now satisfied by CODE: the
1512
- // `if (!terminalKind)` above, which asks the refusal question BEFORE the ladder is consulted and is
1513
- // the reason a refusal cannot buy a park. The arms that prove it are in the ladder's own test file.
1514
- // REACHES THIS LANE ( · E11). The fix for "status.json truncates the cause the journal
1515
- // keeps" landed on the clearance terminal and was never ported here, and this is the lane where it
1516
- // bites hardest: countPreflight's refusals run 300–450 characters and every one of them puts the
1517
- // REMEDY in its last sentence. The bare `.slice(0, 200)` cut the refusal at "There is no off",
1518
- // deleting all three of "set the variable and re-run, order a search this deployment covers, or run
1519
- // the plain knockout level" — on a terminal whose entire purpose is to tell an operator what to do.
1520
- // `reason` keeps its 200 chars (it rides the ping); the cut is now STATED and the tail kept beside it.
1521
- const { reason: shortReason, reasonTruncated, reasonFull } = terminalReasonFields(reason);
1522
- sentinel(run.runDir, ".failed", { stage: failedStage, reason, lane: "knockout", terminalKind });
1523
- runLog(run.runDir, { event: "failed", stage: failedStage, reason, lane: "knockout", ...(terminalKind ? { terminalKind } : {}) });
1524
- writeRunStatus(ctx, { state: "failed", failedStage, reason: shortReason, reasonTruncated, reasonFull, terminalKind });
1525
- recordRunConsumption(ctx, { phase: "failed", tokens: stampTokenRollup(run.runDir, "failed") });
1526
- rollupStatus(run.studioRoot);
1527
- // OWED EITHER WAY, mirroring pipelineInner: the flag is armed whichever lane wrote the packet,
1528
- // because mark_sent is the only clear and it settles a failure.json on the same evidence a delivery
1529
- // needs. The marker is NOT duplicated — the primary lane's own packet lands `<runId>.failed.pending`
1530
- // and the *.pending watch matches it; a second `<runId>.pending` would outlive every settle.
1531
- // THE RECORD OF AN OBLIGATION MUST NOT BE CONTINGENT ON THE ACTION IT OBLIGES — clearance parity,
1532
- // and the same defect this lane would have had. `writeOutboxPacket` returns null rather than throwing,
1533
- // so an unwritable outbox reaches the raw marker write below; with the flag after it, that throw took
1534
- // the record of the obligation with it and the run ended failed and NOT owed. Guards first, then the
1535
- // flag, then the writes that can fail.
1536
- let failPingSent = false;
1537
- try { rmSync(join(run.runDir, ".sent")); } catch { /* none */ }
1538
- try { rmSync(driverDir(run.runDir, "send-receipts.json"), { force: true }); } catch { /* none */ }
1539
- // a fresh notice supersedes an older send's skip-guards (a resumed-then-failed-again run must
1540
- // still notify — the .sent/receipts invariant, clearance parity)
1541
- try { writeRunStatus(ctx, { sendPending: true }); } catch (sErr) {
1542
- note(`knockout failure notice could NOT be recorded as owed (${String(sErr?.message ?? sErr).slice(0, 100)}) — the run directory is unwritable`);
1543
- }
1544
- try {
1545
- const rich = buildFailurePacket({
1546
- runId, agent, job, failedStage, shortReason, terminalKind,
1547
- reasonVerbatim: String(reason).slice(0, 1000),
1548
- });
1549
- const packet = {
1550
- kind: "run-failed", ...rich,
1551
- markName: job.markName ?? job.name ?? null, reason: shortReason,
1552
- text: rich.whatsappText, // the short fallback line legacy relays read (clearance parity)
1553
- };
1554
- writeFileSync(driverDir(run.runDir, "failure.json"), JSON.stringify(packet, null, 2) + "\n");
1555
- failPingSent = Boolean(writeOutboxPacket(`${runId}.failed`, packet));
1556
- if (!failPingSent) {
1557
- mkdirSync(config.outboxDir, { recursive: true });
1558
- writeFileSync(join(config.outboxDir, `${runId}.pending`), `${agent}\n`);
1559
- }
1560
- } catch (nfErr) { note(`knockout failure notice is owed but its packet/marker could not be written (${String(nfErr?.message ?? nfErr).slice(0, 100)}) — status.json carries the obligation`); }
1561
- note(`=== KNOCKOUT ${terminalKind === REFUSAL_TERMINAL_KIND ? "REFUSED" : "FAILED"} ${run.codename} at ${failedStage}: ${shortReason} ===\n`);
1562
- // `codename`: this lane's terminals reach the SAME CLI exit as the clearance lane's, and the
1563
- // CLI composes its resume line from the returned identity. Without it a knockout operator is the only
1564
- // one left with a failure and no way to know what to type.
1565
- //
1566
- // `terminalKind` — THE SECOND WRITER'S ONLY INPUT. This return does not stop at the CLI:
1567
- // runner.mjs's queue terminal writes it whole into `<base>.failed.result`, and that sidecar is what
1568
- // the E2E round reads for a run whose dir it cannot resolve (scripts/e2e.mjs readMarkerTerminal:
1569
- // `st?.terminalKind ?? result?.terminalKind`). The marker's own SUFFIX stays `.failed` deliberately
1570
- // — the runner writes exactly three (`done`/`cancelled`/`failed`) and the harness's
1571
- // TERMINAL_BY_SUFFIX_RAN knows exactly those, so a fourth would not read as "refused" anywhere; it
1572
- // would read as UNDETERMINED, which is how a refusal disappears instead of being mislabelled.
1573
- return { ok: false, failedStage, reason, terminalKind, codename: run.codename, runDir: run.runDir };
1574
- }
1572
+ const verdict = knockoutBarVerdict({ startedAt: readRunStatus(run.runDir)?.startedAt, deliveredAt });
1573
+ runLog(run.runDir, { event: "knockout-run-total", barMinutes: KNOCKOUT_MINUTES_BAR, ...verdict });
1574
+ } catch { /* the bar is a record, never a gate: a summary that could not be written never fails a delivery */ }
1575
+ // The turnaround row every run ending writes. A Knockout computes no quote, so the row carries its wall alone.
1576
+ logTurnaroundReconciliation(run.runDir, ctx.quote, "delivered");
1577
+ // `tier` beside `verdict` — the same band word under the name the clearance lane records it by, so a
1578
+ // reader of either lane's status finds the rating in one place. `verdict` stays as it was. The pool copy
1579
+ // learns its terminal state at the same seam as a clearance's (run-shell.mjs).
1580
+ const archived = endTheDeliveredRun({ ctx, run, published, archive, sentinel }, {
1581
+ status: { state: "delivered", tier: overall, statement: published.statement, url: published.url, reports: published.reports.map((r) => ({ mark: r.mark, url: r.url })), deliveredAt, sendPending: true, stepIndex: STEPS.length - 1, stepLabel: STEPS[STEPS.length - 1], stepN: STEPS.length, stepTotal: STEPS.length },
1582
+ settle: { state: "delivered", tier: overall, deliveredAt, runId: published.runId ?? run.runId, lane: "knockout" },
1583
+ delivered: (archivedAt) => ({ verdict: overall, url: published.url, reports: published.reports.map((r) => ({ mark: r.mark, url: r.url })), notified: "pending", sendPending: true, archived: archivedAt, lane: "knockout" }),
1584
+ });
1585
+ note(`=== KNOCKOUT DELIVERED (${nMarks} marks, worst ${overall}) → ${published.reports.map((r) => r.url).join(", ") || "no report URL (pool URL unset)"}${archived ? ` — archived → ${archived}` : ""} ===\n`);
1586
+ return { ok: true, verdict: overall, url: published.url, reports: published.reports, runDir: archived ?? run.runDir };
1587
+ } },
1588
+ ] });
1575
1589
  }