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,166 @@
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
+ // turn-failure.mjs — what a settled turn's failure is called.
4
+ //
5
+ // The stage ladder (gateway.mjs runStageLadder) asks two questions of a turn the engine hands back. First,
6
+ // whether the turn itself failed (a timeout, a fallback, an exit code, an envelope) before any file is judged.
7
+ // Then, once the rescues have had their say, which name the failure is recorded and retried under: the name
8
+ // decides the retry, so a rate limit, an overload or a model the wire contradicts each gets its own. Both
9
+ // answers are here with the classifiers they use; the gateway re-exports those classifiers.
10
+
11
+ import { envGateOn } from "../driver.config.mjs";
12
+ import { note } from "../log.mjs";
13
+
14
+ export function isEmbeddedFallback(json, stderr = "") {
15
+ const m = json?.meta ?? json?.result?.meta ?? {};
16
+ return m.transport === "embedded" || m.fallbackFrom === "gateway" || /EMBEDDED FALLBACK/.test(stderr);
17
+ }
18
+
19
+ // A gateway turn that ran out of time. Three signals: (1) execFile hit its hard kill (timeoutSec+60);
20
+ // (2) the gateway hit its OWN turn timeout, after which the CLI auto-falls-back to embedded and that
21
+ // attempt errors — surfacing as `EmbeddedAttemptSessionTakeoverError` / "request timed out" on a
22
+ // nonzero exit (the v14 delivery failure, previously mislabelled `nonzero_exit_1`); (3) any nonzero
23
+ // exit whose wall already reached the configured budget. Distinguished from transient errors so the
24
+ // retry policy can give a slow stage ONE longer shot instead of 3 identical doomed attempts.
25
+ export const isTimeout = (facts) => timeoutCause(facts) !== null;
26
+ export function timeoutCause({ killed, code, wall, stderr = "", timeoutSec }) { // which signal fired, or null
27
+ if (killed) return "killed";
28
+ if (/EmbeddedAttemptSessionTakeoverError|request timed out|\bETIMEDOUT\b/i.test(stderr)) return "stderr";
29
+ return code !== 0 && wall >= timeoutSec ? "wall" : null;
30
+ }
31
+
32
+ // A LANE WEDGE: a timeout whose turn moved ZERO tokens — the gateway never admitted it to a command lane (the
33
+ // serial `main` lane saturated by the heartbeat sweep). The real signature (teal-bastion 2026-06-15) is a
34
+ // hard-kill timeout with a NULL usage envelope, so we key on "fail is a timeout AND no tokens moved" rather than
35
+ // on a parsed 0-usage object. A slow-but-working model that times out returns a status_timeout envelope WITH
36
+ // usage (admitted) → NOT a wedge. Kept pure + exported so the classifier is unit-tested (it must not misfire on
37
+ // admitted turns, and it MUST fire on the null-usage hard-kill that the production incident actually produced).
38
+ export function isLaneWedge(fail, usage) {
39
+ if (fail !== "timeout") return false;
40
+ const moved = (usage?.input || 0) + (usage?.output || 0) + (usage?.cacheRead || 0) + (usage?.cacheWrite || 0);
41
+ return moved === 0;
42
+ }
43
+
44
+ // Final wedge classification at the runStage call site. A 0-token timeout LOOKS like a wedge (isLaneWedge), but a
45
+ // HARD-WALL kill (signals.hardWall — the turn ran the full timeout+60 and was SIGKILLed) is a genuine over-budget
46
+ // grind, NOT a saturated command lane; labelling it `lane_wedge` wastes a 2-cycle chain retry on a turn that won't
47
+ // fit. Keep `lane_wedge` only for a STALL (signals.stalled) or a truly-silent non-hard-wall null-usage kill; a
48
+ // hard-wall kill stays `timeout` (gets at most ONE extended shot, then the deferral). PURE + exported for test.
49
+ export function classifyWedge(fail, usage, signals) {
50
+ if (isLaneWedge(fail, usage) && !signals?.hardWall) return "lane_wedge";
51
+ return fail;
52
+ }
53
+
54
+ // D3 — Anthropic overload (HTTP 529 / overloaded_error). Through claude -p a 529 surfaces as a FAILED
55
+ // turn (nonzero exit) whose result text/stderr carries the overloaded_error envelope — classified
56
+ // generically it looked like `nonzero_exit_1` and the ladder re-attempted INSTANTLY, hammering an API
57
+ // that just said "go away" (and burning the retry budget in seconds — the 04:30 restart-window shape).
58
+ // Detect it and reclassify to `status_overloaded`, the token the normalized --json envelope already
59
+ // produces for the same condition: the stage fails on its one model (there is no model cascade), and
60
+ // TRANSIENT_RE routes that failure to the recovery park (.postponed + escalating backoff) — the
61
+ // existing machinery owns the re-attempt; runStage breaks its own ladder on it (mirrors lane_wedge).
62
+ // The 529 match is deliberately ANCHORED (api error / http prefix, or overload vocabulary within the
63
+ // same line) so a stray "529" in ordinary output never misroutes a real content failure. PURE + exported.
64
+ const OVERLOAD_RE = /overloaded_error|"type"\s*:\s*"overloaded"|\bapi[ _]?error:?\s*529\b|\bhttp\s*529\b|\b529\b[^\n]{0,120}overloaded|overloaded[^\n]{0,120}\b529\b/i;
65
+
66
+ export function isOverloaded({ json, stdout = "", stderr = "" } = {}) {
67
+ if (json?.status === "overloaded") return true;
68
+ return OVERLOAD_RE.test(`${stdout}\n${stderr}`);
69
+ }
70
+
71
+ /**
72
+ * IS THIS ATTEMPT A TIMEOUT? A kill and a run past the limit with a non-zero exit always are. A timed-out request named
73
+ * in stderr is one only when the turn did not complete: a turn that exited 0 with its engine's status ok outlived the
74
+ * request, which was a call inside it (a web lookup, a tool), and is judged on what it wrote like any finished turn.
75
+ * Recorded as a timeout, it was run again whole: on one test run a writer finished in 14.7 minutes of its 43, exited 0
76
+ * with its output written, and paid a second attempt of 20.3 minutes. `cause` is `timeoutCause`'s answer. PURE.
77
+ */
78
+ export function attemptTimedOut({ cause, code, json }) {
79
+ if (!cause) return false;
80
+ return !(cause === "stderr" && code === 0 && json?.status === "ok");
81
+ }
82
+
83
+ /**
84
+ * The failure a turn's own outcome names before any file is judged, or null when the turn settled cleanly and
85
+ * its files decide. `timedOutBy` is timeoutCause's answer. PURE.
86
+ */
87
+ export function turnFailure({ timedOutBy, code, json, stderr }) {
88
+ if (attemptTimedOut({ cause: timedOutBy, code, json })) return "timeout";
89
+ if (isEmbeddedFallback(json, stderr)) return "embedded_fallback";
90
+ if (code !== 0) return `nonzero_exit_${code}`;
91
+ if (!json) return "unparseable_json";
92
+ if (json.status !== "ok") return `status_${json.status}`;
93
+ return null;
94
+ }
95
+
96
+ /**
97
+ * The name a failed attempt is recorded and retried under, once the rescues have run. `gauge` is the model the
98
+ * turn asked for against the one the wire reported. Returns the failure unchanged when no rule renames it, and
99
+ * null for a turn that did not fail and whose model the wire confirms.
100
+ */
101
+ export function nameTheFailure(fail, { usage, json, stdout, stderr, signals, gauge, name }) {
102
+ const { modelMismatch, famRequested, famActual, modelRequested, modelActual } = gauge;
103
+ // Lane-wedge reclassification (see isLaneWedge): a 0-token timeout is a saturated command lane, not a slow
104
+ // model. Becoming `lane_wedge` makes the retry policy skip the wasteful extended shot; stage() (pipeline.mjs)
105
+ // waits for the lane to clear and dispatches the stage again on its one model (a shared lane is not
106
+ // model-specific). teal-bastion 2026-06-15.
107
+ // See classifyWedge: a 0-token timeout is a saturated-lane wedge UNLESS it's a hard-wall over-budget kill.
108
+ fail = classifyWedge(fail, usage, signals);
109
+ // D3: an Anthropic 529/overload hides inside the generic transport tokens (nonzero_exit_1 through
110
+ // claude -p) — reclassify to status_overloaded so it stops the same-model ladder below and rides the
111
+ // recovery park instead. Only the transport shapes are eligible: a timeout/wedge has
112
+ // its own policy, and a content failure must never be laundered into a transient by a stray match.
113
+ if (fail && /^(nonzero_exit_|status_error$|unparseable_json$)/.test(fail) && isOverloaded({ json, stdout, stderr })) fail = "status_overloaded";
114
+ // Rate-limit / session-cap (429): the standalone engine maps EVERY tier to the one Claude subscription, so
115
+ // a re-run on any tier is futile — classify distinctly (NOT in FALLBACK_ELIGIBLE) and carry resetsAt so the
116
+ // pipeline POSTPONES the run to resetsAt instead of failing it. (Overrides the nonzero_exit_1 a 429 shows as.)
117
+ // Guarded on `fail`: a turn whose finished, validated artifact was just accepted (the exit-1 rescue above)
118
+ // stays accepted — the NEXT stage's first turn hits the same cap at 0 tokens spent and postpones cleanly.
119
+ if (signals?.rateLimited && fail) fail = "rate_limited";
120
+ // AN ENGINE WHOSE SIGN-IN EXPIRED IS NAMED, not left as `nonzero_exit_1`. codex fails its refresh in
121
+ // seconds with a bare exit code while `codex login status` still reports the user signed in, so the
122
+ // one thing that fixes it has to be in the failure itself. AFTER the rate limit, which wins when both
123
+ // appear: a postponed run resumes on its own, and a signed-out one cannot. The sentence rides after
124
+ // the colon, as `model_mismatch:` carries its detail, so no run-level classifier needs a new token.
125
+ else if (signals?.signedOut && fail) fail = `engine_signed_out: ${signals.signedOut}`;
126
+ // AND ONE WHOSE TOOLS WERE ALL REFUSED IS NAMED, not left as the missing file the refusal caused. The
127
+ // turn reported success and the stage failed for want of what its tools would have produced; a
128
+ // `missing_file` reads as a model that did not write, and sends the reader to the wrong place. The
129
+ // sentence says what fixes this host. After the sign-in, which is the more basic fault when both appear.
130
+ else if (signals?.toolsRefused && fail) fail = `engine_tools_refused: ${signals.toolsRefused}`;
131
+ // A6 (addendum 2026-07-30): stop_reason max_tokens with ZERO usable output is a DETECTED FAULT with a
132
+ // name — never a silent paid retry. The turn ran to its output-token ceiling and the artifact never
133
+ // landed (a content fail on a "successful" turn), or the turn itself died at the ceiling (transport
134
+ // shapes) — either way the CAUSE is the output budget, and an unnamed retry just re-buys the same
135
+ // wall. Naming it here makes the stage-log row carry the fault (counted per attempt), routes
136
+ // correctiveMessage to the shrink-your-output correction, and arms the A4 identical-signature break
137
+ // on a second identical hit. The content detail stays appended (hint derivation and the
138
+ // coverage-quarantine joins still read it); the transport shapes go BARE — their tokens
139
+ // (nonzero_exit / unparseable_json) read as TRANSIENT to the run-level classifier (repairs.mjs
140
+ // TRANSIENT_RE is substring-matched) and would silently re-arm the full recovery ladder for a
141
+ // deterministic ceiling fault. Never fires on a rescued turn (fail is already null) nor on the
142
+ // kill/wedge/overload/rate-limit classes (each keeps its own policy).
143
+ if (fail && json?.stopReason === "max_tokens" && /^(missing_file:|invalid_file:|nonzero_exit_|status_error$|unparseable_json$)/.test(fail)) {
144
+ const named = /^(missing_file:|invalid_file:)/.test(fail) ? `max_tokens_no_output:${fail}` : "max_tokens_no_output";
145
+ note(`[${name}] DETECTED FAULT: stop_reason=max_tokens with no usable output (${fail}) → ${named}`);
146
+ fail = named;
147
+ }
148
+
149
+ // corruption 3, THE ENFORCEMENT — a turn that ran a different model than it was told to is a
150
+ // FAILED turn, not a successful one with an interesting note. Everything the stage produced is
151
+ // attributed to the wrong model, so accepting it would put the corruption on the record permanently
152
+ // (the artifact lands, the row says haiku, sonnet wrote it).
153
+ //
154
+ // Deliberately scoped to `!fail`: a turn that already failed keeps its own cause, because `timeout`
155
+ // and `rate_limited` drive retry policies this must not override. `modelMismatch` is journalled on
156
+ // the row either way, so the mismatch is never lost — only the classification defers.
157
+ //
158
+ // Default-ON gate through `envGateOn` (the rule): `CLEAROTRON_MODEL_WIRE_CHECK=0` disarms it without
159
+ // a deploy if a provider ever starts reporting an id this build's family regex misreads. Disarming
160
+ // silences the REFUSAL, never the record — `modelActual`/`modelMismatch` keep landing on every row.
161
+ if (modelMismatch === true && !fail && envGateOn("CLEAROTRON_MODEL_WIRE_CHECK")) {
162
+ fail = `model_mismatch:${famRequested}->${famActual}`;
163
+ note(`[${name}] MODEL MISMATCH: asked for ${modelRequested} (${famRequested}), the wire says ${modelActual} (${famActual}) — failing the turn. An unhonoured model override is an error, not a substitution; every number attributed to this turn would name the wrong model.`);
164
+ }
165
+ return fail;
166
+ }
package/driver/log.mjs CHANGED
@@ -6,7 +6,7 @@
6
6
  import { appendFileSync, mkdirSync, readFileSync } from "node:fs";
7
7
  import { createHash } from "node:crypto";
8
8
  import { dirname, join, basename } from "node:path";
9
- import { driverDir, RUN_DIR_MODE } from "../shared/driver-dir.mjs"; //
9
+ import { RUN_DIR_MODE, driverDir, paths } from "./run-record.mjs";
10
10
 
11
11
  function appendLine(file, obj) {
12
12
  mkdirSync(dirname(file), { recursive: true, mode: RUN_DIR_MODE }); // a first log line can be what creates the run folder
@@ -50,7 +50,7 @@ export function outputMeta(absPath) {
50
50
 
51
51
  // One line per stage transition + the verdict + delivery result.
52
52
  export function runLog(runDir, obj) {
53
- appendLine(driverDir(runDir, "run.jsonl"), obj);
53
+ appendLine(paths(runDir).run, obj);
54
54
  }
55
55
 
56
56
  // Per-stage attempt detail (argv-redacted, status, file-validation result).
@@ -41,18 +41,18 @@
41
41
  // It is stamped now, from `_driver/instructed-scope.json`, and `frame_scope_missing` cannot arise from a
42
42
  // recorded frame because there is no retyping left to drift. What that does to the token is stated at
43
43
  // the validator, not here — a guard that cannot fail must be deleted or repointed, never left green.
44
- import { readFileSync, writeFileSync, mkdirSync } from "node:fs";
44
+ import { readFileSync, writeFileSync } from "node:fs";
45
45
  import { captureCall, stampVerdict } from "./call-capture.mjs";
46
46
  import { join } from "node:path";
47
- import { driverDir } from "../shared/driver-dir.mjs"; //
48
47
  import { refuseUndeclared as refuseUndeclaredShared, keepIfAbsent, lastAccepted, acceptedEnvelope } from "./preserve-merge.mjs";
48
+ import { paths, readJson } from "./run-record.mjs";
49
49
 
50
50
  export const MATTER_CONTEXT_FILE = "matter-context.md";
51
51
  const SCHEMA_VERSION = 1;
52
52
 
53
53
  /** Where the call's evidence lives — the driver's own record of what the seat handed it. */
54
54
  export function matterFrameCallPaths(runDir) {
55
- const dir = driverDir(runDir, "matter-frame-calls");
55
+ const dir = paths(runDir).matterFrameCalls;
56
56
  return { dir, payload: join(dir, "call-001.json"), accepted: join(dir, "accepted.json") };
57
57
  }
58
58
 
@@ -509,7 +509,7 @@ export function acceptMatterFrame(params, { instructedScope = null } = {}) {
509
509
 
510
510
  /** The driver's own intake record — the values the seat used to be asked to retype. IMPURE. */
511
511
  export function readInstructedScope(runDir) {
512
- try { return JSON.parse(readFileSync(driverDir(String(runDir ?? ""), "instructed-scope.json"), "utf8")); }
512
+ try { return readJson(paths(String(runDir ?? "")).instructedScope); }
513
513
  catch { return null; } // legacy/replay run with no receipt — the section renders `none given`
514
514
  }
515
515
 
@@ -30,8 +30,8 @@
30
30
  import { createHash } from "node:crypto";
31
31
  import { readFileSync, writeFileSync, existsSync, renameSync } from "node:fs";
32
32
  import { basename, win32 } from "node:path";
33
- import { driverDir, ensureDriverDir } from "../shared/driver-dir.mjs"; // — one definition of where `_driver/` is
34
33
  import { sepClass } from "../shared/path-seps.mjs"; // a Windows path is built with "\"
34
+ import { driverDir, ensureDriverDir, readJson } from "./run-record.mjs"; // — one definition of where `_driver/` is
35
35
 
36
36
  export const WITNESS_FILE = "methodology-read.json";
37
37
 
@@ -68,7 +68,7 @@ export function witnessStageMethodology(runDir, stage, message, resolveSkill, {
68
68
 
69
69
  const path = driverDir(runDir, WITNESS_FILE);
70
70
  let doc = { schema: 1, stages: {} };
71
- if (existsSync(path)) { try { doc = JSON.parse(readFileSync(path, "utf8")) || doc; } catch { /* unreadable ⇒ start clean */ } }
71
+ if (existsSync(path)) { try { doc = readJson(path) || doc; } catch { /* unreadable ⇒ start clean */ } }
72
72
  doc.stages ||= {};
73
73
 
74
74
  const seen = [];
@@ -34,12 +34,14 @@
34
34
  // `n` is the render's, taken from array order. A seat-supplied number is a value that can disagree with
35
35
  // the list it labels — duplicated, skipped, or renumbered by a corrective pass — and nothing downstream
36
36
  // would notice. Removing the field removes the defect (the doubt-closure `file_index` rule).
37
- import { writeFileSync, mkdirSync, existsSync, readFileSync, readdirSync } from "node:fs";
37
+ import { writeFileSync, existsSync, readFileSync, readdirSync, statSync } from "node:fs";
38
+ import { dispatchFileName } from "./dispatch-record.mjs";
38
39
  import { captureCall, mergeCapture, nextSeq } from "./call-capture.mjs";
39
40
  import { join } from "node:path";
40
- import { driverDir } from "../shared/driver-dir.mjs";
41
41
  import { normalizeRecordUri } from "./registry-fidelity.mjs";
42
42
  import { parseVerdict, countCitedDefects, parseCorrections, parseCorrectionKinds, correctionFlagContent, CORRECTION_KINDS, SECTION_HEADING_RE } from "./verify.mjs";
43
+ import { driverDir, driverFileName, paths, readJson } from "./run-record.mjs";
44
+ import { REVIEW_ADDRESSES_FILE, resolveDeclared } from "./review-addresses.mjs";
43
45
 
44
46
  export const REVIEW_FILE = "senior-eye-review.md";
45
47
 
@@ -48,7 +50,7 @@ export const REVIEW_VERDICTS = ["CLEAR", "CONDITIONAL", "BLOCKING"];
48
50
 
49
51
  /** Where the call's evidence lives — the driver's own record of what the seat handed it. */
50
52
  export function refutationCallPaths(runDir) {
51
- const dir = driverDir(runDir, "refutation-calls");
53
+ const dir = paths(runDir).refutationCalls;
52
54
  return { dir, payload: join(dir, "call-001.json") };
53
55
  }
54
56
 
@@ -60,7 +62,7 @@ export function refutationCallPaths(runDir) {
60
62
  export const REVIEW_EXCLUSIONS_FILE = "review-exclusions.json";
61
63
  export function listedExclusionPositions(runDir) {
62
64
  try {
63
- const doc = JSON.parse(readFileSync(driverDir(String(runDir ?? ""), REVIEW_EXCLUSIONS_FILE), "utf8"));
65
+ const doc = readJson(driverDir(String(runDir ?? ""), REVIEW_EXCLUSIONS_FILE));
64
66
  const out = new Map();
65
67
  for (const p of Array.isArray(doc?.positions) ? doc.positions : [])
66
68
  for (const m of [p?.uri, ...(Array.isArray(p?.members) ? p.members : [])]) { const k = String(normalizeRecordUri(m) ?? ""); if (k && p?.uri) out.set(k, p.uri); }
@@ -68,9 +70,60 @@ export function listedExclusionPositions(runDir) {
68
70
  } catch { return null; }
69
71
  }
70
72
 
73
+ /**
74
+ * THE POSITIONS A FINDING NOW DELIVERS, by each of their record ids: record id → `{uri, ordinals}`, the position's own id
75
+ * and the findings that deliver it. A later review is listed these as "excluded at the full review, now delivered as a
76
+ * finding" (pipeline.mjs writerExclusionBlock), so a flag may name one, and it is a flag on that finding: no exclusion
77
+ * stands for it to be about. Empty for the full review, for a record written before these were kept, or one that cannot
78
+ * be read, so such a flag is refused as before. Never throws.
79
+ */
80
+ export function listedWithdrawnPositions(runDir) {
81
+ const out = new Map();
82
+ try {
83
+ const doc = readJson(driverDir(String(runDir ?? ""), REVIEW_EXCLUSIONS_FILE));
84
+ for (const p of Array.isArray(doc?.withdrawn) ? doc.withdrawn : []) {
85
+ if (!p?.uri) continue;
86
+ const entry = { uri: p.uri, ordinals: (Array.isArray(p.ordinals) ? p.ordinals : []).filter((n) => Number.isInteger(n) && n >= 1) };
87
+ for (const m of [p.uri, ...(Array.isArray(p.members) ? p.members : [])]) { const k = String(normalizeRecordUri(m) ?? ""); if (k) out.set(k, entry); }
88
+ }
89
+ } catch { /* nothing kept: the flag is checked against the standing exclusions alone */ }
90
+ return out;
91
+ }
92
+
93
+ /**
94
+ * A flag's positions read against both lists: each standing exclusion stays a position, and each position a finding now
95
+ * delivers becomes that finding's ordinal in `ordKey` (`on` for the tool's values, `ordinals` for a parsed file). A
96
+ * delivered position whose finding has no ordinal stays a position. Returns the flag, or `{unknown}` naming the first id
97
+ * on neither list. PURE.
98
+ */
99
+ function onDeliveredFindings(f, ordKey, positionsListed, withdrawnListed) {
100
+ const k = (p) => String(normalizeRecordUri(p) ?? "");
101
+ const unknown = f.positions.find((p) => !positionsListed?.get(k(p)) && !withdrawnListed?.get(k(p)));
102
+ if (unknown != null) return { unknown };
103
+ const ords = f.positions.flatMap((p) => (positionsListed?.get(k(p)) ? [] : withdrawnListed.get(k(p)).ordinals));
104
+ const kept = f.positions.filter((p) => positionsListed?.get(k(p)) || !withdrawnListed.get(k(p)).ordinals.length);
105
+ if (!ords.length) return { flag: f };
106
+ const { positions: _drop, ...rest } = f;
107
+ return { flag: { ...rest, [ordKey]: [...new Set([...(Array.isArray(f[ordKey]) ? f[ordKey] : []), ...ords])], ...(kept.length ? { positions: kept } : {}) } };
108
+ }
109
+
110
+ /**
111
+ * The address list the last review dispatch wrote (review-addresses.mjs): the finding ordinals and the other parts of
112
+ * the report that review was handed. null when none was written or it does not read back, so `on` is checked as it
113
+ * always was and an address in `lines` has nothing to resolve against. Never throws.
114
+ */
115
+ export function listedAddresses(runDir) {
116
+ try {
117
+ const doc = readJson(driverDir(String(runDir ?? ""), REVIEW_ADDRESSES_FILE));
118
+ if (!Array.isArray(doc?.ordinals) || !Array.isArray(doc?.lines)) return null;
119
+ return { ordinals: doc.ordinals.filter((n) => Number.isInteger(n)), lines: doc.lines.filter((l) => typeof l?.address === "string"),
120
+ seq0: Number.isInteger(doc.seq0) ? doc.seq0 : null };
121
+ } catch { return null; }
122
+ }
123
+
71
124
  /** Whether this run has a plan-execution receipt, which is what makes the audit section mandatory. */
72
125
  export function planReceiptPresent(runDir) {
73
- try { return existsSync(driverDir(String(runDir ?? ""), "plan-execution.json")); }
126
+ try { return existsSync(paths(String(runDir ?? "")).planExecution); }
74
127
  catch { return false; }
75
128
  }
76
129
 
@@ -98,7 +151,9 @@ export function renderRefutation(verdict, flags, planAudit) {
98
151
  // A flag about a writer's exclusion names its position; the token is written only then, so a review without one
99
152
  // renders as it always did.
100
153
  const positions = Array.isArray(f.positions) && f.positions.length ? ` [positions: ${f.positions.join(", ")}]` : "";
101
- out.push(`${i + 1}. [kind: ${f.kind}] [on: ${on}]${positions} ${f.text}`);
154
+ // The same for the report's other parts: the token is written only for a flag that declared some.
155
+ const lines = Array.isArray(f.lines) && f.lines.length ? ` [lines: ${f.lines.join(", ")}]` : "";
156
+ out.push(`${i + 1}. [kind: ${f.kind}] [on: ${on}]${positions}${lines} ${f.text}`);
102
157
  if (f.fix) out.push(` Fix: ${f.fix}`);
103
158
  out.push("");
104
159
  });
@@ -144,8 +199,11 @@ const textDefect = (t) => {
144
199
  *
145
200
  * `receiptPresent` is the DRIVER's read, never a parameter of the call: whether the audit section is
146
201
  * owed is a fact about the run, and a seat that could assert it could waive its own audit.
202
+ *
203
+ * `withdrawnListed` is the driver's read too (listedWithdrawnPositions): the positions a later review was told a finding
204
+ * now delivers. A flag naming one is rendered as a flag on that finding.
147
205
  */
148
- export function acceptRefutation(params, { receiptPresent = false, positionsListed = null } = {}) {
206
+ export function acceptRefutation(params, { receiptPresent = false, positionsListed = null, withdrawnListed = null, addresses = null } = {}) {
149
207
  const verdict = params?.verdict;
150
208
  const flags = params?.flags;
151
209
  const planAudit = params?.plan_audit;
@@ -176,12 +234,26 @@ export function acceptRefutation(params, { receiptPresent = false, positionsList
176
234
  if (!Array.isArray(f.on) || f.on.some((n) => !Number.isInteger(n) || n < 1)) {
177
235
  return { ok: false, reason: `refutation_flag_on_invalid:${i} — \`on\` is an array of finding ordinals (1-based), or omit it for a flag about the document rather than a finding` };
178
236
  }
237
+ // An ordinal is resolved against the findings this review was handed, when the dispatch listed them.
238
+ const r = addresses ? resolveDeclared(addresses, { on: f.on }) : { ok: true };
239
+ if (!r.ok) {
240
+ return { ok: false, reason: `refutation_flag_on_unknown:${i}:${r.value} — finding ${r.value} is not among the findings this review was handed; use the correct listed ordinal, or omit \`on\` if the flag is not about a finding` };
241
+ }
242
+ }
243
+ if (f?.lines != null) {
244
+ if (!Array.isArray(f.lines) || !f.lines.length || f.lines.some((l) => typeof l !== "string" || !l.trim())) {
245
+ return { ok: false, reason: `refutation_flag_lines_invalid:${i} — \`lines\` is an array of addresses from the dispatch's address list, or omit it` };
246
+ }
247
+ const r = resolveDeclared(addresses ?? { ordinals: [], lines: [] }, { lines: f.lines });
248
+ if (!r.ok) {
249
+ return { ok: false, reason: `refutation_flag_line_unlisted:${i}:${String(r.value).slice(0, 80)} — name a part of the report by an address the dispatch's address list gives${r.near ? `; the list gives "${r.near}"` : ""}` };
250
+ }
179
251
  }
180
252
  if (f?.positions != null) {
181
253
  if (!Array.isArray(f.positions) || !f.positions.length || f.positions.some((p) => typeof p !== "string" || !p.trim())) {
182
254
  return { ok: false, reason: `refutation_flag_positions_invalid:${i} — \`positions\` is an array of record ids from the writer's exclusions list, or omit it` };
183
255
  }
184
- const unknown = f.positions.find((p) => !positionsListed?.get(String(normalizeRecordUri(p) ?? "")));
256
+ const { unknown } = onDeliveredFindings(f, "on", positionsListed, withdrawnListed);
185
257
  if (unknown != null) {
186
258
  return { ok: false, reason: `refutation_flag_position_unlisted:${i}:${String(unknown).slice(0, 80)} — name a position by a record id the writer's exclusions list gives for it` };
187
259
  }
@@ -194,9 +266,14 @@ export function acceptRefutation(params, { receiptPresent = false, positionsList
194
266
  return { ok: false, reason: "refutation_plan_audit_shape: `plan_audit` is an array of lines" };
195
267
  }
196
268
 
197
- // A position is rendered as the list keys it, whichever of its record ids the flag named.
198
- const byPosition = (p) => positionsListed.get(String(normalizeRecordUri(p) ?? ""));
199
- const rendered = flags.map((f) => (Array.isArray(f?.positions) ? { ...f, positions: [...new Set(f.positions.map(byPosition))] } : f));
269
+ // A position is rendered as the list keys it, whichever of its record ids the flag named; one a finding now delivers is
270
+ // rendered as that finding.
271
+ const byPosition = (p) => { const k = String(normalizeRecordUri(p) ?? ""); return positionsListed?.get(k) ?? withdrawnListed?.get(k)?.uri ?? k; };
272
+ const rendered = flags.map((f) => {
273
+ if (!Array.isArray(f?.positions)) return f;
274
+ const g = onDeliveredFindings(f, "on", positionsListed, withdrawnListed).flag;
275
+ return Array.isArray(g.positions) ? { ...g, positions: [...new Set(g.positions.map(byPosition))] } : g;
276
+ });
200
277
  const content = renderRefutation(verdict, rendered, planAudit);
201
278
 
202
279
  // ── THE ROUND-TRIP. Rendered bytes → the four shipped parsers → exactly what was asked for. ───────
@@ -221,6 +298,12 @@ export function acceptRefutation(params, { receiptPresent = false, positionsList
221
298
  if ((kinds?.untyped ?? 0) !== 0) {
222
299
  return { ok: false, reason: `refutation_roundtrip_untyped:${kinds.untyped} — every flag was typed in the call, so a line landing on the \`fact\` fail-safe means the token did not render onto it` };
223
300
  }
301
+ // The addresses a flag declared must read back off its line as declared, or the correction would bind it to other parts.
302
+ const parsed = parseCorrections(content);
303
+ const lost = rendered.findIndex((f, i) => JSON.stringify([...new Set(f.lines ?? [])]) !== JSON.stringify(parsed[i]?.lines ?? []));
304
+ if (lost !== -1) {
305
+ return { ok: false, reason: `refutation_roundtrip_lines:${lost} — the rendered line does not carry back the addresses the call declared; the \`[lines:]\` channel did not survive the render` };
306
+ }
224
307
 
225
308
  // `flags` stays a COUNT because that is what its readers assert; `acceptedFlags` is the array itself.
226
309
  // ADDED rather than repurposed: changing what `flags` means would move every reader silently, and a
@@ -268,7 +351,9 @@ export function recordRefutation(runDir, received, { now = () => new Date().toIS
268
351
  // Written first so a call that CRASHES the validator still leaves its input — that was the original
269
352
  // reason and it survives — then rewritten with the verdict once there is one.
270
353
  capture({ accepted: null, refusedReason: null });
271
- const verdict = acceptRefutation(received, { receiptPresent: planReceiptPresent(dir0), positionsListed: listedExclusionPositions(dir0) });
354
+ const verdict = acceptRefutation(received, { receiptPresent: planReceiptPresent(dir0), positionsListed: listedExclusionPositions(dir0),
355
+ withdrawnListed: listedWithdrawnPositions(dir0),
356
+ addresses: listedAddresses(dir0) });
272
357
  capture({ accepted: Boolean(verdict.ok), refusedReason: verdict.ok ? null : verdict.reason });
273
358
  if (!verdict.ok) {
274
359
  return { written: null, refused: verdict.reason, captured: captureFailed ? null : payload, capture_failed: captureFailed };
@@ -298,12 +383,13 @@ export function recordRefutation(runDir, received, { now = () => new Date().toIS
298
383
  * THE ACCEPTED FLAGS, AS TYPED — the input T3b keys targeted fixes off.
299
384
  *
300
385
  * Returns the flag objects the tool ACCEPTED, or `null` when there is nothing trustworthy to return.
301
- * Null covers four different states on purpose, and every one of them means "do not act on this":
386
+ * Null covers five different states on purpose, and every one of them means "do not act on this":
302
387
  *
303
388
  * no payload the stage never called the tool
304
389
  * unreadable payload the capture failed or the file is truncated
305
390
  * `accepted: false` the tool REFUSED this call — the review was never rendered
306
391
  * `accepted: null` the capture ran and the validator did not return, so nothing knows the outcome
392
+ * earlier dispatch the call was captured before the latest review dispatch began
307
393
  *
308
394
  * ✕ THE REFUSED CASE IS WHY THIS EXISTS RATHER THAN A BARE JSON READ. The payload is written before
309
395
  * validation, so a refused call leaves a complete, well-formed, entirely authoritative-looking record of
@@ -315,12 +401,39 @@ export function recordRefutation(runDir, received, { now = () => new Date().toIS
315
401
  * it is looking at.
316
402
  */
317
403
  export function readAcceptedFlags(runDir) {
318
- const { payload } = refutationCallPaths(String(runDir ?? ""));
319
- let doc;
320
- try { doc = JSON.parse(readFileSync(payload, "utf8")); } catch { return null; }
321
- if (doc?.accepted !== true) return null;
322
- const flags = doc?.params?.flags;
323
- return Array.isArray(flags) ? flags : null;
404
+ // THE NEWEST ACCEPTED CALL OF THE REVIEW BEING ACTED ON, not the first capture. A review refused once and accepted on
405
+ // its next call left its accepted flags in `call-002.json`, and reading `call-001.json` alone sent that correction to
406
+ // the rendered parse. The calls read start at the dispatch that wrote the address list (`seq0`), so a later dispatch
407
+ // with no accepted call returns null, and its correction takes the logged parse, rather than an earlier review's
408
+ // flags. A refused or unreadable call is passed over, never returned.
409
+ //
410
+ // AND THE CALL IS FROM THE REVIEW DISPATCH NOW IN FORCE, known without the list. A list that could not be written leaves
411
+ // no start, and one whose removal also failed still names an earlier dispatch: either way an earlier review's accepted
412
+ // call is in reach. Every review dispatch writes its first attempt's record before the model runs (gateway.mjs,
413
+ // recordDispatch), so a call captured before the latest one began belongs to an earlier review, and the correction takes
414
+ // the rendered review through its recorded fallback instead. With no record (CLEAROTRON_DISPATCH_RECORD off, or a write
415
+ // that failed) the list alone decides, as it did before. The capture's file time is read, not the `receivedAt` inside it:
416
+ // a replay that serves a saved call copies the file when the dispatch runs, and keeps the saved run's `receivedAt`.
417
+ const dir0 = String(runDir ?? "");
418
+ const accepted = readAcceptedReviewSince(dir0, listedAddresses(dir0)?.seq0 ?? 0);
419
+ if (!accepted) return null;
420
+ const began = reviewDispatchBegan(dir0);
421
+ if (began != null && !(capturedAt(accepted.file) >= began)) return null;
422
+ return accepted.flags;
423
+ }
424
+
425
+ /**
426
+ * When the latest dispatch of the review stage began, in epoch milliseconds: the time its first attempt's record was
427
+ * written, which is before the model ran. null when there is no such record or it cannot be read. Never throws.
428
+ */
429
+ export function reviewDispatchBegan(runDir) {
430
+ try { return Math.floor(statSync(driverDir(String(runDir ?? ""), driverFileName(dispatchFileName("narrative-refutation", 1)))).mtimeMs); }
431
+ catch { return null; }
432
+ }
433
+
434
+ /** When a call's capture file was last written, in whole epoch milliseconds, or NaN when it cannot be read. Never throws. */
435
+ function capturedAt(file) {
436
+ try { return Math.floor(statSync(file).mtimeMs); } catch { return Number.NaN; }
324
437
  }
325
438
 
326
439
  /**
@@ -338,8 +451,8 @@ export function nextRefutationSeq(runDir) {
338
451
  /**
339
452
  * THE LAST ACCEPTED REVIEW CALL FROM `seq0` ON, AS TYPED: `{seq, verdict, flags, planAudit}`, or null.
340
453
  *
341
- * The review after a delivery-check repair is a later call than the first review's, so `readAcceptedFlags`
342
- * (which opens the first call) cannot read it. A refused or unfinished call is skipped, as it is there: null
454
+ * The review after a delivery-check repair is a later dispatch than the first review, and its caller names that
455
+ * dispatch's `seq0` itself (`readAcceptedFlags` takes it from the address list). A refused or unfinished call is skipped: null
343
456
  * means there is no review from that dispatch the driver can act on, and its caller says so rather than
344
457
  * reading anything else in its place. Never throws.
345
458
  */
@@ -353,10 +466,10 @@ export function readAcceptedReviewSince(runDir, seq0) {
353
466
  .sort((a, b) => b.seq - a.seq);
354
467
  for (const c of calls) {
355
468
  let doc;
356
- try { doc = JSON.parse(readFileSync(c.file, "utf8")); } catch { continue; }
469
+ try { doc = readJson(c.file); } catch { continue; }
357
470
  if (doc?.accepted !== true) continue;
358
471
  const p = doc?.params ?? {};
359
- return { seq: c.seq, verdict: p.verdict ?? null, flags: Array.isArray(p.flags) ? p.flags : [], planAudit: p.plan_audit ?? null };
472
+ return { seq: c.seq, verdict: p.verdict ?? null, flags: Array.isArray(p.flags) ? p.flags : [], planAudit: p.plan_audit ?? null, file: c.file };
360
473
  }
361
474
  return null;
362
475
  }
@@ -393,10 +506,12 @@ export function planAuditLines(reviewMd) {
393
506
 
394
507
  /**
395
508
  * The typed values of a review saved as a file, as `{ok: true, verdict, flags, planAudit}`, or `{ok: false, reason}` with
396
- * the token the tool refuses the same review with. `receiptPresent` and `positionsListed` are the driver's reads, as for
397
- * acceptRefutation. PURE.
509
+ * the token the tool refuses the same review with. `receiptPresent`, `positionsListed` and `withdrawnListed` are the
510
+ * driver's reads, as for acceptRefutation, and a flag on a position a finding now delivers is read as a flag on that
511
+ * finding. The file keeps the reviewer's words: no correction is routed by a later review's positions (the correction
512
+ * after a repair's review is handed none). PURE.
398
513
  */
399
- export function acceptReviewFile(content, { receiptPresent = false, positionsListed = null } = {}) {
514
+ export function acceptReviewFile(content, { receiptPresent = false, positionsListed = null, withdrawnListed = null } = {}) {
400
515
  const text = String(content ?? "");
401
516
  const verdict = parseVerdict(text);
402
517
  if (!REVIEW_VERDICTS.includes(verdict)) return { ok: false, reason: `refutation_verdict_invalid:${String(verdict).slice(0, 40)}` };
@@ -405,8 +520,10 @@ export function acceptReviewFile(content, { receiptPresent = false, positionsLis
405
520
  for (let i = 0; i < flags.length; i++) {
406
521
  if (!String(flags[i].text ?? "").trim()) return { ok: false, reason: `refutation_flag_text_empty:${i}` };
407
522
  if ((flags[i].ordinals ?? []).some((n) => n < 1)) return { ok: false, reason: `refutation_flag_on_invalid:${i}` };
408
- const unknown = (flags[i].positions ?? []).find((p) => !positionsListed?.get(String(normalizeRecordUri(p) ?? "")));
523
+ if (!Array.isArray(flags[i].positions) || !flags[i].positions.length) continue;
524
+ const { unknown, flag } = onDeliveredFindings(flags[i], "ordinals", positionsListed, withdrawnListed);
409
525
  if (unknown != null) return { ok: false, reason: `refutation_flag_position_unlisted:${i}:${String(unknown).slice(0, 80)}` };
526
+ flags[i] = flag;
410
527
  }
411
528
  const planAudit = planAuditLines(text);
412
529
  if (receiptPresent && !planAudit.length) return { ok: false, reason: "refutation_plan_audit_missing" };
@@ -432,7 +549,7 @@ export function settleRecheckSave(runDir, { before = null, stageOk = false, seq0
432
549
  try { now = readFileSync(join(dir0, REVIEW_FILE), "utf8"); } catch { now = null; }
433
550
  const earlierBack = before != null && now !== before ? before : null;
434
551
  if (!stageOk) return { read: null, fail: null, refused: null, restore: earlierBack };
435
- const rules = { receiptPresent: planReceiptPresent(dir0), positionsListed: listedExclusionPositions(dir0) };
552
+ const rules = { receiptPresent: planReceiptPresent(dir0), positionsListed: listedExclusionPositions(dir0), withdrawnListed: listedWithdrawnPositions(dir0) };
436
553
  const call = readAcceptedReviewSince(dir0, seq0);
437
554
  const typed = call ? acceptRefutation({ verdict: call.verdict, flags: call.flags, plan_audit: call.planAudit }, rules) : null;
438
555
  const saved = typed?.ok ? typed.content : null;
@@ -446,17 +563,3 @@ export function settleRecheckSave(runDir, { before = null, stageOk = false, seq0
446
563
  if (byTool) return { read: byTool, fail: null, refused: file.reason, restore: saved };
447
564
  return { read: null, fail: `file-save-refused:${file.reason}`, refused: file.reason, restore: earlierBack };
448
565
  }
449
-
450
- /** Read back what was written — the verdict view of the stored file, through the one parse. */
451
- export function readRecordedVerdict(runDir) {
452
- try { return parseVerdict(readFileSync(join(String(runDir ?? ""), REVIEW_FILE), "utf8")); }
453
- catch { return null; }
454
- }
455
-
456
- /** The flag lines as the corrective ladder sees them — through the shipped selector, not a local one. */
457
- export function readRecordedFlagLines(runDir) {
458
- try {
459
- return readFileSync(join(String(runDir ?? ""), REVIEW_FILE), "utf8")
460
- .split("\n").map((l) => correctionFlagContent(l)).filter(Boolean);
461
- } catch { return null; }
462
- }
@@ -0,0 +1,62 @@
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
+ // one-build-per-run.mjs — a run is finished on the build it started on, or not at all.
4
+ //
5
+ // The owner's ruling of 2026-11-09: a search is not upgraded part-way, and a run is not resumed after an upgrade. Code
6
+ // that carries a run from one build into the next is not kept. Each segment of a run already writes the build it loaded
7
+ // as an `engine-build` row in `run.jsonl`; this reads the first of them and compares it with the build now running.
8
+ //
9
+ // WHERE IT IS ASKED. The runner's resumes ask it before re-entering the pipeline: a postponed claim and a crash reclaim
10
+ // in `runPrepared`, and a run folder's own resume in `resumeRunDirOrphans`. `pipeline()` itself does not, because the
11
+ // bench resumes saved runs on new code to measure what a change does, and that comparison reads a copy and delivers
12
+ // nothing. Only the doors a client's run comes back through refuse.
13
+ //
14
+ // AN ABSENT RECORD REFUSES. A run with no `engine-build` row started before the row existed, which is an earlier
15
+ // version, and a build that cannot name itself cannot show that a run started on it.
16
+ import { readFileSync } from "node:fs";
17
+
18
+ import { engineProvenance } from "./engine-build.mjs";
19
+ import { paths } from "./run-record.mjs";
20
+
21
+ /** The commit a run's first segment loaded, from its first `engine-build` row, or null when it recorded none. */
22
+ export function startedOnBuild(runDir) {
23
+ let text;
24
+ try { text = readFileSync(paths(runDir).run, "utf8"); } catch { return null; }
25
+ for (const line of text.split("\n")) {
26
+ if (!line.includes('"engine-build"')) continue;
27
+ try {
28
+ const row = JSON.parse(line);
29
+ if (row?.event === "engine-build") return typeof row.engineHead === "string" && row.engineHead ? row.engineHead : null;
30
+ } catch { /* a torn line is not the row */ }
31
+ }
32
+ return null;
33
+ }
34
+
35
+ /**
36
+ * Why this run may not be resumed on the running build, as one sentence, or null when it may.
37
+ * `current` is injected for tests; callers leave it to the running build.
38
+ */
39
+ export function crossBuildResumeRefusal(runDir, { current = engineProvenance().engineHead } = {}) {
40
+ const why = !current
41
+ ? "this install cannot name its own build, so it cannot show the run started on it"
42
+ : (() => {
43
+ const started = startedOnBuild(runDir);
44
+ if (!started) return "the run recorded no build when it started, so it started on an earlier version";
45
+ return started === current ? null : `the run started on build ${started.slice(0, 12)} and this is ${current.slice(0, 12)}`;
46
+ })();
47
+ return why && `resume refused: ${why}. A run is finished on the build it started on and is not resumed after an update; start a new run.`;
48
+ }
49
+
50
+ /**
51
+ * Why `pool-admin republish` may not re-render this archived run on the running build, as one sentence, or null when
52
+ * it may. The run's stored page stays as it is: only a re-render through today's publisher is refused, so a report
53
+ * from an earlier version is never rewritten by code it was not made with (design's ruling, 2026-11-11). The demo's
54
+ * player and the bench's comparison call the publisher directly and are not this door. A run that recorded no build,
55
+ * and an install that cannot name its own, cannot show the run was made here, so both refuse. `current` is injected
56
+ * for tests; callers leave it to the running build.
57
+ */
58
+ export function crossBuildRepublishRefusal(runDir, { current = engineProvenance().engineHead } = {}) {
59
+ const started = startedOnBuild(runDir);
60
+ if (current && started === current) return null;
61
+ return "This report was created by a different Clearotron build. Its saved report remains available; this build cannot republish it.";
62
+ }