clearotron 0.5.1 → 0.6.0-beta.1

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 (390) 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 +88 -33
  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 +69 -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/band-shape.mjs +21 -3
  37. package/driver/best-draft.mjs +3 -3
  38. package/driver/blind-frame-record.mjs +2 -2
  39. package/driver/cancel.mjs +3 -2
  40. package/driver/carry-through.mjs +2 -2
  41. package/driver/citation-census.json +3 -3
  42. package/driver/clearance-variants-record.mjs +4 -10
  43. package/driver/common-law-coverage-status.mjs +3 -3
  44. package/driver/common-law-receipts.mjs +2 -2
  45. package/driver/commonlaw-carry-floor.json +3 -3
  46. package/driver/compare.mjs +1 -1
  47. package/driver/config-inventory.mjs +6 -79
  48. package/driver/consumption-ledger.mjs +2 -1
  49. package/driver/contract-arm2-baseline.json +2 -3
  50. package/driver/contract-dictation-registry.mjs +5 -0
  51. package/driver/contract-e3-backlog.mjs +45 -66
  52. package/driver/contract-e3-baseline.json +16 -16
  53. package/driver/contract-vocabulary.mjs +8 -6
  54. package/driver/corrections-feedforward.mjs +3 -1
  55. package/driver/coverage-form-io.mjs +7 -8
  56. package/driver/coverage-tool.mjs +1 -1
  57. package/driver/declination-tool.mjs +2 -2
  58. package/driver/degraded-parts.mjs +9 -9
  59. package/driver/demo-container.mjs +5 -4
  60. package/driver/demo-posture.mjs +17 -0
  61. package/driver/deploy-live-run-guard.mjs +19 -7
  62. package/driver/derived-state.mjs +2 -2
  63. package/driver/dev-portal.mjs +2 -1
  64. package/driver/dispatch-record.mjs +1 -1
  65. package/driver/disposition-tool.mjs +2 -1
  66. package/driver/doubt-closure-tool.mjs +2 -2
  67. package/driver/driver.config.mjs +35 -724
  68. package/driver/e2e-rounds.mjs +3 -4
  69. package/driver/engine/CONTRACT.md +3 -0
  70. package/driver/engine/README.md +2 -0
  71. package/driver/engine/anthropic-agent.mjs +13 -42
  72. package/driver/engine/auth.mjs +74 -0
  73. package/driver/engine/child-record.mjs +1 -1
  74. package/driver/engine/deny-authority-write.mjs +2 -2
  75. package/driver/engine/jx-turn.mjs +10 -2
  76. package/driver/engine/mcp/README.md +1 -1
  77. package/driver/engine/mcp/band-server.mjs +20 -13
  78. package/driver/engine/mcp/codex-config.mjs +1 -1
  79. package/driver/engine/mcp/declination-server.mjs +2 -3
  80. package/driver/engine/mcp/dispositions-server.mjs +3 -3
  81. package/driver/engine/mcp/gather-config.mjs +24 -19
  82. package/driver/engine/mcp/grid-provenance.mjs +1 -1
  83. package/driver/engine/mcp/held-answers.mjs +5 -5
  84. package/driver/engine/mcp/perplexity-server.mjs +16 -7
  85. package/driver/engine/mcp/recording-server.mjs +7 -6
  86. package/driver/engine/mcp/register-server.mjs +29 -0
  87. package/driver/engine/mcp/stdio-server.mjs +5 -5
  88. package/driver/engine/mcp/supplemental.mjs +9 -9
  89. package/driver/engine/openai-agent.mjs +5 -2
  90. package/driver/engine/registry.mjs +103 -0
  91. package/driver/engine/run-choices.mjs +162 -0
  92. package/driver/engine/stamps.mjs +35 -0
  93. package/driver/enqueue-schema.mjs +4 -4
  94. package/driver/envelope-settle.mjs +3 -2
  95. package/driver/feedback-issues.mjs +1 -1
  96. package/driver/feedback-mint.mjs +3 -2
  97. package/driver/feedback-store.mjs +3 -2
  98. package/driver/findings-model.mjs +1 -1
  99. package/driver/flag-snapshot.mjs +5 -4
  100. package/driver/floor-duty.mjs +3 -3
  101. package/driver/foreign-record-links.mjs +1 -1
  102. package/driver/frame-diff-record.mjs +2 -8
  103. package/driver/framework.mjs +1 -1
  104. package/driver/gate-metrics.mjs +10 -11
  105. package/driver/gateway.mjs +220 -839
  106. package/driver/goods-evidence.mjs +26 -14
  107. package/driver/jx-lanes.mjs +3 -3
  108. package/driver/jx-units.mjs +31 -37
  109. package/driver/jx.mjs +44 -59
  110. package/driver/knockout-assess-record.mjs +3 -3
  111. package/driver/knockout-caveats.mjs +21 -0
  112. package/driver/knockout-correction-record.mjs +58 -28
  113. package/driver/knockout-frame-record.mjs +2 -2
  114. package/driver/knockout-register-read.mjs +38 -21
  115. package/driver/knockout-register-record.mjs +5 -6
  116. package/driver/knockout-review-record.mjs +12 -11
  117. package/driver/ladder/model-gauge.mjs +88 -0
  118. package/driver/ladder/next-rung.mjs +296 -0
  119. package/driver/ladder/rescue.mjs +146 -0
  120. package/driver/ladder/stage-tools.mjs +57 -0
  121. package/driver/ladder/turn-failure.mjs +166 -0
  122. package/driver/log.mjs +2 -2
  123. package/driver/matter-frame-record.mjs +4 -4
  124. package/driver/methodology-witness.mjs +2 -2
  125. package/driver/named-band.mjs +60 -3
  126. package/driver/narrative-refutation-record.mjs +145 -42
  127. package/driver/one-build-per-run.mjs +62 -0
  128. package/driver/outbox-backoff.mjs +4 -4
  129. package/driver/owner-screen.mjs +0 -10
  130. package/driver/owner-use-check.mjs +2 -28
  131. package/driver/package.json +1 -1
  132. package/driver/partial-payload-baseline.json +1 -1
  133. package/driver/parts-not-completed.mjs +1 -1
  134. package/driver/pipeline-knockout.mjs +1015 -1001
  135. package/driver/pipeline.mjs +714 -9351
  136. package/driver/placement-decisions.mjs +2 -2
  137. package/driver/placement-form-io.mjs +7 -9
  138. package/driver/placement-union.mjs +0 -6
  139. package/driver/plan-stability.mjs +7 -10
  140. package/driver/portal-acks.mjs +3 -2
  141. package/driver/portal-confirmation.mjs +48 -0
  142. package/driver/portal-families.mjs +3 -2
  143. package/driver/portal-local-auth.mjs +1 -2
  144. package/driver/portal-routes/README.md +24 -0
  145. package/driver/portal-routes/admin.mjs +425 -0
  146. package/driver/portal-routes/compose.mjs +66 -0
  147. package/driver/portal-routes/config.mjs +118 -0
  148. package/driver/portal-routes/connect.mjs +283 -0
  149. package/driver/portal-routes/feedback.mjs +178 -0
  150. package/driver/portal-routes/me.mjs +165 -0
  151. package/driver/portal-routes/queue.mjs +64 -0
  152. package/driver/portal-routes/report.mjs +106 -0
  153. package/driver/portal-routes/run.mjs +508 -0
  154. package/driver/portal-routes/runs.mjs +127 -0
  155. package/driver/portal-routes/usage.mjs +82 -0
  156. package/driver/portal-runs.mjs +588 -0
  157. package/driver/portal-service.mjs +82 -2593
  158. package/driver/portal-static.mjs +3 -1
  159. package/driver/predelivery-lint.mjs +101 -9
  160. package/driver/production-pool-guard.mjs +1 -1
  161. package/driver/profiles.mjs +5 -4
  162. package/driver/progress.mjs +29 -24
  163. package/driver/publish/README.md +10 -5
  164. package/driver/publish/archive-tags.mjs +3 -2
  165. package/driver/publish/demo-marking.mjs +2 -2
  166. package/driver/publish/index.mjs +215 -140
  167. package/driver/publish/knockout.mjs +153 -107
  168. package/driver/publish/office-record-links.mjs +22 -0
  169. package/driver/publish/parse.mjs +20 -5
  170. package/driver/publish/pool-admin.mjs +9 -3
  171. package/driver/publish/render.mjs +11 -3
  172. package/driver/publish/report-dates.mjs +3 -4
  173. package/driver/publish/report-registry.mjs +7 -10
  174. package/driver/publish/seed-pool.mjs +3 -2
  175. package/driver/publish/shell.mjs +106 -0
  176. package/driver/publish/templates/report.css +9 -7
  177. package/driver/queue-order.mjs +4 -3
  178. package/driver/record-carry.mjs +0 -9
  179. package/driver/record-discard.mjs +1 -4
  180. package/driver/record-fold.mjs +3 -3
  181. package/driver/record-goods.mjs +79 -23
  182. package/driver/reference-score.mjs +2 -3
  183. package/driver/register-capabilities.mjs +0 -6
  184. package/driver/register-count.mjs +3 -2
  185. package/driver/register-digest-record.mjs +7 -7
  186. package/driver/register-fixture-marker.mjs +3 -3
  187. package/driver/register-plan.mjs +2 -2
  188. package/driver/register-records.mjs +2 -2
  189. package/driver/register-taint.mjs +3 -3
  190. package/driver/register-unit-record.mjs +48 -9
  191. package/driver/register-unreachable.mjs +4 -3
  192. package/driver/registry-fidelity.mjs +79 -34
  193. package/driver/repair-composers.mjs +14 -9
  194. package/driver/repair-digest.mjs +4 -6
  195. package/driver/repair-scope.mjs +3 -3
  196. package/driver/repair-targets.mjs +24 -9
  197. package/driver/repairs.mjs +44 -58
  198. package/driver/replay-archive.mjs +7 -7
  199. package/driver/report-card-record.mjs +3 -3
  200. package/driver/report-overview-record.mjs +4 -4
  201. package/driver/research-answers.mjs +38 -6
  202. package/driver/research-checks.mjs +4 -4
  203. package/driver/result-noun-fields.mjs +28 -11
  204. package/driver/review-addresses.mjs +163 -0
  205. package/driver/rule-shape.mjs +1 -1
  206. package/driver/run-delivered.mjs +340 -0
  207. package/driver/run-economics.mjs +8 -26
  208. package/driver/run-failed.mjs +545 -0
  209. package/driver/run-integrity.mjs +1 -1
  210. package/driver/run-outcome.mjs +314 -0
  211. package/driver/run-park.mjs +23 -0
  212. package/driver/run-quote.mjs +32 -0
  213. package/driver/run-record.mjs +352 -0
  214. package/driver/run-requirements.mjs +22 -0
  215. package/driver/run-shell.mjs +55 -0
  216. package/driver/runner.mjs +71 -33
  217. package/driver/saved-register-pages.mjs +4 -4
  218. package/driver/score-redaction.mjs +2 -2
  219. package/driver/search-policy.mjs +12 -13
  220. package/driver/settle-stamp.mjs +4 -3
  221. package/driver/skeptic-record.mjs +2 -2
  222. package/driver/skeptic-search.mjs +1 -1
  223. package/driver/skills/README.md +7 -7
  224. package/driver/skills/blind-frame/SKILL.md +1 -2
  225. package/driver/skills/case-law-citation/SKILL.md +9 -37
  226. package/driver/skills/case-law-citation/sources/courtlistener.md +1 -3
  227. package/driver/skills/case-law-citation/sources/eurlex.md +8 -11
  228. package/driver/skills/case-law-citation/sources/legaldatahunter.md +1 -1
  229. package/driver/skills/clearance-common-law/SKILL.md +45 -111
  230. package/driver/skills/clearance-common-law/perplexity-prompts.md +7 -79
  231. package/driver/skills/clearance-register/SKILL.md +15 -33
  232. package/driver/skills/clearance-register/digest.md +35 -96
  233. package/driver/skills/clearance-register/providers/clarivate.md +2 -2
  234. package/driver/skills/clearance-register/providers/corsearch.md +5 -5
  235. package/driver/skills/clearance-register/providers/euipo.md +1 -2
  236. package/driver/skills/clearance-register/providers/free-tier.md +0 -19
  237. package/driver/skills/clearance-register/providers/signa.md +6 -25
  238. package/driver/skills/clearance-register/providers/uspto-local.md +0 -24
  239. package/driver/skills/clearance-register/register-recipes.md +8 -15
  240. package/driver/skills/clearance-register/status-rules.md +6 -24
  241. package/driver/skills/clearance-register/unit.md +11 -20
  242. package/driver/skills/clearance-search/delivery-contract.md +24 -120
  243. package/driver/skills/clearance-search/field-doctrine-pharma.md +1 -5
  244. package/driver/skills/clearance-search/firm-wide-reasoning.md +24 -43
  245. package/driver/skills/clearance-search/phase2-execution.md +29 -77
  246. package/driver/skills/clearance-search/report-prose.md +3 -4
  247. package/driver/skills/clearance-search/risk-framework-demo.md +1 -1
  248. package/driver/skills/clearance-search/risk-framework-triage.manifest.json +3 -3
  249. package/driver/skills/clearance-search/risk-framework-triage.md +7 -9
  250. package/driver/skills/clearance-search/risk-framework.manifest.json +1 -1
  251. package/driver/skills/clearance-search/risk-framework.md +1 -1
  252. package/driver/skills/clearance-search/synthesis-rules.md +30 -107
  253. package/driver/skills/clearance-search/worked-examples.md +5 -5
  254. package/driver/skills/clearance-variants/SKILL.md +46 -45
  255. package/driver/skills/clearance-variants/transliteration-scripts.md +4 -4
  256. package/driver/skills/frame-diff/SKILL.md +1 -1
  257. package/driver/skills/knockout-assess/SKILL.md +6 -14
  258. package/driver/skills/knockout-frame/SKILL.md +1 -1
  259. package/driver/skills/matter-frame/SKILL.md +7 -12
  260. package/driver/skills/matter-frame/watchlist-reference.md +1 -4
  261. package/driver/skills/narrative-refutation/SKILL.md +20 -30
  262. package/driver/skills/placement-inquiry/SKILL.md +10 -20
  263. package/driver/skills-store-provenance.mjs +1 -1
  264. package/driver/stage-context.mjs +32 -35
  265. package/driver/stage-freshness.mjs +127 -11
  266. package/driver/stages-knockout.mjs +49 -22
  267. package/driver/stages.mjs +89 -288
  268. package/driver/status-snapshot.mjs +2 -1
  269. package/driver/steps/correction-cycle.mjs +311 -0
  270. package/driver/steps/corrections.mjs +644 -0
  271. package/driver/steps/delivery.mjs +1287 -0
  272. package/driver/steps/frame-comparison.mjs +927 -0
  273. package/driver/steps/intake.mjs +84 -0
  274. package/driver/steps/open-run.mjs +419 -0
  275. package/driver/steps/overview-and-cards.mjs +899 -0
  276. package/driver/steps/placement-and-digest.mjs +23 -0
  277. package/driver/steps/register-sweep.mjs +1563 -0
  278. package/driver/steps/skeptic-and-follow-up.mjs +836 -0
  279. package/driver/steps/synthesis.mjs +261 -0
  280. package/driver/steps/verdict-gate.mjs +968 -0
  281. package/driver/suite-census.json +456 -96
  282. package/driver/surface-exit-verdict.mjs +0 -8
  283. package/driver/synthesis-record.mjs +72 -6
  284. package/driver/terminal-clamp.mjs +10 -0
  285. package/driver/tokens.mjs +8 -62
  286. package/driver/tool-calls.mjs +2 -2
  287. package/driver/unexecuted-asserts.json +2 -2
  288. package/driver/unit-state-verdict.mjs +1 -1
  289. package/driver/usage-ledger.mjs +2 -1
  290. package/driver/verify-knockout.mjs +20 -35
  291. package/driver/verify.mjs +47 -36
  292. package/driver/web-grid.mjs +3 -4
  293. package/driver/whatif-memo-run.mjs +2 -2
  294. package/driver/whatif-queue.mjs +4 -3
  295. package/driver/withheld-families.mjs +14 -15
  296. package/driver/worker-heartbeat.mjs +3 -2
  297. package/driver/write-up-form.mjs +0 -3
  298. package/mcp-server/CHANGELOG.md +8 -0
  299. package/mcp-server/http-server.mjs +11 -12
  300. package/mcp-server/lib/brief.mjs +22 -4
  301. package/mcp-server/lib/events.mjs +2 -2
  302. package/mcp-server/lib/evidence.mjs +3 -2
  303. package/mcp-server/lib/findings.mjs +2 -1
  304. package/mcp-server/lib/knockout.mjs +9 -10
  305. package/mcp-server/lib/ops.mjs +9 -9
  306. package/mcp-server/lib/runs.mjs +9 -10
  307. package/mcp-server/lib/trace.mjs +1 -1
  308. package/mcp-server/lib/whatif.mjs +2 -3
  309. package/mcp-server/package.json +1 -1
  310. package/mcp-server/server.mjs +5 -5
  311. package/node_modules/buffers/package.json +1 -1
  312. package/package.json +2 -1
  313. package/portal-ui/dist/assets/{index-fPqAU0sx.js → index-CYaO2ygd.js} +26 -14
  314. package/portal-ui/dist/assets/{index-AtB9ZpDH.css → index-izLa9apq.css} +2 -2
  315. package/portal-ui/dist/index.html +4 -4
  316. package/portal-ui/package.json +3 -3
  317. package/providers/README.md +1 -1
  318. package/providers/_shared/answer-memory.mjs +4 -5
  319. package/providers/_shared/execute-plan.mjs +48 -1
  320. package/providers/_shared/records-from-search.mjs +46 -0
  321. package/providers/clarivate/README.md +2 -2
  322. package/providers/clarivate/src/adapter.js +147 -0
  323. package/providers/clarivate/src/core.js +1 -14
  324. package/{driver/engine/mcp/clarivate-server.mjs → providers/clarivate/src/mount.js} +5 -10
  325. package/providers/corsearch/README.md +3 -3
  326. package/providers/corsearch/src/adapter.js +80 -0
  327. package/providers/corsearch/src/core.js +14 -11
  328. package/{driver/engine/mcp/corsearch-server.mjs → providers/corsearch/src/mount.js} +5 -10
  329. package/providers/euipo/README.md +2 -2
  330. package/providers/euipo/src/adapter.js +85 -0
  331. package/providers/euipo/src/core.js +1 -1
  332. package/providers/euipo/src/euipo-client.js +1 -2
  333. package/{driver/engine/mcp/euipo-server.mjs → providers/euipo/src/mount.js} +5 -10
  334. package/providers/free-tier/README.md +2 -2
  335. package/providers/free-tier/src/adapter.js +127 -0
  336. package/{driver/engine/mcp/free-tier-server.mjs → providers/free-tier/src/mount.js} +5 -10
  337. package/providers/jx-subclass/coverage.mjs +1 -6
  338. package/providers/jx-subclass/score-truth.mjs +2 -1
  339. package/providers/oauth-mcp-bridge/CHANGELOG.md +8 -0
  340. package/providers/oauth-mcp-bridge/package.json +1 -1
  341. package/providers/perplexity/src/core.js +2 -2
  342. package/providers/signa/README.md +2 -2
  343. package/providers/signa/src/adapter.js +157 -0
  344. package/providers/signa/src/capabilities.js +0 -3
  345. package/providers/signa/src/core.js +2 -2
  346. package/{driver/engine/mcp/signa-server.mjs → providers/signa/src/mount.js} +7 -12
  347. package/providers/signa/src/offices.generated.js +17 -15
  348. package/providers/uspto-local/README.md +1 -1
  349. package/providers/uspto-local/bin/verify-index.mjs +1 -1
  350. package/providers/uspto-local/src/adapter.js +75 -0
  351. package/{driver/engine/mcp/uspto-local-server.mjs → providers/uspto-local/src/mount.js} +5 -10
  352. package/scripts/band-shape-probe.mjs +2 -2
  353. package/scripts/citation-line-check.mjs +7 -7
  354. package/scripts/compare.mjs +1 -1
  355. package/scripts/dead-names.mjs +2 -2
  356. package/scripts/e2e-first-time.mjs +19 -7
  357. package/scripts/e2e.mjs +13 -13
  358. package/scripts/engine-probe.mjs +1 -1
  359. package/scripts/env-audit.mjs +7 -4
  360. package/scripts/env-classify.mjs +5 -1
  361. package/scripts/feedback-mint.mjs +1 -1
  362. package/scripts/freeze-example-run.mjs +7 -7
  363. package/scripts/mint-suite-census.mjs +2 -2
  364. package/scripts/nightly-notice.mjs +1 -1
  365. package/scripts/release-cut-decision.mjs +7 -2
  366. package/scripts/release-note-required.mjs +26 -9
  367. package/scripts/release-notes-lint.mjs +3 -2
  368. package/scripts/release-version-pr-checks.mjs +1 -1
  369. package/scripts/render-check.mjs +1 -1
  370. package/scripts/settings-render-check.mjs +23 -3
  371. package/scripts/test-run.mjs +5 -5
  372. package/scripts/travelling-predicates.mjs +1 -1
  373. package/scripts/undeclared-field-census.mjs +1 -1
  374. package/scripts/unexecuted-asserts.mjs +3 -3
  375. package/scripts/verify-publishable.mjs +1 -1
  376. package/shared/client-door.mjs +1 -1
  377. package/shared/connect-clients.mjs +1 -1
  378. package/shared/connector-signin-probe.mjs +1 -1
  379. package/shared/customer-store.mjs +3 -2
  380. package/shared/env-aliases.mjs +1 -1
  381. package/shared/invocation.mjs +14 -2
  382. package/shared/names-in-force.mjs +2 -0
  383. package/shared/register-selection.mjs +2 -2
  384. package/shared/store-in-repo.mjs +3 -3
  385. package/shared/summary-blocks.mjs +0 -3
  386. package/shared/trigger-lane.mjs +1 -1
  387. package/shared/vacuous-pass.mjs +2 -2
  388. package/shared/verb-shim.mjs +4 -2
  389. package/vendor/buffers/package.json +1 -1
  390. package/node_modules/exceljs/README.md +0 -3023
@@ -0,0 +1,296 @@
1
+ // SPDX-License-Identifier: AGPL-3.0-only
2
+ // Copyright 2026 Cordillera Sàrl. Additional terms under section 7 of the AGPL-3.0 apply — see ADDITIONAL-TERMS.md
3
+ // next-rung.mjs — what the stage ladder does after a failed attempt.
4
+ //
5
+ // The stage ladder (gateway.mjs runStageLadder) asks this once an attempt has failed, been rescued or not
6
+ // (rescue.mjs) and been named (turn-failure.mjs). The answer is one of four: "retry" goes on to the next attempt,
7
+ // "break" stops the ladder and lets the stage fail on what it has, "identical" stops it because the failure
8
+ // repeated byte for byte, and "rate-limited" returns at once so the run can be postponed. It also returns the
9
+ // ladder state the decision moves: the escalation point, the refunded rungs, the timeout retry and its budget.
10
+
11
+ import { runLog, note } from "../log.mjs";
12
+ import { everyToolCallRefused } from "../engine/tool-refusal.mjs";
13
+
14
+ // #5b — stop a WARM attempt after ONE try when it ran to the HARD WALL. The warm patch is the one rung that resumes
15
+ // a session: it is passed the session that just produced a content failure. If that resumed turn was SIGKILLed at
16
+ // the full timeout+60 wall (signals.hardWall, NOT a 0-token stall), break and let the caller record the
17
+ // coverage-limited deferral. A warm attempt can itself time out; warmEligible() only stops the attempt AFTER a
18
+ // timeout from being warm. A FOLLOWUP IS NOT STOPPED HERE. It is a new stage() call, attempt 1, with no resumeRef,
19
+ // so it is a fresh session with its own wall. This rule used to stop it too, on the premise that it resumed an
20
+ // already-loaded session, and that premise was false; it now gets the one extended retry any fresh dispatch gets.
21
+ // Measured 2026-11-05 over saved runs: no follow-up attempt and no warm attempt had timed out, so neither form of
22
+ // the rule had decided a run. A STALL (no hardWall) is NOT stopped here: it keeps its one retry at the same budget,
23
+ // since a transient stall can clear. PURE + exported for test: the live path needs a wall-clock kill.
24
+ export function warmHardWallStop({ fail, warm, signals }) {
25
+ return fail === "timeout" && Boolean(warm) && Boolean(signals?.hardWall);
26
+ }
27
+
28
+ // criterion 1 — A WARM TURN THAT NEVER REACHED THE MODEL DOES NOT COST A RUNG, ONCE.
29
+ //
30
+ // Measured before this existed: a warm turn returning `usage: null` and `runId: null` — the
31
+ // startup-death shape, exit 1 under a second, zero tokens — still advanced the ladder. A stage with
32
+ // three attempts spent one on a turn that did nothing, which is the defect this issue names: "a
33
+ // warm-patch attempt either reaches the model or does not consume a ladder rung."
34
+ //
35
+ // THE BOUND IS THE WHOLE DESIGN. Refunding unconditionally lets a warm turn that never lands loop
36
+ // until the wall. ONE free rung per ladder is the concession; a second zero-usage warm turn in the
37
+ // same ladder is charged, and the record says so rather than leaving the difference to be inferred.
38
+ //
39
+ // PROVISIONAL, and deliberately one line to change: the number below is a routed parameter (2026-08-22),
40
+ // not a measured optimum. Nobody has yet counted how often a second free rung would have
41
+ // converted, and until someone does, 1 is the smallest concession that closes the defect.
42
+ //
43
+ // THE CHARGING BRANCH CANNOT FIRE TODAY, and that is stated rather than left to be discovered. `warm`
44
+ // requires `!warmUsed` and `warmUsed` is set the moment one fires, so a ladder gets AT MOST ONE warm
45
+ // turn — there can be no second zero-usage warm turn to charge. This counter is therefore defence, not
46
+ // arithmetic anyone reaches: it keeps the bound LOCAL and explicit, so that if the one-warm-per-ladder
47
+ // invariant is ever relaxed, the refund does not silently become unbounded along with it. Deriving the
48
+ // bound from `warmUsed` instead would have coupled a rung policy to an unrelated rule and hidden the
49
+ // dependency. The arms pin the invariant as the premise rather than pretending to exercise the branch.
50
+ const WARM_ZERO_USAGE_FREE_RUNGS = 1;
51
+
52
+
53
+ export function nextRung({ fail, warm, attempt, maxRetries, attemptFails, usage, json, turn, signals, runDir, name, timeoutSec,
54
+ saidBackOpen, warmEscalatedAt, rungsRefunded, timeoutRetriesUsed, effTimeout }) {
55
+ const out = (rung) => ({ rung, warmEscalatedAt, rungsRefunded, timeoutRetriesUsed, effTimeout });
56
+ // A4 (addendum 2026-07-30): a byte-identical CONTENT failure signature on consecutive attempts is a
57
+ // proven-deterministic defect — the previous attempt already carried this exact validator string and
58
+ // the corrective/warm re-dispatch reproduced it byte-for-byte, so another paid turn cannot converge
59
+ // (VENZY/E2E-R2: 63% of the run was correction, much of it re-buying identical failures). Stop NOW
60
+ // and park honestly: the run-level recovery ladder (classifyFailureReason → one "unknown" park →
61
+ // repeat-signature terminal) owns what happens next, with proper accounting — that lane's single
62
+ // fresh sample replaces the blind third attempt this used to buy. Scoped to the content classes
63
+ // (missing_file / invalid_file / max_tokens_no_output — same stage, same validator string); every
64
+ // transport class keeps its own policy (timeout's single extended shot, and the
65
+ // wedge/overload breaks above and below).
66
+ //
67
+ // BUILD 2 — A4's PREMISE FAILS ON EXACTLY ONE ATTEMPT, AND IT IS THE ONE IT USUALLY FIRES ON.
68
+ // "Another paid turn cannot converge" assumes the two consecutive attempts are independent samples.
69
+ // A warm patch is not a sample: it RESUMES the session that produced the previous failure (key =
70
+ // lastKey, resumeRef = lastSessionRef), so a session that wrote a document with zero rulings writes
71
+ // it again. It has no capacity to disagree with itself, and its repeat proves nothing about whether
72
+ // a fresh dispatch would converge.
73
+ //
74
+ // The 2026-08-07 round measured both sides of this on the meaning-sweep stage. Where it cost a run:
75
+ // fresh ruled 0 of 72 → warm ruled 0 of 72, byte-identical, the artifact never rewritten → A4 broke
76
+ // the ladder at 2 of 3 with attempt 3's budget unspent → RECOVERABLE park, ~90s, one of three defect
77
+ // lanes → the recovery lane then re-dispatched FRESH and ruled 69 of 72. Two dispatches and a park to
78
+ // reach the attempt the ladder still had in hand. The control is the run whose warm attempt MOVED
79
+ // (78 unruled → 1): the string changed, A4 never fired, and cold attempt 3 cleared it in the ladder.
80
+ //
81
+ // So: discard the SESSION, not the ladder. Fall through to attempt N+1, which is necessarily FRESH
82
+ // (`warmUsed` is already spent, so `warm` cannot be true again) and carries the full corrective
83
+ // message. Three existing bounds keep this finite and none of them is new or relaxed here:
84
+ // 1. `warmUsed` caps warm at ONE attempt per stage run, and `warm` is this escalation's trigger —
85
+ // so the escalation can fire at most once per ladder, structurally. It is never reset below.
86
+ // 2. `while (attempt < maxRetries + 1)` is untouched: the ceiling stays 3 attempts in production.
87
+ // 3. The guard below only escalates when a further attempt already exists. With no budget left the
88
+ // break happens exactly as it does today, terminal signal intact.
89
+ // Worst case: fresh(X) → warm(X, escalate) → fresh(X) → A4 fires normally (attempt 3 is not warm) →
90
+ // terminal at 3 attempts.
91
+ //
92
+ // The escalated dispatch does NOT re-buy the paid sweep: perplexity-server short-circuits on a
93
+ // complete recorded ledger ("the sweep is a fact of this run, not of this attempt"), and the seat
94
+ // opens a form already carrying every prior ruling.
95
+ //
96
+ // NOT de-allowlisting the connotation family from WARM_ELIGIBLE_RE instead: on the same round another
97
+ // clearance cleared 61 unruled → 0 on a warm attempt 2. That lane works, and removing it would cost
98
+ // every run that converges on it. This refuses to treat a warm no-op as proof, and nothing more.
99
+ const identicalContent = /^(missing_file:|invalid_file:|max_tokens_no_output)/.test(fail)
100
+ && attemptFails.length >= 2 && attemptFails[attemptFails.length - 2] === fail;
101
+ // ── — THE ESCALATION IS FOR A SEAT THAT PRODUCED SOMETHING ───────────────────────────────
102
+ //
103
+ // BUILD 2 (above) buys ONE fresh attempt after a warm repeat, because a resumed session cannot
104
+ // disagree with itself and its repeat proves nothing about a fresh dispatch. Measured, that is true
105
+ // of a seat whose output was WRONG and false of a seat that wrote nothing at all:
106
+ //
107
+ // invalid_file repeated (the seat produced something) fresh attempt 3 converged 9 of 9
108
+ // missing_file repeated (the seat produced nothing) fresh attempt 3 converged 0 of 6
109
+ //
110
+ // The second case cost ~3.4 min and ~19k output tokens per affected run for an attempt that has never
111
+ // once converged. So the escalation keeps its budget where it pays and stops buying the case where it
112
+ // does not. This is the deterministic-vs-transient line asked for, drawn on what the record
113
+ // already shows before attempt 3 is spent — not a shorter ladder, which would hide the escalation
114
+ // rather than decide it.
115
+ //
116
+ // A CHANGED FAILURE IS NEVER CUT, and that is structural rather than a second condition:
117
+ // `identicalContent` requires this attempt's failure to repeat the previous one byte-for-byte, so a
118
+ // run that moved missing_file → invalid_file never reaches here at all. Two of the measured runs did
119
+ // exactly that, with real quantity — precisely where the ladder earns its keep.
120
+ //
121
+ // `noChange` says the same thing one line up and is NOT read here on purpose: it is RECORDING ONLY,
122
+ // and no break/park/terminate decision reads it ( owns that policy). `identicalContent` is the
123
+ // live signal this branch already decides on, so the rule needs no new input.
124
+ //
125
+ // SIX IS SIX, and all of it from the test box. If a fresh attempt 3 ever converges after a
126
+ // produced-nothing repeat, this is the line to revisit — the note below names the case in the run log
127
+ // so that event is findable rather than silent.
128
+ const producedNothing = /^missing_file:/.test(fail);
129
+ // (round 2) — THE CUT WAS RECORDED AND THE BREAK BESIDE IT WAS NOT, SO THE PATHOLOGY SURVIVED.
130
+ //
131
+ // The comment below says a decision that prevents an attempt must leave a trace. It shipped attached
132
+ // to ONE of the two branches that prevent one. Measured on a delivered run of the test instance (engine 734689e8): the
133
+ // marker `escalationDeclined` appears in ZERO files anywhere in the workspace, because the cut also
134
+ // requires `warm` and that run's attempt rows carry no `warm` field at all — while `"warm"` appears
135
+ // in 98 jsonl files instance-wide, so the absence is the run's, not the field's. With `warm` falsy
136
+ // the run fell through to the pre-existing `else if (identicalContent)` break, which stopped attempt
137
+ // 3 exactly as the cut would have and recorded NOTHING: its note is gated on `warm`, and note() is
138
+ // stderr regardless.
139
+ //
140
+ // `warm` is CORRECT on the cut and is not an accidental narrowing of the decision: the thing being
141
+ // declined is the warm→fresh escalation, which only exists on a warm attempt. On a cold path there is
142
+ // no escalation to decline — the ladder simply breaks. What was narrowed with it was the RECORDING,
143
+ // and both branches end the same way, with budget still in hand.
144
+ //
145
+ // ONE STATEMENT, so a third branch cannot arrive recording a fourth shape. `wouldHaveBeenAttempt` is
146
+ // the number when budget remained and NULL when the ladder was genuinely spent — that is the whole
147
+ // difference between a choice and an ending, and a row that printed `attempt + 1` unconditionally
148
+ // would claim a prevented attempt that never existed.
149
+ // THE RUN SPINE, NOT THE SEAT JSONL — and the first cut had this wrong.
150
+ //
151
+ // `_driver/<stage>.jsonl` IS THE ATTEMPT LEDGER. Nothing states that in one place, and it is relied on
152
+ // everywhere: convergence-ledger derives quantities per row, warm-retry and retry-backoff count rows as
153
+ // attempts, seat-attempts.mjs claims any row carrying `{attempt:int≥1, key, status}` as a dispatch for
154
+ // seat-retry-report's statistics. A decision is not an attempt, and filing one there put a row with no
155
+ // quantity into ledgers that derive quantities — four test files caught it the moment this fired on a
156
+ // path that is actually common. The escalation cut merged into that file first and had the same fault
157
+ // latent: it fires only on warm produced-nothing, so nothing had reached it yet.
158
+ //
159
+ // `run.jsonl` is where this codebase already files the things that are NOT attempts — `form-repair`
160
+ // above, `repair-attempted`, `engine-turn-probe`. It is durable, it is one file per run, and it is the
161
+ // one the wall decomposition deliberately skips. Findable was the requirement; the seat ledger was
162
+ // never what made it so.
163
+ const recordAttemptPrevented = (decision, rule) => {
164
+ try {
165
+ runLog(runDir, {
166
+ event: "attempt-prevented", stage: name, attempt, of: maxRetries + 1, decision, rule,
167
+ fail: String(fail).slice(0, 200),
168
+ warm: Boolean(warm), producedNothing,
169
+ // The whole difference between a CHOICE and an ENDING. Null when the ladder was genuinely spent:
170
+ // printing `attempt + 1` there claims a prevented attempt that never existed, and every count
171
+ // taken off these rows would be high by exactly the runs that had nothing left to prevent.
172
+ // Null and PRESENT — an omitted key cannot be told from a row written before this existed.
173
+ wouldHaveBeenAttempt: attempt < maxRetries + 1 ? attempt + 1 : null,
174
+ });
175
+ } catch { /* telemetry best-effort — never fail a turn over a journal line */ }
176
+ };
177
+ // criterion 1 — the rung decision, recorded on BOTH branches.
178
+ //
179
+ // `usage == null && runId == null` is the seat never having answered: no token count and no run
180
+ // identity, which together mean the turn died before the model saw it. Either alone is weaker —
181
+ // a turn can legitimately report no usage on some paths — so both are required.
182
+ const zeroUsageWarm = Boolean(warm) && fail && usage == null && json?.runId == null;
183
+ if (zeroUsageWarm) {
184
+ const free = rungsRefunded < WARM_ZERO_USAGE_FREE_RUNGS;
185
+ if (free) rungsRefunded++;
186
+ note(`[${name}] attempt ${attempt} [warm patch] returned no usage and no runId — it never reached the model`
187
+ + (free ? `; NOT charging the ladder a rung for it (${rungsRefunded}/${WARM_ZERO_USAGE_FREE_RUNGS} free rungs used)`
188
+ : `; CHARGING it — the ladder has already refunded ${rungsRefunded}, and a second one would let a warm turn that never lands loop`));
189
+ try {
190
+ runLog(runDir, { event: "warm-rung", stage: name, attempt, of: maxRetries + 1 + rungsRefunded,
191
+ rung_free: free,
192
+ reason: free ? "warm turn never reached the model" : "second zero-usage warm turn",
193
+ free_rungs_used: rungsRefunded, free_rungs_max: WARM_ZERO_USAGE_FREE_RUNGS,
194
+ fail: String(fail).slice(0, 200) });
195
+ } catch { /* telemetry best-effort — never fail a turn over a journal line */ }
196
+ }
197
+ // Exactly one row per prevented attempt: the warm produced-nothing case satisfies the cut AND then
198
+ // falls into the break below, and two rows for one decision would double every count taken off them.
199
+ const cutFired = identicalContent && producedNothing && warm && attempt < maxRetries + 1;
200
+ if (cutFired) {
201
+ 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.`);
202
+ // THE CUT IS RECORDED, NOT JUST NOTED. `note` is stderr only (log.mjs) and reaches no artifact, so
203
+ // the run record held no trace of a decision that PREVENTS an attempt — and because the cut
204
+ // returns, the prevented attempt never runs. n=6 would therefore be permanent: a seat or model
205
+ // change that made attempt 3 worth buying again could not be noticed, because nothing anywhere
206
+ // counts how often the cut fired or on what. Its own row in the seat's attempt jsonl, where every
207
+ // attempt already lives, is the smallest thing that makes it findable.
208
+ //
209
+ // FINDABILITY ONLY. This samples nothing: the prevented attempt is still prevented, and the row
210
+ // records the case rather than the counterfactual. Re-opening the question needs a deliberate
211
+ // measurement, not a quiet retry ladder that buys one anyway.
212
+ recordAttemptPrevented("escalation-declined:produced-nothing", "#1062");
213
+ }
214
+ if (identicalContent && !producedNothing && warm && attempt < maxRetries + 1) {
215
+ warmEscalatedAt = attempt + 1;
216
+ 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)`);
217
+ } else if (identicalContent) {
218
+ // — NOT said when the break was a CHOICE. A produced-nothing repeat reaches here with budget
219
+ // still in hand, and "there is no attempt left" would be false: the attempt exists and was
220
+ // deliberately not spent. Its own note above says which case this is.
221
+ 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`);
222
+ 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`);
223
+ // RECORDED, on the path the cut does not reach. This break is the PRE-EXISTING rule and this change
224
+ // does not re-decide it: my 0-of-6 measurement is about the warm→fresh escalation and licenses
225
+ // nothing about a cold break. It makes the population countable, which is what a later ruling on
226
+ // that question would need and could not have had.
227
+ if (!cutFired) recordAttemptPrevented("ladder-break:identical-signature", "#460");
228
+ // A said-back refusal the step left as it was: the pass stands, below, with what it left open recorded.
229
+ if (saidBackOpen) return out("break");
230
+ return out("identical");
231
+ }
232
+
233
+ // Lane-wedge: the turn never got a command lane (0 tokens). The extended ×1.5 shot can't help (it produced
234
+ // nothing), and another attempt on a SHARED lane cannot help — so stop here and hand it on fast. The
235
+ // lane-wedge retry in stage() (pipeline.mjs) waits for the lane to clear and dispatches the stage again.
236
+ if (fail === "lane_wedge") return out("break");
237
+ //: a model mismatch is a CONFIGURATION fault, not a transient. The next attempt sends the same
238
+ // argv to the same provider and gets the same substitution, so retrying only buys the wrong model
239
+ // twice. Break immediately and let the stage fail with the mismatch named on every row.
240
+ if (fail.startsWith("model_mismatch:")) {
241
+ note(`[${name}] model mismatch is deterministic — breaking the ladder (a retry re-buys the same wrong model)`);
242
+ return out("break");
243
+ }
244
+ // A sign-in that could not be refreshed refuses every attempt the same way: the next one sends the
245
+ // same credential and gets the same 401, seconds apart. Break, and let the stage fail with it named.
246
+ if (fail.startsWith("engine_signed_out:")) {
247
+ note(`[${name}] the engine's sign-in could not be refreshed — breaking the ladder (a retry re-sends the same credential)`);
248
+ return out("break");
249
+ }
250
+ // EVERY TOOL CALL THE TURN MADE WAS REFUSED. On some hosts codex's own sandbox refuses the stage's
251
+ // tool servers while the turn reports success, and the stage then fails for want of what the tools
252
+ // would have produced. The next attempt spawns the same sandbox and is refused the same way, so a
253
+ // retry re-buys the refusal: measured at three paid attempts per stage on a production run before the
254
+ // identical-failure break stopped it. Break on the first. A turn where any call completed is not this.
255
+ if (everyToolCallRefused(turn)) {
256
+ note(`[${name}] every tool call this turn made was refused (${turn.mcpToolCallsRefused}) — breaking the ladder (a retry is refused the same way)`);
257
+ return out("break");
258
+ }
259
+ // D3: overload (529 / status_overloaded) — stop the ladder here: an in-ladder re-attempt hammers an
260
+ // API that just said it is overloaded, seconds apart, on the SAME model. Breaking hands the failure
261
+ // to the existing machinery: the stage fails on its one model (there is no model cascade), and that
262
+ // failure parks the run for recovery with escalating backoff (TRANSIENT_RE → .postponed).
263
+ if (fail === "status_overloaded") return out("break");
264
+ // Rate-limit: do NOT retry (every retry hits the same capped subscription) and do NOT fall back — return
265
+ // immediately so the pipeline can postpone + auto-resume after the window. resetsAt rides the result.
266
+ if (fail === "rate_limited") return out("rate-limited");
267
+ // Timeout-aware retry: a genuinely over-budget/hung stage will just re-time-out on an identical
268
+ // attempt (the v14 delivery burned 3 × 600s). Give it exactly ONE longer shot, then stop.
269
+ if (fail === "timeout") {
270
+ // A WARM attempt, the one rung that resumes a session, that ran to its HARD WALL breaks after this attempt,
271
+ // and the caller records the coverage-limited DEFERRAL (which the gate clamps CLEAR→CONDITIONAL). A
272
+ // FOLLOWUP is a fresh session and is not stopped here: it takes the one extended retry below, as any fresh
273
+ // dispatch does. Until 2026-11-05 a followup stopped here too, on the false premise that it resumed a loaded
274
+ // session. See warmHardWallStop.
275
+ if (warmHardWallStop({ fail, warm, signals })) {
276
+ note(`[${name}] warm attempt hit the hard wall — breaking (recording the deferral)`);
277
+ return out("break");
278
+ }
279
+ if (timeoutRetriesUsed >= 1) {
280
+ note(`[${name}] second timeout — stopping (won't finish on a 3rd identical attempt)`);
281
+ return out("break");
282
+ }
283
+ timeoutRetriesUsed++;
284
+ // Stall honesty (charter P1 §1): a STALL kill (byte-silent or no-progress — signals.stalled) is NOT
285
+ // "the stage needed more time" — the R-round evidence retry did the identical work in 369s after a
286
+ // 1500s stall burn. Retry ONCE at the SAME budget; extending would only extend the next stall's burn.
287
+ // A hard-wall kill (a genuine over-budget grind) keeps the single 1.5× extended shot.
288
+ if (signals?.stalled) {
289
+ note(`[${name}] stall kill${signals?.noProgress ? " (no-progress watchdog)" : ""} → one retry at the SAME ${effTimeout}s budget (a stall is not a slow turn)`);
290
+ } else {
291
+ effTimeout = Math.round(timeoutSec * 1.5);
292
+ note(`[${name}] timeout → one extended retry at ${effTimeout}s`);
293
+ }
294
+ }
295
+ return out("retry");
296
+ }
@@ -0,0 +1,146 @@
1
+ // SPDX-License-Identifier: AGPL-3.0-only
2
+ // Copyright 2026 Cordillera Sàrl. Additional terms under section 7 of the AGPL-3.0 apply — see ADDITIONAL-TERMS.md
3
+ // rescue.mjs — when a failed attempt's own artifacts are the stage's answer after all.
4
+ //
5
+ // The stage ladder (gateway.mjs runStageLadder) asks this after a turn fails and before the failure is named
6
+ // (turn-failure.mjs nameTheFailure). Two rescues: a nonzero exit whose artifacts this attempt wrote whole, and a
7
+ // hard-wall kill whose artifacts had been quiet long enough to be complete. Each refusal is recorded with its cause.
8
+
9
+ import { statSync } from "node:fs";
10
+ import { note } from "../log.mjs";
11
+
12
+ // ── — WALL RESCUE QUIESCENCE. How long every declared artifact must have been UNTOUCHED when the
13
+ // turn settled, for its write to count as provably COMPLETE rather than possibly torn.
14
+ //
15
+ // The torn-write window is [watchdog decision, child death]: one poll tick plus the SIGTERM→SIGKILL
16
+ // escalation (engine/common.mjs killEscalateMs, default 5000ms). 60s is that window with an order of
17
+ // magnitude to spare, and the incident clears it by another: on the 2026-08-04 R1 run the
18
+ // placement artifact's last write was 13:58:46Z and the wall kill was 14:15:00Z — 974 seconds quiet.
19
+ //
20
+ // This is the ONE fact a shape validator cannot supply, and it is the entire reason this rescue may do
21
+ // what the exit-1 rescue must not. Setting it to 0 is NOT tuning — it deletes the only completeness
22
+ // evidence and would rescue post-merge audit 2's torn draft. Disarm with CLEAROTRON_WALL_RESCUE=0 instead.
23
+ const wallRescueQuiesceMs = () => 60000; // step 3 — was a knob; no environment ever set it
24
+ const wallRescueEnabled = () => !/^(0|off|false|no)$/i.test(String(process.env.CLEAROTRON_WALL_RESCUE ?? "").trim());
25
+
26
+ // Exit-1 adapter truth (charter P1 §2): the claude CLI reports a provider error on the FINAL assistant
27
+ // message (an HTTP 500 after the work was done) as subtype:"success" + is_error:true, which the adapter
28
+ // rightly converts to a nonzero exit — but by then the turn's Write already landed the artifact, and
29
+ // re-running finished work burned ~35 min on the R-round evidence run. So before a nonzero exit is
30
+ // accepted as failure, judge the ARTIFACT exactly as the skip path does (exists + validates), with one
31
+ // extra requirement the skip path doesn't need: the file must have been WRITTEN by THIS ATTEMPT
32
+ // (differs from the attempt-start snapshot) — an inherited/stale file, and equally an EARLIER
33
+ // ATTEMPT's file, never rescues a failed turn.
34
+ //
35
+ // A KILL ANYWHERE IN THIS LADDER CLOSES THE RESCUE (post-merge audit 2, 2026-07-31). The design
36
+ // always said the rescue "never applies to a kill — a cut-down turn's artifact may be mid-write";
37
+ // testing only the CURRENT attempt's `killed` honoured that one attempt at a time, so attempt 1 =
38
+ // kill that wrote a torn partial + attempt 2 = nonzero exit shipped the partial as stage truth.
39
+ // Both legs of the fix are needed, because they refuse different things:
40
+ // · the per-attempt snapshot refuses an EARLIER attempt's bytes outright;
41
+ // · `killSeen` refuses this attempt's own write once a kill has torn the file underneath it —
42
+ // freshness is `stat differs`, i.e. a MUTATION, never a proof of complete rewrite (a patch, an
43
+ // append, or a Write killed mid-flush all satisfy it), and a stage `validate` is a SHAPE check,
44
+ // not a completeness proof: the audit repro is a torn draft that passes its own validator.
45
+ // Only register stages carry a backstop for this (register-taint.mjs, on these very rows);
46
+ // synthesis / narrative / cards / digest have none, and synthesis is where the evidence run took its
47
+ // 137 hard-wall kill. This does NOT touch the plain retry ladder register-taint's corpus audit found
48
+ // benign (kill → fresh full redo that EXITS CLEAN): that turn reports completion and is gated on its
49
+ // final state by the normal success path above. The rescue is the opposite case by construction — the
50
+ // turn did not report completion, and completeness of its write is exactly what is unknown.
51
+ // Still never applies to a rate-limit rejection either (0 tokens, nothing written).
52
+ //
53
+ // `wroteTruth(why)` is the ladder's one judgement of this attempt's artifacts: present, written by this attempt and
54
+ // passing the stage's validator. Returns the failure after the rescues, null when one accepted the artifacts, with
55
+ // what the attempt row records about it.
56
+ export function rescueAttempt({ fail, files, killClass, killSeen, signals, validate, wall, settledAt, name, rel, wroteTruth }) {
57
+ let rescued = null;
58
+ let quiescentMs = null; //: how long the artifact had been untouched when the turn settled
59
+ let rescueRefused = null; //: WHICH of the rescue's four causes refused — on the row, not only in a note
60
+ let rescueRefusedFile = null, rescueRefusedReason = null; //: and which file, and on what
61
+ if (fail && /^nonzero_exit_/.test(fail) && files.length) {
62
+ if (killClass || killSeen) {
63
+ 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`);
64
+ } else if (wroteTruth()) {
65
+ rescued = fail;
66
+ fail = null;
67
+ 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)`);
68
+ }
69
+ }
70
+ // ── — THE WALL RESCUE ────────────────────────────────────────────────────────────────────
71
+ //
72
+ // A stage SIGKILLed at its hard wall AFTER it had already written a complete, valid artifact is a
73
+ // stage that SUCCEEDED. Measured on R1 2026-08-04: placement-inquiry walled twice (1861s/1800s and
74
+ // 2760s/2700s, both `wrote: true`, the second `noChange: true`), parked the run — and the resume two
75
+ // minutes later SKIPPED it, because pipeline.mjs's skip predicate found the artifact present and
76
+ // passing its own validator. 77 minutes of dispatch, 335,782 output tokens and one park out of a
77
+ // budget of three, all spent after the deliverable was finished.
78
+ //
79
+ // WHY THIS MAY DO WHAT THE EXIT-1 RESCUE ABOVE MUST NOT. That refusal is not wrong and is not being
80
+ // reversed: post-merge audit 2 pinned a torn draft that CLEARS its own shape validator, and
81
+ // `stat differs` is a mutation, never a proof of complete rewrite. What this arm adds is the one
82
+ // fact neither has — QUIESCENCE. The torn-write window is [watchdog decision, child death]: a poll
83
+ // tick plus the SIGTERM→SIGKILL escalation, single-digit seconds. An artifact that had been
84
+ // untouched for a full minute when the turn settled was not being written when the turn was killed.
85
+ // On the incident the margin was 974 seconds. On the audit's repro it is zero, which is why that
86
+ // fixture still fails exactly as it did.
87
+ //
88
+ // AND IT ADMITS NOTHING THE RESUME WOULD REFUSE. The skip predicate accepts these same bytes minutes
89
+ // later on the same disk; this only stops the run paying a second wall, a park and a resume to reach
90
+ // the same answer. The resume's `!freshness.stale` arm is deliberately NOT copied: it compares
91
+ // declared inputs against a stamp written only on success, so at kill time it is not merely
92
+ // unnecessary but meaningless — and the stage cannot be stale against inputs it has just this moment
93
+ // read and acted on.
94
+ //
95
+ // A stage with no validator, or whose artifact fails it, or which never wrote, is untouched.
96
+ else if (fail === "timeout" && signals?.hardWall && files.length && validate && wallRescueEnabled()) {
97
+ // — A FILE THAT COULD NOT BE STAT'ED IS NAMED, WITH WHY, rather than folded into a number. It
98
+ // used to be a -1 in `quiescentMs` and the cause `artifact-unreadable`, and the commonest way to get
99
+ // there is not a filesystem fault at all: the turn was killed before it wrote. Measured on two
100
+ // stages of one run, 2026-09-10: both rows read `wrote: false`, `quiescentMs: -1`,
101
+ // `artifact-unreadable`, for files that did not exist. An ABSENT file (ENOENT) is its own cause now;
102
+ // `artifact-unreadable` stays for a stat that fails any other way, with its error code. Rows
103
+ // written before this change say `artifact-unreadable` for both.
104
+ //
105
+ // `quiescentMs` IS A MEASUREMENT OR IT IS ABSENT. With a file unstat'able there is no quiescence of
106
+ // the set to measure, so it stays null and the row omits it: a -1 reads as a number to anything that
107
+ // averages or compares it. An mtime that lands after the settle instant (written in that same
108
+ // instant, or a clock step) measures 0 rather than a negative; it is the under-quiescence case.
109
+ let missing = null;
110
+ const quiet = [];
111
+ for (const f of files) {
112
+ try { quiet.push(Math.max(0, settledAt - statSync(f).mtimeMs)); }
113
+ catch (e) { if (!missing) missing = { file: rel(f), code: String(e?.code ?? "unknown") }; }
114
+ }
115
+ quiescentMs = missing || !quiet.length ? null : Math.min(...quiet);
116
+ const bar = wallRescueQuiesceMs();
117
+ const why = {};
118
+ if (quiescentMs !== null && quiescentMs >= bar && wroteTruth(why)) {
119
+ rescued = fail;
120
+ fail = null;
121
+ 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)`);
122
+ } else {
123
+ // Said out loud, because "the rescue considered it and refused" and "the rescue never looked"
124
+ // must not be the same silence. This is the file that reads an absence as a diagnosis otherwise.
125
+ //
126
+ // — AND SAID ON THE ROW, not only in a note. The note goes to the operator's console; the
127
+ // JOURNAL is what a later round reads, and `rescued: null` reads identically for all three
128
+ // refusal causes. Measured on the 2026-08-09 R1: placement-inquiry was killed at its
129
+ // hard wall having WRITTEN its artifact and lain quiescent for 371 s against a 60 s bar — so the
130
+ // rescue was refused on the third cause, its validator — and 31 minutes of finished work were
131
+ // discarded and re-run cold. `grep -c rescue run.jsonl` on that run returns 0. Nothing in the
132
+ // record said why, and reconstructing it took a file-mtime comparison against a preserved run dir.
133
+ rescueRefused = missing ? (missing.code === "ENOENT" ? "artifact-absent" : "artifact-unreadable")
134
+ : quiescentMs < bar ? "under-quiescence"
135
+ : "not-written-by-this-attempt-or-invalid";
136
+ // — AND WHICH FILE, AND ON WHAT: an unstat'able file with its error code; under the bar, the file
137
+ // touched last (`quiescentMs` carries the number); otherwise the first file the artifact judgement
138
+ // failed, with its cause — `absent`, `not-written-by-this-attempt`, or the validator's own reason.
139
+ if (missing) { rescueRefusedFile = missing.file; rescueRefusedReason = missing.code; }
140
+ else if (quiescentMs < bar) rescueRefusedFile = rel(files[quiet.indexOf(quiescentMs)]);
141
+ else { rescueRefusedFile = why.file ?? null; rescueRefusedReason = why.reason ?? why.cause ?? null; }
142
+ 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`);
143
+ }
144
+ }
145
+ return { fail, rescued, quiescentMs, rescueRefused, rescueRefusedFile, rescueRefusedReason };
146
+ }
@@ -0,0 +1,57 @@
1
+ // SPDX-License-Identifier: AGPL-3.0-only
2
+ // Copyright 2026 Cordillera Sàrl. Additional terms under section 7 of the AGPL-3.0 apply — see ADDITIONAL-TERMS.md
3
+ // stage-tools.mjs — what one stage's turns are handed: tool servers, allowed tools, skills folder and read grants.
4
+ //
5
+ // The stage ladder (gateway.mjs runStageLadder) asks this once per stage, before its first attempt, and hands the
6
+ // same answer to every turn of the stage, its form repairs included.
7
+
8
+ import { config } from "../driver.config.mjs";
9
+ import { buildGatherMcpConfig, allowedToolsFor, toolGroupsForStage, recordAxisFor, seatWritesForGroups } from "../engine/mcp/gather-config.mjs";
10
+ import { GROUP_READING_STAGES } from "../stages.mjs";
11
+ import { recordedRegister } from "../engine/run-choices.mjs";
12
+
13
+ export function stageTools({ engine, name, sessionKey, agent, runDir, correction, excludeTools }) {
14
+ // Two INDEPENDENT engine capability flags (both default ON for an engine that declares neither, so the
15
+ // anthropic engine — which sets neither — behaves exactly as before). A future adapter can opt out of
16
+ // either without the other:
17
+ let gatherMcpConfig, gatherAllowedTools, engineSkillsDir, engineSkillsGrantRoots, engineResolveSkill;
18
+ // — the DECLARATION half of the run-dir read grant. `null` means this stage has no recording
19
+ // row to declare anything, and the adapter treats unknown as "keep the grant" — so a stage the
20
+ // gateway says nothing about is unaffected by that change.
21
+ let gatherSeatWrites = null;
22
+ // (a) Skills plumbing (usesSkillsDir): a CLI-agentic engine resolves the stage prompts' `skills/…` refs
23
+ // against its neutral cwd (a tmpdir) and confines file tools to cwd + --add-dir roots, so hand it the
24
+ // compute-skills dir (config.skillsDir — the driver-co-located tree) + this run's dir so it can absolutize
25
+ // the refs and grant read(skills)/write(runDir). The agent's own workspace is no longer involved.
26
+ if (engine.usesSkillsDir !== false) {
27
+ engineSkillsDir = config.skillsDir;
28
+ engineSkillsGrantRoots = config.skillsGrantRoots; // layered skills: BOTH roots reach the seat, resolve overlay-first
29
+ engineResolveSkill = (rel) => config.resolveSkillPath(rel);
30
+ }
31
+ // (b) Gather tools (usesGatherMcp): a gather stage gets its tool group's MCP servers + allowedTools;
32
+ // tool-free judgment stages get none (lean context). Both current engines get the SAME claude-shaped
33
+ // mcpConfig; a codex engine translates it to config.toml internally, so gather-config.mjs is untouched.
34
+ if (engine.usesGatherMcp !== false) {
35
+ const groups = toolGroupsForStage(name);
36
+ if (groups.length) {
37
+ // The bound card index rides the same label the grant was resolved from — derived by the SAME
38
+ // declared rule (`perAxis`), never by a second string-sniff that could disagree with it.
39
+ // The register the run recorded names the register tool server and the tools it grants; none recorded, the machine's.
40
+ const register = recordedRegister(runDir);
41
+ const cfg = buildGatherMcpConfig(groups, { sessionKey, agent, runDir, recordAxis: recordAxisFor(name)?.axis,
42
+ bandGroups: GROUP_READING_STAGES.has(name), correctionPositions: correction?.positions ?? null, register });
43
+ gatherMcpConfig = cfg ? JSON.stringify(cfg) : undefined;
44
+ gatherAllowedTools = allowedToolsFor(groups, { register });
45
+ gatherSeatWrites = seatWritesForGroups(groups); // — the SAME derivation allowedToolsFor uses
46
+ // Per-stage exclusion (copper-lattice re-route): a supplemental-lane register unit loses
47
+ // register_enumerate — its judgment additions go through register_propose_supplemental, so the
48
+ // free-enumerate hand-transcription lane cannot silently return. Group-level removal is
49
+ // infeasible (synthesis + legacy no-plan units share the group); the validator is the backstop.
50
+ if (Array.isArray(excludeTools) && excludeTools.length && gatherAllowedTools) {
51
+ const drop = new Set(excludeTools);
52
+ gatherAllowedTools = gatherAllowedTools.split(" ").filter((t) => !drop.has(t)).join(" ");
53
+ }
54
+ }
55
+ }
56
+ return { gatherMcpConfig, gatherAllowedTools, gatherSeatWrites, engineSkillsDir, engineSkillsGrantRoots, engineResolveSkill };
57
+ }