clearotron 0.5.1 → 0.6.0-beta.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (379) hide show
  1. package/.env.example +7 -7
  2. package/INSTALL.md +10 -10
  3. package/QUICKSTART.md +6 -6
  4. package/README.md +2 -2
  5. package/THIRD-PARTY-NOTICES.md +4 -4
  6. package/bin/README.md +2 -2
  7. package/bin/clearotron.mjs +1 -1
  8. package/bin/connect.mjs +1 -1
  9. package/bin/disconnect.mjs +1 -1
  10. package/bin/example.mjs +2 -2
  11. package/bin/grant.mjs +1 -1
  12. package/bin/onboard.mjs +78 -23
  13. package/bin/start.mjs +49 -18
  14. package/bin/update.mjs +13 -3
  15. package/build-info.json +2 -2
  16. package/docs/DELIVERY.md +1 -1
  17. package/docs/PORTAL.md +1 -1
  18. package/docs/RELEASES.md +1 -1
  19. package/docs/architecture/02-architecture.md +10 -2
  20. package/docs/architecture/03-run-lifecycle.md +6 -2
  21. package/docs/architecture/04-configuration-reference.md +3 -3
  22. package/docs/architecture/05-config-governance.md +5 -4
  23. package/docs/architecture/08-development-guide.md +4 -4
  24. package/docs/architecture/09-security-and-data.md +1 -1
  25. package/{driver/skills/clearance-search/SKILL.md → docs/architecture/retired-manuals/clearance-search-spine.md} +17 -30
  26. package/{driver/skills/clearance-search/templates/email/generic.md → docs/architecture/retired-manuals/email-generic.md} +1 -1
  27. package/{driver/skills/clearance-search → docs/architecture/retired-manuals}/template-formatting.md +3 -4
  28. package/docs/configuration.md +1 -1
  29. package/docs/decisions/0002-no-dark-functionality.md +5 -0
  30. package/driver/CHANGELOG.md +60 -0
  31. package/driver/README.md +11 -1
  32. package/driver/accepted-order.mjs +13 -5
  33. package/driver/attempt-rows.mjs +64 -0
  34. package/driver/attributed-span.mjs +1 -1
  35. package/driver/authority-trees.mjs +1 -1
  36. package/driver/best-draft.mjs +3 -3
  37. package/driver/blind-frame-record.mjs +2 -2
  38. package/driver/cancel.mjs +3 -2
  39. package/driver/carry-through.mjs +2 -2
  40. package/driver/citation-census.json +3 -3
  41. package/driver/clearance-variants-record.mjs +4 -10
  42. package/driver/common-law-coverage-status.mjs +3 -3
  43. package/driver/common-law-receipts.mjs +2 -2
  44. package/driver/compare.mjs +1 -1
  45. package/driver/config-inventory.mjs +6 -79
  46. package/driver/consumption-ledger.mjs +2 -1
  47. package/driver/contract-dictation-registry.mjs +5 -0
  48. package/driver/contract-e3-backlog.mjs +45 -66
  49. package/driver/contract-e3-baseline.json +16 -16
  50. package/driver/contract-vocabulary.mjs +8 -6
  51. package/driver/corrections-feedforward.mjs +3 -1
  52. package/driver/coverage-form-io.mjs +7 -8
  53. package/driver/coverage-tool.mjs +1 -1
  54. package/driver/declination-tool.mjs +2 -2
  55. package/driver/degraded-parts.mjs +9 -9
  56. package/driver/demo-container.mjs +5 -4
  57. package/driver/deploy-live-run-guard.mjs +19 -7
  58. package/driver/derived-state.mjs +2 -2
  59. package/driver/dev-portal.mjs +2 -1
  60. package/driver/dispatch-record.mjs +1 -1
  61. package/driver/disposition-tool.mjs +2 -1
  62. package/driver/doubt-closure-tool.mjs +2 -2
  63. package/driver/driver.config.mjs +35 -724
  64. package/driver/e2e-rounds.mjs +3 -4
  65. package/driver/engine/CONTRACT.md +3 -0
  66. package/driver/engine/README.md +2 -0
  67. package/driver/engine/anthropic-agent.mjs +8 -37
  68. package/driver/engine/auth.mjs +74 -0
  69. package/driver/engine/child-record.mjs +1 -1
  70. package/driver/engine/deny-authority-write.mjs +2 -2
  71. package/driver/engine/jx-turn.mjs +10 -2
  72. package/driver/engine/mcp/README.md +1 -1
  73. package/driver/engine/mcp/band-server.mjs +6 -6
  74. package/driver/engine/mcp/codex-config.mjs +1 -1
  75. package/driver/engine/mcp/declination-server.mjs +2 -3
  76. package/driver/engine/mcp/dispositions-server.mjs +3 -3
  77. package/driver/engine/mcp/gather-config.mjs +24 -19
  78. package/driver/engine/mcp/grid-provenance.mjs +1 -1
  79. package/driver/engine/mcp/held-answers.mjs +5 -5
  80. package/driver/engine/mcp/perplexity-server.mjs +16 -7
  81. package/driver/engine/mcp/recording-server.mjs +7 -6
  82. package/driver/engine/mcp/register-server.mjs +29 -0
  83. package/driver/engine/mcp/stdio-server.mjs +5 -5
  84. package/driver/engine/mcp/supplemental.mjs +9 -9
  85. package/driver/engine/openai-agent.mjs +5 -2
  86. package/driver/engine/registry.mjs +103 -0
  87. package/driver/engine/run-choices.mjs +162 -0
  88. package/driver/engine/stamps.mjs +35 -0
  89. package/driver/enqueue-schema.mjs +4 -4
  90. package/driver/envelope-settle.mjs +3 -2
  91. package/driver/feedback-issues.mjs +1 -1
  92. package/driver/feedback-mint.mjs +3 -2
  93. package/driver/feedback-store.mjs +3 -2
  94. package/driver/findings-model.mjs +1 -1
  95. package/driver/flag-snapshot.mjs +5 -4
  96. package/driver/floor-duty.mjs +3 -3
  97. package/driver/foreign-record-links.mjs +1 -1
  98. package/driver/frame-diff-record.mjs +2 -8
  99. package/driver/framework.mjs +1 -1
  100. package/driver/gate-metrics.mjs +10 -11
  101. package/driver/gateway.mjs +220 -839
  102. package/driver/goods-evidence.mjs +10 -6
  103. package/driver/jx-lanes.mjs +3 -3
  104. package/driver/jx-units.mjs +31 -37
  105. package/driver/jx.mjs +44 -59
  106. package/driver/knockout-assess-record.mjs +3 -3
  107. package/driver/knockout-caveats.mjs +21 -0
  108. package/driver/knockout-correction-record.mjs +58 -28
  109. package/driver/knockout-frame-record.mjs +2 -2
  110. package/driver/knockout-register-read.mjs +38 -21
  111. package/driver/knockout-register-record.mjs +5 -6
  112. package/driver/knockout-review-record.mjs +12 -11
  113. package/driver/ladder/model-gauge.mjs +88 -0
  114. package/driver/ladder/next-rung.mjs +296 -0
  115. package/driver/ladder/rescue.mjs +146 -0
  116. package/driver/ladder/stage-tools.mjs +57 -0
  117. package/driver/ladder/turn-failure.mjs +166 -0
  118. package/driver/log.mjs +2 -2
  119. package/driver/matter-frame-record.mjs +4 -4
  120. package/driver/methodology-witness.mjs +2 -2
  121. package/driver/narrative-refutation-record.mjs +145 -42
  122. package/driver/one-build-per-run.mjs +62 -0
  123. package/driver/outbox-backoff.mjs +4 -4
  124. package/driver/owner-screen.mjs +0 -10
  125. package/driver/owner-use-check.mjs +2 -28
  126. package/driver/package.json +1 -1
  127. package/driver/partial-payload-baseline.json +1 -1
  128. package/driver/parts-not-completed.mjs +1 -1
  129. package/driver/pipeline-knockout.mjs +1015 -1001
  130. package/driver/pipeline.mjs +511 -9265
  131. package/driver/placement-decisions.mjs +2 -2
  132. package/driver/placement-form-io.mjs +7 -9
  133. package/driver/placement-union.mjs +0 -6
  134. package/driver/plan-stability.mjs +7 -10
  135. package/driver/portal-acks.mjs +3 -2
  136. package/driver/portal-confirmation.mjs +48 -0
  137. package/driver/portal-families.mjs +3 -2
  138. package/driver/portal-local-auth.mjs +1 -2
  139. package/driver/portal-routes/README.md +24 -0
  140. package/driver/portal-routes/admin.mjs +425 -0
  141. package/driver/portal-routes/compose.mjs +66 -0
  142. package/driver/portal-routes/config.mjs +118 -0
  143. package/driver/portal-routes/connect.mjs +283 -0
  144. package/driver/portal-routes/feedback.mjs +178 -0
  145. package/driver/portal-routes/me.mjs +165 -0
  146. package/driver/portal-routes/queue.mjs +64 -0
  147. package/driver/portal-routes/report.mjs +106 -0
  148. package/driver/portal-routes/run.mjs +508 -0
  149. package/driver/portal-routes/runs.mjs +127 -0
  150. package/driver/portal-routes/usage.mjs +82 -0
  151. package/driver/portal-runs.mjs +588 -0
  152. package/driver/portal-service.mjs +78 -2592
  153. package/driver/portal-static.mjs +3 -1
  154. package/driver/predelivery-lint.mjs +92 -9
  155. package/driver/production-pool-guard.mjs +1 -1
  156. package/driver/profiles.mjs +5 -4
  157. package/driver/progress.mjs +29 -24
  158. package/driver/publish/README.md +10 -5
  159. package/driver/publish/archive-tags.mjs +3 -2
  160. package/driver/publish/demo-marking.mjs +2 -2
  161. package/driver/publish/index.mjs +215 -140
  162. package/driver/publish/knockout.mjs +153 -107
  163. package/driver/publish/office-record-links.mjs +22 -0
  164. package/driver/publish/parse.mjs +20 -5
  165. package/driver/publish/pool-admin.mjs +9 -3
  166. package/driver/publish/render.mjs +11 -3
  167. package/driver/publish/report-dates.mjs +3 -4
  168. package/driver/publish/report-registry.mjs +7 -10
  169. package/driver/publish/seed-pool.mjs +3 -2
  170. package/driver/publish/shell.mjs +106 -0
  171. package/driver/publish/templates/report.css +3 -1
  172. package/driver/queue-order.mjs +4 -3
  173. package/driver/record-carry.mjs +0 -9
  174. package/driver/record-discard.mjs +1 -4
  175. package/driver/record-fold.mjs +3 -3
  176. package/driver/record-goods.mjs +5 -5
  177. package/driver/reference-score.mjs +2 -3
  178. package/driver/register-capabilities.mjs +0 -6
  179. package/driver/register-count.mjs +3 -2
  180. package/driver/register-digest-record.mjs +7 -7
  181. package/driver/register-fixture-marker.mjs +3 -3
  182. package/driver/register-plan.mjs +2 -2
  183. package/driver/register-records.mjs +2 -2
  184. package/driver/register-taint.mjs +3 -3
  185. package/driver/register-unit-record.mjs +48 -9
  186. package/driver/register-unreachable.mjs +4 -3
  187. package/driver/registry-fidelity.mjs +79 -34
  188. package/driver/repair-composers.mjs +14 -9
  189. package/driver/repair-digest.mjs +4 -6
  190. package/driver/repair-scope.mjs +3 -3
  191. package/driver/repair-targets.mjs +24 -9
  192. package/driver/repairs.mjs +44 -58
  193. package/driver/replay-archive.mjs +7 -7
  194. package/driver/report-card-record.mjs +3 -3
  195. package/driver/report-overview-record.mjs +4 -4
  196. package/driver/research-answers.mjs +38 -6
  197. package/driver/research-checks.mjs +4 -4
  198. package/driver/result-noun-fields.mjs +28 -11
  199. package/driver/review-addresses.mjs +163 -0
  200. package/driver/rule-shape.mjs +1 -1
  201. package/driver/run-delivered.mjs +340 -0
  202. package/driver/run-economics.mjs +8 -26
  203. package/driver/run-failed.mjs +545 -0
  204. package/driver/run-integrity.mjs +1 -1
  205. package/driver/run-outcome.mjs +314 -0
  206. package/driver/run-park.mjs +23 -0
  207. package/driver/run-quote.mjs +32 -0
  208. package/driver/run-record.mjs +352 -0
  209. package/driver/run-requirements.mjs +22 -0
  210. package/driver/run-shell.mjs +55 -0
  211. package/driver/runner.mjs +71 -33
  212. package/driver/saved-register-pages.mjs +4 -4
  213. package/driver/score-redaction.mjs +2 -2
  214. package/driver/search-policy.mjs +12 -13
  215. package/driver/settle-stamp.mjs +4 -3
  216. package/driver/skeptic-record.mjs +2 -2
  217. package/driver/skeptic-search.mjs +1 -1
  218. package/driver/skills/README.md +7 -7
  219. package/driver/skills/blind-frame/SKILL.md +1 -2
  220. package/driver/skills/case-law-citation/SKILL.md +9 -37
  221. package/driver/skills/case-law-citation/sources/courtlistener.md +1 -3
  222. package/driver/skills/case-law-citation/sources/eurlex.md +8 -11
  223. package/driver/skills/case-law-citation/sources/legaldatahunter.md +1 -1
  224. package/driver/skills/clearance-common-law/SKILL.md +45 -111
  225. package/driver/skills/clearance-common-law/perplexity-prompts.md +7 -79
  226. package/driver/skills/clearance-register/SKILL.md +15 -33
  227. package/driver/skills/clearance-register/digest.md +31 -92
  228. package/driver/skills/clearance-register/providers/clarivate.md +2 -2
  229. package/driver/skills/clearance-register/providers/corsearch.md +5 -5
  230. package/driver/skills/clearance-register/providers/euipo.md +1 -2
  231. package/driver/skills/clearance-register/providers/free-tier.md +0 -19
  232. package/driver/skills/clearance-register/providers/signa.md +6 -25
  233. package/driver/skills/clearance-register/providers/uspto-local.md +0 -24
  234. package/driver/skills/clearance-register/register-recipes.md +8 -15
  235. package/driver/skills/clearance-register/status-rules.md +6 -24
  236. package/driver/skills/clearance-register/unit.md +11 -20
  237. package/driver/skills/clearance-search/delivery-contract.md +24 -120
  238. package/driver/skills/clearance-search/field-doctrine-pharma.md +1 -5
  239. package/driver/skills/clearance-search/firm-wide-reasoning.md +24 -43
  240. package/driver/skills/clearance-search/phase2-execution.md +29 -77
  241. package/driver/skills/clearance-search/report-prose.md +3 -4
  242. package/driver/skills/clearance-search/risk-framework-demo.md +1 -1
  243. package/driver/skills/clearance-search/risk-framework-triage.manifest.json +3 -3
  244. package/driver/skills/clearance-search/risk-framework-triage.md +7 -9
  245. package/driver/skills/clearance-search/risk-framework.manifest.json +1 -1
  246. package/driver/skills/clearance-search/risk-framework.md +1 -1
  247. package/driver/skills/clearance-search/synthesis-rules.md +30 -107
  248. package/driver/skills/clearance-search/worked-examples.md +5 -5
  249. package/driver/skills/clearance-variants/SKILL.md +46 -45
  250. package/driver/skills/clearance-variants/transliteration-scripts.md +4 -4
  251. package/driver/skills/frame-diff/SKILL.md +1 -1
  252. package/driver/skills/knockout-assess/SKILL.md +6 -14
  253. package/driver/skills/knockout-frame/SKILL.md +1 -1
  254. package/driver/skills/matter-frame/SKILL.md +7 -12
  255. package/driver/skills/matter-frame/watchlist-reference.md +1 -4
  256. package/driver/skills/narrative-refutation/SKILL.md +20 -30
  257. package/driver/skills/placement-inquiry/SKILL.md +8 -18
  258. package/driver/skills-store-provenance.mjs +1 -1
  259. package/driver/stage-context.mjs +32 -35
  260. package/driver/stage-freshness.mjs +127 -11
  261. package/driver/stages-knockout.mjs +49 -22
  262. package/driver/stages.mjs +88 -283
  263. package/driver/status-snapshot.mjs +2 -1
  264. package/driver/steps/correction-cycle.mjs +311 -0
  265. package/driver/steps/corrections.mjs +644 -0
  266. package/driver/steps/delivery.mjs +1287 -0
  267. package/driver/steps/frame-comparison.mjs +922 -0
  268. package/driver/steps/intake.mjs +84 -0
  269. package/driver/steps/open-run.mjs +419 -0
  270. package/driver/steps/overview-and-cards.mjs +899 -0
  271. package/driver/steps/placement-and-digest.mjs +23 -0
  272. package/driver/steps/register-sweep.mjs +1563 -0
  273. package/driver/steps/skeptic-and-follow-up.mjs +831 -0
  274. package/driver/steps/synthesis.mjs +261 -0
  275. package/driver/steps/verdict-gate.mjs +968 -0
  276. package/driver/suite-census.json +403 -91
  277. package/driver/surface-exit-verdict.mjs +0 -8
  278. package/driver/synthesis-record.mjs +72 -6
  279. package/driver/terminal-clamp.mjs +10 -0
  280. package/driver/tokens.mjs +8 -62
  281. package/driver/tool-calls.mjs +2 -2
  282. package/driver/unit-state-verdict.mjs +1 -1
  283. package/driver/usage-ledger.mjs +2 -1
  284. package/driver/verify-knockout.mjs +20 -35
  285. package/driver/verify.mjs +47 -36
  286. package/driver/web-grid.mjs +3 -4
  287. package/driver/whatif-memo-run.mjs +2 -2
  288. package/driver/whatif-queue.mjs +4 -3
  289. package/driver/withheld-families.mjs +14 -15
  290. package/driver/worker-heartbeat.mjs +3 -2
  291. package/driver/write-up-form.mjs +0 -3
  292. package/mcp-server/CHANGELOG.md +4 -0
  293. package/mcp-server/http-server.mjs +1 -1
  294. package/mcp-server/lib/brief.mjs +22 -4
  295. package/mcp-server/lib/events.mjs +2 -2
  296. package/mcp-server/lib/evidence.mjs +3 -2
  297. package/mcp-server/lib/findings.mjs +2 -1
  298. package/mcp-server/lib/knockout.mjs +9 -10
  299. package/mcp-server/lib/ops.mjs +9 -9
  300. package/mcp-server/lib/runs.mjs +9 -10
  301. package/mcp-server/lib/trace.mjs +1 -1
  302. package/mcp-server/lib/whatif.mjs +2 -3
  303. package/mcp-server/package.json +1 -1
  304. package/mcp-server/server.mjs +5 -5
  305. package/package.json +2 -1
  306. package/portal-ui/dist/assets/{index-fPqAU0sx.js → index-D5rkCjDc.js} +26 -14
  307. package/portal-ui/dist/index.html +1 -1
  308. package/portal-ui/package.json +3 -3
  309. package/providers/README.md +1 -1
  310. package/providers/_shared/answer-memory.mjs +4 -5
  311. package/providers/_shared/execute-plan.mjs +48 -1
  312. package/providers/_shared/records-from-search.mjs +46 -0
  313. package/providers/clarivate/README.md +2 -2
  314. package/providers/clarivate/src/adapter.js +147 -0
  315. package/providers/clarivate/src/core.js +1 -14
  316. package/{driver/engine/mcp/clarivate-server.mjs → providers/clarivate/src/mount.js} +5 -10
  317. package/providers/corsearch/README.md +3 -3
  318. package/providers/corsearch/src/adapter.js +80 -0
  319. package/providers/corsearch/src/core.js +14 -11
  320. package/{driver/engine/mcp/corsearch-server.mjs → providers/corsearch/src/mount.js} +5 -10
  321. package/providers/euipo/README.md +2 -2
  322. package/providers/euipo/src/adapter.js +85 -0
  323. package/providers/euipo/src/core.js +1 -1
  324. package/providers/euipo/src/euipo-client.js +1 -2
  325. package/{driver/engine/mcp/euipo-server.mjs → providers/euipo/src/mount.js} +5 -10
  326. package/providers/free-tier/README.md +2 -2
  327. package/providers/free-tier/src/adapter.js +127 -0
  328. package/{driver/engine/mcp/free-tier-server.mjs → providers/free-tier/src/mount.js} +5 -10
  329. package/providers/jx-subclass/coverage.mjs +1 -6
  330. package/providers/jx-subclass/score-truth.mjs +2 -1
  331. package/providers/oauth-mcp-bridge/CHANGELOG.md +4 -0
  332. package/providers/oauth-mcp-bridge/package.json +1 -1
  333. package/providers/perplexity/src/core.js +2 -2
  334. package/providers/signa/README.md +2 -2
  335. package/providers/signa/src/adapter.js +157 -0
  336. package/providers/signa/src/capabilities.js +0 -3
  337. package/providers/signa/src/core.js +2 -2
  338. package/{driver/engine/mcp/signa-server.mjs → providers/signa/src/mount.js} +7 -12
  339. package/providers/signa/src/offices.generated.js +17 -15
  340. package/providers/uspto-local/README.md +1 -1
  341. package/providers/uspto-local/bin/verify-index.mjs +1 -1
  342. package/providers/uspto-local/src/adapter.js +75 -0
  343. package/{driver/engine/mcp/uspto-local-server.mjs → providers/uspto-local/src/mount.js} +5 -10
  344. package/scripts/band-shape-probe.mjs +2 -2
  345. package/scripts/citation-line-check.mjs +7 -7
  346. package/scripts/compare.mjs +1 -1
  347. package/scripts/dead-names.mjs +2 -2
  348. package/scripts/e2e-first-time.mjs +19 -7
  349. package/scripts/e2e.mjs +13 -13
  350. package/scripts/engine-probe.mjs +1 -1
  351. package/scripts/env-audit.mjs +7 -4
  352. package/scripts/env-classify.mjs +5 -1
  353. package/scripts/feedback-mint.mjs +1 -1
  354. package/scripts/freeze-example-run.mjs +7 -7
  355. package/scripts/mint-suite-census.mjs +2 -2
  356. package/scripts/nightly-notice.mjs +1 -1
  357. package/scripts/release-cut-decision.mjs +7 -2
  358. package/scripts/release-note-required.mjs +26 -9
  359. package/scripts/release-notes-lint.mjs +3 -2
  360. package/scripts/release-version-pr-checks.mjs +1 -1
  361. package/scripts/settings-render-check.mjs +23 -3
  362. package/scripts/test-run.mjs +5 -5
  363. package/scripts/travelling-predicates.mjs +1 -1
  364. package/scripts/undeclared-field-census.mjs +1 -1
  365. package/scripts/unexecuted-asserts.mjs +1 -1
  366. package/scripts/verify-publishable.mjs +1 -1
  367. package/shared/client-door.mjs +1 -1
  368. package/shared/connect-clients.mjs +1 -1
  369. package/shared/connector-signin-probe.mjs +1 -1
  370. package/shared/env-aliases.mjs +1 -1
  371. package/shared/invocation.mjs +14 -2
  372. package/shared/names-in-force.mjs +2 -0
  373. package/shared/register-selection.mjs +2 -2
  374. package/shared/store-in-repo.mjs +3 -3
  375. package/shared/summary-blocks.mjs +0 -3
  376. package/shared/trigger-lane.mjs +1 -1
  377. package/shared/vacuous-pass.mjs +2 -2
  378. package/shared/verb-shim.mjs +4 -2
  379. package/node_modules/exceljs/README.md +0 -3023
@@ -0,0 +1,545 @@
1
+ // SPDX-License-Identifier: AGPL-3.0-only
2
+ // Copyright 2026 Cordillera Sàrl. Additional terms under section 7 of the AGPL-3.0 apply — see ADDITIONAL-TERMS.md
3
+ //
4
+ // run-failed.mjs — what a run does when a step fails: postpone, stop, park for recovery, or end, and the notice it sends.
5
+ //
6
+ // The failure path of both products. A clearance and a Knockout fail, park, recover, stop and end the same way here;
7
+ // what differs is the product's data, `product` below. Every path through it returns the run's result or throws, so
8
+ // each product's step loop returns what it returns. `helpers` are functions still held in pipeline.mjs, handed in
9
+ // because this module must not import that one back; a Knockout hands in only `sentinel`.
10
+ import { writePark } from "./run-park.mjs";
11
+ import { ensureDriverDir } from "../shared/driver-dir.mjs";
12
+ import { stopReason } from "../shared/stop-reason.mjs";
13
+ import { RunCancelled } from "./cancel.mjs";
14
+ import { recordRunConsumption } from "./consumption-ledger.mjs";
15
+ import { config } from "./driver.config.mjs";
16
+ import { note, runLog } from "./log.mjs";
17
+ import { writeOutboxPacket } from "./outbox.mjs";
18
+ import { axesNotYetDisclosed, clearPartsNotCompleted, readPartNotCompleted, slicesNotYetRecorded, unitsNotYetRecorded, writePartNotCompleted } from "./parts-not-completed.mjs";
19
+ import { rollupStatus, writeRunStatus } from "./progress.mjs";
20
+ import { abbrev } from "./repair-contract.mjs";
21
+ import { REFUSAL_TERMINAL_KIND, capParkSchedule, capWaitFrom, classificationSource, classifyFailureReason, countRecoveryLanes, countTrailingStageStrikes, decideRecovery, failureSignature, isCapPark, isContentShapedFail, unnamedStructuredFailure, weatherCeilingFor } from "./repairs.mjs";
22
+ import { logTurnaroundReconciliation } from "./run-quote.mjs";
23
+ import { StageFailure, buildFailurePacket, isDesignedRefusal, terminalReasonFields } from "./run-outcome.mjs";
24
+ import { paths } from "./stages.mjs";
25
+ import { stampTokenRollup } from "./tokens.mjs";
26
+ import { mkdirSync, readFileSync, rmSync, writeFileSync } from "node:fs";
27
+ import { join } from "node:path";
28
+
29
+ /**
30
+ * What a product hands the failure path: the stage a failure is named at when its error names none, which reaches the
31
+ * notice; how a stop names its stage; and the tag on the log lines. Nothing here changes what a failure buys.
32
+ */
33
+ export const CLEARANCE_ENDING = Object.freeze({ unnamedStage: "pipeline", stopStage: (stage) => stage, logTag: "pipeline" });
34
+
35
+ export async function endTheFailedRun({ P, agent, ctx, e, job, run, product = CLEARANCE_ENDING }, helpers) {
36
+ const { recordConnotationAudit = null, sentinel, undoTaintRenames } = helpers;
37
+ const tag = `[${product.logTag}]`;
38
+ // RATE-LIMIT POSTPONE (re-throw): a 429 session-cap is NOT a terminal failure — RE-THROW it so pipeline()'s
39
+ // outer catch parks the run resumable (.postponed, no .failed, no notify-fail) and the runner auto-resumes
40
+ // after the cap window, vs stranding every completed stage and forcing a ~$40 cold re-run. This catch wraps
41
+ // the ENTIRE stage sequence (the try in `runShell`, run-shell.mjs), so without this guard a rate-limited
42
+ // StageFailure is swallowed HERE and the postpone path (pipeline() catch + postponeRun + runner
43
+ // .resumePostponed) is unreachable — the exact bug behind the 2026-06-22 register-stage 429 hard-fails.
44
+ if (e instanceof StageFailure && e.rateLimited) throw e;
45
+ // — RECORD THE TWO NUMBERS ON THE WAY DOWN. A run that still goes terminal at the meaning
46
+ // gate never reaches the merge seam, and its failure token carries only the BLOCKING count by
47
+ // design. Recorded only where the gate passed, "dispositions that did not bind" would be missing
48
+ // from precisely the runs that need explaining — and that count is what the boundary gets tuned
49
+ // against. Reads whatever is on disk (merged pair, else each half's, else its preserved best
50
+ // draft) and can never mask the failure it is describing.
51
+ // A clearance hands this in; its meaning gate is a step a Knockout does not run.
52
+ if (recordConnotationAudit) { try { recordConnotationAudit(run, P); } catch { /* observability must never mask the failure */ } }
53
+ // ── STOPPED BY THE USER ──────────────────────────────────────────────────────────────────────
54
+ // Terminal, and deliberately NOT routed through anything below. Two reasons:
55
+ //
56
+ // 1. decideRecovery would park it. A cancel carries no failure signature, so the class guess
57
+ // lands on "unknown", which buys one recovery park — the run would write `.postponed` and the
58
+ // runner would auto-resume it two minutes later and keep billing.
59
+ // 2. The failure packet would tell them their search BROKE. buildFailurePacket's copy is
60
+ // "❌ Clearotron search for X FAILED at Y", pushed to the customer over the outbox. Someone who
61
+ // pressed Stop must never be told something went wrong; they already know what happened.
62
+ //
63
+ // Partial work is not deliverable, so nothing is published — but the spend up to this point is
64
+ // real, which is why this leaves a row rather than vanishing: the consumption ledger records it with
65
+ // the cancelled status, and the run list is refreshed, as for a Knockout. The ledger keeps one row per
66
+ // run, so handling a stop twice counts it once, and neither write can turn the stop into a resume.
67
+ if (e instanceof RunCancelled) {
68
+ note(`${tag} STOPPED ${run.codename} at ${e.stage} by user request${e.requestedAt ? ` (asked ${e.requestedAt})` : ""} — terminal, nothing delivered`);
69
+ try { sentinel(run.runDir, ".cancelled", { stage: e.stage, requestedAt: e.requestedAt, via: e.via }); } catch { /* best-effort */ }
70
+ try { runLog(run.runDir, { event: "cancelled", stage: e.stage, requestedAt: e.requestedAt, via: e.via }); } catch { /* best-effort */ }
71
+ try { recordRunConsumption(ctx, { phase: "cancelled", tokens: stampTokenRollup(run.runDir, "cancelled") }); } catch { /* best-effort — a stop still spent what it spent */ }
72
+ logTurnaroundReconciliation(run.runDir, ctx?.quote, "cancelled"); // a stop still consumed wall
73
+ writeRunStatus(ctx, { state: "cancelled", failedStage: e.stage,
74
+ reason: stopReason({ stage: product.stopStage(e.stage), via: e.via, requestedAt: e.requestedAt }) });
75
+ try { rollupStatus(run.studioRoot); } catch { /* best-effort */ }
76
+ // `failedStage` non-null satisfies the runner's backstop predicate, so it does not overwrite
77
+ // this with a spurious "pre-run" failure notice.
78
+ //
79
+ // — `reason` USED TO STAY NULL HERE, on the ground that "there is no fault". That was true
80
+ // and it was answering a different question: `state` already carries whether there was a fault,
81
+ // and what `reason` owes is why the run ENDED. A stop has an answer to that, and it is the one
82
+ // fact that tells this apart from a crash for anyone holding status.json alone — which is what
83
+ // the portal and every metrics reader hold. Five of five cancelled runs on the test box read
84
+ // `reason: null`, with the provenance sitting unreachable in the `.cancelled` sidecar beside them.
85
+ return { ok: false, cancelled: true, failedStage: e.stage, codename: run?.codename ?? null, runDir: run.runDir };
86
+ }
87
+ // judgment-relocation (revised 2026-06-24): there is NO judgment-driven halt terminal. A run only stops
88
+ // without delivering on a TECHNICAL failure (below) or pauses on a rate-limit (.postponed, above). A
89
+ // material coverage gap the lawyer flagged ships as a CONDITIONAL (the deliver-conditional clamp earlier),
90
+ // never a no-deliver halt — a lawyer always gets a report unless something technically broke.
91
+ const reason = e instanceof StageFailure ? e.reason : String(e?.stack ?? e);
92
+ // — the OPEN-SET payload, kept apart from the sentence all the way to the status file, so the
93
+ // portal can render one and put the other behind a disclosure. Null on every failure that carries
94
+ // none, and on every non-StageFailure throw.
95
+ const reasonDetail = e instanceof StageFailure ? e.detail : null;
96
+ const failedStage = e?.stage ?? product.unnamedStage;
97
+ // A DESIGNED REFUSAL BUYS NOTHING. A throw stamped `refusal` is the product declining an order before any spend, not
98
+ // the engine breaking, so it is asked first and kept away from every recovery path below: no strike count, no
99
+ // classification row, no park. Re-sampling a refusal re-earns the same refusal. It ends with its own kind.
100
+ const refused = isDesignedRefusal(e);
101
+ // ── 2026-07-04 (senior lawyer, production doctrine): AUTOMATIC RUN-LEVEL RECOVERY ─────────────────
102
+ // A business-critical report must converge to an honest delivery WITHOUT a human re-trigger. The
103
+ // VENZY bake run proved the gap: the corrective re-synthesis exhausted its in-stage ladder on
104
+ // model vocabulary misses and the run went TERMINAL — dead until someone noticed, even though a
105
+ // fresh resume (new sampling, valid stages skipped) converges with high probability. So a
106
+ // recoverable failure PARKS the run on the SAME self-contained .postponed machinery the
107
+ // rate-limit path uses (runner's self-resume watcher re-invokes pipeline(); idempotency skips
108
+ // every valid stage; ONLY the broken segment re-runs), with bounded attempts + escalating backoff.
109
+ // Recovery can never ship garbage: every resume passes the same validators, reviewer and gates.
110
+ //
111
+ // ── repair-first phase 2 (2026-07-05, senior lawyer): recovery is CLASS-AWARE — parks are only bought
112
+ // where a fresh re-sample is the plausible remedy. TRANSIENT keeps the full ladder; UNKNOWN gets
113
+ // exactly one park (the VENZY doctrine above — one fresh sample often converges); DETERMINISTIC
114
+ // and FACTUAL get none (their repairs already ran at the point of defect; a re-sample re-derives
115
+ // the same failure). And the universal backstop: a failure whose SIGNATURE already parked once is
116
+ // re-hitting the same wall — terminal immediately, whatever the class guess said. Open Country
117
+ // (TMP8729, 2026-07-05) is the proof case: the identical 414-shaped fan-in failure was bought 3×
118
+ // (~77 min) before a terminal with a WRONG "systemic cause" diagnosis. Non-recoverable by denylist
119
+ // only: credential/config/job-shape failures, where a retry is provably futile.
120
+ const NON_RECOVERABLE_RE = /credential|CORSEARCH_(USER|PASS|TOKEN)|missing register credential|invalid job|job file|profile\.json is corrupt/i;
121
+ const recoveryMax = Math.max(0, Number(process.env.CLEAROTRON_RECOVERY_MAX ?? 3));
122
+ const RECOVERY_BACKOFF_MIN = [2, 15, 60]; // attempt N resumes after BACKOFF[N-1] minutes (last repeats)
123
+ const statusSnapshot = (() => { try { return JSON.parse(readFileSync(join(run.runDir, "status.json"), "utf8")) ?? {}; } catch { return {}; } })();
124
+ const priorAttempts = Number(statusSnapshot.recoveryAttempts) || 0;
125
+ const recoveryHistory = Array.isArray(statusSnapshot.recoveryHistory) ? statusSnapshot.recoveryHistory : [];
126
+ // ── two park lanes (2026-07-29) ─────────────────────────────────────────────────────────────────
127
+ // `recoveryAttempts` stays the TOTAL park count and keeps every meaning it already had (the repair
128
+ // ledger's epoch, the taint-rerun session key, the ".tainted-N" forensic suffix, the failure
129
+ // notice's "after N automatic recovery attempts"). What changed is which counter the run-level
130
+ // CEILING is measured against: upstream weather draws on its own bounded lane so it can no longer
131
+ // spend the budget reserved for the run's own recoverable defects. Both lane counts are read back
132
+ // off the append-only park history, so there is one source of truth and nothing to drift.
133
+ const laneCounts = countRecoveryLanes(recoveryHistory, { total: priorAttempts });
134
+ const weatherCeiling = weatherCeilingFor(recoveryMax);
135
+ // A4: sign on the throw site's stable reason CODES when it carries them (the client gate) — the
136
+ // sorted unique code set, so prose drift between attempts can never re-arm a per-signature budget.
137
+ const failSig = failureSignature(failedStage, reason, { codes: e instanceof StageFailure ? e.reasonCodes : undefined });
138
+ let failClass = (e instanceof StageFailure && e.failClass) || classifyFailureReason(String(reason));
139
+ // BUILD A (owner-ruled 2026-08-19) — NAME the source when the validator already named it.
140
+ // Three sources, in precedence order, and the ordering is the whole design:
141
+ // throw-site the stage stamped its own class. It counted the things; nothing outranks it.
142
+ // validator-token the reason carries an ALLOWLISTED validator token (PROGRESS_TOKENS, via
143
+ // progressQuantity). This is the case the issue was filed on: a structured
144
+ // reason a validator emitted, landing on the catch-all with nothing recording
145
+ // that it had. The classifier now says where the name came from.
146
+ // reason-text neither — the generic regex read, which is a guess and is labelled as one.
147
+ //
148
+ // SCOPED TO `quantityToken`, NOT to `kindToken`, and that is deliberate. `kindToken` is any leading
149
+ // `word:` prefix (`^([a-z][a-z0-9_]*)\s*:`), not a vocabulary — `invalid_file:<path>` is 71 of 76
150
+ // recorded stage failures and no validator named it. Treating a prefix as a validator's name would
151
+ // silence the detector on precisely the shape it was widened to catch, and it would do it by
152
+ // relabelling rather than by understanding anything.
153
+ //
154
+ // CHANGES NO BUDGET, structurally rather than by care: `decideRecovery` takes no `classSource`
155
+ // argument at all, so there is no branch for this to reach. The 2026-08-13 correction on the issue
156
+ // withdrew the trend rule — R6's flat 74 → 74 was a stage about to succeed — and B stays unruled.
157
+ let classSource = classificationSource({
158
+ stamped: Boolean(e instanceof StageFailure && e.failClass), quantityToken: failSig.quantityToken });
159
+ // ── A5 invalid-artifact strikes (2026-07-28 postmortem backstop) ────────────────────────────────────────────
160
+ // A stage that keeps producing an INVALID output can loop forever: the idempotency skip can't fire
161
+ // over an invalid artifact, so every resume re-runs it, and the reclaim/self-resume lanes keep the
162
+ // resumes coming (the 2026-07-28 postmortem run: common-law-half:a re-failed validation on every resume while the
163
+ // surface said "running 7/9"). Three TRAILING CONSECUTIVE content-shaped failures of ONE stage in
164
+ // the append-only run.jsonl spine mean re-sampling has disproved itself — the failure is
165
+ // deterministic in practice whatever the text guess says (parkBudget 0 ⇒ terminal WITH artifacts,
166
+ // terminalKind "invalid-artifact-loop"). Content-shaped ONLY (isContentShapedFail: transient-classified
167
+ // OR fallback-eligible failures break the streak): a flapping provider, a rate-limit postpone trail, or
168
+ // a timeout streak never converts — waiting is a real remedy there. A throw-site FACTUAL
169
+ // stamp outranks the strike relabel (it is already terminal, and its kind is the truer diagnosis).
170
+ const INVALID_ARTIFACT_STRIKE_CAP = 3;
171
+ let strikeTerminalKind = null;
172
+ if (run?.runDir && failClass !== "factual" && !refused) {
173
+ try {
174
+ const rows = readFileSync(paths(run.runDir).run, "utf8").trim().split("\n")
175
+ .map((l) => { try { return JSON.parse(l); } catch { return null; } }).filter(Boolean);
176
+ const strikes = countTrailingStageStrikes(rows, failedStage, { isContentShaped: isContentShapedFail });
177
+ if (strikes >= INVALID_ARTIFACT_STRIKE_CAP) {
178
+ strikeTerminalKind = "invalid-artifact-loop";
179
+ failClass = "deterministic";
180
+ classSource = "invalid-artifact-strikes";
181
+ runLog(run.runDir, { event: "invalid-artifact-strikes", stage: failedStage, strikes, cap: INVALID_ARTIFACT_STRIKE_CAP });
182
+ note(`${tag} ${failedStage} has produced ${strikes} consecutive invalid/failed outputs — terminal (invalid-artifact-loop), artifacts kept for diagnosis`);
183
+ }
184
+ } catch { /* the strike backstop must never mask the original failure */ }
185
+ }
186
+ const attemptedRepairs = e instanceof StageFailure && e.repairs?.length ? e.repairs : undefined;
187
+ // — the progress quantity, UN-TRUNCATED, reaching the break/park comparison. The throw site's
188
+ // stamp wins (it counted the things); the allowlisted text read of the full reason is the fallback
189
+ // for throw sites that only have prose. null = ABSENT, never zero. `quantitySource` names which,
190
+ // exactly like `classSource` above — a number in a ledger is worth less than a number that says
191
+ // where it came from. The comparison RECORDS this; no branch of it reads the value ( owns policy).
192
+ const stampedQuantity = e instanceof StageFailure && Number.isFinite(e.quantity) ? e.quantity : null;
193
+ const quantity = stampedQuantity ?? failSig.quantity;
194
+ const quantitySource = quantity === null ? null : stampedQuantity !== null ? "throw-site" : "reason-text";
195
+ const decision = decideRecovery({
196
+ failClass, sig: failSig.sig, reason: String(reason), history: recoveryHistory, priorAttempts, recoveryMax,
197
+ nonRecoverable: NON_RECOVERABLE_RE.test(String(reason)), hasRunDir: Boolean(run?.runDir),
198
+ weatherAttempts: laneCounts.weather, defectAttempts: laneCounts.defect, weatherCeiling, quantity,
199
+ });
200
+ // The stamped kind: a refusal's own; the strike relabel names the loop precisely; otherwise the decision's own kind.
201
+ const terminalKind = refused ? REFUSAL_TERMINAL_KIND : decision.recoverable ? null : (strikeTerminalKind ?? decision.terminalKind);
202
+ if (run?.runDir && !refused) {
203
+ try {
204
+ runLog(run.runDir, { event: "recovery-classified", sig: failSig.sig, class: failClass, stage: failedStage, classSource, priorAttempts, parkBudget: decision.parkBudget, lane: decision.lane, laneAttempts: decision.laneAttempts, laneCeiling: decision.laneCeiling, ...(terminalKind ? { terminalKind } : {}), ...(failSig.codes?.length ? { reasonCodes: failSig.codes } : {}), ...(attemptedRepairs ? { repairs: attemptedRepairs } : {}),
205
+ //: what the comparison SAW — this failure's count, the last count for the same signature,
206
+ // and the direction between them. "unknown" whenever either side is absent.
207
+ quantity, quantitySource, progress: decision.progress,
208
+ //: the NAME of the structured token in the reason, or null. It comes from failSig — i.e.
209
+ // from progressQuantity over the reason text — regardless of which source won the VALUE above.
210
+ // The run this issue was filed on logged quantitySource:"throw-site", so a token threaded only
211
+ // through the stamp path would have been null on exactly that run.
212
+ reasonToken: failSig.quantityToken });
213
+ } catch { /* observability must never mask the failure */ }
214
+ // — THE CLASSIFIER GAP, MADE INTO AN EVENT. The classifier returning "unknown" over a reason
215
+ // a validator structured is a gap in classifyFailureReason, not an unknowable failure, and until
216
+ // now it was legible only to somebody reading run.jsonl by hand. Emitted beside the classification
217
+ // and NOT through the stderr-only note path, which is a family records as still live.
218
+ // It changes nothing about the decision above: the class, the lane and the budget are already set.
219
+ try {
220
+ // — the KIND rides beside the quantity token, and either one makes the failure nameable.
221
+ // Both keys are written unconditionally as value-or-null: "this failure had no kind" and "this
222
+ // build does not record kinds" are different facts, and a key present only when it is populated
223
+ // makes its absence a claim.
224
+ if (unnamedStructuredFailure({ failClass, classSource, token: failSig.quantityToken, kind: failSig.kindToken })) {
225
+ runLog(run.runDir, { event: "classifier-gap", stage: failedStage, sig: failSig.sig,
226
+ token: failSig.quantityToken ?? null, kind: failSig.kindToken ?? null, quantity, class: failClass });
227
+ }
228
+ } catch { /* never mask the failure */ }
229
+ }
230
+ if (!refused && decision.recoverable) {
231
+ const attempt = priorAttempts + 1;
232
+ // The rung follows THIS SIGNATURE's own park count, not the run-global attempt: a repeated
233
+ // transient (a provider outage that has not ended) must wait longer each time — 2 → 15 → 60 —
234
+ // while an unrelated first-time defect later in the run still gets the short first rung rather
235
+ // than inheriting an earlier defect's escalation.
236
+ const rung = Math.min(decision.sigAttempts ?? (attempt - 1), RECOVERY_BACKOFF_MIN.length - 1);
237
+ const backoffMin = RECOVERY_BACKOFF_MIN[rung];
238
+ // A4 field split (2026-07-28 postmortem): a recovery park writes `recoveryResumesAt` and STOPS writing
239
+ // `resetsAt` — resetsAt keeps its one documented meaning (the rate-limit cap-reset clock), so a
240
+ // reader can no longer mistake a recovery backoff for a provider cap. Status also actively clears
241
+ // any lingering resetsAt from an earlier rate-limit park on the same run.
242
+ //
243
+ // The lane split does NOT get its own clock field, and that is the honest choice. `resetsAt`
244
+ // means one thing — a provider TOLD us when its cap window reopens — and a weather park has no
245
+ // such promise: nobody said when the overload ends, the 2/15/60 ladder is our own guess, which
246
+ // is precisely what `recoveryResumesAt` means. So a weather park writes `recoveryResumesAt` like
247
+ // any other recovery park, still leaves `resetsAt` null, and the record says WHICH lane bought
248
+ // the wait in `recoveryLane` instead of implying a provider clock that does not exist.
249
+ // A CAP PARK IS NOT A STAGE FAILING, and the 2/15/60 ladder cannot survive one.
250
+ // A cap that classifies `rate_limited` already takes the postpone path and waits for its stated
251
+ // reset. One that does NOT lands here, where two things used to go wrong: the provider's own reset
252
+ // hint was dropped even though StageFailure carries it all the way to this site, and the ladder
253
+ // topped out at 60 minutes, so six probes covered ~3 hours and a daily cap outlived every one of
254
+ // them. Cap parks now ride their own ladder (15/30/60/120/240) and a STATED reset time beats it.
255
+ const capResetHint = (e instanceof StageFailure && e.resetsAt) || null;
256
+ const capPark = isCapPark(reason, capResetHint);
257
+ const capSchedule = capPark
258
+ ? capParkSchedule({ resetsAt: capResetHint, attempts: decision.sigAttempts ?? (attempt - 1) })
259
+ : null;
260
+ const recoveryResumesAt = capSchedule
261
+ ? capSchedule.resumesAt
262
+ : new Date(Date.now() + backoffMin * 60000).toISOString();
263
+ // What the wait was bought on: "provider" = its own clock said so, "ladder" = our guess. Same
264
+ // honesty rule the adapters apply to resetsAtBasis — a reader must be able to tell a stated fact
265
+ // from an inference, or the record quietly upgrades one into the other.
266
+ const recoveryWaitBasis = capSchedule ? capSchedule.basis : "ladder";
267
+ const recoveryWaitMin = capSchedule ? capSchedule.waitMin : backoffMin;
268
+ const lane = decision.lane;
269
+ const laneAttempt = (decision.laneAttempts ?? 0) + 1;
270
+ const laneLabel = lane === "weather" ? "upstream weather" : "defect";
271
+ // Both counters, always both, whichever lane was charged — a reader must be able to see that the
272
+ // defect budget is intact while weather is being spent (that is the whole point of the split).
273
+ const recoveryLanes = {
274
+ weather: { attempts: laneCounts.weather + (lane === "weather" ? 1 : 0), ceiling: weatherCeiling },
275
+ defect: { attempts: laneCounts.defect + (lane === "defect" ? 1 : 0), ceiling: recoveryMax },
276
+ };
277
+ note(`${tag} RECOVERABLE failure in ${run.codename} at ${failedStage} — parking for AUTO-RECOVERY, ${laneLabel} lane ${laneAttempt}/${decision.laneCeiling} (defect budget ${recoveryLanes.defect.attempts}/${recoveryMax} spent; resumes ~${recoveryWaitMin}min${capSchedule ? ` on the ${recoveryWaitBasis === "provider" ? "provider's stated reset" : "cap ladder"}` : ""}; valid stages skip on resume): ${String(reason).slice(0, 160)}`);
278
+ // no fromStage: the failed-stage label can be decorated ("synthesis(blocking)") and is not a
279
+ // resume key — plain idempotent resume re-runs exactly the invalid/missing outputs.
280
+ try { writePark(run.runDir, { kind: "recovery", recoveryResumesAt, postponedAt: new Date().toISOString(), codename: run.codename, job, agent, attempt, reason: String(reason).slice(0, 300), sig: failSig.sig, class: failClass, lane }, { job, agent, codename: run.codename }); }
281
+ catch (err) {
282
+ // The marker is how the runner finds a parked run again. A park that could not write it is said, where a reader
283
+ // of the run looks, so a run that never comes back is not a silence.
284
+ note(`${tag} park marker NOT written for ${run.codename}: ${String(err?.message ?? err).slice(0, 160)} — the runner cannot resume this run from it`);
285
+ try { runLog(run.runDir, { event: "park-marker-unwritten", kind: "recovery", cause: String(err?.message ?? err).slice(0, 200) }); } catch { /* the note is the record */ }
286
+ }
287
+ // recoveryHistory is the repeat-signature memory AND the lane ledger: append-only, one row per
288
+ // park, read back on the next failure so an identical defect is never bought twice and so each
289
+ // lane's spend is recomputed from the record rather than from a second counter that could drift
290
+ // (writeRunStatus shallow-merges, so the full array is passed each time).
291
+ // — a PARKED run is the one a reader diagnoses from status.json alone, and this cut at 200
292
+ // and said nothing. `recovering` is not terminal, so it was never covered by the terminal
293
+ // fields; the reader's problem is identical either way — a sentence that stops mid-thought with
294
+ // no key admitting it stopped. Same three fields, same function, so the two cannot drift.
295
+ // EACH WRITE BELOW IS GUARDED: the marker above already makes the run resumable, and a throw from the record or
296
+ // the bookkeeping would escape this path and end a parked run as a crash with a notice that misnames its cause.
297
+ try {
298
+ writeRunStatus(ctx, { state: "recovering", recoveryAttempts: attempt, recoveryMax, failedStage,
299
+ ...terminalReasonFields(reason),
300
+ recoveryResumesAt, resetsAt: null,
301
+ recoveryLane: lane, recoveryLanes,
302
+ //: the row carries the park's progress QUANTITY, so the next failure's comparison can see
303
+ // 9 → 6 (converging) where the signature alone shows only "the same defect again". Written
304
+ // unconditionally as number|null — a row that says null means "this failure had no count", which
305
+ // is a different fact from a pre-change row that has no such key at all.
306
+ //
307
+ //: `quantityToken` and `classSource` ride beside it, written unconditionally as value|null
308
+ // for the same reason. This row is the ONLY one of the three records here that repair-digest.mjs
309
+ // reads — runLog writes run.jsonl, which that module never opens — so without these two fields
310
+ // the classifier gap would be recorded and still unreportable, which is this issue's own defect
311
+ // committed inside its own fix. `classSource` rides too rather than a pre-computed verdict, so
312
+ // the digest applies the SAME exported predicate the pipeline applies instead of guessing from
313
+ // half the inputs. It also makes the epoch legible: a row with no `classSource` KEY predates
314
+ // this field and was never measured, which is a different fact from a row that says "no gap".
315
+ recoveryHistory: [...recoveryHistory, { sig: failSig.sig, stage: failedStage, class: failClass, lane, attempt, quantity, quantityToken: failSig.quantityToken ?? null, kindToken: failSig.kindToken ?? null, classSource, ts: new Date().toISOString(),
316
+ // THE SAME FACTS THE RUN LOG ALREADY GETS, in the record that SURVIVES.
317
+ // The auto-recovery-parked event below carries capPark/basis/waitMin and says in its own note
318
+ // that a cap has to be legible or nobody can tell a stated reset from our ladder's guess. But
319
+ // run.jsonl is not what the terminal reads: status.json's recoveryHistory is the only record
320
+ // that survives a park/resume, so the cap died with the run log and the failure notice could
321
+ // only ever say 'a provider was overloaded'. Spread the same way, ABSENT on a non-cap park
322
+ // rather than false, for the reason stated below: a row that says nothing is honest about not
323
+ // having looked; `capPark: false` claims we checked.
324
+ ...(capSchedule ? { capPark: true, recoveryWaitBasis, recoveryWaitMin } : {}) }] });
325
+ } catch { /* best-effort — the marker is the resumable record */ }
326
+ try { rollupStatus(run.studioRoot); } catch { /* best-effort */ }
327
+ try { runLog(run.runDir, { event: "auto-recovery-parked", stage: failedStage, attempt, of: recoveryMax, lane, laneAttempt, laneOf: decision.laneCeiling, recoveryResumesAt, reason: String(reason).slice(0, 200), sig: failSig.sig, class: failClass,
328
+ // a cap park has to be legible in the record, or the next reader diagnosing
329
+ // "why did this wait 21 hours" cannot tell a provider's stated reset from our own ladder guess.
330
+ // Absent on a non-cap park rather than false: a row that says nothing is honest about not having
331
+ // looked, while `capPark: false` would read as "we checked and it was not one".
332
+ ...(capSchedule ? { capPark: true, recoveryWaitBasis, recoveryWaitMin, capResetHint: capResetHint ?? null } : {}) }); } catch { /* best-effort */ }
333
+ logTurnaroundReconciliation(run.runDir, ctx?.quote, "recovery-parked");
334
+ try { recordRunConsumption(ctx, { phase: "recovery-park", tokens: stampTokenRollup(run.runDir, "recovery-park") }); } catch { /* best-effort */ }
335
+ // the return's `resetsAt` is the runner's due-clock contract (parkPostponed meta / postponedDueAt),
336
+ // not a status surface — it stays under the machinery name deliberately.
337
+ return { ok: false, postponed: true, recovery: true, attempt, resetsAt: recoveryResumesAt, codename: run.codename, runDir: run.runDir };
338
+ }
339
+ // ── A COVERED PART WHOSE RECOVERY IS SPENT IS DELIVERED WITHOUT, NOT ENDED ON ────────────────────────
340
+ //
341
+ // A failure the throw site named as a covered part (`notCompletedPart`, parts-not-completed.mjs) reaches here once
342
+ // the decision above has nothing left to buy: every recovery lane spent, a repeated signature, or a deterministic
343
+ // refusal such as a band too large to dispatch. The run holds everything but that part, so it is not ended with the
344
+ // stop notice: the part is recorded as not completed, and the run parks for an immediate resume. The resumed pass
345
+ // reaches the part, finds the record, and delivers without it, with the gap stated.
346
+ //
347
+ // ONCE PER PART: a part whose record already exists is not routed again, so a failure on the pass that delivers
348
+ // without it ends the run below, as every failure did. Written before `.failed` and before the failure packet, so
349
+ // a run that delivers carries neither. A rate limit and a stop never reach this line (both are handled above), and
350
+ // a storage failure is not a covered part: no throw site names one.
351
+ const coveredPart = e instanceof StageFailure && !refused ? (e.notCompletedPart ?? null) : null;
352
+ const heldRecord = coveredPart && run?.runDir ? readPartNotCompleted(run.runDir, coveredPart) : null;
353
+ // THE SEARCHES' RECORD GROWS: a failure is routed again while it names a slice the record does not hold yet.
354
+ const addedSlices = coveredPart === "searches" ? slicesNotYetRecorded(heldRecord, e.excludedSlices) : [];
355
+ const addedAxes = coveredPart === "searches" ? axesNotYetDisclosed(heldRecord, e.taintedAxes) : [];
356
+ const addedUnits = coveredPart === "searches" ? unitsNotYetRecorded(heldRecord, e.unfinishedUnits) : [];
357
+ if (coveredPart && run?.runDir && (coveredPart === "searches" ? addedSlices.length + addedAxes.length + addedUnits.length > 0 : !heldRecord)) {
358
+ let parked = null;
359
+ try {
360
+ // A TIMED-OUT AXIS IS READ AS THE LAST PASS LEFT IT: the park renamed its unit, band and digest so a resume would
361
+ // run it again, and with its recovery spent nothing will, so they are put back.
362
+ if (addedAxes.length) undoTaintRenames(e.undoRenames);
363
+ writePartNotCompleted(run.runDir, coveredPart, { stage: failedStage, reason: String(reason), sig: failSig.sig, terminalKind,
364
+ ...(coveredPart === "searches" ? { slices: [...(Array.isArray(heldRecord?.slices) ? heldRecord.slices : []), ...addedSlices],
365
+ disclosedAxes: [...(Array.isArray(heldRecord?.disclosed_axes) ? heldRecord.disclosed_axes : []), ...addedAxes],
366
+ unfinishedUnits: [...(Array.isArray(heldRecord?.unfinished_units) ? heldRecord.unfinished_units : []), ...addedUnits] } : {}) });
367
+ const resumesAt = new Date().toISOString();
368
+ // The payload the runner's self-resume needs (job, agent, codename), and the recovery kind, whose stated
369
+ // clock it keeps exactly: now. No recovery attempt is counted, because nothing is being retried.
370
+ writePark(run.runDir, { kind: "recovery", recoveryResumesAt: resumesAt, postponedAt: resumesAt,
371
+ codename: run.codename, job, agent, attempt: priorAttempts, reason: String(reason).slice(0, 300), sig: failSig.sig,
372
+ class: failClass, notCompleted: coveredPart }, { job, agent, codename: run.codename });
373
+ // The cause's payload rides beside the sentence, as on the stop it replaces, so the record still points at it.
374
+ writeRunStatus(ctx, { state: "recovering", failedStage, ...terminalReasonFields(reason), recoveryResumesAt: resumesAt, resetsAt: null,
375
+ reasonDetail: reasonDetail ? abbrev(String(reasonDetail).replace(/\s+/g, " ").trim(), 600) : null });
376
+ rollupStatus(run.studioRoot);
377
+ runLog(run.runDir, { event: "part-not-completed", part: coveredPart, stage: failedStage, sig: failSig.sig, class: failClass,
378
+ terminalKind: terminalKind ?? null, resumesAt });
379
+ logTurnaroundReconciliation(run.runDir, ctx?.quote, "recovery-parked");
380
+ recordRunConsumption(ctx, { phase: "recovery-park", tokens: stampTokenRollup(run.runDir, "recovery-park") });
381
+ note(`${tag} ${failedStage} could not be completed once its recovery was spent — recorded as the ${coveredPart} not completed; the run resumes now and delivers what it holds`);
382
+ parked = { ok: false, postponed: true, recovery: true, attempt: priorAttempts, resetsAt: resumesAt, codename: run.codename, runDir: run.runDir };
383
+ } catch (rErr) {
384
+ note(`${tag} the ${coveredPart} could not be recorded as not completed (${String(rErr?.message ?? rErr).slice(0, 120)}) — the run ends with the stop notice`);
385
+ }
386
+ if (parked) return parked;
387
+ }
388
+ // A RUN THAT ENDS WITH THE STOP NOTICE CARRIES NO RECORD OF A PART NOT COMPLETED: nothing was delivered without it,
389
+ // and a later resume should try the part again.
390
+ if (run?.runDir) clearPartsNotCompleted(run.runDir);
391
+ // Both lane ceilings end the run, and both say so. "weather-exhausted" is the honest terminal for
392
+ // a provider that was still refusing after the whole weather ladder — the run did not break, the
393
+ // far end never came back, and the notice must not read as a defect in the run's own output.
394
+ if (!refused && (decision.terminalKind === "exhausted" || decision.terminalKind === "weather-exhausted") && recoveryMax > 0) {
395
+ runLog(run.runDir, { event: "auto-recovery-exhausted", attempts: priorAttempts, of: recoveryMax, lane: decision.lane, laneAttempts: decision.laneAttempts, laneOf: decision.laneCeiling });
396
+ }
397
+ sentinel(run.runDir, ".failed", { stage: failedStage, reason, recoveryAttempts: priorAttempts, sig: failSig.sig, class: failClass, terminalKind });
398
+ runLog(run.runDir, { event: "failed", stage: failedStage, reason, sig: failSig.sig, class: failClass, terminalKind });
399
+ logTurnaroundReconciliation(run.runDir, ctx?.quote, "failed"); // a run that never delivered still burned wall
400
+ // Record the failure in status FIRST (so the on-demand STATUS.md surfaces it even if the ping can't fire —
401
+ // e.g. a gateway-wide outage where the agent send itself would also fail). reason is truncated for the ping.
402
+ // terminalKind (A5): "failed with artifacts" is not a new enum — it is `failed` + the stamped kind
403
+ // (invalid-artifact-loop | reclaim-exhausted | exhausted | …), so every status reader can say WHY the
404
+ // run ended without parsing sentinels.
405
+ const { reason: shortReason, reasonTruncated, reasonFull } = terminalReasonFields(reason);
406
+ // — THE TAXONOMY'S NAMED SOURCE MUST CONTAIN THE CAUSE.
407
+ //
408
+ // `reason` is capped at 200 because it rides the ping. On the 2026-08-12 round that cap fell exactly
409
+ // where the provider's verbatim error begins: status.json read
410
+ // "…1 dictated qid(s) own no band block: incumbent-class:owner:… ← provider error on the count
411
+ // probe (after one in-tool retry): "
412
+ // — ending on the colon, with nothing after it. The journal had
413
+ // `HTTP 400: APPLICANT_NAME - The system did not recognize the syntax`, but the failure taxonomy
414
+ // sends a diagnosing agent to status.json, and for this failure it was the one place the answer was
415
+ // not. It produced a wrong finding in the round itself: the cause was read as ABSENT, and an absent
416
+ // error string was then reasoned about as if it were the defect.
417
+ //
418
+ // `reasonDetail` could not cover it. That field carries `StageFailure.detail`, and the fan-in throw
419
+ // passes none — so for the failure that exposed this, the only carrier was the truncated `reason`.
420
+ // Widening the 200 cap was the rejected alternative: it is load-bearing for the ping, and the next
421
+ // message longer than whatever new number is chosen would reopen this silently.
422
+ //
423
+ // So the cut is made VISIBLE and the tail is kept beside it. `reasonTruncated` is written on every
424
+ // terminal failure, true or false, because "no reasonFull key" and "nothing was cut" have to be
425
+ // distinguishable — an absence must read as an absence, never as an empty cause.
426
+ // — `reasonDetail` rides beside `reason`, never inside it. abbrev, not a bare slice: a cut that
427
+ // reads as a word is worse than one that reads as a cut, and this one is read by an engineer
428
+ // chasing a defect.
429
+ // — one spelling of the payload for BOTH sinks. status.json already carried `reasonDetail`;
430
+ // `_driver/failure.json` carried neither it nor the count, and `reasonQuantity` reached
431
+ // no file at all — so the operator read "dropped 1 dictated connotation query" and had to replay the
432
+ // gate against the preserved artifacts to learn which one. Derived once here and passed to both
433
+ // writers, so the notice and the status file can never disagree about the payload.
434
+ const reasonDetailField = reasonDetail ? abbrev(String(reasonDetail).replace(/\s+/g, " ").trim(), 600) : null;
435
+ writeRunStatus(ctx, { state: "failed", failedStage, reason: shortReason, terminalKind,
436
+ reasonTruncated, reasonFull,
437
+ // number|null, written on every terminal failure like reasonTruncated: null means THIS failure
438
+ // carries no count, which is a different fact from a status file with no such key. Never 0.
439
+ reasonDetail: reasonDetailField, reasonQuantity: quantity });
440
+ // A terminal failure spent everything up to the break — and carries the run's worst retry waste.
441
+ // Stamped AFTER the state write so a status reader never sees tokens without knowing the run failed.
442
+ recordRunConsumption(ctx, { phase: "failed", tokens: stampTokenRollup(run.runDir, "failed") });
443
+ rollupStatus(run.studioRoot);
444
+ // Best-effort failure notice — must NEVER throw or mask the original failure. The failure event
445
+ // rides the outbox like every other event (the engine has no message tool; a chat-ping stage on it
446
+ // would burn a turn and fail) — the never-silent guarantee, headless form (docs/DELIVERY.md
447
+ // run-failed packet; the level-triggered *.pending watch keeps it alive until ack_event).
448
+ // failPingSent records which lane WROTE the packet. It no longer decides whether the notice is
449
+ // owed: a failure arms sendPending either way (below), because mark_sent is the only clear and it
450
+ // settles a failure.json on the same evidence a delivery needs. ONE SEND PATH, ruled 2026-09-12.
451
+ let failPingSent = false;
452
+ {
453
+ try {
454
+ const runId = `${run.slug}-${run.date}-${run.codename}`; // ONE canonical runId form (charter P1 §3) — matches status.runId
455
+ // The packet carries the FULL code-authored notice (terminal-kind sentence, verbatim
456
+ // machine reason, attempted repairs, burned recovery attempts) — the courier relays it verbatim,
457
+ // so the requester reads the honest diagnosis, not a thin one-liner. `text` stays as the short
458
+ // WhatsApp-sized fallback for legacy relays.
459
+ const rich = buildFailurePacket({
460
+ runId, agent, job, failedStage, shortReason,
461
+ reasonVerbatim: String(reason).slice(0, 1000), sig: failSig.sig, failClass,
462
+ terminalKind: terminalKind ?? null, repairs: attemptedRepairs ?? [],
463
+ priorAttempts,
464
+ // Read off the park history rather than recomputed: the history is what survived the parks.
465
+ capWait: capWaitFrom(Array.isArray(statusSnapshot?.recoveryHistory) ? statusSnapshot.recoveryHistory : []),
466
+ reasonDetail: reasonDetailField, reasonQuantity: quantity, // — the payload reaches the notice
467
+ });
468
+ const packet = {
469
+ kind: "run-failed", ...rich,
470
+ markName: job.markName ?? job.name ?? null, reason: shortReason,
471
+ text: rich.whatsappText,
472
+ // machine fields (repair-digest's primary source — the.failed sentinel stays the fallback)
473
+ failureSignature: failSig.sig, recoveryAttempts: priorAttempts,
474
+ };
475
+ ensureDriverDir(run.runDir);
476
+ writeFileSync(paths(run.runDir).failure, JSON.stringify(packet, null, 2) + "\n");
477
+ failPingSent = Boolean(writeOutboxPacket(`${runId}.failed`, packet));
478
+ } catch (evErr) {
479
+ note(`failure event packet threw (swallowed): ${evErr?.message ?? evErr}`);
480
+ }
481
+ }
482
+ // T5 (J5) — the failure NOTICE rides the SAME guaranteed lane as success delivery: a
483
+ // CODE-authored packet (_driver/failure.json) + sendPending + the outbox wake marker, consumed by
484
+ // the completion-watch → clearotron-deliver skill exactly like a delivery packet. This makes the
485
+ // notice failure-independent: no WhatsApp binding, a handoff-mode engine, or a dead ping stage can
486
+ // no longer silence it ( F9: teal-keystone died silently on exactly that). Best-effort —
487
+ // packet-write trouble must never mask the original failure; the .failed sentinel + status.json
488
+ // remain the durable record either way.
489
+ //
490
+ // OWED EITHER WAY, AND EXACTLY ONE MARKER. A failed run used to read sendPending:false whenever the
491
+ // packet write SUCCEEDED, so the owed-run scan could not see it and the notice waited on a reader of
492
+ // the outbox instead. Now the flag is armed on both lanes. What is NOT duplicated is the marker: the
493
+ // primary lane's packet IS one, because writeOutboxPacket("<runId>.failed") lands
494
+ // `<runId>.failed.pending` and the *.pending watch already matches it. Arming a second
495
+ // `<runId>.pending` beside it would leave a file mark_sent does not clear — it clears `<id>.pending`
496
+ // for each id the run was known by, not this suffixed form — and the sweep re-arms off whatever is
497
+ // on disk, which is how a permanent SEND PENDING was born. So: the flag always, the packet and the
498
+ // marker only when nothing wrote them.
499
+ // THE RECORD OF AN OBLIGATION MUST NOT BE CONTINGENT ON THE ACTION IT OBLIGES. The flag says
500
+ // somebody is owed a notice. Setting it downstream of the attempt to deliver that notice means it is
501
+ // only set when the delivery path already worked — the case that needed it least. This block did
502
+ // exactly that for one revision: `writeOutboxPacket` swallows its own failure and returns null, so
503
+ // an unwritable outbox fell to the branch below, where the RAW marker write threw and took the flag
504
+ // with it. The run then ended failed and NOT owed, in the one condition where the flag is the only
505
+ // thing that could still record the obligation. Order, therefore: supersede the old send's guards,
506
+ // arm the flag, and only then attempt the writes that can fail.
507
+ try { rmSync(join(run.runDir, ".sent")); } catch { /* none */ }
508
+ try { rmSync(paths(run.runDir).sendReceipts, { force: true }); } catch { /* none */ }
509
+ // A fresh notice supersedes an older send's .sent marker AND its per-channel receipts (a resumed run
510
+ // that fails again must still notify on every channel, not be skip-guarded by the earlier send's).
511
+ // Both are best-effort removals above, so neither can keep the flag below from being written.
512
+ try { writeRunStatus(ctx, { sendPending: true }); } catch (sErr) {
513
+ note(`failure notice could NOT be recorded as owed (${String(sErr?.message ?? sErr).slice(0, 100)}) — the run directory is unwritable, so nothing here can say a notice is outstanding`);
514
+ }
515
+ try {
516
+ if (!failPingSent) {
517
+ const packet = buildFailurePacket({
518
+ runId: `${run.slug}-${run.date}-${run.codename}`, agent, job, failedStage, shortReason, // canonical runId form (charter P1 §3)
519
+ reasonVerbatim: String(reason).slice(0, 1000), sig: failSig.sig, failClass, terminalKind,
520
+ repairs: attemptedRepairs ?? [], priorAttempts,
521
+ reasonDetail: reasonDetailField, reasonQuantity: quantity, // — the BACKSTOP notice carries it too
522
+ });
523
+ writeFileSync(paths(run.runDir).failure, JSON.stringify(packet, null, 2) + "\n");
524
+ mkdirSync(config.outboxDir, { recursive: true });
525
+ writeFileSync(join(config.outboxDir, `${packet.runId}.pending`), `${agent}\n`);
526
+ }
527
+ note(`failure notice OWED (${failPingSent ? "event lane wrote the packet" : "handoff wrote the packet"}) — mark_sent is the only clear`);
528
+ } catch (nfErr) {
529
+ // NOT "status.json remains the record" — that sentence was here and it was false on exactly the
530
+ // path that reaches this catch, because the flag was written after the throw. It is written before
531
+ // it now, so the record genuinely does stand, and saying which part failed is what keeps the next
532
+ // reader looking in the right place.
533
+ note(`failure notice is owed but its packet/marker could not be written (${String(nfErr?.message ?? nfErr).slice(0, 100)}) — status.json carries the obligation; the outbox does not`);
534
+ }
535
+ note(`=== ${refused ? "REFUSED" : "FAILED"} ${run.codename} at ${failedStage}: ${reason} ===\n`);
536
+ // `codename` matches the three sibling terminals (postpone, recovery park, cancelled). Without it
537
+ // the CLI could not name the run to resume at the one terminal where resuming is the whole remedy.
538
+ //
539
+ // `terminalKind`: the RETURN is a sink. runner.mjs's queue terminal stringifies this object
540
+ // whole into `<base>.failed.result`, and that file is what scripts/e2e.mjs reads when the run dir
541
+ // cannot be reached — `terminalKind: st?.terminalKind ?? result?.terminalKind ?? null`. The second
542
+ // half of that expression could never fire, on either lane, because neither terminal returned the
543
+ // field it had already computed. It costs one word to stop computing a diagnostic and dropping it.
544
+ return { ok: false, failedStage, reason, terminalKind, codename: run.codename, runDir: run.runDir };
545
+ }
@@ -33,7 +33,7 @@
33
33
  import { readFileSync, readdirSync, statSync } from "node:fs";
34
34
  import { createHash } from "node:crypto";
35
35
  import { join } from "node:path";
36
- import { driverDir } from "../shared/driver-dir.mjs"; //
36
+ import { driverDir } from "./run-record.mjs"; //
37
37
  import { WITNESS_FILE } from "./methodology-witness.mjs"; // — named by its writer, never retyped
38
38
  import { DISPATCH_SUFFIX } from "./dispatch-record.mjs"; // — the dispatch record's own suffix
39
39