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,18 +11,20 @@
11
11
  // nothing and stops the next reader looking for a gateway.
12
12
  import { existsSync, mkdirSync, readFileSync, statSync, writeFileSync } from "node:fs";
13
13
  import { join, dirname, basename } from "node:path";
14
- import { driverDir } from "../shared/driver-dir.mjs"; //
14
+ import { driverDir, readJson } from "./run-record.mjs"; //
15
15
  import { NO_SEARCH_RESULT, RESEARCH_CORRECTION } from "./research-answers.mjs"; // a search that did not answer supplies no result
16
- import { tmpdir } from "node:os";
17
- import { config, resolveModel, modelFamily, modelSnapshotKind, envOn, envGateOn, preflightEngineBinary, olderThanFloor, ENGINE_BINARIES } from "./driver.config.mjs";
18
- import { probeCliVersion } from "./engine/cli-version.mjs";
16
+ import { config, envOn, envGateOn } from "./driver.config.mjs";
19
17
  import { stageLog, runLog, note, outputMeta } from "./log.mjs";
20
18
  // — the closed disposition set has ONE author; this file dictates it and must not retype it.
21
19
  import { DISPOSITIONS, POSITION_REQUIRED_DISPOSITIONS } from "./findings-model.mjs";
22
20
  import { frozenSnapshot, describeDrift } from "./run-integrity.mjs"; // — the frozen judged-by set across a seat turn
23
21
  import { isCancelled, readCancel, RunCancelled } from "./cancel.mjs";
24
- import { anthropicAgentEngine } from "./engine/anthropic-agent.mjs";
25
- import { openaiAgentEngine, makeCodexHome, releaseCodexHome } from "./engine/openai-agent.mjs";
22
+ import { engineForRun, selectEngine, modelIdOf } from "./engine/registry.mjs";
23
+ import { timeoutCause, turnFailure, nameTheFailure } from "./ladder/turn-failure.mjs";
24
+ import { modelGauge, servingProgram } from "./ladder/model-gauge.mjs";
25
+ import { rescueAttempt } from "./ladder/rescue.mjs";
26
+ import { nextRung } from "./ladder/next-rung.mjs";
27
+ import { stageTools } from "./ladder/stage-tools.mjs";
26
28
  import { resolveAuthMode } from "./engine/auth.mjs";
27
29
  // ABBREVIATED_VALUE_NOTE is no longer imported: it explained the "…" marker on a value the model
28
30
  // had to reproduce EXACTLY, and the only messages that rendered one were the connotation arms telling a
@@ -227,7 +229,7 @@ export function toolWrittenArtifact(p) {
227
229
  ?? TOOL_WRITTEN_PATTERNS.find((r) => r.re.test(base))
228
230
  ?? null;
229
231
  }
230
- import { buildGatherMcpConfig, allowedToolsFor, toolGroupsForStage, recordAxisFor, seatWritesForGroups, withSendUntil } from "./engine/mcp/gather-config.mjs";
232
+ import { withSendUntil } from "./engine/mcp/gather-config.mjs";
231
233
  import { sendReserveMs } from "../providers/_shared/send-until.mjs"; // each turn's plan calls stop sending ahead of its deadline
232
234
  import { everyToolCallRefused } from "./engine/tool-refusal.mjs"; // one definition, shared with the engine probe
233
235
  export { everyToolCallRefused };
@@ -244,7 +246,7 @@ import { KNOCKOUT_RECHECK_RE, knockoutReviewFile, knockoutReviewRefusalsFor } fr
244
246
  import { profilesStoreDir } from "./profiles.mjs";
245
247
  // The supplemental lane's single source (stages.mjs). The import is acyclic — stages.mjs reads
246
248
  // verify/coverage-ledger/config/framework and never reaches back here.
247
- import { REGISTER_ENUMERATE_TOOL, SUPPLEMENTAL_LANE_STEERING, GROUP_READING_STAGES } from "./stages.mjs";
249
+ import { REGISTER_ENUMERATE_TOOL, SUPPLEMENTAL_LANE_STEERING } from "./stages.mjs";
248
250
  // The ONE kill-class discriminator (timeout/status_timeout fails, exit 137, killed, hard-wall/stall
249
251
  // signals; lane_wedge and rate_limited deliberately excluded). Reused verbatim so "a kill" means the
250
252
  // same thing to the exit-1 rescue below as it does to the register taint chain that reads the very
@@ -262,7 +264,7 @@ import { undispatchableFiringDirectives } from "./frame-diff-model.mjs";
262
264
  import { witnessStageMethodology, describeMethodologyDrift } from "./methodology-witness.mjs";
263
265
  // — the meaning-sweep form and its accumulator. Both PURE and acyclic: connotation-search.mjs
264
266
  // imports nothing, disposition-union.mjs imports only it, and neither reaches back here.
265
- import { parsePrRiskResults, connotationObligations, parseDispositionForm, rulingsProse, CONNOTATION_FORM_TOKEN_SRC,
267
+ import { parsePrRiskResults, connotationObligations, parseDispositionForm, CONNOTATION_FORM_TOKEN_SRC,
266
268
  CONNOTATION_UNMATCHED_MARK, CONNOTATION_NO_RESEMBLANCE_MARK, CONNOTATION_FORM_TOKEN_RE } from "./connotation-search.mjs";
267
269
  import { unionDispositionForm, formSidecarPath } from "./disposition-union.mjs";
268
270
  import { unionCoverageForm } from "./coverage-union.mjs";
@@ -290,30 +292,11 @@ import { PLAN_AUDIT_CLASSES } from "./register-plan.mjs"; // — the repair tu
290
292
  // was — CLEAROTRON_GATHER_CONCURRENCY x CLEAROTRON_MAX_CONCURRENT_RUNS, and pipeline.acquireRunSlot, which is
291
293
  // the OTHER user of slot-lock.mjs and is untouched.
292
294
 
293
- export function isEmbeddedFallback(json, stderr = "") {
294
- const m = json?.meta ?? json?.result?.meta ?? {};
295
- return m.transport === "embedded" || m.fallbackFrom === "gateway" || /EMBEDDED FALLBACK/.test(stderr);
296
- }
297
-
298
- // A gateway turn that ran out of time. Three signals: (1) execFile hit its hard kill (timeoutSec+60);
299
- // (2) the gateway hit its OWN turn timeout, after which the CLI auto-falls-back to embedded and that
300
- // attempt errors — surfacing as `EmbeddedAttemptSessionTakeoverError` / "request timed out" on a
301
- // nonzero exit (the v14 delivery failure, previously mislabelled `nonzero_exit_1`); (3) any nonzero
302
- // exit whose wall already reached the configured budget. Distinguished from transient errors so the
303
- // retry policy can give a slow stage ONE longer shot instead of 3 identical doomed attempts.
304
- export const isTimeout = (facts) => timeoutCause(facts) !== null;
305
- export function timeoutCause({ killed, code, wall, stderr = "", timeoutSec }) { // which signal fired, or null
306
- if (killed) return "killed";
307
- if (/EmbeddedAttemptSessionTakeoverError|request timed out|\bETIMEDOUT\b/i.test(stderr)) return "stderr";
308
- return code !== 0 && wall >= timeoutSec ? "wall" : null;
309
- }
295
+ // What a settled turn's failure is called lives in ladder/turn-failure.mjs, and what the ladder does after it in
296
+ // ladder/next-rung.mjs, both carved out of the stage ladder below; these are re-exported so every importer is unchanged.
297
+ export { isEmbeddedFallback, isTimeout, timeoutCause, isLaneWedge, classifyWedge, isOverloaded, attemptTimedOut } from "./ladder/turn-failure.mjs";
298
+ export { warmHardWallStop } from "./ladder/next-rung.mjs";
310
299
 
311
- // A LANE WEDGE: a timeout whose turn moved ZERO tokens — the gateway never admitted it to a command lane (the
312
- // serial `main` lane saturated by the heartbeat sweep). The real signature (teal-bastion 2026-06-15) is a
313
- // hard-kill timeout with a NULL usage envelope, so we key on "fail is a timeout AND no tokens moved" rather than
314
- // on a parsed 0-usage object. A slow-but-working model that times out returns a status_timeout envelope WITH
315
- // usage (admitted) → NOT a wedge. Kept pure + exported so the classifier is unit-tested (it must not misfire on
316
- // admitted turns, and it MUST fire on the null-usage hard-kill that the production incident actually produced).
317
300
  /**
318
301
  * Did this attempt spend its whole derived budget, exit cleanly, and still fail? PURE.
319
302
  *
@@ -345,21 +328,6 @@ export function spentBudgetCleanly({ fail, killed, code, wall, derivedLimitSec }
345
328
  return wall >= derivedLimitSec;
346
329
  }
347
330
 
348
- export function isLaneWedge(fail, usage) {
349
- if (fail !== "timeout") return false;
350
- const moved = (usage?.input || 0) + (usage?.output || 0) + (usage?.cacheRead || 0) + (usage?.cacheWrite || 0);
351
- return moved === 0;
352
- }
353
-
354
- // Final wedge classification at the runStage call site. A 0-token timeout LOOKS like a wedge (isLaneWedge), but a
355
- // HARD-WALL kill (signals.hardWall — the turn ran the full timeout+60 and was SIGKILLed) is a genuine over-budget
356
- // grind, NOT a saturated command lane; labelling it `lane_wedge` wastes a 2-cycle chain retry on a turn that won't
357
- // fit. Keep `lane_wedge` only for a STALL (signals.stalled) or a truly-silent non-hard-wall null-usage kill; a
358
- // hard-wall kill stays `timeout` (gets at most ONE extended shot, then the deferral). PURE + exported for test.
359
- export function classifyWedge(fail, usage, signals) {
360
- if (isLaneWedge(fail, usage) && !signals?.hardWall) return "lane_wedge";
361
- return fail;
362
- }
363
331
 
364
332
  // ── — THE RATE, DERIVED ONCE ──────────────────────────────────────────────────────────────────
365
333
  //
@@ -462,31 +430,7 @@ export function tokensPerSec(usage, wall) {
462
430
  return Math.round((out / w) * 100) / 100;
463
431
  }
464
432
 
465
- // #5b — stop a WARM attempt after ONE try when it ran to the HARD WALL. The warm patch is the one rung that resumes
466
- // a session: it is passed the session that just produced a content failure. If that resumed turn was SIGKILLed at
467
- // the full timeout+60 wall (signals.hardWall, NOT a 0-token stall), break and let the caller record the
468
- // coverage-limited deferral. A warm attempt can itself time out; warmEligible() only stops the attempt AFTER a
469
- // timeout from being warm. A FOLLOWUP IS NOT STOPPED HERE. It is a new stage() call, attempt 1, with no resumeRef,
470
- // so it is a fresh session with its own wall. This rule used to stop it too, on the premise that it resumed an
471
- // already-loaded session, and that premise was false; it now gets the one extended retry any fresh dispatch gets.
472
- // Measured 2026-11-05 over saved runs: no follow-up attempt and no warm attempt had timed out, so neither form of
473
- // the rule had decided a run. A STALL (no hardWall) is NOT stopped here: it keeps its one retry at the same budget,
474
- // since a transient stall can clear. PURE + exported for test: the live path needs a wall-clock kill.
475
- export function warmHardWallStop({ fail, warm, signals }) {
476
- return fail === "timeout" && Boolean(warm) && Boolean(signals?.hardWall);
477
- }
478
433
 
479
- // D3 — Anthropic overload (HTTP 529 / overloaded_error). Through claude -p a 529 surfaces as a FAILED
480
- // turn (nonzero exit) whose result text/stderr carries the overloaded_error envelope — classified
481
- // generically it looked like `nonzero_exit_1` and the ladder re-attempted INSTANTLY, hammering an API
482
- // that just said "go away" (and burning the retry budget in seconds — the 04:30 restart-window shape).
483
- // Detect it and reclassify to `status_overloaded`, the token the normalized --json envelope already
484
- // produces for the same condition: the stage fails on its one model (there is no model cascade), and
485
- // TRANSIENT_RE routes that failure to the recovery park (.postponed + escalating backoff) — the
486
- // existing machinery owns the re-attempt; runStage breaks its own ladder on it (mirrors lane_wedge).
487
- // The 529 match is deliberately ANCHORED (api error / http prefix, or overload vocabulary within the
488
- // same line) so a stray "529" in ordinary output never misroutes a real content failure. PURE + exported.
489
- const OVERLOAD_RE = /overloaded_error|"type"\s*:\s*"overloaded"|\bapi[ _]?error:?\s*529\b|\bhttp\s*529\b|\b529\b[^\n]{0,120}overloaded|overloaded[^\n]{0,120}\b529\b/i;
490
434
  // ── — THE CAUSE HAS TO SURVIVE THE DIGEST, AND `slice(-3)` IS WHY IT DID NOT ──────────────────────
491
435
  //
492
436
  // Both attempt records kept the LAST three non-empty stderr lines. That is the wrong end for the failure
@@ -511,10 +455,6 @@ export function streamDigest(text, { keep = STREAM_DIGEST_KEEP } = {}) {
511
455
  return [...lines.slice(0, keep), `… ${dropped} line(s) elided …`, ...lines.slice(-keep)].join(" ⏎ ");
512
456
  }
513
457
 
514
- export function isOverloaded({ json, stdout = "", stderr = "" } = {}) {
515
- if (json?.status === "overloaded") return true;
516
- return OVERLOAD_RE.test(`${stdout}\n${stderr}`);
517
- }
518
458
 
519
459
  // D3 — inter-attempt retry backoff. The ladder used to re-dispatch the SAME SECOND an attempt failed,
520
460
  // so a failure caused by the environment (the 04:30 gateway restart, a still-booting gateway, a
@@ -545,74 +485,12 @@ export function payloadText(json) {
545
485
  return (json?.result?.payloads ?? []).map((p) => p?.text ?? "").join("\n").trim();
546
486
  }
547
487
 
548
- // ── — WALL RESCUE QUIESCENCE. How long every declared artifact must have been UNTOUCHED when the
549
- // turn settled, for its write to count as provably COMPLETE rather than possibly torn.
550
- //
551
- // The torn-write window is [watchdog decision, child death]: one poll tick plus the SIGTERM→SIGKILL
552
- // escalation (engine/common.mjs killEscalateMs, default 5000ms). 60s is that window with an order of
553
- // magnitude to spare, and the incident clears it by another: on the 2026-08-04 R1 run the
554
- // placement artifact's last write was 13:58:46Z and the wall kill was 14:15:00Z — 974 seconds quiet.
555
- //
556
- // This is the ONE fact a shape validator cannot supply, and it is the entire reason this rescue may do
557
- // what the exit-1 rescue must not. Setting it to 0 is NOT tuning — it deletes the only completeness
558
- // evidence and would rescue post-merge audit 2's torn draft. Disarm with CLEAROTRON_WALL_RESCUE=0 instead.
559
- const wallRescueQuiesceMs = () => 60000; // step 3 — was a knob; no environment ever set it
560
- const wallRescueEnabled = () => !/^(0|off|false|no)$/i.test(String(process.env.CLEAROTRON_WALL_RESCUE ?? "").trim());
561
488
 
562
489
  // ── Engine seam (CLEAROTRON_AI) ──────────────────────────────────────────────────────────────────
563
- // The 14 stages run on the anthropic-agent engine (`claude -p` off-gateway with the stall-watchdog; see
564
- // engine/CONTRACT.md). Its runTurn() returns the normalized tuple runStage consumes
565
- // ({code,killed,wall,stdout,stderr,laneWaitMs,json,usage,sessionRef,signals}); all the
566
- // classification/retry/warm logic below is engine-agnostic. There is no second exec path beside it —
567
- // the comms one-shots that used to have one now write outbox packets and spawn nothing.
568
- //
569
- // Engine registry (provider adapters). The driver orchestration + the classification/retry/warm ladder are
570
- // ENGINE-AGNOSTIC: everything provider-specific lives behind an engine's runTurn() → the normalized tuple. So
571
- // provider CHOICE (e.g. Anthropic → OpenAI) = which adapter is registered and selected via CLEAROTRON_AI —
572
- // NOT a model-name swap: each provider needs its own agentic-runtime adapter (MCP/tools/skills/streaming/resume).
573
- // One is implemented today: `anthropic-agent` (`claude -p`, off-gateway). Adding e.g. `openai-agent` = write
574
- // engine/openai-agent.mjs implementing the same runTurn() contract (engine/CONTRACT.md §1), registerEngine() it,
575
- // and select it via CLEAROTRON_AI — runStage is untouched. (The legacy gateway-bin engine removed in the
576
- // extraction was a *runtime*, not a provider choice, and coupled the driver to one integrator platform.) An
577
- // unknown CLEAROTRON_AI fails loud — no silent wrong-provider run. There are no comms stages: every
578
- // requester-facing event is an outbox packet (docs/DELIVERY.md).
579
- const ENGINES = new Map([
580
- [anthropicAgentEngine.name, anthropicAgentEngine],
581
- [openaiAgentEngine.name, openaiAgentEngine], // second provider adapter (codex exec) — CLEAROTRON_AI=openai-agent
582
- ]);
583
- export const DEFAULT_ENGINE = anthropicAgentEngine.name; // "anthropic-agent" — production default UNCHANGED
584
- /**
585
- * The ids this registry actually holds — read-only, so a SECOND list can be pinned against the first
586
- * rather than drifting away from it in silence. `ENGINE_BINARIES` in driver.config names the
587
- * binary variable per engine and the wizard builds its menu from it; without this, "the wizard offers
588
- * an engine the driver does not ship" and "the driver ships an engine setup cannot reach" are both
589
- * invisible until a reader picks the row that does not exist. Same guarantee the register-provider
590
- * list already has (onboard-wizard.test.mjs, "a new adapter must not be invisible to setup").
591
- */
592
- export function registeredEngines() { return [...ENGINES.keys()]; }
593
- export function registerEngine(engine) {
594
- if (!engine?.name || typeof engine.runTurn !== "function") throw new Error("registerEngine: expected an { name, runTurn } engine adapter");
595
- ENGINES.set(engine.name.toLowerCase(), engine);
596
- }
597
- /**
598
- * The engine for this activation. PROCESS-WIDE, and the missing parameter is the point.
599
- *
600
- * This took a `_stageName` it ignored, under a call-site comment reading "per-stage: CLEAROTRON_AI base,
601
- * comms forced to the gateway, override-able". None of that existed: no per-stage override, no comms
602
- * forcing, no per-job override. `CLEAROTRON_AI` is read from the process env at every activation and
603
- * governs every stage of every job in it.
604
- *
605
- * A comment describing a capability that does not exist is worse than no comment — it gets believed and
606
- * planned against, and the plan only fails once someone tries to use it. Corrected rather than built:
607
- * per-stage selection is an architecture change (a job spec would have to carry the engine, and the
608
- * routing would have to survive resume), not a comment fix.
609
- *
610
- * WHAT THE ABSENCE COSTS, stated so a round plan does not discover it mid-round: **an A/B cannot run
611
- * both engines concurrently on one instance.** Comparing codex against anthropic means flipping
612
- * CLEAROTRON_AI and running sequentially, or standing up a second instance with its own env, pool and
613
- * ports. The same absence blocks routing the refutation reviewer to a different engine for family
614
- * diversity (ENGINE-OPENAI-ADAPTER §6). Recorded in docs/E2E.md, which is where a round plan looks.
615
- */
490
+ // Which adapters exist and which one this activation runs are engine/registry.mjs's; the gateway asks it
491
+ // and names no engine. Re-exported here, so every importer of these names is unchanged.
492
+ export { DEFAULT_ENGINE, registeredEngines, registerEngine, selectEngine } from "./engine/registry.mjs";
493
+
616
494
  // — THE ENGINE'S OWN WRITE GUARANTEE, for the run record.
617
495
  //
618
496
  // The boundary is enforced on the anthropic path and absent on the codex path, and until now nothing
@@ -628,13 +506,6 @@ export const writeBoundaryOf = (engine) => {
628
506
  return v || "undeclared";
629
507
  };
630
508
 
631
- export function selectEngine() {
632
- const id = (process.env.CLEAROTRON_AI || DEFAULT_ENGINE).toLowerCase();
633
- const engine = ENGINES.get(id);
634
- if (!engine) throw new Error(`CLEAROTRON_AI="${id}" is not a registered engine adapter (available: ${[...ENGINES.keys()].join(", ")}). Implement one and registerEngine() it — see engine/CONTRACT.md.`);
635
- return engine;
636
- }
637
-
638
509
  // ── B — THE MEANING-SWEEP ACCUMULATOR IS REGENERATED AND COUNTED BEFORE IT IS JUDGED ───────────────
639
510
  //
640
511
  // Under the typed transport the rulings reach the accumulator at CALL time (disposition-tool.mjs — the
@@ -691,7 +562,7 @@ export function syncDispositionForm(files) {
691
562
  const dir = dirname(String(f)), half = m[1] ?? null;
692
563
  const specPath = driverDir(dir, seat.spec(half));
693
564
  let spec = null;
694
- try { spec = JSON.parse(readFileSync(specPath, "utf8")); }
565
+ try { spec = readJson(specPath); }
695
566
  catch {
696
567
  // No spec sidecar ⇒ a pre-change archived resume: nothing dictated, nothing owed, nothing to count.
697
568
  // A spec that EXISTS and does not parse is a different fact: the stage owes a sweep whose state
@@ -700,9 +571,6 @@ export function syncDispositionForm(files) {
700
571
  return existsSync(specPath) ? { countable: false } : null;
701
572
  }
702
573
  const formPath = spec?.connotation?.dispositions_path;
703
- // No dictated path ⇒ a pre-change spec (an archived run being resumed). Nothing to count, and the
704
- // gate has nothing to judge either — the two agree by construction.
705
- if (!formPath || spec?.connotation?.disposition_required !== true) return null;
706
574
  let recorded = null;
707
575
  try { recorded = parsePrRiskResults(readFileSync(join(dir, seat.ledger(half)), "utf8")); }
708
576
  catch { return { countable: false }; } // owes a sweep; the ledger — the obligations' source — is unreadable
@@ -848,22 +716,23 @@ export function syncPlacementForm(files) {
848
716
  // Anthropic needs none of this: `claude -p --resume` resolves against an ambient store nothing wipes,
849
717
  // which is precisely why warm resume worked there and not here.
850
718
  export async function runStage(name, opts) {
851
- const engineForHome = selectEngine();
852
- let stageCodexHome = null;
853
- if (engineForHome?.name === "openai-agent") {
854
- try { stageCodexHome = makeCodexHome(`stage-${String(name).replace(/[^a-z0-9-]/gi, "_")}-`); }
855
- catch { stageCodexHome = null; } // fall back to the engine's own per-turn home rather than fail a stage
719
+ // The run's own engine: the one it recorded when it started, or the machine's for a run with no record.
720
+ const engineForHome = engineForRun(opts?.runDir);
721
+ let stageHome = null;
722
+ if (engineForHome?.makeStageHome) {
723
+ try { stageHome = engineForHome.makeStageHome(name); }
724
+ catch { stageHome = null; } // fall back to the engine's own per-turn home rather than fail a stage
856
725
  }
857
726
  try {
858
- return await runStageLadder(name, opts, stageCodexHome);
727
+ return await runStageLadder(name, opts, stageHome, engineForHome);
859
728
  } finally {
860
729
  // Deleted when the LADDER settles — every resume that needed it has happened by then. Best-effort:
861
730
  // a home we cannot remove must never turn a completed stage into a failure.
862
- if (stageCodexHome) releaseCodexHome(stageCodexHome);
731
+ if (stageHome) engineForHome.releaseStageHome(stageHome);
863
732
  }
864
733
  }
865
734
 
866
- async function runStageLadder(name, opts, stageCodexHome = null) {
735
+ async function runStageLadder(name, opts, stageHome = null, engine = selectEngine()) {
867
736
  const {
868
737
  agent = config.defaultAgent,
869
738
  message,
@@ -903,53 +772,16 @@ async function runStageLadder(name, opts, stageCodexHome = null) {
903
772
  // agrees with the toolset the attempt actually gets, instead of contradicting the base prompt.
904
773
  const supplementalLane = Array.isArray(excludeTools) && excludeTools.includes(REGISTER_ENUMERATE_TOOL);
905
774
 
906
- const engine = selectEngine(); // process-wide, not per-stage — see selectEngine
907
775
  // Billing-mode (auth) resolution — fail LOUD if a mode claims API billing but has no key (fixes the
908
776
  // anthropic silent-fallthrough WITHOUT editing anthropic-agent.mjs), and give the stamp its value. Frozen
909
777
  // per run (env-derived). The throw is caught by pipelineInner's terminal catch and turned into a run
910
778
  // FAILURE carrying the named auth error on the guaranteed failure-packet lane (verified) — loud + named,
911
779
  // NOT a silent mis-bill. (Same catch as the unknown-engine throw above.)
912
780
  const auth = resolveAuthMode({ engineName: engine.name });
913
- // Two INDEPENDENT engine capability flags (both default ON for an engine that declares neither, so the
914
- // anthropic engine — which sets neither — behaves exactly as before). A future adapter can opt out of
915
- // either without the other:
916
- let gatherMcpConfig, gatherAllowedTools, engineSkillsDir, engineSkillsGrantRoots, engineResolveSkill;
917
- // — the DECLARATION half of the run-dir read grant. `null` means this stage has no recording
918
- // row to declare anything, and the adapter treats unknown as "keep the grant" — so a stage the
919
- // gateway says nothing about is unaffected by that change.
920
- let gatherSeatWrites = null;
921
- // (a) Skills plumbing (usesSkillsDir): a CLI-agentic engine resolves the stage prompts' `skills/…` refs
922
- // against its neutral cwd (a tmpdir) and confines file tools to cwd + --add-dir roots, so hand it the
923
- // compute-skills dir (config.skillsDir — the driver-co-located tree) + this run's dir so it can absolutize
924
- // the refs and grant read(skills)/write(runDir). The agent's own workspace is no longer involved.
925
- if (engine.usesSkillsDir !== false) {
926
- engineSkillsDir = config.skillsDir;
927
- engineSkillsGrantRoots = config.skillsGrantRoots; // layered skills: BOTH roots reach the seat, resolve overlay-first
928
- engineResolveSkill = (rel) => config.resolveSkillPath(rel);
929
- }
930
- // (b) Gather tools (usesGatherMcp): a gather stage gets its tool group's MCP servers + allowedTools;
931
- // tool-free judgment stages get none (lean context). Both current engines get the SAME claude-shaped
932
- // mcpConfig; a codex engine translates it to config.toml internally, so gather-config.mjs is untouched.
933
- if (engine.usesGatherMcp !== false) {
934
- const groups = toolGroupsForStage(name);
935
- if (groups.length) {
936
- // The bound card index rides the same label the grant was resolved from — derived by the SAME
937
- // declared rule (`perAxis`), never by a second string-sniff that could disagree with it.
938
- const cfg = buildGatherMcpConfig(groups, { sessionKey, agent, runDir, recordAxis: recordAxisFor(name)?.axis,
939
- bandGroups: GROUP_READING_STAGES.has(name), correctionPositions: correction?.positions ?? null });
940
- gatherMcpConfig = cfg ? JSON.stringify(cfg) : undefined;
941
- gatherAllowedTools = allowedToolsFor(groups);
942
- gatherSeatWrites = seatWritesForGroups(groups); // — the SAME derivation allowedToolsFor uses
943
- // Per-stage exclusion (copper-lattice re-route): a supplemental-lane register unit loses
944
- // register_enumerate — its judgment additions go through register_propose_supplemental, so the
945
- // free-enumerate hand-transcription lane cannot silently return. Group-level removal is
946
- // infeasible (synthesis + legacy no-plan units share the group); the validator is the backstop.
947
- if (Array.isArray(excludeTools) && excludeTools.length && gatherAllowedTools) {
948
- const drop = new Set(excludeTools);
949
- gatherAllowedTools = gatherAllowedTools.split(" ").filter((t) => !drop.has(t)).join(" ");
950
- }
951
- }
952
- }
781
+ // The stage's tool servers, allowed tools, skills folder and read grants, by the engine's two capability flags
782
+ // (ladder/stage-tools.mjs).
783
+ const { gatherMcpConfig, gatherAllowedTools, gatherSeatWrites, engineSkillsDir, engineSkillsGrantRoots, engineResolveSkill } =
784
+ stageTools({ engine, name, sessionKey, agent, runDir, correction, excludeTools });
953
785
  // EACH TURN'S OWN COPY of the stage's tool config, carrying that turn's time to stop sending: ahead of the turn's
954
786
  // deadline by the reserve, so a plan call returns what it holds while the turn can still write it (send-until.mjs).
955
787
  const turnConfig = (sec) => withSendUntil(gatherMcpConfig, Date.now() + sec * 1000 - sendReserveMs(sec));
@@ -986,29 +818,7 @@ async function runStageLadder(name, opts, stageCodexHome = null) {
986
818
  // entitled to on attempt 2.
987
819
  let formRepairsUsed = 0;
988
820
  let attempt = 0;
989
- // criterion 1 — A WARM TURN THAT NEVER REACHED THE MODEL DOES NOT COST A RUNG, ONCE.
990
- //
991
- // Measured before this existed: a warm turn returning `usage: null` and `runId: null` — the
992
- // startup-death shape, exit 1 under a second, zero tokens — still advanced the ladder. A stage with
993
- // three attempts spent one on a turn that did nothing, which is the defect this issue names: "a
994
- // warm-patch attempt either reaches the model or does not consume a ladder rung."
995
- //
996
- // THE BOUND IS THE WHOLE DESIGN. Refunding unconditionally lets a warm turn that never lands loop
997
- // until the wall. ONE free rung per ladder is the concession; a second zero-usage warm turn in the
998
- // same ladder is charged, and the record says so rather than leaving the difference to be inferred.
999
- //
1000
- // PROVISIONAL, and deliberately one line to change: the number below is a routed parameter (2026-08-22),
1001
- // not a measured optimum. Nobody has yet counted how often a second free rung would have
1002
- // converted, and until someone does, 1 is the smallest concession that closes the defect.
1003
- //
1004
- // THE CHARGING BRANCH CANNOT FIRE TODAY, and that is stated rather than left to be discovered. `warm`
1005
- // requires `!warmUsed` and `warmUsed` is set the moment one fires, so a ladder gets AT MOST ONE warm
1006
- // turn — there can be no second zero-usage warm turn to charge. This counter is therefore defence, not
1007
- // arithmetic anyone reaches: it keeps the bound LOCAL and explicit, so that if the one-warm-per-ladder
1008
- // invariant is ever relaxed, the refund does not silently become unbounded along with it. Deriving the
1009
- // bound from `warmUsed` instead would have coupled a rung policy to an unrelated rule and hidden the
1010
- // dependency. The arms pin the invariant as the premise rather than pretending to exercise the branch.
1011
- const WARM_ZERO_USAGE_FREE_RUNGS = 1;
821
+ // A warm turn that never reached the model costs no rung, once per ladder: WARM_ZERO_USAGE_FREE_RUNGS in ladder/next-rung.mjs.
1012
822
  let rungsRefunded = 0;
1013
823
  let timeoutRetriesUsed = 0; // a slow stage gets ONE longer shot, then we stop (don't burn 3× the budget)
1014
824
  let effTimeout = timeoutSec; // bumped ×1.5 for the single timeout retry
@@ -1051,12 +861,6 @@ async function runStageLadder(name, opts, stageCodexHome = null) {
1051
861
  note(`[${name}] CANCELLED by user — not dispatching attempt ${attempt}`);
1052
862
  throw new RunCancelled(name, readCancel(runDir));
1053
863
  }
1054
- // D3: inter-attempt backoff (see retryBackoffMs) — a retry dispatched the same second it failed
1055
- // tends to re-hit the same still-booting gateway / still-overloaded provider. Attempt 1 never waits.
1056
- if (attempt > 1) {
1057
- const backoff = retryBackoffMs();
1058
- if (backoff > 0) { note(`[${name}] retry backoff ${backoff}ms before attempt ${attempt}`); await sleep(backoff); }
1059
- }
1060
864
  // Warm patch retry: resume the COMPLETED failed session with only the fix instruction (see design note
1061
865
  // above warmEligible). Otherwise: fresh key + full corrective message (Fix B), exactly as before.
1062
866
  // — the warm patch is VETOED, not de-allowlisted, and the veto keys on the DIRECT STATE:
@@ -1073,6 +877,18 @@ async function runStageLadder(name, opts, stageCodexHome = null) {
1073
877
  if (warm) warmUsed = true;
1074
878
  else if (vetoedResume && !warmUsed && process.env.CLEAROTRON_WARM_RETRY !== "0" && warmEligible(lastFail, lastJson))
1075
879
  note(`[${name}] attempt ${attempt - 1} left this stage's meaning population with ZERO ruled rows (${String(lastFail).slice(0, 100)}) — a resumed session re-reads its own output and cannot rule what it did not rule; SKIPPING the warm patch and dispatching attempt ${attempt} FRESH (the warm attempt is not spent: a partial failure later in this ladder still gets it)`);
880
+ // D3: inter-attempt backoff (see retryBackoffMs) — a retry dispatched the same second it failed
881
+ // tends to re-hit the same still-booting gateway / still-overloaded provider. Attempt 1 never waits.
882
+ // NOT WHEN THE TURN FINISHED AND ONLY THE VALIDATOR REFUSED IT: nothing in the environment failed, so
883
+ // the wait buys nothing and costs the stage its length on the critical path. Known positively, by the
884
+ // predicate the warm patch already uses (the turn's status ok, a validator refusal); a spawn,
885
+ // transport or kill failure still waits.
886
+ if (attempt > 1) {
887
+ const validatorOnly = warmEligible(lastFail, lastJson);
888
+ const backoff = validatorOnly ? 0 : retryBackoffMs();
889
+ if (validatorOnly) note(`[${name}] no retry backoff before attempt ${attempt}: attempt ${attempt - 1} finished and only the validator refused it`);
890
+ else if (backoff > 0) { note(`[${name}] retry backoff ${backoff}ms before attempt ${attempt}`); await sleep(backoff); }
891
+ }
1076
892
  // Snapshot each expected artifact at THIS attempt's start. TWO readers, one base — so they can never
1077
893
  // disagree about what this dispatch emitted:
1078
894
  // · AD-4 emitted-vs-landed telemetry — `wrote` says whether this dispatch WROTE its artifact, as
@@ -1143,7 +959,7 @@ async function runStageLadder(name, opts, stageCodexHome = null) {
1143
959
  // written to disk before the comparison, so the thing being watched cannot reach it. See
1144
960
  // run-integrity.mjs for why it is not a manifest file and why the append-only journals are excluded.
1145
961
  const integrityBefore = frozenSnapshot(runDir);
1146
- const turn = await engine.runTurn({ agent, sessionKey: key, message: effMessage, grantDispatch: base, model, thinking, timeoutSec: effTimeout, resumeRef: warm ? lastSessionRef : undefined, codexHome: stageCodexHome, mcpConfig, allowedTools: gatherAllowedTools, seatWrites: gatherSeatWrites, skillsDir: engineSkillsDir, skillsGrantRoots: engineSkillsGrantRoots, profilesDir: profilesStoreDir, resolveSkill: engineResolveSkill, runDir, stallSec,
962
+ const turn = await engine.runTurn({ agent, sessionKey: key, message: effMessage, grantDispatch: base, model, thinking, timeoutSec: effTimeout, resumeRef: warm ? lastSessionRef : undefined, stageHome, mcpConfig, allowedTools: gatherAllowedTools, seatWrites: gatherSeatWrites, skillsDir: engineSkillsDir, skillsGrantRoots: engineSkillsGrantRoots, profilesDir: profilesStoreDir, resolveSkill: engineResolveSkill, runDir, stallSec,
1147
963
  progressFiles: files, // the no-progress watchdog's artifact-advance signal (anthropic-agent; other adapters ignore it)
1148
964
  // The raw stream of this session, beside its dispatch record (engine/session-record.mjs). The engines
1149
965
  // keep it while the disk has room and say on the tuple's `stream` what landed.
@@ -1217,79 +1033,10 @@ async function runStageLadder(name, opts, stageCodexHome = null) {
1217
1033
  return { fail: null, quantity: null, file: null, graded: null };
1218
1034
  };
1219
1035
 
1220
- // ── corruption 3 — WHAT WAS ASKED FOR vs WHAT ACTUALLY RAN ─────────────────────────────────
1221
- //
1222
- // Until this landed, every model figure on every record was a pure function of the REQUESTED alias:
1223
- // `resolveModel(model)` / `engine.resolveModelId(model)`, computed here without ever looking at the
1224
- // provider's answer. So `--model gemini` logged `google/gemini-3.1-pro-preview` and ran sonnet (the
1225
- // engine's alias table substituted, silently), a haiku stage that bounced to sonnet logged haiku,
1226
- // and every attribution downstream — the A/B arm's manifest, tokens.mjs' per-model rollup, the
1227
- // billing classes — was keyed to a model that had not run. Patching the log would not have fixed
1228
- // it; the log was already saying what the code believed.
1229
- //
1230
- // TWO FIELDS, NEVER COLLAPSED INTO ONE:
1231
- // modelUsed — the requested resolution, unchanged in meaning and value: run-economics.mjs and
1232
- // tokens.mjs both read it, and a field that quietly changes meaning is its own corruption.
1233
- // modelActual — the id the WIRE reported (engine tuple `modelWire`), or NULL when the stream never
1234
- // said: an engine that does not emit one (codex), a turn killed before any event, a
1235
- // spawn error. It NEVER falls back to the requested alias, and `modelBasis` ("actual" or
1236
- // "unknown") never dresses a requested value as an observed one. `providerReported` is
1237
- // the provider word the same stream gave (tuple `providerWire`), null on the same terms.
1238
- const modelRequested = engine.resolveModelId ? engine.resolveModelId(model) : resolveModel(model);
1239
- const modelActual = (typeof turn.modelWire === "string" && turn.modelWire) ? turn.modelWire : null;
1240
- const modelBasis = modelActual ? "actual" : "unknown";
1241
- const providerReported = (typeof turn.providerWire === "string" && turn.providerWire) ? turn.providerWire : null;
1242
- // WHETHER THE OBSERVED ID NAMES A FIXED BUILD. `modelBasis: "actual"` says the provider answered,
1243
- // not that the answer is pinned: two of the three tiers come back as undated aliases the provider
1244
- // may repoint, and recorded beside a dated one they read identically. null when there is nothing to
1245
- // judge, never collapsed into "alias".
1246
- const modelSnapshot = modelSnapshotKind(modelActual);
1247
- // WHICH BUILD OF THE TOOL SERVED THIS TURN. `modelSnapshot` above answers "did the model move";
1248
- // this answers "did the tool move", and the two have one symptom — a run whose judgment differs from
1249
- // last week's. Captured at dispatch rather than read back afterwards, because the binary a reader
1250
- // could probe later is not necessarily the one that ran.
1251
- //
1252
- // Written as an object with its own `probe` field, so an unreadable version is a RECORDED state
1253
- // rather than a missing one. Omitting it on failure would collapse "asked and could not say" into
1254
- // "written before anybody asked", which is the distinction the field exists for. One spawn per
1255
- // binary per process; a probe never throws, because taking down a dispatch to record a version
1256
- // would be a worse defect than the gap it closes.
1257
- // `source` says WHICH copy served (explicit / path / installed), and it is attached here, outside the
1258
- // probe's cache: that cache is keyed by the file, and one file can be reached by more than one route.
1259
- const cli = (() => {
1260
- try {
1261
- const pre = preflightEngineBinary(process.env);
1262
- const probed = probeCliVersion(pre?.resolved ?? null);
1263
- // ── THE FLOOR, COMPARED WHERE THE RUN CAN SEE IT ────────────────────────────────────────
1264
- //
1265
- // The build declares a minimum version for each engine's program, and until now nothing
1266
- // compared a running copy against it. The floor was passed to the installer, so a copy this
1267
- // product installs cannot land beneath it — but resolution walks PATH first and takes the
1268
- // first hit, so a copy already on the machine wins and was never measured against anything.
1269
- // That is the common case, not the edge one: most machines have their own copy. A stage then
1270
- // runs on a program below the floor and is served whatever that program serves, silently.
1271
- //
1272
- // RECORDED, NOT REFUSED. Refusing here would stop every run on any machine whose copy is
1273
- // behind — including ones already deployed and working — and that is a decision about those
1274
- // deployments rather than a defect fix. What was missing is the fact, so the fact is what is
1275
- // written: an operator, and anyone reading the run afterwards, can now see it. Whether it
1276
- // should also refuse is a separate question and is not answered here.
1277
- //
1278
- // THREE-VALUED and written unconditionally, like the model fields below: true, false, or null
1279
- // when either side names no version this build can compare — an unknown is an unknown, never
1280
- // an all-clear. The floor itself rides along so the record says what it was measured against
1281
- // rather than leaving a later reader to guess which build's floor applied.
1282
- const floor = ENGINE_BINARIES[pre?.engine]?.floor ?? null;
1283
- const belowFloor = floor ? olderThanFloor(probed?.version ?? null, floor) : null;
1284
- return { ...probed, source: pre?.source ?? null, floor, belowFloor };
1285
- } catch (e) { return { version: null, probe: "unreadable", why: String(e?.message ?? e).slice(0, 160), source: null, floor: null, belowFloor: null }; }
1286
- })();
1036
+ // What the turn asked for against what the wire reported, and which program served it (ladder/model-gauge.mjs).
1037
+ const { modelRequested, modelActual, modelBasis, providerReported, modelSnapshot, famRequested, famActual, modelMismatch } = modelGauge(engine, model, turn);
1038
+ const cli = servingProgram();
1287
1039
  if (modelActual) lastModelWire = modelActual; // — never overwritten with null
1288
- // The comparison is by FAMILY (driver.config modelFamily), because `--model haiku` legitimately comes
1289
- // back as `claude-haiku-4-5-20251001`. THREE-VALUED: null when either side names no family this
1290
- // build recognises — an unknown is recorded as unknown and never as agreement.
1291
- const famRequested = modelFamily(modelRequested), famActual = modelFamily(modelActual);
1292
- const modelMismatch = (famRequested && famActual) ? famRequested !== famActual : null;
1293
1040
 
1294
1041
  let fail = null;
1295
1042
  let stampedQuantity = null; //: a validator's own exact count, when it stamped one (see below)
@@ -1297,12 +1044,8 @@ async function runStageLadder(name, opts, stageCodexHome = null) {
1297
1044
  // A TURN THAT COMPLETED IS JUDGED ON WHAT IT WROTE, whatever its stderr says about a request inside it
1298
1045
  // (attemptTimedOut). Which signal fired is kept on the row either way.
1299
1046
  const timedOutBy = timeoutCause({ killed, code, wall, stderr, timeoutSec: effTimeout });
1300
- if (attemptTimedOut({ cause: timedOutBy, code, json })) fail = "timeout";
1301
- else if (isEmbeddedFallback(json, stderr)) fail = "embedded_fallback";
1302
- else if (code !== 0) fail = `nonzero_exit_${code}`;
1303
- else if (!json) fail = "unparseable_json";
1304
- else if (json.status !== "ok") fail = `status_${json.status}`;
1305
- else {
1047
+ fail = turnFailure({ timedOutBy, code, json, stderr });
1048
+ if (fail === null) {
1306
1049
  const j = judgeArtifacts();
1307
1050
  fail = j.fail; stampedQuantity = j.quantity; failingFile = j.file; lastGraded = j.graded ?? lastGraded;
1308
1051
  }
@@ -1369,7 +1112,7 @@ async function runStageLadder(name, opts, stageCodexHome = null) {
1369
1112
  // under the run dir to win the grant back, and warmPatchMessage renders the target through rel();
1370
1113
  // a relative path there would silently strip the write root off the one turn that needs it most.
1371
1114
  const rt = await engine.runTurn({ agent, sessionKey: key, message: repairMessage, model, thinking,
1372
- timeoutSec: effTimeout, resumeRef: repairRef, codexHome: stageCodexHome, mcpConfig: turnConfig(effTimeout), allowedTools: gatherAllowedTools,
1115
+ timeoutSec: effTimeout, resumeRef: repairRef, stageHome, mcpConfig: turnConfig(effTimeout), allowedTools: gatherAllowedTools,
1373
1116
  skillsDir: engineSkillsDir, skillsGrantRoots: engineSkillsGrantRoots, profilesDir: profilesStoreDir, resolveSkill: engineResolveSkill, runDir, stallSec,
1374
1117
  progressFiles: files, streamFile: streamFilePath(runDir, name, attempt, formRepairsUsed + 1) });
1375
1118
  repairRef = rt.sessionRef ?? repairRef;
@@ -1404,7 +1147,7 @@ async function runStageLadder(name, opts, stageCodexHome = null) {
1404
1147
  // last line of the stage's telemetry (compare.mjs reads exactly that line).
1405
1148
  stageLog(runDir, name, {
1406
1149
  attempt, key, agent, model,
1407
- modelUsed: (lastModelUsed = engine.resolveModelId ? engine.resolveModelId(model) : resolveModel(model)),
1150
+ modelUsed: (lastModelUsed = modelIdOf(engine, model)),
1408
1151
  // Same billing stamp as the attempt row, written on the same terms — see the note there.
1409
1152
  engine: engine.name, writeBoundary: writeBoundaryOf(engine), authMode: auth.mode, apiBilled: auth.apiBilled === true, cloud: auth.cloud ?? null,
1410
1153
  code: rt.code, wall: rt.wall, timeoutSec: effTimeout,
@@ -1446,7 +1189,7 @@ async function runStageLadder(name, opts, stageCodexHome = null) {
1446
1189
  runLog(runDir, {
1447
1190
  event: "form-repair", stage: name, attempt, repair: formRepairsUsed, of: MAX_FORM_REPAIRS,
1448
1191
  fail: triggeredBy, outcome, landed, ok: outcome === "repaired",
1449
- model: engine.resolveModelId ? engine.resolveModelId(model) : resolveModel(model),
1192
+ model: modelIdOf(engine, model),
1450
1193
  });
1451
1194
  } catch { /* telemetry best-effort — never fail a turn over a journal line */ }
1452
1195
  }
@@ -1456,32 +1199,8 @@ async function runStageLadder(name, opts, stageCodexHome = null) {
1456
1199
  // doctrine, applied inside the dispatch). In all three the ORIGINAL fail goes to the ladder.
1457
1200
  if (outcome !== "moved") break;
1458
1201
  }
1459
- // Exit-1 adapter truth (charter P1 §2): the claude CLI reports a provider error on the FINAL assistant
1460
- // message (an HTTP 500 after the work was done) as subtype:"success" + is_error:true, which the adapter
1461
- // rightly converts to a nonzero exit — but by then the turn's Write already landed the artifact, and
1462
- // re-running finished work burned ~35 min on the R-round evidence run. So before a nonzero exit is
1463
- // accepted as failure, judge the ARTIFACT exactly as the skip path does (exists + validates), with one
1464
- // extra requirement the skip path doesn't need: the file must have been WRITTEN by THIS ATTEMPT
1465
- // (differs from the attempt-start snapshot) — an inherited/stale file, and equally an EARLIER
1466
- // ATTEMPT's file, never rescues a failed turn.
1467
- //
1468
- // A KILL ANYWHERE IN THIS LADDER CLOSES THE RESCUE (post-merge audit 2, 2026-07-31). The design
1469
- // always said the rescue "never applies to a kill — a cut-down turn's artifact may be mid-write";
1470
- // testing only the CURRENT attempt's `killed` honoured that one attempt at a time, so attempt 1 =
1471
- // kill that wrote a torn partial + attempt 2 = nonzero exit shipped the partial as stage truth.
1472
- // Both legs of the fix are needed, because they refuse different things:
1473
- // · the per-attempt snapshot refuses an EARLIER attempt's bytes outright;
1474
- // · `killSeen` refuses this attempt's own write once a kill has torn the file underneath it —
1475
- // freshness is `stat differs`, i.e. a MUTATION, never a proof of complete rewrite (a patch, an
1476
- // append, or a Write killed mid-flush all satisfy it), and a stage `validate` is a SHAPE check,
1477
- // not a completeness proof: the audit repro is a torn draft that passes its own validator.
1478
- // Only register stages carry a backstop for this (register-taint.mjs, on these very rows);
1479
- // synthesis / narrative / cards / digest have none, and synthesis is where the evidence run took its
1480
- // 137 hard-wall kill. This does NOT touch the plain retry ladder register-taint's corpus audit found
1481
- // benign (kill → fresh full redo that EXITS CLEAN): that turn reports completion and is gated on its
1482
- // final state by the normal success path above. The rescue is the opposite case by construction — the
1483
- // turn did not report completion, and completeness of its write is exactly what is unknown.
1484
- // Still never applies to a rate-limit rejection either (0 tokens, nothing written).
1202
+ // Whether this attempt's own artifacts answer its failure is ladder/rescue.mjs (rescueAttempt), with why a kill
1203
+ // anywhere in this ladder closes the exit-1 rescue; `killClass` and `killSeen` carry that kill to it.
1485
1204
  const killClass = isTaintRow({ fail, code, killed, signals: turn.signals });
1486
1205
  // ONE artifact judgement, shared by both rescues below (the rule: never a second, drifting copy of
1487
1206
  // the contract). Present + written by THIS attempt (the per-attempt snapshot — an inherited file and
@@ -1510,95 +1229,10 @@ async function runStageLadder(name, opts, stageCodexHome = null) {
1510
1229
  return true;
1511
1230
  });
1512
1231
  };
1513
- let rescued = null;
1514
- let quiescentMs = null; //: how long the artifact had been untouched when the turn settled
1515
- let rescueRefused = null; //: WHICH of the rescue's four causes refused — on the row, not only in a note
1516
- let rescueRefusedFile = null, rescueRefusedReason = null; //: and which file, and on what
1517
1232
  let attemptRefusals = null; //: this dispatch's refusals of a tool-written artifact, on a timeout
1518
- if (fail && /^nonzero_exit_/.test(fail) && files.length) {
1519
- if (killClass || killSeen) {
1520
- note(`[${name}] ${fail} with a kill-class attempt in this ladder — the exit-1 rescue stays CLOSED (a killed turn's artifact may be torn mid-write and a validator cannot prove it whole); failing honestly instead`);
1521
- } else if (attemptWroteTruth()) {
1522
- rescued = fail;
1523
- fail = null;
1524
- note(`[${name}] ${rescued} but every expected artifact is present, fresh and valid — accepting the artifact as stage truth (a final-message provider error must not re-run finished work)`);
1525
- }
1526
- }
1527
- // ── — THE WALL RESCUE ────────────────────────────────────────────────────────────────────
1528
- //
1529
- // A stage SIGKILLed at its hard wall AFTER it had already written a complete, valid artifact is a
1530
- // stage that SUCCEEDED. Measured on R1 2026-08-04: placement-inquiry walled twice (1861s/1800s and
1531
- // 2760s/2700s, both `wrote: true`, the second `noChange: true`), parked the run — and the resume two
1532
- // minutes later SKIPPED it, because pipeline.mjs's skip predicate found the artifact present and
1533
- // passing its own validator. 77 minutes of dispatch, 335,782 output tokens and one park out of a
1534
- // budget of three, all spent after the deliverable was finished.
1535
- //
1536
- // WHY THIS MAY DO WHAT THE EXIT-1 RESCUE ABOVE MUST NOT. That refusal is not wrong and is not being
1537
- // reversed: post-merge audit 2 pinned a torn draft that CLEARS its own shape validator, and
1538
- // `stat differs` is a mutation, never a proof of complete rewrite. What this arm adds is the one
1539
- // fact neither has — QUIESCENCE. The torn-write window is [watchdog decision, child death]: a poll
1540
- // tick plus the SIGTERM→SIGKILL escalation, single-digit seconds. An artifact that had been
1541
- // untouched for a full minute when the turn settled was not being written when the turn was killed.
1542
- // On the incident the margin was 974 seconds. On the audit's repro it is zero, which is why that
1543
- // fixture still fails exactly as it did.
1544
- //
1545
- // AND IT ADMITS NOTHING THE RESUME WOULD REFUSE. The skip predicate accepts these same bytes minutes
1546
- // later on the same disk; this only stops the run paying a second wall, a park and a resume to reach
1547
- // the same answer. The resume's `!freshness.stale` arm is deliberately NOT copied: it compares
1548
- // declared inputs against a stamp written only on success, so at kill time it is not merely
1549
- // unnecessary but meaningless — and the stage cannot be stale against inputs it has just this moment
1550
- // read and acted on.
1551
- //
1552
- // A stage with no validator, or whose artifact fails it, or which never wrote, is untouched.
1553
- else if (fail === "timeout" && turn.signals?.hardWall && files.length && validate && wallRescueEnabled()) {
1554
- // — A FILE THAT COULD NOT BE STAT'ED IS NAMED, WITH WHY, rather than folded into a number. It
1555
- // used to be a -1 in `quiescentMs` and the cause `artifact-unreadable`, and the commonest way to get
1556
- // there is not a filesystem fault at all: the turn was killed before it wrote. Measured on two
1557
- // stages of one run, 2026-09-10: both rows read `wrote: false`, `quiescentMs: -1`,
1558
- // `artifact-unreadable`, for files that did not exist. An ABSENT file (ENOENT) is its own cause now;
1559
- // `artifact-unreadable` stays for a stat that fails any other way, with its error code. Rows
1560
- // written before this change say `artifact-unreadable` for both.
1561
- //
1562
- // `quiescentMs` IS A MEASUREMENT OR IT IS ABSENT. With a file unstat'able there is no quiescence of
1563
- // the set to measure, so it stays null and the row omits it: a -1 reads as a number to anything that
1564
- // averages or compares it. An mtime that lands after the settle instant (written in that same
1565
- // instant, or a clock step) measures 0 rather than a negative; it is the under-quiescence case.
1566
- let missing = null;
1567
- const quiet = [];
1568
- for (const f of files) {
1569
- try { quiet.push(Math.max(0, settledAt - statSync(f).mtimeMs)); }
1570
- catch (e) { if (!missing) missing = { file: rel(f), code: String(e?.code ?? "unknown") }; }
1571
- }
1572
- quiescentMs = missing || !quiet.length ? null : Math.min(...quiet);
1573
- const bar = wallRescueQuiesceMs();
1574
- const why = {};
1575
- if (quiescentMs !== null && quiescentMs >= bar && attemptWroteTruth(why)) {
1576
- rescued = fail;
1577
- fail = null;
1578
- note(`[${name}] hard-wall kill at ${Math.round(wall)}s, but every expected artifact was written by this attempt, passes its validator and had been untouched for ${Math.round(quiescentMs / 1000)}s when the turn settled — the stage FINISHED and the wall is a fact about the dispatch, not a failure of the stage (the resume's skip path would accept these same bytes)`);
1579
- } else {
1580
- // Said out loud, because "the rescue considered it and refused" and "the rescue never looked"
1581
- // must not be the same silence. This is the file that reads an absence as a diagnosis otherwise.
1582
- //
1583
- // — AND SAID ON THE ROW, not only in a note. The note goes to the operator's console; the
1584
- // JOURNAL is what a later round reads, and `rescued: null` reads identically for all three
1585
- // refusal causes. Measured on the 2026-08-09 R1: placement-inquiry was killed at its
1586
- // hard wall having WRITTEN its artifact and lain quiescent for 371 s against a 60 s bar — so the
1587
- // rescue was refused on the third cause, its validator — and 31 minutes of finished work were
1588
- // discarded and re-run cold. `grep -c rescue run.jsonl` on that run returns 0. Nothing in the
1589
- // record said why, and reconstructing it took a file-mtime comparison against a preserved run dir.
1590
- rescueRefused = missing ? (missing.code === "ENOENT" ? "artifact-absent" : "artifact-unreadable")
1591
- : quiescentMs < bar ? "under-quiescence"
1592
- : "not-written-by-this-attempt-or-invalid";
1593
- // — AND WHICH FILE, AND ON WHAT: an unstat'able file with its error code; under the bar, the file
1594
- // touched last (`quiescentMs` carries the number); otherwise the first file the artifact judgement
1595
- // failed, with its cause — `absent`, `not-written-by-this-attempt`, or the validator's own reason.
1596
- if (missing) { rescueRefusedFile = missing.file; rescueRefusedReason = missing.code; }
1597
- else if (quiescentMs < bar) rescueRefusedFile = rel(files[quiet.indexOf(quiescentMs)]);
1598
- else { rescueRefusedFile = why.file ?? null; rescueRefusedReason = why.reason ?? why.cause ?? null; }
1599
- note(`[${name}] hard-wall kill at ${Math.round(wall)}s — wall rescue REFUSED (${rescueRefused}: ${rescueRefusedFile ?? "no file named"}${rescueRefusedReason ? `, ${rescueRefusedReason}` : quiescentMs < bar ? `, touched ${Math.round(quiescentMs / 1000)}s before the kill, under the ${Math.round(bar / 1000)}s bar` : ""}); failing honestly as timeout`);
1600
- }
1601
- }
1233
+ const rescue = rescueAttempt({ fail, files, killClass, killSeen, signals: turn.signals, validate, wall, settledAt, name, rel, wroteTruth: attemptWroteTruth });
1234
+ fail = rescue.fail;
1235
+ const { rescued, quiescentMs, rescueRefused, rescueRefusedFile, rescueRefusedReason } = rescue;
1602
1236
  // — WHAT A KILLED ATTEMPT WAS DOING, where its transport kept a record. A tool-written artifact's
1603
1237
  // refusal journal says how many times this attempt sent its record and was told no, and the reason the
1604
1238
  // last time. The missing-file row has carried that last reason since the journal existed; a timeout row
@@ -1609,68 +1243,8 @@ async function runStageLadder(name, opts, stageCodexHome = null) {
1609
1243
  // the rescue above needs it; the two can never disagree in reach — isTaintRow excludes lane_wedge, and
1610
1244
  // a wedge is a `timeout` fail that breaks the ladder immediately, so no later attempt exists to judge.
1611
1245
  if (killClass) killSeen = true;
1612
- // Lane-wedge reclassification (see isLaneWedge): a 0-token timeout is a saturated command lane, not a slow
1613
- // model. Becoming `lane_wedge` makes the retry policy skip the wasteful extended shot; stage() (pipeline.mjs)
1614
- // waits for the lane to clear and dispatches the stage again on its one model (a shared lane is not
1615
- // model-specific). teal-bastion 2026-06-15.
1616
- // See classifyWedge: a 0-token timeout is a saturated-lane wedge UNLESS it's a hard-wall over-budget kill.
1617
- fail = classifyWedge(fail, usage, turn.signals);
1618
- // D3: an Anthropic 529/overload hides inside the generic transport tokens (nonzero_exit_1 through
1619
- // claude -p) — reclassify to status_overloaded so it stops the same-model ladder below and rides the
1620
- // recovery park instead. Only the transport shapes are eligible: a timeout/wedge has
1621
- // its own policy, and a content failure must never be laundered into a transient by a stray match.
1622
- if (fail && /^(nonzero_exit_|status_error$|unparseable_json$)/.test(fail) && isOverloaded({ json, stdout: turn.stdout, stderr })) fail = "status_overloaded";
1623
- // Rate-limit / session-cap (429): the standalone engine maps EVERY tier to the one Claude subscription, so
1624
- // a re-run on any tier is futile — classify distinctly (NOT in FALLBACK_ELIGIBLE) and carry resetsAt so the
1625
- // pipeline POSTPONES the run to resetsAt instead of failing it. (Overrides the nonzero_exit_1 a 429 shows as.)
1626
- // Guarded on `fail`: a turn whose finished, validated artifact was just accepted (the exit-1 rescue above)
1627
- // stays accepted — the NEXT stage's first turn hits the same cap at 0 tokens spent and postpones cleanly.
1628
- if (turn.signals?.rateLimited && fail) fail = "rate_limited";
1629
- // AN ENGINE WHOSE SIGN-IN EXPIRED IS NAMED, not left as `nonzero_exit_1`. codex fails its refresh in
1630
- // seconds with a bare exit code while `codex login status` still reports the user signed in, so the
1631
- // one thing that fixes it has to be in the failure itself. AFTER the rate limit, which wins when both
1632
- // appear: a postponed run resumes on its own, and a signed-out one cannot. The sentence rides after
1633
- // the colon, as `model_mismatch:` carries its detail, so no run-level classifier needs a new token.
1634
- else if (turn.signals?.signedOut && fail) fail = `engine_signed_out: ${turn.signals.signedOut}`;
1635
- // AND ONE WHOSE TOOLS WERE ALL REFUSED IS NAMED, not left as the missing file the refusal caused. The
1636
- // turn reported success and the stage failed for want of what its tools would have produced; a
1637
- // `missing_file` reads as a model that did not write, and sends the reader to the wrong place. The
1638
- // sentence says what fixes this host. After the sign-in, which is the more basic fault when both appear.
1639
- else if (turn.signals?.toolsRefused && fail) fail = `engine_tools_refused: ${turn.signals.toolsRefused}`;
1640
- // A6 (addendum 2026-07-30): stop_reason max_tokens with ZERO usable output is a DETECTED FAULT with a
1641
- // name — never a silent paid retry. The turn ran to its output-token ceiling and the artifact never
1642
- // landed (a content fail on a "successful" turn), or the turn itself died at the ceiling (transport
1643
- // shapes) — either way the CAUSE is the output budget, and an unnamed retry just re-buys the same
1644
- // wall. Naming it here makes the stage-log row carry the fault (counted per attempt), routes
1645
- // correctiveMessage to the shrink-your-output correction, and arms the A4 identical-signature break
1646
- // on a second identical hit. The content detail stays appended (hint derivation and the
1647
- // coverage-quarantine joins still read it); the transport shapes go BARE — their tokens
1648
- // (nonzero_exit / unparseable_json) read as TRANSIENT to the run-level classifier (repairs.mjs
1649
- // TRANSIENT_RE is substring-matched) and would silently re-arm the full recovery ladder for a
1650
- // deterministic ceiling fault. Never fires on a rescued turn (fail is already null) nor on the
1651
- // kill/wedge/overload/rate-limit classes (each keeps its own policy).
1652
- if (fail && json?.stopReason === "max_tokens" && /^(missing_file:|invalid_file:|nonzero_exit_|status_error$|unparseable_json$)/.test(fail)) {
1653
- const named = /^(missing_file:|invalid_file:)/.test(fail) ? `max_tokens_no_output:${fail}` : "max_tokens_no_output";
1654
- note(`[${name}] DETECTED FAULT: stop_reason=max_tokens with no usable output (${fail}) → ${named}`);
1655
- fail = named;
1656
- }
1657
-
1658
- // corruption 3, THE ENFORCEMENT — a turn that ran a different model than it was told to is a
1659
- // FAILED turn, not a successful one with an interesting note. Everything the stage produced is
1660
- // attributed to the wrong model, so accepting it would put the corruption on the record permanently
1661
- // (the artifact lands, the row says haiku, sonnet wrote it).
1662
- //
1663
- // Deliberately scoped to `!fail`: a turn that already failed keeps its own cause, because `timeout`
1664
- // and `rate_limited` drive retry policies this must not override. `modelMismatch` is journalled on
1665
- // the row either way, so the mismatch is never lost — only the classification defers.
1666
- //
1667
- // Default-ON gate through `envGateOn` (the rule): `CLEAROTRON_MODEL_WIRE_CHECK=0` disarms it without
1668
- // a deploy if a provider ever starts reporting an id this build's family regex misreads. Disarming
1669
- // silences the REFUSAL, never the record — `modelActual`/`modelMismatch` keep landing on every row.
1670
- if (modelMismatch === true && !fail && envGateOn("CLEAROTRON_MODEL_WIRE_CHECK")) {
1671
- fail = `model_mismatch:${famRequested}->${famActual}`;
1672
- note(`[${name}] MODEL MISMATCH: asked for ${modelRequested} (${famRequested}), the wire says ${modelActual} (${famActual}) — failing the turn. An unhonoured model override is an error, not a substitution; every number attributed to this turn would name the wrong model.`);
1673
- }
1246
+ fail = nameTheFailure(fail, { usage, json, stdout: turn.stdout, stderr, signals: turn.signals, name,
1247
+ gauge: { modelMismatch, famRequested, famActual, modelRequested, modelActual } });
1674
1248
 
1675
1249
  // AD-4 house rule — both computed UNCONDITIONALLY, three-valued on purpose:
1676
1250
  // wrote: did THIS attempt move any expected artifact? true/false when the stage has expected files,
@@ -1963,245 +1537,13 @@ async function runStageLadder(name, opts, stageCodexHome = null) {
1963
1537
  lastSessionRef = turn.sessionRef ?? lastSessionRef; // anthropic warm-resume target for the next attempt
1964
1538
  note(`[${name}] attempt ${attempt} FAILED: ${fail}${quantity === null ? "" : ` (count ${quantity}${noChange ? ", unchanged" : ""})`}`);
1965
1539
 
1966
- // A4 (addendum 2026-07-30): a byte-identical CONTENT failure signature on consecutive attempts is a
1967
- // proven-deterministic defect — the previous attempt already carried this exact validator string and
1968
- // the corrective/warm re-dispatch reproduced it byte-for-byte, so another paid turn cannot converge
1969
- // (VENZY/E2E-R2: 63% of the run was correction, much of it re-buying identical failures). Stop NOW
1970
- // and park honestly: the run-level recovery ladder (classifyFailureReason → one "unknown" park →
1971
- // repeat-signature terminal) owns what happens next, with proper accounting — that lane's single
1972
- // fresh sample replaces the blind third attempt this used to buy. Scoped to the content classes
1973
- // (missing_file / invalid_file / max_tokens_no_output — same stage, same validator string); every
1974
- // transport class keeps its own policy (timeout's single extended shot, and the
1975
- // wedge/overload breaks above and below).
1976
- //
1977
- // BUILD 2 — A4's PREMISE FAILS ON EXACTLY ONE ATTEMPT, AND IT IS THE ONE IT USUALLY FIRES ON.
1978
- // "Another paid turn cannot converge" assumes the two consecutive attempts are independent samples.
1979
- // A warm patch is not a sample: it RESUMES the session that produced the previous failure (key =
1980
- // lastKey, resumeRef = lastSessionRef), so a session that wrote a document with zero rulings writes
1981
- // it again. It has no capacity to disagree with itself, and its repeat proves nothing about whether
1982
- // a fresh dispatch would converge.
1983
- //
1984
- // The 2026-08-07 round measured both sides of this on the meaning-sweep stage. Where it cost a run:
1985
- // fresh ruled 0 of 72 → warm ruled 0 of 72, byte-identical, the artifact never rewritten → A4 broke
1986
- // the ladder at 2 of 3 with attempt 3's budget unspent → RECOVERABLE park, ~90s, one of three defect
1987
- // lanes → the recovery lane then re-dispatched FRESH and ruled 69 of 72. Two dispatches and a park to
1988
- // reach the attempt the ladder still had in hand. The control is the run whose warm attempt MOVED
1989
- // (78 unruled → 1): the string changed, A4 never fired, and cold attempt 3 cleared it in the ladder.
1990
- //
1991
- // So: discard the SESSION, not the ladder. Fall through to attempt N+1, which is necessarily FRESH
1992
- // (`warmUsed` is already spent, so `warm` cannot be true again) and carries the full corrective
1993
- // message. Three existing bounds keep this finite and none of them is new or relaxed here:
1994
- // 1. `warmUsed` caps warm at ONE attempt per stage run, and `warm` is this escalation's trigger —
1995
- // so the escalation can fire at most once per ladder, structurally. It is never reset below.
1996
- // 2. `while (attempt < maxRetries + 1)` is untouched: the ceiling stays 3 attempts in production.
1997
- // 3. The guard below only escalates when a further attempt already exists. With no budget left the
1998
- // break happens exactly as it does today, terminal signal intact.
1999
- // Worst case: fresh(X) → warm(X, escalate) → fresh(X) → A4 fires normally (attempt 3 is not warm) →
2000
- // terminal at 3 attempts.
2001
- //
2002
- // The escalated dispatch does NOT re-buy the paid sweep: perplexity-server short-circuits on a
2003
- // complete recorded ledger ("the sweep is a fact of this run, not of this attempt"), and the seat
2004
- // opens a form already carrying every prior ruling.
2005
- //
2006
- // NOT de-allowlisting the connotation family from WARM_ELIGIBLE_RE instead: on the same round another
2007
- // clearance cleared 61 unruled → 0 on a warm attempt 2. That lane works, and removing it would cost
2008
- // every run that converges on it. This refuses to treat a warm no-op as proof, and nothing more.
2009
- const identicalContent = /^(missing_file:|invalid_file:|max_tokens_no_output)/.test(fail)
2010
- && attemptFails.length >= 2 && attemptFails[attemptFails.length - 2] === fail;
2011
- // ── — THE ESCALATION IS FOR A SEAT THAT PRODUCED SOMETHING ───────────────────────────────
2012
- //
2013
- // BUILD 2 (above) buys ONE fresh attempt after a warm repeat, because a resumed session cannot
2014
- // disagree with itself and its repeat proves nothing about a fresh dispatch. Measured, that is true
2015
- // of a seat whose output was WRONG and false of a seat that wrote nothing at all:
2016
- //
2017
- // invalid_file repeated (the seat produced something) fresh attempt 3 converged 9 of 9
2018
- // missing_file repeated (the seat produced nothing) fresh attempt 3 converged 0 of 6
2019
- //
2020
- // The second case cost ~3.4 min and ~19k output tokens per affected run for an attempt that has never
2021
- // once converged. So the escalation keeps its budget where it pays and stops buying the case where it
2022
- // does not. This is the deterministic-vs-transient line asked for, drawn on what the record
2023
- // already shows before attempt 3 is spent — not a shorter ladder, which would hide the escalation
2024
- // rather than decide it.
2025
- //
2026
- // A CHANGED FAILURE IS NEVER CUT, and that is structural rather than a second condition:
2027
- // `identicalContent` requires this attempt's failure to repeat the previous one byte-for-byte, so a
2028
- // run that moved missing_file → invalid_file never reaches here at all. Two of the measured runs did
2029
- // exactly that, with real quantity — precisely where the ladder earns its keep.
2030
- //
2031
- // `noChange` says the same thing one line up and is NOT read here on purpose: it is RECORDING ONLY,
2032
- // and no break/park/terminate decision reads it ( owns that policy). `identicalContent` is the
2033
- // live signal this branch already decides on, so the rule needs no new input.
2034
- //
2035
- // SIX IS SIX, and all of it from the test box. If a fresh attempt 3 ever converges after a
2036
- // produced-nothing repeat, this is the line to revisit — the note below names the case in the run log
2037
- // so that event is findable rather than silent.
2038
- const producedNothing = /^missing_file:/.test(fail);
2039
- // (round 2) — THE CUT WAS RECORDED AND THE BREAK BESIDE IT WAS NOT, SO THE PATHOLOGY SURVIVED.
2040
- //
2041
- // The comment below says a decision that prevents an attempt must leave a trace. It shipped attached
2042
- // to ONE of the two branches that prevent one. Measured on a delivered run of the test instance (engine 734689e8): the
2043
- // marker `escalationDeclined` appears in ZERO files anywhere in the workspace, because the cut also
2044
- // requires `warm` and that run's attempt rows carry no `warm` field at all — while `"warm"` appears
2045
- // in 98 jsonl files instance-wide, so the absence is the run's, not the field's. With `warm` falsy
2046
- // the run fell through to the pre-existing `else if (identicalContent)` break, which stopped attempt
2047
- // 3 exactly as the cut would have and recorded NOTHING: its note is gated on `warm`, and note() is
2048
- // stderr regardless.
2049
- //
2050
- // `warm` is CORRECT on the cut and is not an accidental narrowing of the decision: the thing being
2051
- // declined is the warm→fresh escalation, which only exists on a warm attempt. On a cold path there is
2052
- // no escalation to decline — the ladder simply breaks. What was narrowed with it was the RECORDING,
2053
- // and both branches end the same way, with budget still in hand.
2054
- //
2055
- // ONE STATEMENT, so a third branch cannot arrive recording a fourth shape. `wouldHaveBeenAttempt` is
2056
- // the number when budget remained and NULL when the ladder was genuinely spent — that is the whole
2057
- // difference between a choice and an ending, and a row that printed `attempt + 1` unconditionally
2058
- // would claim a prevented attempt that never existed.
2059
- // THE RUN SPINE, NOT THE SEAT JSONL — and the first cut had this wrong.
2060
- //
2061
- // `_driver/<stage>.jsonl` IS THE ATTEMPT LEDGER. Nothing states that in one place, and it is relied on
2062
- // everywhere: convergence-ledger derives quantities per row, warm-retry and retry-backoff count rows as
2063
- // attempts, seat-attempts.mjs claims any row carrying `{attempt:int≥1, key, status}` as a dispatch for
2064
- // seat-retry-report's statistics. A decision is not an attempt, and filing one there put a row with no
2065
- // quantity into ledgers that derive quantities — four test files caught it the moment this fired on a
2066
- // path that is actually common. The escalation cut merged into that file first and had the same fault
2067
- // latent: it fires only on warm produced-nothing, so nothing had reached it yet.
2068
- //
2069
- // `run.jsonl` is where this codebase already files the things that are NOT attempts — `form-repair`
2070
- // above, `repair-attempted`, `engine-turn-probe`. It is durable, it is one file per run, and it is the
2071
- // one the wall decomposition deliberately skips. Findable was the requirement; the seat ledger was
2072
- // never what made it so.
2073
- const recordAttemptPrevented = (decision, rule) => {
2074
- try {
2075
- runLog(runDir, {
2076
- event: "attempt-prevented", stage: name, attempt, of: maxRetries + 1, decision, rule,
2077
- fail: String(fail).slice(0, 200),
2078
- warm: Boolean(warm), producedNothing,
2079
- // The whole difference between a CHOICE and an ENDING. Null when the ladder was genuinely spent:
2080
- // printing `attempt + 1` there claims a prevented attempt that never existed, and every count
2081
- // taken off these rows would be high by exactly the runs that had nothing left to prevent.
2082
- // Null and PRESENT — an omitted key cannot be told from a row written before this existed.
2083
- wouldHaveBeenAttempt: attempt < maxRetries + 1 ? attempt + 1 : null,
2084
- });
2085
- } catch { /* telemetry best-effort — never fail a turn over a journal line */ }
2086
- };
2087
- // criterion 1 — the rung decision, recorded on BOTH branches.
2088
- //
2089
- // `usage == null && runId == null` is the seat never having answered: no token count and no run
2090
- // identity, which together mean the turn died before the model saw it. Either alone is weaker —
2091
- // a turn can legitimately report no usage on some paths — so both are required.
2092
- const zeroUsageWarm = Boolean(warm) && fail && usage == null && json?.runId == null;
2093
- if (zeroUsageWarm) {
2094
- const free = rungsRefunded < WARM_ZERO_USAGE_FREE_RUNGS;
2095
- if (free) rungsRefunded++;
2096
- note(`[${name}] attempt ${attempt} [warm patch] returned no usage and no runId — it never reached the model`
2097
- + (free ? `; NOT charging the ladder a rung for it (${rungsRefunded}/${WARM_ZERO_USAGE_FREE_RUNGS} free rungs used)`
2098
- : `; CHARGING it — the ladder has already refunded ${rungsRefunded}, and a second one would let a warm turn that never lands loop`));
2099
- try {
2100
- runLog(runDir, { event: "warm-rung", stage: name, attempt, of: maxRetries + 1 + rungsRefunded,
2101
- rung_free: free,
2102
- reason: free ? "warm turn never reached the model" : "second zero-usage warm turn",
2103
- free_rungs_used: rungsRefunded, free_rungs_max: WARM_ZERO_USAGE_FREE_RUNGS,
2104
- fail: String(fail).slice(0, 200) });
2105
- } catch { /* telemetry best-effort — never fail a turn over a journal line */ }
2106
- }
2107
- // Exactly one row per prevented attempt: the warm produced-nothing case satisfies the cut AND then
2108
- // falls into the break below, and two rows for one decision would double every count taken off them.
2109
- const cutFired = identicalContent && producedNothing && warm && attempt < maxRetries + 1;
2110
- if (cutFired) {
2111
- note(`[${name}] attempt ${attempt} [warm patch] reproduced attempt ${attempt - 1}'s failure byte-for-byte and the seat produced NOTHING either time (${fail.slice(0, 140)}) — NOT escalating to a fresh attempt ${attempt + 1}: measured 0 of 6 convergences on this shape. A seat whose output was merely wrong still escalates.`);
2112
- // THE CUT IS RECORDED, NOT JUST NOTED. `note` is stderr only (log.mjs) and reaches no artifact, so
2113
- // the run record held no trace of a decision that PREVENTS an attempt — and because the cut
2114
- // returns, the prevented attempt never runs. n=6 would therefore be permanent: a seat or model
2115
- // change that made attempt 3 worth buying again could not be noticed, because nothing anywhere
2116
- // counts how often the cut fired or on what. Its own row in the seat's attempt jsonl, where every
2117
- // attempt already lives, is the smallest thing that makes it findable.
2118
- //
2119
- // FINDABILITY ONLY. This samples nothing: the prevented attempt is still prevented, and the row
2120
- // records the case rather than the counterfactual. Re-opening the question needs a deliberate
2121
- // measurement, not a quiet retry ladder that buys one anyway.
2122
- recordAttemptPrevented("escalation-declined:produced-nothing", "#1062");
2123
- }
2124
- if (identicalContent && !producedNothing && warm && attempt < maxRetries + 1) {
2125
- warmEscalatedAt = attempt + 1;
2126
- note(`[${name}] attempt ${attempt} [warm patch] reproduced attempt ${attempt - 1}'s failure byte-for-byte (${fail.slice(0, 140)}) — a resumed session cannot disagree with itself; DISCARDING that session and escalating attempt ${attempt + 1} to a FRESH dispatch (the recovery lane's fresh sample, bought here without the park)`);
2127
- } else if (identicalContent) {
2128
- // — NOT said when the break was a CHOICE. A produced-nothing repeat reaches here with budget
2129
- // still in hand, and "there is no attempt left" would be false: the attempt exists and was
2130
- // deliberately not spent. Its own note above says which case this is.
2131
- if (warm && !producedNothing) note(`[${name}] the warm patch reproduced its own failure and there is no attempt left to escalate to (attempt ${attempt} of ${maxRetries + 1}) — breaking; the fresh sample falls to the recovery lane`);
2132
- note(`[${name}] attempt ${attempt} failed BYTE-IDENTICALLY to attempt ${attempt - 1} (${fail.slice(0, 140)}) — breaking the ladder: same stage, same validator string, further retries are provably futile`);
2133
- // RECORDED, on the path the cut does not reach. This break is the PRE-EXISTING rule and this change
2134
- // does not re-decide it: my 0-of-6 measurement is about the warm→fresh escalation and licenses
2135
- // nothing about a cold break. It makes the population countable, which is what a later ruling on
2136
- // that question would need and could not have had.
2137
- if (!cutFired) recordAttemptPrevented("ladder-break:identical-signature", "#460");
2138
- // A said-back refusal the step left as it was: the pass stands, below, with what it left open recorded.
2139
- if (SAID_BACK_OPEN_RE.test(fail)) break;
2140
- return { ok: false, attempts: attempt, fail, sessionKey: key, modelWire: lastModelWire, modelUsed: lastModelUsed, attemptFails: [...attemptFails], identicalSignature: true, warmEscalated: warmEscalatedAt > 0 || undefined, quantity, noChange, reads, readsTruncated, warm, wrote, formRepairs: formRepairsUsed };
2141
- }
2142
-
2143
- // Lane-wedge: the turn never got a command lane (0 tokens). The extended ×1.5 shot can't help (it produced
2144
- // nothing), and another attempt on a SHARED lane cannot help — so stop here and hand it on fast. The
2145
- // lane-wedge retry in stage() (pipeline.mjs) waits for the lane to clear and dispatches the stage again.
2146
- if (fail === "lane_wedge") break;
2147
- //: a model mismatch is a CONFIGURATION fault, not a transient. The next attempt sends the same
2148
- // argv to the same provider and gets the same substitution, so retrying only buys the wrong model
2149
- // twice. Break immediately and let the stage fail with the mismatch named on every row.
2150
- if (fail.startsWith("model_mismatch:")) {
2151
- note(`[${name}] model mismatch is deterministic — breaking the ladder (a retry re-buys the same wrong model)`);
2152
- break;
2153
- }
2154
- // A sign-in that could not be refreshed refuses every attempt the same way: the next one sends the
2155
- // same credential and gets the same 401, seconds apart. Break, and let the stage fail with it named.
2156
- if (fail.startsWith("engine_signed_out:")) {
2157
- note(`[${name}] the engine's sign-in could not be refreshed — breaking the ladder (a retry re-sends the same credential)`);
2158
- break;
2159
- }
2160
- // EVERY TOOL CALL THE TURN MADE WAS REFUSED. On some hosts codex's own sandbox refuses the stage's
2161
- // tool servers while the turn reports success, and the stage then fails for want of what the tools
2162
- // would have produced. The next attempt spawns the same sandbox and is refused the same way, so a
2163
- // retry re-buys the refusal: measured at three paid attempts per stage on a production run before the
2164
- // identical-failure break stopped it. Break on the first. A turn where any call completed is not this.
2165
- if (everyToolCallRefused(turn)) {
2166
- note(`[${name}] every tool call this turn made was refused (${turn.mcpToolCallsRefused}) — breaking the ladder (a retry is refused the same way)`);
2167
- break;
2168
- }
2169
- // D3: overload (529 / status_overloaded) — stop the ladder here: an in-ladder re-attempt hammers an
2170
- // API that just said it is overloaded, seconds apart, on the SAME model. Breaking hands the failure
2171
- // to the existing machinery: the stage fails on its one model (there is no model cascade), and that
2172
- // failure parks the run for recovery with escalating backoff (TRANSIENT_RE → .postponed).
2173
- if (fail === "status_overloaded") break;
2174
- // Rate-limit: do NOT retry (every retry hits the same capped subscription) and do NOT fall back — return
2175
- // immediately so the pipeline can postpone + auto-resume after the window. resetsAt rides the result.
2176
- if (fail === "rate_limited") return { ok: false, attempts: attempt, fail, resetsAt: turn.signals?.resetsAt, sessionKey: key, modelWire: lastModelWire, modelUsed: lastModelUsed, attemptFails: [...attemptFails], quantity, noChange, reads, readsTruncated, warm, wrote, formRepairs: formRepairsUsed };
2177
- // Timeout-aware retry: a genuinely over-budget/hung stage will just re-time-out on an identical
2178
- // attempt (the v14 delivery burned 3 × 600s). Give it exactly ONE longer shot, then stop.
2179
- if (fail === "timeout") {
2180
- // A WARM attempt, the one rung that resumes a session, that ran to its HARD WALL breaks after this attempt,
2181
- // and the caller records the coverage-limited DEFERRAL (which the gate clamps CLEAR→CONDITIONAL). A
2182
- // FOLLOWUP is a fresh session and is not stopped here: it takes the one extended retry below, as any fresh
2183
- // dispatch does. Until 2026-11-05 a followup stopped here too, on the false premise that it resumed a loaded
2184
- // session. See warmHardWallStop.
2185
- if (warmHardWallStop({ fail, warm, signals: turn.signals })) {
2186
- note(`[${name}] warm attempt hit the hard wall — breaking (recording the deferral)`);
2187
- break;
2188
- }
2189
- if (timeoutRetriesUsed >= 1) {
2190
- note(`[${name}] second timeout — stopping (won't finish on a 3rd identical attempt)`);
2191
- break;
2192
- }
2193
- timeoutRetriesUsed++;
2194
- // Stall honesty (charter P1 §1): a STALL kill (byte-silent or no-progress — signals.stalled) is NOT
2195
- // "the stage needed more time" — the R-round evidence retry did the identical work in 369s after a
2196
- // 1500s stall burn. Retry ONCE at the SAME budget; extending would only extend the next stall's burn.
2197
- // A hard-wall kill (a genuine over-budget grind) keeps the single 1.5× extended shot.
2198
- if (turn.signals?.stalled) {
2199
- note(`[${name}] stall kill${turn.signals?.noProgress ? " (no-progress watchdog)" : ""} → one retry at the SAME ${effTimeout}s budget (a stall is not a slow turn)`);
2200
- } else {
2201
- effTimeout = Math.round(timeoutSec * 1.5);
2202
- note(`[${name}] timeout → one extended retry at ${effTimeout}s`);
2203
- }
2204
- }
1540
+ // What the ladder does next after this failure — escalate, retry, break, or return — is ladder/next-rung.mjs.
1541
+ const next = nextRung({ fail, warm, attempt, maxRetries, attemptFails, usage, json, turn, signals: turn.signals, runDir, name, timeoutSec,
1542
+ saidBackOpen: SAID_BACK_OPEN_RE.test(fail), warmEscalatedAt, rungsRefunded, timeoutRetriesUsed, effTimeout });
1543
+ ({ warmEscalatedAt, rungsRefunded, timeoutRetriesUsed, effTimeout } = next);
1544
+ if (next.rung === "identical") return { ok: false, attempts: attempt, fail, sessionKey: key, modelWire: lastModelWire, modelUsed: lastModelUsed, attemptFails: [...attemptFails], identicalSignature: true, warmEscalated: warmEscalatedAt > 0 || undefined, quantity, noChange, reads, readsTruncated, warm, wrote, formRepairs: formRepairsUsed };
1545
+ if (next.rung === "rate-limited") return { ok: false, attempts: attempt, fail, resetsAt: turn.signals?.resetsAt, sessionKey: key, modelWire: lastModelWire, modelUsed: lastModelUsed, attemptFails: [...attemptFails], quantity, noChange, reads, readsTruncated, warm, wrote, formRepairs: formRepairsUsed };
1546
+ if (next.rung === "break") break;
2205
1547
  }
2206
1548
  // A SAID-BACK REFUSAL NEVER WITHHOLDS THE REPORT (reports always ship, ruled 2026-08-27). The placement form's
2207
1549
  // refusals refuse the pass so that a corrective turn carries them to the step, which is the only way back to it
@@ -2409,14 +1751,16 @@ export const heldSynthesisRecord = (files) => {
2409
1751
  return Boolean(f) && existsSync(synthesisCallPaths(dirname(f)).accepted);
2410
1752
  };
2411
1753
 
2412
- export function correctionHint(lastFail, { gridLedgerName = "common-law-grid.json", supplementalLane = false, undispatchable = [], toolWritten = null, heldRecord = false, adds = false } = {}) {
2413
- // The repair act, for the hints that name one. Kept to a single sentence and a single decision so a
2414
- // new hint has one thing to append rather than a branch to reproduce.
2415
- const resaveClause = toolWritten
2416
- ? `Fix exactly that and send the corrected values — the driver re-derives this file and the prose table together from your \`${toolWritten}\` call, so there is nothing here for you to save`
2417
- : `Fix exactly that, re-save the COMPLETE JSON file, and leave the prose table unchanged`;
2418
- let hint = "the required output file is actually written and contains every required section IN FULL";
2419
- if (CLEARANCE_FINDINGS_TOKEN_RE.test(lastFail)) {
1754
+ // ── THE REPAIR HINTS: ONE ROW PER FAILURE, READ IN ORDER ─────────────────────────────────────────
1755
+ //
1756
+ // Each row names the failure it answers (`code`), the pattern that recognises that failure in the
1757
+ // failure string (`when`), and the end state the corrective turn is told to reach (`hint`). The FIRST row
1758
+ // whose pattern matches answers, so the order is part of the table: a row that must sit above another
1759
+ // says so in its own comments, as the findings row does above the coverage rows. A failure no row
1760
+ // recognises gets REPAIR_HINT_DEFAULT. `failureCode` names the row a failure selects, so a test or a
1761
+ // record can say which repair a turn was handed without matching the sentence.
1762
+ const REPAIR_HINTS = [
1763
+ { code: "findings_contract", when: CLEARANCE_FINDINGS_TOKEN_RE, hint(lastFail, { heldRecord, adds }) {
2420
1764
  // The per-finding machine contract (findings-model.mjs). MUST sit ABOVE the coverage_ branch — a
2421
1765
  // findings_coverage_* token would otherwise route to the (wrong) coverage-ledger hint. The structural
2422
1766
  // "findings-heading" token has no underscore after "findings", so it never matches this branch.
@@ -2467,7 +1811,7 @@ export function correctionHint(lastFail, { gridLedgerName = "common-law-grid.jso
2467
1811
  `findings are NOT rated and carry NO band. The top level carries "rated_under_framework" = the ` +
2468
1812
  `framework key you were told to rate under, verbatim.`;
2469
1813
  }
2470
- hint = `findings.json is a JSON OBJECT { schema_version, rated_under_framework, findings[], coverage[], context_notes[] } ` +
1814
+ return `findings.json is a JSON OBJECT { schema_version, rated_under_framework, findings[], coverage[], context_notes[] } ` +
2471
1815
  `(schema_version 5 additionally allows top-level ask_answers[] = [{ask, answer}], structured mark_assessment fields, ` +
2472
1816
  // review — coverage_judgment.rows USED TO BE LISTED HERE as a key the model may emit, and
2473
1817
  // this is the message the seat reads at the moment it is REPAIRING findings.json: the one turn
@@ -2512,19 +1856,21 @@ export function correctionHint(lastFail, { gridLedgerName = "common-law-grid.jso
2512
1856
  (USE_CHECK_TOKEN_RE.test(lastFail) ? useCheckCorrection(heldRecord, adds)
2513
1857
  : heldRecord && !VERSION_FAILURE_RE.test(lastFail) ? heldRecordRetry(adds)
2514
1858
  : `Fix exactly that, re-save the COMPLETE findings.json, and leave the narrative prose unchanged`);
2515
- } else if (/coverage_status_offenum/.test(lastFail)) {
1859
+ } },
1860
+ { code: "coverage_status_offenum", when: /coverage_status_offenum/, hint(lastFail) {
2516
1861
  // D1 — the off-enum PROSE Status cell (distinct from coverage_status_invalid, which is the JSON
2517
1862
  // mirror's token): the defect lives in register-findings.md's own Coverage-ledger table, so the
2518
1863
  // repair is a one-cell prose relabel — never a JSON re-save. MUST sit above the JSON-mirror
2519
1864
  // coverage_ branch so the shared substring never routes this to the wrong file.
2520
1865
  const det = (lastFail.match(/\(axis ([a-z-]+)/) || [])[1] || ""; // the status text itself may carry parens — anchor on the token's own "(axis …" tail
2521
- hint = `every row of the prose Coverage ledger's Status column is EXACTLY one bare token of ` +
1866
+ return `every row of the prose Coverage ledger's Status column is EXACTLY one bare token of ` +
2522
1867
  `confirmed-clean / coverage-limited / deferred${det ? ` (the off-enum row is on axis ${det})` : ""}. ` +
2523
1868
  `Relabel the offending Status cell(s) to the honest enum token and move any qualifier or commentary ` +
2524
1869
  `("N/A", "confirmed", "not-searched (…)", ✅, bolding) into the Reason column — an axis that was not ` +
2525
1870
  `applicable or not searched is an honest \`deferred\` with the reason stated. Leave every other row ` +
2526
1871
  `and section unchanged`;
2527
- } else if (/coverage_(ledger_unparseable|ledger_empty|axis_invalid|axis_missing|status_invalid|key_unknown|mirror_missing)/.test(lastFail)) {
1872
+ } },
1873
+ { code: "coverage_ledger_shape", when: /coverage_(ledger_unparseable|ledger_empty|axis_invalid|axis_missing|status_invalid|key_unknown|mirror_missing)/, hint(lastFail, { resaveClause }) {
2528
1874
  // Map #3 — `mirror_missing` is LEGACY and never fires anymore (the JSON is code-derived from the prose,
2529
1875
  // so the prose↔JSON cross-check was retired); the alternation keeps it only to give a sane hint to any
2530
1876
  // in-flight pre-Map-#3 run that might surface it. The structure tokens (unparseable/empty/axis_*/status_*/
@@ -2539,7 +1885,7 @@ export function correctionHint(lastFail, { gridLedgerName = "common-law-grid.jso
2539
1885
  // retry was told to redo the very derivation that failed, so it looped until the attempts ran out.
2540
1886
  // The validator's own message carries the allowed list; quote it back rather than re-deriving it here.
2541
1887
  const allowedAxes = (lastFail.match(/\(not in: ([^)]+)\)/) || [])[1] || "";
2542
- hint = `register-coverage-ledger.json is a JSON ARRAY mirroring the prose Coverage ledger — one object ` +
1888
+ return `register-coverage-ledger.json is a JSON ARRAY mirroring the prose Coverage ledger — one object ` +
2543
1889
  `per table row with EXACTLY the keys {"axis","scope","status","reason"}: axis = lowercase text left of ` +
2544
1890
  `the first " / " of the Coverage-unit cell, and it must be ` +
2545
1891
  (allowedAxes ? `EXACTLY one of the run's active axes (${allowedAxes})` : `one of the run's ACTIVE AXES`) +
@@ -2550,21 +1896,24 @@ export function correctionHint(lastFail, { gridLedgerName = "common-law-grid.jso
2550
1896
  `verbatim right side; status = EXACTLY one bare token of confirmed-clean / coverage-limited / deferred ` +
2551
1897
  `(a qualifier like "(count-only, saturated)" moves into reason). The failed check was: ${tok}. ` +
2552
1898
  resaveClause;
2553
- } else if (/use_check_missing/.test(lastFail)) {
2554
- hint = "every Composite-3-or-higher finding whose risk turns on the owner's actual use ENDS with a " +
2555
- "\"**Use-check source:** <result URL | 'perplexity_research — no result'>\" line — run the scoped marketplace " +
2556
- "use-check (owner + mark + goods/field) and cite its result, or state the honest 'no result'; never assert a " +
2557
- "use-negative you did not search";
2558
- } else if (/connotation_form_damaged/.test(lastFail)) {
1899
+ } },
1900
+ { code: "use_check_missing", when: /use_check_missing/, hint(lastFail) {
1901
+ return "every finding the failed check names by number, a finding at a material band whose owner's use is recorded as " +
1902
+ "confirmed or not-confirmed, carries the cite of record in its `use_check.source`: a result URL, or " +
1903
+ "'perplexity_research — no result'. Run the scoped marketplace use-check (owner + mark + goods/field) and record " +
1904
+ "its result there, or record the honest 'no result'; never assert a use-negative you did not search";
1905
+ } },
1906
+ { code: "connotation_form_damaged", when: /connotation_form_damaged/, hint(lastFail) {
2559
1907
  // The accumulator is DRIVER-WRITTEN, so a damaged row is a narrow, nameable fault: a row's recorded
2560
1908
  // receipt is no longer one of that row's own candidates (the ledger regenerates candidates every
2561
1909
  // pass, so a top-up can orphan a recorded id). The remedy is ONE tool call about the named row —
2562
1910
  // never a file edit; the seat writes no dispositions file.
2563
- hint = "every recorded row's receipt is one of THAT ROW's own listed candidates. Re-send ONLY the " +
1911
+ return "every recorded row's receipt is one of THAT ROW's own listed candidates. Re-send ONLY the " +
2564
1912
  "named row(s) through the `record_dispositions` tool with `receipt_index` set to the POSITION of " +
2565
1913
  "the candidate you ruled on in that row's own list (1, 2, …) — never a typed id. Your other rows " +
2566
1914
  "are recorded and KEPT; do not re-send them and do not write any file";
2567
- } else if (/connotation_quote_unbound/.test(lastFail)) {
1915
+ } },
1916
+ { code: "connotation_quote_unbound", when: /connotation_quote_unbound/, hint(lastFail) {
2568
1917
  // — THE ARM THAT MAKES THE LOOP ESCAPABLE. Its own token and its own remedy, deliberately not
2569
1918
  // folded into the no-ruling arm below: the seat this fires on HAS ruled, and telling it to add a
2570
1919
  // ruling is the message R6 received four times before the run died. Every one of those attempts was
@@ -2600,7 +1949,7 @@ export function correctionHint(lastFail, { gridLedgerName = "common-law-grid.jso
2600
1949
  //
2601
1950
  // Each field carries its own imperative in its own sentence — measured a field phrased outside one
2602
1951
  // as written 0 of 9 times against 74 of 74 when imperative-carried.
2603
- hint = "every row owing proof of reading carries BOTH fields. Give `segment_index` — the NUMBER of the " +
1952
+ return "every row owing proof of reading carries BOTH fields. Give `segment_index` — the NUMBER of the " +
2604
1953
  `passage you relied on, in the numbered passages of the receipt you ruled on. And copy \`fragment\` — a ` +
2605
1954
  `few characters taken EXACTLY out of that same passage, in whatever script it is written in. ` +
2606
1955
  `${rowTok ? `The failure names the row (${rowTok}) and every other row is already accepted` : "The failure names the rows"} — ` +
@@ -2608,11 +1957,12 @@ export function correctionHint(lastFail, { gridLedgerName = "common-law-grid.jso
2608
1957
  `through the \`record_dispositions\` tool (keep \`row_index\`, \`ruling\` and ` +
2609
1958
  `\`note\` as you had them) — never write or edit any file. ` +
2610
1959
  `You are POINTING at the passage, not reproducing it — short and exact beats long and approximate. ${where}`;
2611
- } else if (/connotation_call_never_made/.test(lastFail)) {
1960
+ } },
1961
+ { code: "connotation_call_never_made", when: /connotation_call_never_made/, hint(lastFail) {
2612
1962
  // B — rows are owed and no `record_dispositions` call was ever STARTED this run. The one thing R6's
2613
1963
  // dead attempts were never told was WHERE the gate was counting; under the typed transport the
2614
1964
  // answer is a TOOL, and this arm names it. — composed into `Fix exactly this: ensure <hint>.`.
2615
- hint = "every meaning obligation is recorded through the `record_dispositions` tool. NOTHING has been " +
1965
+ return "every meaning obligation is recorded through the `record_dispositions` tool. NOTHING has been " +
2616
1966
  "recorded this run — no call was ever made — and rulings written into your findings prose, or into " +
2617
1967
  "any file, are not read by this check and cannot make it pass. Call `record_dispositions` now with " +
2618
1968
  "`grid_spec_path` (the driver-written spec path your grid instructions name) and `rows`: one entry " +
@@ -2622,43 +1972,37 @@ export function correctionHint(lastFail, { gridLedgerName = "common-law-grid.jso
2622
1972
  "outstanding and which rows still owe proof of reading — a `segment_index` and a `fragment`. " +
2623
1973
  "Rule from what the receipts say, never from memory, " +
2624
1974
  "and carry any loaded reading into Findings as well";
2625
- } else if (/connotation_call_truncated/.test(lastFail)) {
1975
+ } },
1976
+ { code: "connotation_call_truncated", when: /connotation_call_truncated/, hint(lastFail) {
2626
1977
  // B — a call STARTED and never returned: a driver-side or transport fault, NOT a fault in the
2627
1978
  // rulings. The one message a seat must never take from this is "re-derive your rulings".
2628
- hint = "the `record_dispositions` call(s) that never returned are re-sent AS THEY WERE. This is NOT a " +
1979
+ return "the `record_dispositions` call(s) that never returned are re-sent AS THEY WERE. This is NOT a " +
2629
1980
  "fault in your rulings — a call was killed in flight before its rows were recorded, which is the " +
2630
1981
  "driver's fault, not yours. Do not re-derive or change any ruling: call `record_dispositions` again " +
2631
1982
  "with the same rows for whatever the tool's answer still lists as outstanding, and stop when it " +
2632
1983
  "reports nothing outstanding";
2633
- } else if (/connotation_call_schema_violation/.test(lastFail)) {
1984
+ } },
1985
+ { code: "connotation_call_schema_violation", when: /connotation_call_schema_violation/, hint(lastFail) {
2634
1986
  // B — calls arrived and not one row was accepted from any of them: the payload SHAPE is wrong. The
2635
1987
  // remedy is the shape, never the rulings — the tool's own answer named each refusal in-turn.
2636
- hint = "the `record_dispositions` payload has the right SHAPE — the rulings themselves are not in " +
1988
+ return "the `record_dispositions` payload has the right SHAPE — the rulings themselves are not in " +
2637
1989
  "question. `rows` must be an ARRAY of objects, each with `row_index` (the obligation's NUMBER in the " +
2638
1990
  "obligations block) as an INTEGER, `ruling`, `note`, and `receipt_index` as an INTEGER position " +
2639
1991
  "(1, 2, …) — never a typed id of any kind, never a query string, never a string index, never extra " +
2640
1992
  "fields. Re-send your rulings with the corrected " +
2641
1993
  "shape; the tool's answer names each refusal and what is still outstanding";
2642
- } else if (/connotation_(no_ruling|token_absent|cite_absent)/.test(lastFail)) {
2643
- // READER TOLERANCE, not a live path: this engine's gate can no longer mint these three — any unruled
2644
- // residual surfaces as a call token (the audit runs whenever rows are owed). What CAN still carry
2645
- // one is the recorded lastFail of a run parked under the previous engine and resumed on this one,
2646
- // and the golden-rule boundary is exactly that parsing history is fine. The remedy under this
2647
- // engine is the same as call_partial's: record the remainder through the tool.
2648
- hint = "every remaining meaning obligation is recorded through the `record_dispositions` tool — " +
2649
- "never by writing or editing any file. Everything already recorded is KEPT. Call " +
2650
- "`record_dispositions` with rows for the obligations still outstanding; the tool's answer lists " +
2651
- "them, marks which still owe a `segment_index` and a `fragment`, and reports when nothing remains";
2652
- } else if (/connotation_call_partial/.test(lastFail)) {
1994
+ } },
1995
+ { code: "connotation_call_partial", when: /connotation_call_partial/, hint(lastFail) {
2653
1996
  // B — rows landed and obligations remain. What is recorded is KEPT; the remedy is the remainder.
2654
- hint = "every remaining meaning obligation is recorded through the `record_dispositions` tool. " +
1997
+ return "every remaining meaning obligation is recorded through the `record_dispositions` tool. " +
2655
1998
  "Everything you already recorded is KEPT — do not re-send it and do not re-derive it. Call " +
2656
1999
  "`record_dispositions` with rows for ONLY the obligations the failure counts as outstanding " +
2657
2000
  "(the tool's answer lists them and marks which still owe a `segment_index` and a `fragment`), and " +
2658
2001
  "stop when it reports nothing " +
2659
2002
  "outstanding. Rule from what the receipts say, never from memory, and carry any loaded reading " +
2660
2003
  "into Findings as well";
2661
- } else if (/meaning_angles_missing|matterframe_meaning_angles/.test(lastFail)) {
2004
+ } },
2005
+ { code: "meaning_angles_missing", when: /meaning_angles_missing|matterframe_meaning_angles/, hint(lastFail) {
2662
2006
  // P2-C (Round-2 §8b): the matter frame's derived-connotation angles are required on fresh runs.
2663
2007
  //
2664
2008
  // CONVERSION 2 — THIS ORDERED A HAND-WRITE AND NOW ORDERS A CALL. It ended "Re-save the COMPLETE file
@@ -2669,7 +2013,7 @@ export function correctionHint(lastFail, { gridLedgerName = "common-law-grid.jso
2669
2013
  //
2670
2014
  // The ANGLES themselves are described in the same words as before: what the seat has to decide has not
2671
2015
  // changed, only how it hands the decision over.
2672
- hint = "the matter frame must carry the per-matter meaning/connotation angles — derived from the mark's " +
2016
+ return "the matter frame must carry the per-matter meaning/connotation angles — derived from the mark's " +
2673
2017
  "OWN semantic field and this matter's market/industry (cultural origin and communities the word " +
2674
2018
  "evokes, charged historical/political associations of the term or its imagery, category-specific " +
2675
2019
  "controversy for these goods) — short queries, each anchored on the mark's element(s); they are the " +
@@ -2678,14 +2022,16 @@ export function correctionHint(lastFail, { gridLedgerName = "common-law-grid.jso
2678
2022
  "empty array ONLY when the mark is a coined term with no real-word semantic field to probe. The call " +
2679
2023
  "replaces the stored frame, so send the whole frame again, not only the angles — the driver renders " +
2680
2024
  "the file and there is nothing for you to save";
2681
- } else if (/own_rights_missing/.test(lastFail)) {
2682
- hint = "every finding whose clearance reasoning relies on the client's own house mark / franchise root ENDS " +
2025
+ } },
2026
+ { code: "own_rights_missing", when: /own_rights_missing/, hint(lastFail) {
2027
+ return "every finding whose clearance reasoning relies on the client's own house mark / franchise root ENDS " +
2683
2028
  "with an \"**Own-rights source:** <record URI(s) | 'no applicant-owned registrations in the searched register material'>\" line — " +
2684
2029
  "run ONE owner-scoped band_lookup over the run's frozen register material (plus band_record for any cite) and cite the record URIs, " +
2685
2030
  "or state the honest SCOPED negative (never a portfolio-wide 'no registrations found' — the frozen material covers only this " +
2686
2031
  "matter's dispatched slices), adjust the reasoning to stand without the crutch, and record the missing owner query as an open " +
2687
2032
  "Coverage/open-item row for the escalation lane; the affiliate-exclusion mandate covers CONFLICTS, never this supporting evidence";
2688
- } else if (/blindframe_/.test(lastFail)) {
2033
+ } },
2034
+ { code: "blindframe", when: /blindframe_/, hint(lastFail) {
2689
2035
  // Property 1 (frame-omission design): the blind-frame stage's STRUCTURED MODEL, which since is
2690
2036
  // the stage's whole output — there is no prose companion to leave alone. A JSON-defect repair on a
2691
2037
  // clean turn: warm-eligible (WARM_ELIGIBLE_RE), and warmPatchMessage aims it at the file itself
@@ -2696,13 +2042,14 @@ export function correctionHint(lastFail, { gridLedgerName = "common-law-grid.jso
2696
2042
  // act the grant denies: a failure on obedience, mid-round, on the first repair rung that fires. Same
2697
2043
  // shape as the ten anchor sites, caught before it shipped rather than after. The one-change
2698
2044
  // invariant covers a dictation AND the ladder that corrects it.
2699
- hint = `the model is a set of VALUES you hand to the \`record_blind_frame\` tool: dominant_element, ` +
2045
+ return `the model is a set of VALUES you hand to the \`record_blind_frame\` tool: dominant_element, ` +
2700
2046
  `variants[] (each {value, direction (add|drop|phonetic|homophone|neighbour|composite), rationale}), ` +
2701
2047
  `fields[] (each {goods, on_field — a JSON boolean, rationale}), sources[] (each {channel, rationale}) ` +
2702
2048
  `and ranking_basis (goods-overlap | class-number). The failed check was: ${tok}. Call ` +
2703
2049
  `\`record_blind_frame\` again with the corrected values — everything that already validated can be ` +
2704
2050
  `sent as it was. Do not write or edit any file: blind-frame-model.json is the driver's to write`;
2705
- } else if (/framediff_directive_undispatchable/.test(lastFail)) {
2051
+ } },
2052
+ { code: "framediff_directive_undispatchable", when: /framediff_directive_undispatchable/, hint(lastFail, { undispatchable }) {
2706
2053
  // P2-B (charter P2e — the ask contract). This is the ONE frame-diff defect whose repair is not
2707
2054
  // "re-save the JSON": a firing directive named a thing to search in words nothing can dispatch.
2708
2055
  // The refusal used to arrive hours later at reopen, after this session had exited — so it arrives
@@ -2724,7 +2071,7 @@ export function correctionHint(lastFail, { gridLedgerName = "common-law-grid.jso
2724
2071
  // reproduce; both were cut with no marker. Same class as the recurrence receipt.
2725
2072
  ? offenders.map((o, i) => ` ${i + 1}. "${abbrev(String(o.item), 120)}" — ${abbrev(String(o.why || "not dispatchable as written"), 260)}`).join("\n")
2726
2073
  : ` (the saved frame-diff.json could not be re-read — re-check EVERY firing directive yourself)`;
2727
- hint = `${offenders.length || "one or more"} of your FIRING directives (severity dominant-element or material) ask for a search the driver cannot dispatch. ` +
2074
+ return `${offenders.length || "one or more"} of your FIRING directives (severity dominant-element or material) ask for a search the driver cannot dispatch. ` +
2728
2075
  `EVERY ONE of them is listed here, and ALL of them must be fixed in ONE re-save — the repair ladder counts ATTEMPTS, not directives, ` +
2729
2076
  `so fixing only the first will exhaust it and lose the whole reopen pass:\n${enumerated}\n` +
2730
2077
  //, third conversion — THE ORDER IS A CALL, NOT A RE-SAVE. This read "re-save the COMPLETE
@@ -2737,7 +2084,8 @@ export function correctionHint(lastFail, { gridLedgerName = "common-law-grid.jso
2737
2084
  `and the dominant element is then the term. Do NOT delete any directive and do NOT downgrade one to "minor" to make this pass: ` +
2738
2085
  `a real omission that cannot be searched must still be raised — but it has to say what the search IS. Send the whole diff again, ` +
2739
2086
  `not only the corrected directives — the call replaces the stored model`;
2740
- } else if (/framediff_/.test(lastFail)) {
2087
+ } },
2088
+ { code: "framediff", when: /framediff_/, hint(lastFail) {
2741
2089
  const tok = (lastFail.match(/framediff_[a-z_]+(?::[^\s)]*)?/) || ["frame-diff defect"])[0];
2742
2090
  //, third conversion — the shape hint stays (it is what the values must satisfy) and the ORDER
2743
2091
  // changes. The seat sends `directives[]` and `dominant_element_gap` as values; the driver serializes
@@ -2751,41 +2099,46 @@ export function correctionHint(lastFail, { gridLedgerName = "common-law-grid.jso
2751
2099
  // the field back into existence one rung down from the dispatch that stopped asking. This is the third
2752
2100
  // repair surface a frame-diff change has had to sweep; see recording-agreement.mjs on why the sweep is
2753
2101
  // never optional.
2754
- hint = `the structured diff is { schema_version, directives[], ` +
2102
+ return `the structured diff is { schema_version, directives[], ` +
2755
2103
  `dominant_element_gap (a JSON boolean) } — send directives:[] for a clean diff. Each directive is ` +
2756
2104
  `{layer (variant|field|source), item, observation, severity (dominant-element|material|minor)}. ` +
2757
2105
  `The dominant element itself is the driver's — it is bound from the blind model, not sent by you. ` +
2758
2106
  `The failed check was: ${tok}. Send the corrected diff in one \`record_frame_diff\` call — the driver ` +
2759
2107
  `writes frame-diff.json and renders the prose from it, so there is nothing for you to save`;
2760
- } else if (/receipts_short/.test(lastFail)) {
2108
+ } },
2109
+ { code: "receipts_short", when: /receipts_short/, hint(lastFail) {
2761
2110
  const shorts = (lastFail.match(/receipts_short:([^\s]+)/) || [])[1] || "";
2762
- hint = `the Negative-results matrix accounts for EVERY (variant × platform) grid cell — these variants are ` +
2111
+ return `the Negative-results matrix accounts for EVERY (variant × platform) grid cell — these variants are ` +
2763
2112
  `short (variant:rows/expected): ${shorts}. Re-transcribe their cells from the grid call's stdout JSON ` +
2764
2113
  `(every cell needs a receipt row: "No results" / "No similar listings (N candidates reviewed)" / ` +
2765
2114
  `"Similar listing(s) found — see Findings" / "not executed — coverage-limited"); re-run the grid call ` +
2766
2115
  `only if those cells are genuinely absent from its output`;
2767
- } else if (/grid_ledger_unparseable/.test(lastFail)) {
2768
- hint = `${gridLedgerName} is the grid call's stdout JSON saved VERBATIM — a single stdout object, or a ` +
2116
+ } },
2117
+ { code: "grid_ledger_unparseable", when: /grid_ledger_unparseable/, hint(lastFail, { gridLedgerName }) {
2118
+ return `${gridLedgerName} is the grid call's stdout JSON saved VERBATIM — a single stdout object, or a ` +
2769
2119
  `JSON ARRAY of the per-batch stdout objects in batch order, each with its cells[] (and gaps[]) intact. ` +
2770
2120
  `Re-save the file exactly as the tool returned it — no reformatting, no re-typing, no judging. If the ` +
2771
2121
  `saved file is TRUNCATED mid-string (an unterminated value near the end), your single call's stdout ` +
2772
2122
  `EXCEEDED the output budget: re-run the grid SPLIT into MORE, SMALLER batches (fewer variants per call) ` +
2773
2123
  `and save each batch's stdout as its own element of the JSON array — never try to re-emit one oversized object.`;
2774
- } else if (/grid_join_missing/.test(lastFail)) {
2124
+ } },
2125
+ { code: "grid_join_missing", when: /grid_join_missing/, hint(lastFail, { gridLedgerName }) {
2775
2126
  const shorts = (lastFail.match(/grid_join_missing:([^\s]+)/) || [])[1] || "";
2776
- hint = `the saved ${gridLedgerName} must account for EVERY dictated (variant × platform) grid cell — ` +
2127
+ return `the saved ${gridLedgerName} must account for EVERY dictated (variant × platform) grid cell — ` +
2777
2128
  `these variants are short (variant:cells/expected): ${shorts}. Append the missing cells' grid stdout to ` +
2778
2129
  `the JSON (make the file a JSON array of stdout objects if it is not already), re-running ONLY the cells ` +
2779
2130
  `genuinely absent from the prior output; then make sure the Negative-results matrix matches`;
2780
- } else if (/platforms_missing/.test(lastFail)) {
2131
+ } },
2132
+ { code: "platforms_missing", when: /platforms_missing/, hint(lastFail, { gridLedgerName }) {
2781
2133
  // capture to end-of-string: real manifest variants are multi-word, a [^\s]+ capture would chop
2782
2134
  // "PROJECT NOVA PULSE:itch.io+…" at the first space and dictate a garbage cell list.
2783
2135
  const det = (lastFail.match(/platforms_missing:(.+)$/s) || [])[1] || "";
2784
- hint = `the grid must sweep EVERY platform DICTATED in your task message's PLATFORMS list — never a ` +
2136
+ return `the grid must sweep EVERY platform DICTATED in your task message's PLATFORMS list — never a ` +
2785
2137
  `remembered or skill-example list. These variants are missing dictated platforms ` +
2786
2138
  `(variant:domain+domain): ${det}. Run exactly those missing (variant × platform) cells, append their ` +
2787
2139
  `stdout to ${gridLedgerName}, and account for them in the Negative-results matrix`;
2788
- } else if (/connotation_query_unrecorded/.test(lastFail)) {
2140
+ } },
2141
+ { code: "connotation_query_unrecorded", when: /connotation_query_unrecorded/, hint(lastFail, { gridLedgerName }) {
2789
2142
  // — THE TOKEN THAT HAD NO HINT, and the absence is what made the failure
2790
2143
  // permanent rather than merely wrong.
2791
2144
  //
@@ -2835,7 +2188,7 @@ export function correctionHint(lastFail, { gridLedgerName = "common-law-grid.jso
2835
2188
  // opposite repairs, and a re-worded label with a stale matcher here keeps sending the wrong one.
2836
2189
  const anyUnmatched = String(dropped).includes(CONNOTATION_UNMATCHED_MARK);
2837
2190
  const anyUnresembled = String(dropped).includes(CONNOTATION_NO_RESEMBLANCE_MARK);
2838
- hint = anyUnmatched && !anyUnresembled
2191
+ return anyUnmatched && !anyUnresembled
2839
2192
  ? `these dictated meaning queries ARE recorded in ${gridLedgerName} extras.pr_risk[] under a ` +
2840
2193
  `different wording, which is why the driver cannot match them: ${dropped}. Do NOT re-run them — ` +
2841
2194
  `the search already ran and its results are already in the ledger. EDIT each row's \`query\` ` +
@@ -2855,10 +2208,11 @@ export function correctionHint(lastFail, { gridLedgerName = "common-law-grid.jso
2855
2208
  `reworded query reads as one you never ran. Touch ONLY the listed queries and leave every other ` +
2856
2209
  `recorded row exactly as it is. Where a query is marked \`[unmatched; nearest recorded: …]\` the ` +
2857
2210
  `driver has already found its row for you: edit that row's \`query\` and do not search again`;
2858
- } else if (/connotation_search_missing/.test(lastFail)) {
2211
+ } },
2212
+ { code: "connotation_search_missing", when: /connotation_search_missing/, hint(lastFail) {
2859
2213
  // — was "your PR / reputational section claims a clean meaning … but the ledger recorded ZERO
2860
2214
  // searches", which under the `ensure` prefix instructed the model to make the unbacked claim.
2861
- hint = "a clean-meaning claim has the sweep behind it — yours does not: your PR / reputational section " +
2215
+ return "a clean-meaning claim has the sweep behind it — yours does not: your PR / reputational section " +
2862
2216
  "claims a clean meaning (None identified / no gang / no offensive " +
2863
2217
  "association / affirmative sweep) but the grid ledger's extras.pr_risk recorded ZERO connotation searches. " +
2864
2218
  "Run the CONNOTATION / MEANING sweep — the mark AND its near-forms on the general web (Urban Dictionary, " +
@@ -2866,7 +2220,8 @@ export function correctionHint(lastFail, { gridLedgerName = "common-law-grid.jso
2866
2220
  "zero-result ones) into extras.pr_risk, and cite a `Connotation-search source:` line in the PR section. A " +
2867
2221
  "dictionary gloss is never a clearance (a mark can read as a benign given name yet sit one letter off \"Mara\", a street-gang label). You may " +
2868
2222
  "instead report a real connotation hit — but a clean claim needs the search behind it";
2869
- } else if (/named_band_collapsed/.test(lastFail)) {
2223
+ } },
2224
+ { code: "named_band_collapsed", when: /named_band_collapsed/, hint(lastFail, { supplementalLane }) {
2870
2225
  const slices = (lastFail.match(/named_band_collapsed:(.+)$/s) || [])[1] || "";
2871
2226
  // The diagnosis is lane-independent; the REPAIR is not. This hint rides correctiveMessage, so it is
2872
2227
  // appended to the register-unit stage message itself — and on the supplemental lane that message has
@@ -2876,7 +2231,7 @@ export function correctionHint(lastFail, { gridLedgerName = "common-law-grid.jso
2876
2231
  const diagnosis = `your named band has a COLLAPSED enumerated slice — a block that claimed hits (total_hits>0) but ` +
2877
2232
  `carried ZERO records (slice~claimed-hits): ${slices}. The funnel enumerated the slice yet nothing reached ` +
2878
2233
  `the band — a clean can never ship over a searched-but-lost slice. `;
2879
- hint = supplementalLane
2234
+ return supplementalLane
2880
2235
  ? diagnosis +
2881
2236
  `On this run the TOOLS own every band block: if the collapsed slice belongs to a DICTATED plan entry ` +
2882
2237
  `(it carries a qid from the frozen plan), close it by calling register_execute_plan ONCE with the exact ` +
@@ -2894,7 +2249,8 @@ export function correctionHint(lastFail, { gridLedgerName = "common-law-grid.jso
2894
2249
  `has_more:false, and APPEND its records as an "enumerated" block (every record with its screening facts). ` +
2895
2250
  `If the slice is genuinely a crowd you cannot exhaust, write an honest "incomplete" block (count + sample + ` +
2896
2251
  `reason) — NEVER an empty "enumerated" block`;
2897
- } else if (/intake_ask_unanswered/.test(lastFail)) {
2252
+ } },
2253
+ { code: "intake_ask_unanswered", when: /intake_ask_unanswered/, hint(lastFail) {
2898
2254
  // T9 (A2): the committed-check completion gate — every frozen intake ask needs its line.
2899
2255
  const det = (lastFail.match(/intake_ask_unanswered:(\d+):of:(\d+)/) || []);
2900
2256
  // RE-AIMED AT THE CALL. This ordered the seat to "End the narrative with the
@@ -2906,14 +2262,15 @@ export function correctionHint(lastFail, { gridLedgerName = "common-law-grid.jso
2906
2262
  // The SUBSTANCE is unchanged, because none of it was wrong: answer from the gather stages' actual
2907
2263
  // results, and an un-run check gets the honest not-executed line plus an open coverage row rather
2908
2264
  // than silence. What moves is where the answer goes.
2909
- hint = `your record is missing ${det[1] ?? "some"} of the ${det[2] ?? "frozen"} intake-ask answers. ` +
2265
+ return `your record is missing ${det[1] ?? "some"} of the ${det[2] ?? "frozen"} intake-ask answers. ` +
2910
2266
  `Send one \`ask_answers\` entry per frozen ask (_driver/intake-asks.json) on the findings record you ` +
2911
2267
  `hand to \`record_synthesis\` — the ask VERBATIM as it was given to you, and the ANSWER ALONE: the ` +
2912
2268
  `driver renders the labelled line into the narrative and the report from those entries, so there is ` +
2913
2269
  `no section for you to write and nothing you write by hand is read. ` +
2914
2270
  `Answer from the gather stages' actual results (the owning stage was instructed to run each check); an ` +
2915
2271
  `un-run check gets the honest "NOT executed this run — <reason>" answer plus an open coverage[] row — never silence`;
2916
- } else if (/\btool_timeout:/.test(lastFail)) {
2272
+ } },
2273
+ { code: "tool_timeout", when: /\btool_timeout:/, hint(lastFail) {
2917
2274
  // — THE SAME ABSENT BAND, AND THE OPPOSITE INSTRUCTION.
2918
2275
  //
2919
2276
  // `named_band_missing`'s hint below tells the model it never made its call. When the call WAS made
@@ -2926,24 +2283,26 @@ export function correctionHint(lastFail, { gridLedgerName = "common-law-grid.jso
2926
2283
  // dies again the honest audit note IS the answer. Nothing here asks for a shorter or cheaper call —
2927
2284
  // no model gets a time budget, and the cap that killed it is the bridge's, fixed in this issue's
2928
2285
  // other half.
2929
- hint = `your dictated register tool call was MADE and never RETURNED — it was still running when ` +
2286
+ return `your dictated register tool call was MADE and never RETURNED — it was still running when ` +
2930
2287
  `the bridge killed it, so the band was never written. This is NOT a missing-structure defect and ` +
2931
2288
  `NOT something you did wrong. Call register_execute_plan ONCE more with the exact ` +
2932
2289
  `{"plan_path", "axis", "output_path"} from your stage instructions. If it is killed again, do ` +
2933
2290
  `NOT author band blocks by hand and do NOT narrate coverage you did not get — the driver's own call ` +
2934
2291
  `log records that the call never returned`;
2935
- } else if (/named_band_missing/.test(lastFail)) {
2292
+ } },
2293
+ { code: "named_band_missing", when: /named_band_missing/, hint(lastFail) {
2936
2294
  // 2026-07-14 (copper-keystone): the unit's .md narrated success but the band file was NEVER WRITTEN —
2937
2295
  // the model skipped its one register_execute_plan call and fabricated the narrative. Unlike the
2938
2296
  // defective-block repairs below, the fix here IS re-calling the tool: with no existing blocks there
2939
2297
  // is nothing the qid-ownership merge could wrongly preserve, and a hand-authored band fails the stage.
2940
- hint = `your unit's NAMED BAND file (<axis>-band.json beside your .md) was NEVER WRITTEN — the ` +
2298
+ return `your unit's NAMED BAND file (<axis>-band.json beside your .md) was NEVER WRITTEN — the ` +
2941
2299
  `load-bearing artifact is absent, so the stage cannot pass no matter what the .md says. Produce it ` +
2942
2300
  `NOW by CALLING register_execute_plan ONCE with the exact {"plan_path", "axis", "output_path"} ` +
2943
2301
  `from your stage instructions — the TOOL executes the dictated entries and writes the band itself, ` +
2944
2302
  `qid-stamped. Do NOT author band blocks by hand (a hand-authored band fails the stage), do NOT ` +
2945
2303
  `re-do your digest prose, and NEVER claim the band was written without the tool call actually made`;
2946
- } else if (/named_band_(state_invalid|block_invalid|unparseable)/.test(lastFail)) {
2304
+ } },
2305
+ { code: "named_band_shape", when: /named_band_(state_invalid|block_invalid|unparseable)/, hint(lastFail, { supplementalLane }) {
2947
2306
  // T1 (J1b): the copper-spire killer. The generic hint never named the fix, and re-calling
2948
2307
  // register_execute_plan cannot repair a model-authored block (its merge PRESERVES qid-less blocks) —
2949
2308
  // so every retry deterministically re-failed. Name the exact repair.
@@ -2958,7 +2317,7 @@ export function correctionHint(lastFail, { gridLedgerName = "common-law-grid.jso
2958
2317
  const bandDiagnosis = `your band JSON has a defective MODEL-AUTHORED block${badState ? ` (state "${badState}")` : ""}. ` +
2959
2318
  `The ONLY legal states are "enumerated" (paged to has_more:false, records carried) and "incomplete" ` +
2960
2319
  `(count + sample + reason) — there is no "verified"/"checked"/"complete"/"clean" state. `;
2961
- hint = supplementalLane
2320
+ return supplementalLane
2962
2321
  ? bandDiagnosis +
2963
2322
  `On this run the TOOLS own every block, so a hand-authored one is the defect itself — not something to ` +
2964
2323
  `repair into shape (the next pass rejects any qid-less block outright). DELETE the offending qid-less ` +
@@ -2973,7 +2332,8 @@ export function correctionHint(lastFail, { gridLedgerName = "common-law-grid.jso
2973
2332
  `file and REWRITE the offending qid-less block(s) IN PLACE to the correct state (records present ⇒ ` +
2974
2333
  `"enumerated"; otherwise an honest "incomplete" descriptor). NEVER touch a qid-stamped block, and do ` +
2975
2334
  `NOT re-call register_execute_plan to fix this — its merge preserves your defective block verbatim`;
2976
- } else if (/plan_audit_missing/.test(lastFail)) {
2335
+ } },
2336
+ { code: "plan_audit_missing", when: /plan_audit_missing/, hint(lastFail) {
2977
2337
  // T1 (J3b): the reviewer omitted the deterministic plan audit — the validator requires the
2978
2338
  // exact section title whenever the plan-execution receipt exists.
2979
2339
  // — THE GRADING IS QUOTED, NOT PARAPHRASED. What stood here restated the three classes in its
@@ -2982,12 +2342,14 @@ export function correctionHint(lastFail, { gridLedgerName = "common-law-grid.jso
2982
2342
  // exactly the moment it is rewriting the section the rule governs. The dispatch blocks now share a
2983
2343
  // single literal; this is its third reader, so a change to the grading reaches the repair turn too
2984
2344
  // instead of leaving it teaching the previous version.
2985
- hint = `your review lacks the section titled exactly "PLAN-EXECUTION CHECK". Add it: audit the ` +
2345
+ return `your review carries a plan audit: audit the ` +
2986
2346
  `driver-fed plan-execution receipt, under the same grading you were given with it — ` +
2987
2347
  `${PLAN_AUDIT_CLASSES} — flagging a clean claim that rests on class (1), a class (2) fringe ` +
2988
2348
  `claimed searched-clean, and a class (3) slice the narrative shows no materiality reasoning for. ` +
2989
- `Keep the verdict (CLEAR / CONDITIONAL / BLOCKING) on the FIRST line and the rest of your review intact`;
2990
- } else if (/coverage_no_status/.test(lastFail)) {
2349
+ `Send it as \`plan_audit\` in a new \`record_narrative_refutation\` call, or, if you saved the review by ` +
2350
+ `rewriting its file, as the section titled exactly "PLAN-EXECUTION CHECK". Keep your verdict and flags as they were`;
2351
+ } },
2352
+ { code: "coverage_no_status", when: /coverage_no_status/, hint(lastFail) {
2991
2353
  // — THE HINT NO LONGER EXPLAINS A TRANSCRIPTION REQUIREMENT, BECAUSE THERE IS NOT ONE.
2992
2354
  // What stood here were two arms (coverage_deferred_unaccounted and coverage_clean_unverified_
2993
2355
  // incomplete) whose entire content was instructions for reproducing an identifier: "each qid must
@@ -3015,7 +2377,7 @@ export function correctionHint(lastFail, { gridLedgerName = "common-law-grid.jso
3015
2377
  : unset && !badAxis
3016
2378
  ? `row(s) of your coverage form carry no status this gate accepts`
3017
2379
  : `row(s) of your coverage form were refused`;
3018
- hint = `${lead}: ${abbrev(rows, 200) || "see the failure"}. ` +
2380
+ return `${lead}: ${abbrev(rows, 200) || "see the failure"}. ` +
3019
2381
  `The driver computed every obligation and every identifier in it — the coverage unit, the query id, the hit ` +
3020
2382
  `count, the unaccounted classes and terms, each deferred slice's own receipt reason. Record the named row(s) ` +
3021
2383
  `through the \`record_coverage\` tool — {"row_id","status","reason"} per row, never by writing or editing any ` +
@@ -3031,7 +2393,8 @@ export function correctionHint(lastFail, { gridLedgerName = "common-law-grid.jso
3031
2393
  `slices that genuinely enumerated to has_more:false STAY confirmed-clean — do not downgrade them, that trades ` +
3032
2394
  `one false claim for another. Everything already recorded is kept. Do NOT re-run ` +
3033
2395
  `searches yourself and do NOT hand-write a Coverage ledger table — the driver renders it from what the tool records`;
3034
- } else if (/coverage_form_axis_invalid/.test(lastFail)) {
2396
+ } },
2397
+ { code: "coverage_form_axis_invalid", when: /coverage_form_axis_invalid/, hint(lastFail) {
3035
2398
  // fix round — THE HINT NAMES THE CELL AND QUOTES THE ALLOWED SET, which is the whole of the
3036
2399
  // 2026-07-30 lesson recorded on the `coverage_axis_invalid` arm above: "the retry was told to redo
3037
2400
  // the very derivation that failed, so it looped until the attempts ran out … The validator's own
@@ -3049,7 +2412,7 @@ export function correctionHint(lastFail, { gridLedgerName = "common-law-grid.jso
3049
2412
  // correctionHint caller passes ONE validator reason (verify returns a single fail object), so no
3050
2413
  // fail string carries two coverage tokens for an earlier arm to match first.
3051
2414
  const rows = (lastFail.match(/coverage_form_axis_invalid:[^;]*;([^\n]*)/) || [])[1] || "";
3052
- hint = `row(s) YOU ADDED to the coverage form carry an "axis" outside the register-axis vocabulary, which ` +
2415
+ return `row(s) YOU ADDED to the coverage form carry an "axis" outside the register-axis vocabulary, which ` +
3053
2416
  `is CLOSED: ${abbrev(rows, 220) || "see the failure"}. Each entry above is the row's id followed by the value ` +
3054
2417
  `that was rejected — "axis=<empty>" means that row has no "axis" at all. ` +
3055
2418
  `Re-send each of those rows through the \`record_coverage\` tool — {"kind":"seat","axis","unit","status",` +
@@ -3065,18 +2428,20 @@ export function correctionHint(lastFail, { gridLedgerName = "common-law-grid.jso
3065
2428
  `The rows the DRIVER wrote already carry a correct axis: do not touch them — every "status" and "reason" ` +
3066
2429
  `already recorded is kept. Do NOT re-run any search, do NOT write or edit any file, and do NOT hand-write a ` +
3067
2430
  `Coverage ledger table — the driver renders it from what the tool records`;
3068
- } else if (/coverage_form_damaged/.test(lastFail)) {
2431
+ } },
2432
+ { code: "coverage_form_damaged", when: /coverage_form_damaged/, hint(lastFail) {
3069
2433
  // Typed transport: the seat holds no writer onto the accumulator, so a damaged one is the driver's
3070
2434
  // own serialization or filesystem at fault — never the seat's JSON. The repair is still a tool
3071
2435
  // call, because record_coverage rewrites the accumulator whole from the regenerated rows plus the
3072
2436
  // call: statuses in the unreadable copy cannot be carried, so the seat re-sends its rulings.
3073
2437
  const detail = (lastFail.match(/coverage_form_damaged:form_damaged=\d+;([^\n]*)/) || [])[1] || "";
3074
- hint = `the driver's coverage accumulator could not be read${detail ? ` (${abbrev(detail, 120)})` : ""} — a ` +
2438
+ return `the driver's coverage accumulator could not be read${detail ? ` (${abbrev(detail, 120)})` : ""} — a ` +
3075
2439
  `driver-side fault, not your JSON (you never write this file). Re-record your statuses through the ` +
3076
2440
  `\`record_coverage\` tool — {"row_id","status","reason"} per obligation row — which rewrites the record ` +
3077
2441
  `from the driver's own rows plus your call. Statuses in the unreadable copy cannot be read, so re-send ` +
3078
2442
  `every ruling the tool's answer still lists as outstanding. Never write or edit any file`;
3079
- } else if (/coverage_form_(missing|empty)/.test(lastFail)) {
2443
+ } },
2444
+ { code: "coverage_form_missing", when: /coverage_form_(missing|empty)/, hint(lastFail) {
3080
2445
  // Named for readability in the journal, not because a model can act on either: both mean the DRIVER
3081
2446
  // did not write the form it stamped as required — absent in one case, present with no obligations in
3082
2447
  // it in the other. Deliberately out of the warm allowlist, and for the same reason: a resumed seat
@@ -3084,7 +2449,7 @@ export function correctionHint(lastFail, { gridLedgerName = "common-law-grid.jso
3084
2449
  // fix a driver bug. `coverage_form_empty` is matched HERE rather than by the `coverage_no_status`
3085
2450
  // arm above so an empty form never reads to the seat as rows it forgot to fill in.
3086
2451
  const empty = /coverage_form_empty/.test(lastFail);
3087
- hint = `the driver-written coverage form is ${empty ? "present but carries no rows" : "absent"} although this run ` +
2452
+ return `the driver-written coverage form is ${empty ? "present but carries no rows" : "absent"} although this run ` +
3088
2453
  `requires one. This is a DRIVER defect, not something your turn can repair: write your findings as normal and ` +
3089
2454
  `report the ${empty ? "empty" : "missing"} form in your final message`;
3090
2455
  // ── — THE TWO ARMS BELOW SERVE THE UNSTAMPED (PROSE) ERA, AND THEY ARE BACK BECAUSE THEIR
@@ -3100,18 +2465,20 @@ export function correctionHint(lastFail, { gridLedgerName = "common-law-grid.jso
3100
2465
  // `coverage_clean_deferred` gets NO arm: its token is folded into the superset above and nothing emits
3101
2466
  // it any more, and an arm for a token nobody emits is what the closed-vocabulary rule refuses to leave
3102
2467
  // lying around.
3103
- } else if (/coverage_deferred_unaccounted/.test(lastFail)) {
2468
+ } },
2469
+ { code: "coverage_deferred_unaccounted", when: /coverage_deferred_unaccounted/, hint(lastFail) {
3104
2470
  //: the accounting requirement, not the clean-claim gate. The distinction matters in the hint —
3105
2471
  // this fires when the ledger is SILENT about a deferred qid, so telling the model to "correct its
3106
2472
  // clean claim" would send it looking for a row that does not exist. The qids ride in the token.
3107
2473
  const [, ax = "", qids = ""] = lastFail.match(/coverage_deferred_unaccounted:([^:\s)]+):?([^\s)]*)/) || [];
3108
- hint = `your Coverage ledger does not account for ${qids ? `these DEFERRED slice(s): ${qids}` : "every DEFERRED slice"} ` +
2474
+ return `your Coverage ledger does not account for ${qids ? `these DEFERRED slice(s): ${qids}` : "every DEFERRED slice"} ` +
3109
2475
  `on ${ax ? `axis "${ax}"` : "a dictated axis"}. The active register provider cannot express those queries at all, ` +
3110
2476
  `so they were never searched and nothing can make them run — the plan recorded that before this stage began. ` +
3111
2477
  `Each qid must appear VERBATIM in a row on its own axis with Status "deferred" (or "coverage-limited"), quoting ` +
3112
2478
  `the receipt's mechanical reason. A ledger that says nothing about a slice the plan could not run is incomplete ` +
3113
2479
  `output, not a clean one; treat the gap as an OPEN, disclosed question for the lawyer`;
3114
- } else if (/coverage_clean_unverified_incomplete/.test(lastFail)) {
2480
+ } },
2481
+ { code: "coverage_clean_unverified_incomplete", when: /coverage_clean_unverified_incomplete/, hint(lastFail) {
3115
2482
  // The discriminated incomplete gate (copper-lattice): clean claimed over a multi-term OR-stack
3116
2483
  // crowd whose per-term truth is not fully accounted. Relabel — the re-enumeration is the driver's.
3117
2484
  // ION/copper-foundry: the repair is now a DISCLOSURE, not a mass downgrade — the gate joins the
@@ -3139,7 +2506,7 @@ export function correctionHint(lastFail, { gridLedgerName = "common-law-grid.jso
3139
2506
  ? `these terms of its OR-stack are neither verified-zero nor individually enumerated nor themselves ` +
3140
2507
  `crowds: ${terms}`
3141
2508
  : `part of it is neither verified-zero nor enumerated nor itself a crowd`;
3142
- hint = `${ax ? `axis "${ax}"` : "an axis"} has ONE undisclosed incomplete block and this is it: ` +
2509
+ return `${ax ? `axis "${ax}"` : "an axis"} has ONE undisclosed incomplete block and this is it: ` +
3143
2510
  `${qid ? `qid ${qid}` : "the block named in the failure"}${hits ? ` (${hits} hits)` : ""}. ${what} — and no ` +
3144
2511
  `Coverage-ledger row discloses it, so that axis's confirmed-clean rows swallow it. Give THAT block its ` +
3145
2512
  `OWN coverage-limited (or deferred) row on this axis. The gate recognises the disclosure by exactly two ` +
@@ -3149,49 +2516,74 @@ export function correctionHint(lastFail, { gridLedgerName = "common-law-grid.jso
3149
2516
  `that genuinely enumerated to has_more:false STAY confirmed-clean: do not downgrade them, that trades one ` +
3150
2517
  `false claim for another. Correct exactly that row and change nothing else. Do NOT re-run searches ` +
3151
2518
  `yourself — the driver owns the re-run`;
3152
- } else if (/coverage_clean_unexecuted/.test(lastFail)) {
2519
+ } },
2520
+ { code: "coverage_clean_unexecuted", when: /coverage_clean_unexecuted/, hint(lastFail) {
3153
2521
  // T1 (J6): the F3 gate — a clean claim over a slice the plan-execution receipt says never ran.
3154
2522
  const ax = (lastFail.match(/coverage_clean_unexecuted:([^\s)]+)/) || [])[1] || "";
3155
- hint = `the plan-execution receipt says ${ax ? `axis "${ax}"` : "a dictated axis"} did NOT fully execute, ` +
2523
+ return `the plan-execution receipt says ${ax ? `axis "${ax}"` : "a dictated axis"} did NOT fully execute, ` +
3156
2524
  `yet your findings claim it clean. Either the claim is wrong — correct it to an honest ` +
3157
2525
  `coverage-limited/deferred row carrying the mechanical reason from the receipt — or the coverage ` +
3158
2526
  `actually ran and your ledger row mis-states it: fix the row to match the receipt. A clean can never ` +
3159
2527
  `rest on a slice the plan dictated and nothing ran`;
3160
- } else if (/band_block_unplanned/.test(lastFail)) {
2528
+ } },
2529
+ { code: "band_block_unplanned", when: /band_block_unplanned/, hint(lastFail) {
3161
2530
  // copper-lattice re-route: a hand-authored band block under the supplemental_lane contract.
3162
2531
  const qs = (lastFail.match(/band_block_unplanned:([^\s)]+)/) || [])[1] || "";
3163
- hint = `this run's register plan carries the supplemental_lane contract: EVERY band block is written by ` +
2532
+ return `this run's register plan carries the supplemental_lane contract: EVERY band block is written by ` +
3164
2533
  `a TOOL and carries a qid — you never author band blocks. The qid-less block(s) (${abbrev(qs, 100)}) came ` +
3165
2534
  `from a hand append. REMOVE them from the band file, then re-run their queries the sanctioned way: ` +
3166
2535
  `register_propose_supplemental with the same query as a proposal (the tool executes it and merges the ` +
3167
2536
  `band itself, qid-stamped). Leave every qid-stamped block untouched`;
3168
- } else if (/coverage_clean_tainted/.test(lastFail)) {
2537
+ } },
2538
+ { code: "coverage_clean_tainted", when: /coverage_clean_tainted/, hint(lastFail) {
3169
2539
  // Timeout-taint gate (copper-lattice): a clean claim over an axis whose winning register-unit pass
3170
2540
  // was cut down mid-work. The repair is a RELABEL, never a re-search — the re-run is the driver's job
3171
2541
  // (taint chain / envelope), the digest's job is the honest status.
3172
2542
  const ax = (lastFail.match(/coverage_clean_tainted:([^\s)]+)/) || [])[1] || "";
3173
- hint = `the register-unit pass that produced ${ax ? `axis "${ax}"` : "a tainted axis"} was killed at the ` +
2543
+ return `the register-unit pass that produced ${ax ? `axis "${ax}"` : "a tainted axis"} was killed at the ` +
3174
2544
  `timeout wall mid-work (the per-attempt log is code-truth you cannot argue with), so its self-reported ` +
3175
2545
  `clean is unverified. Relabel that axis's confirmed-clean Coverage-ledger row(s) to deferred with the ` +
3176
2546
  `reason "timeout-tainted pass — self-reported clean downgraded pending re-run", and change nothing ` +
3177
2547
  `else. Do NOT re-run searches yourself — the driver owns the re-run`;
3178
- } else if (/declared_unavailable/.test(lastFail)) {
3179
- hint = "you never write a fallback/partial findings file: if the perplexity_research tool returned results, write " +
2548
+ } },
2549
+ { code: "declared_unavailable", when: /declared_unavailable/, hint(lastFail) {
2550
+ return "you never write a fallback/partial findings file: if the perplexity_research tool returned results, write " +
3180
2551
  "the COMPLETE findings file from them; if the tool is genuinely failing after retries, write NO findings file " +
3181
2552
  "at all and report the tool failure with diagnostics in your final message (the driver fails the run — a report " +
3182
2553
  "must never ship without its marketplace layer)";
3183
- } else if (/findings\+ledger|no_coverage_status_row/.test(lastFail)) {
2554
+ } },
2555
+ { code: "coverage_status_row", when: /findings\+ledger|no_coverage_status_row/, hint(lastFail) {
3184
2556
  // — `findings+ledger` IS BACK IN THIS ALTERNATION. The first cut of this build removed it on
3185
2557
  // the reading that the seat never writes a Coverage-ledger table any more; that is true only on a
3186
2558
  // run the driver stamped as form-required, and the stamp is conditional. On an unstamped run
3187
2559
  // validators.registerFindings demands the table exactly as it did before and emits this label,
3188
2560
  // so dropping the arm left the one lane that can still fire it with a generic hint.
3189
- hint = "the file has a findings heading plus a Coverage ledger with a status row (confirmed-clean / coverage-limited / deferred)"; // the common-law clause went with that lane's status gate (ruling 2026-10-01)
3190
- } else if (/negative-results|coverage-ledger|audit-trail|findings-heading/.test(lastFail)) {
3191
- hint = "the findings file carries ALL required sections: a findings heading, the Negative results matrix " +
2561
+ return "the file has a findings heading plus a Coverage ledger with a status row (confirmed-clean / coverage-limited / deferred)"; // the common-law clause went with that lane's status gate (ruling 2026-10-01)
2562
+ } },
2563
+ { code: "prose_sections", when: /negative-results|coverage-ledger|audit-trail|findings-heading/, hint(lastFail) {
2564
+ return "the findings file carries ALL required sections: a findings heading, the Negative results matrix " +
3192
2565
  "(every variant × platform row), the Coverage ledger with a status row, and the Audit trail call log";
3193
- }
3194
- return hint;
2566
+ } },
2567
+ ];
2568
+
2569
+ const REPAIR_HINT_DEFAULT = "the required output file is actually written and contains every required section IN FULL";
2570
+
2571
+ /** The code of the repair hint a failure string selects, or null when it gets the default. PURE. */
2572
+ export function failureCode(lastFail) { // @internal — driven by its test
2573
+ return REPAIR_HINTS.find((row) => row.when.test(lastFail))?.code ?? null;
2574
+ }
2575
+
2576
+ /** Every row's code, in the order the rows are read. */
2577
+ export const REPAIR_HINT_CODES = Object.freeze(REPAIR_HINTS.map((row) => row.code)); // @internal — driven by its test
2578
+
2579
+ export function correctionHint(lastFail, { gridLedgerName = "common-law-grid.json", supplementalLane = false, undispatchable = [], toolWritten = null, heldRecord = false, adds = false } = {}) {
2580
+ // The repair act, for the hints that name one. Kept to a single sentence and a single decision so a
2581
+ // new hint has one thing to append rather than a branch to reproduce.
2582
+ const resaveClause = toolWritten
2583
+ ? `Fix exactly that and send the corrected values — the driver re-derives this file and the prose table together from your \`${toolWritten}\` call, so there is nothing here for you to save`
2584
+ : `Fix exactly that, re-save the COMPLETE JSON file, and leave the prose table unchanged`;
2585
+ const row = REPAIR_HINTS.find((r) => r.when.test(lastFail));
2586
+ return row ? row.hint(lastFail, { resaveClause, gridLedgerName, supplementalLane, undispatchable, toolWritten, heldRecord, adds }) : REPAIR_HINT_DEFAULT;
3195
2587
  }
3196
2588
 
3197
2589
  // ── the DEFERRED-SLICE BLOCK IS GONE ──────────────────────────────────────────────────────
@@ -3773,14 +3165,3 @@ function toolCallCounts(turn) {
3773
3165
  toolCallsErroredByName: errored && typeof errored === "object" && !Array.isArray(errored) ? { ...errored } : null };
3774
3166
  }
3775
3167
 
3776
- /**
3777
- * IS THIS ATTEMPT A TIMEOUT? A kill and a run past the limit with a non-zero exit always are. A timed-out request named
3778
- * in stderr is one only when the turn did not complete: a turn that exited 0 with its engine's status ok outlived the
3779
- * request, which was a call inside it (a web lookup, a tool), and is judged on what it wrote like any finished turn.
3780
- * Recorded as a timeout, it was run again whole: on one test run a writer finished in 14.7 minutes of its 43, exited 0
3781
- * with its output written, and paid a second attempt of 20.3 minutes. `cause` is `timeoutCause`'s answer. PURE.
3782
- */
3783
- export function attemptTimedOut({ cause, code, json }) {
3784
- if (!cause) return false;
3785
- return !(cause === "stderr" && code === 0 && json?.status === "ok");
3786
- }