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
@@ -21,6 +21,7 @@ import { config } from "./driver.config.mjs";
21
21
  import { resolveNumericSetting } from "./numeric-setting.mjs"; // — resolve without the throw a diagnostic surface must not take
22
22
  import { enumerateRuns as enumerateRunsDefault } from "../mcp-server/lib/runs.mjs";
23
23
  import { readActivity as readActivityDefault } from "./run-activity.mjs";
24
+ import { readJson } from "./run-record.mjs";
24
25
 
25
26
  // kill-0 liveness, matching slot-lock.mjs: EPERM proves the pid exists (another user), only ESRCH is death.
26
27
  function pidAlive(pid) {
@@ -51,7 +52,7 @@ function agentOfQueue(qdir) {
51
52
  // raw, fall back to a legacy inline manifest value. A malformed manifest never throws (the job still lists).
52
53
  function readJob(qdir, file) {
53
54
  const base = file.slice(0, -".json".length);
54
- let j = {}; try { j = JSON.parse(readFileSync(join(qdir, file), "utf8")); } catch { /* list it anyway */ }
55
+ let j = {}; try { j = readJson(join(qdir, file)); } catch { /* list it anyway */ }
55
56
  let markName = j.markName || null;
56
57
  try { const mp = join(qdir, `${base}.markName.md`); if (existsSync(mp)) markName = readFileSync(mp, "utf8").trim() || markName; } catch { /* sidecar optional */ }
57
58
  let enqueuedAt = null; try { enqueuedAt = statSync(join(qdir, file)).mtime.toISOString(); } catch { /* race */ }
@@ -0,0 +1,311 @@
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
+ // steps/correction-cycle.mjs — the correction after the review, and the recheck of it.
5
+ //
6
+ // One phase of a run, moved out of pipelineInner unchanged. `helpers` are functions still held in pipeline.mjs, handed in
7
+ // because this module must not import that one back; each moves here when the other phases that share it have moved.
8
+ import { buildCorrectionsApplied, correctionsAppliedTable, scopeDrift } from "../corrections-feedforward.mjs";
9
+ import { evidenceClaimTable, evidenceClaimViolations } from "../evidence-claim-invariant.mjs";
10
+ import { parseFindingsJsonLenient } from "../findings-model.mjs";
11
+ import { note, runLog } from "../log.mjs";
12
+ import { nextRefutationSeq, settleRecheckSave } from "../narrative-refutation-record.mjs";
13
+ import { signoffPatch, writeRunStatus } from "../progress.mjs";
14
+ import { atomicWrite, driverDir, readJson } from "../run-record.mjs";
15
+ import { modelRecordPath } from "../record-fold.mjs";
16
+ import { repairFollowup } from "../repair-composers.mjs";
17
+ import { partsDrift, writeReviewAddresses } from "../review-addresses.mjs";
18
+ import { lastAcceptedCall } from "../synthesis-record.mjs";
19
+ import { shaOf } from "../stage-freshness.mjs";
20
+ import { parseVerdict } from "../verify.mjs";
21
+ import { existsSync, readFileSync, renameSync, rmSync, writeFileSync } from "node:fs";
22
+
23
+ export async function runCorrectionCycle({ ctx, run, P, verdict, firstRef, synthesisKey, synthesisModel, synthesisThinking }, helpers) {
24
+ const { CORRECTIONS_DELIVERED_FILE, CORRECTIVE_RECHECK_FILE, asPartNotCompleted, correctionNamedLines, correctionNamedOrdinals, correctionNamedSet, correctionReading, correctionRows, correctionsExtra, correctiveCycleSettledDecision, enforceCorrectionsReachFindings, must, planAuditExtra, prepareDeclinationSpec, recordCorrectionsBasis, recordSynthesisSeam, removalRepairedRow, repairUnnamedRemovals, restoredFindingsTable, rollbackCorrectivePass, snapshotFindingsForCorrections, stage, writerExclusionBlock } = helpers;
25
+ // AD-2 A1 (E2E-R2, recovery granularity) — the corrective cycle fires ONCE per settled
26
+ // review/narrative state. Both legs below run `force:true` (they bypass the stage-freshness skip
27
+ // by design), so on EVERY resume of a CONDITIONAL/BLOCKING run the cycle used to re-fire: two
28
+ // opus-class calls that re-emit the narrative + findings, staling the whole delivery tail behind
29
+ // them — which is how a stale-artifact recovery became a full pipeline re-run (34% of E2E-R2).
30
+ // The completion receipt records the exact review + narrative bytes the cycle settled; a resume
31
+ // whose bytes are unchanged skips both legs (`verdict` on such a pass is already the post-recheck
32
+ // verdict — refute() parsed it off the very review the receipt fingerprints). Either file moving
33
+ // re-arms the cycle. findings.json is deliberately NOT keyed: four sanctioned driver-owned
34
+ // mutators rewrite it after this point on every pass (the restamp class — injectDeferralCoverage /
35
+ // enrichFindingDeadlines / consolidateFindingsFile / the coverage-floor clamp), so keying on it
36
+ // would re-arm the settled cycle on every resume, the exact cost this receipt kills. Whether the
37
+ // corrections REACHED findings.json is enforced inside the cycle (enforceCorrectionsReachFindings
38
+ // + the verdict-recheck), never by this receipt.
39
+ const correctiveCyclePath = P.correctiveCycle;
40
+ const correctiveCycleShas = () => ({ review: shaOf(P.seniorEyeReview), narrative: shaOf(P.narrative) });
41
+ const correctiveEntryVerdict = verdict; // the recheck reassigns `verdict`; the receipt keys on the entry gate
42
+ let correctiveCycleSettled = false;
43
+ let correctiveRecheckOk = false;
44
+ if (correctiveEntryVerdict === "CONDITIONAL" || correctiveEntryVerdict === "BLOCKING") {
45
+ let cycleReceipt = null;
46
+ try { cycleReceipt = readJson(correctiveCyclePath); } catch { /* no receipt — the cycle runs */ }
47
+ correctiveCycleSettled = correctiveCycleSettledDecision(cycleReceipt, correctiveCycleShas());
48
+ if (correctiveCycleSettled) {
49
+ runLog(run.runDir, { event: "corrective-cycle-settled", verdict, receiptTs: cycleReceipt?.ts ?? null });
50
+ note(`corrective cycle already settled for these exact review/narrative bytes — not re-firing (a stale-artifact recovery re-does what went stale, never the settled corrective loop)`);
51
+ }
52
+ }
53
+ // One corrective re-synthesis on CONDITIONAL/BLOCKING, feeding the reviewer's flags back in, dispatched on the
54
+ // WINNING synthesis attempt's key, model and thinking, so the model that wrote a fallback-won synthesis corrects
55
+ // it. Its first attempt is a fresh turn handed the flags and the inputs; it never resumes the synthesis session.
56
+ let correctionsApplied = null; // — the driver's flag-by-flag observation, shared by both legs
57
+ let evidenceViolations = []; // — claims that moved against their own evidence, carried to the recheck
58
+ let correctionsScope = null; // — the declared per-finding scope, and whether the pass held to it
59
+ let recheckRecords = []; // — the records before and after the pass, so the recheck can name a finding either holds
60
+ let correctiveRollback = null; // T3b — set when the corrective pass failed and the last good findings came back
61
+ let correctiveRepair = null; // — set when the driver put back a removal no flag named
62
+ if (!correctiveCycleSettled && (verdict === "CONDITIONAL" || verdict === "BLOCKING")) { // T3: the quarantine path is terminal now — the corrective pass always runs
63
+ const preCorrective = snapshotFindingsForCorrections(P, run.runDir); // A1
64
+ // — re-prepared, not reused. The findings surface cannot move between these two passes today
65
+ // (nothing writes placements.json or register-findings.md between them — checked), so this rewrites
66
+ // the same list. It is here anyway, because the alternative is an invariant a future change breaks
67
+ // silently: if the surface ever did move, the corrective's `row_index` would point into the previous
68
+ // pass's list and a declination would land on the wrong record.
69
+ prepareDeclinationSpec(ctx, P);
70
+ // THE CORRECTION RIDES ITS OWN DISPATCH: the excluded positions its flags name go to the writer's save with this
71
+ // dispatch, its retries and the follow-up below, and with no other. The message names the same positions.
72
+ const reading = correctionReading(P);
73
+ const correction = { positions: reading.positions };
74
+ const correctivePass = await stage("synthesis", ctx, { force: true, followup: correctionsExtra(P, ctx.depth, ctx.framework, reading), correction, sessionKey: synthesisKey, model: synthesisModel, thinking: synthesisThinking, trigger: "corrective" });
75
+ // half one — the corrective pass rewrites findings.json under a closed minimal-edit contract,
76
+ // so it is the pass most likely to change one record's fate. Its own account, at its own moment; the
77
+ // winner rule in record-discard.mjs lets this carry cancel an earlier discard.
78
+ recordSynthesisSeam(ctx, correctivePass, "corrective");
79
+ // T3b — a corrective pass that cannot produce a valid document no longer kills the run. The
80
+ // pre-corrective findings come back and the run delivers, with the reviewer's objections printed
81
+ // by `buildReviewerOpenPointsSection` — which is the other half of the same owner decision and is
82
+ // what makes this honest rather than quiet. `must` still runs where the rollback declines.
83
+ correctiveRollback = correctivePass.ok
84
+ ? null
85
+ : rollbackCorrectivePass(P, run.runDir, preCorrective, correctivePass);
86
+ if (correctiveRollback) {
87
+ runLog(run.runDir, { event: "corrective-rollback", reason: correctiveRollback.reason,
88
+ restored: correctiveRollback.restored, verdict });
89
+ note(`[corrections] the corrective pass failed (${correctiveRollback.reason}) — `
90
+ + `${correctiveRollback.restored ? "findings.json restored to the version the reviewer read" : "findings.json was never changed"}`
91
+ + `; the run delivers with the reviewer's points printed rather than failing`);
92
+ } else {
93
+ // The rollback declined: a rate limit, which waits, or no record from before the pass to trust, which is the
94
+ // assessment not completed, as for the correction after the review of a repair.
95
+ await asPartNotCompleted("assessment", async () => must(correctivePass, `synthesis(${verdict.toLowerCase()})`));
96
+ // ── — THE THIRD BRANCH, AND IT IS ON THE SUCCESS SIDE ON PURPOSE ─────────
97
+ //
98
+ // A repair is not a rollback and must never be reached by falling through to one. The rollback
99
+ // branch above deliberately skips both the corrections-reached-findings gate and the reviewer's
100
+ // re-read, because what it delivers is the PRE-corrective document — the exact bytes the
101
+ // reviewer already read, so there is nothing new to re-read. A repaired document is the
102
+ // opposite: it is a document nobody has seen, assembled by the driver from two sources.
103
+ //
104
+ // So it stays here, before the gate, with `correctiveRollback` still null — which is what makes
105
+ // the reviewer's re-read run over it. That dispatch is guarded on `!correctiveRollback`, so a
106
+ // repair hung off the rollback side would have inherited the skip silently and shipped a
107
+ // driver-assembled document no reviewer ever saw. Every check the successful branch runs, the
108
+ // repair branch runs, on the repaired bytes.
109
+ //
110
+ // NAMED AGAINST THE PRE-CORRECTIVE DOCUMENT. A removed finding is absent from the post-pass
111
+ // file, so matching the review's names against that file would find none of them and call every
112
+ // named removal unnamed.
113
+ let preDocForNames = null;
114
+ try { preDocForNames = preCorrective ? parseFindingsJsonLenient(preCorrective.raw) : null; } catch { /* fall back to the file */ }
115
+ const repaired = repairUnnamedRemovals(P, run.runDir, preCorrective,
116
+ correctionNamedOrdinals(P), correctionNamedSet(P, preDocForNames), correctionNamedLines(P, preDocForNames));
117
+ correctiveRepair = repaired; // carried to the reviewer's re-read, which must know these are the DRIVER's
118
+ if (repaired) {
119
+ // A DEFECT SIGNAL, not a success. After the schema fix a corrective pass sends a targeted edit
120
+ // and cannot remove a finding at all, so e2e asserts this count is ZERO — a firing reports the
121
+ // primary fix not holding, never this backstop working.
122
+ runLog(run.runDir, removalRepairedRow(repaired)); // with `base`: whether the merge base took the restore
123
+ note(`[corrections] the corrective pass removed ${repaired.restoredFindings.length} finding(s) `
124
+ + `no flag named — restored whole from the pre-corrective snapshot: `
125
+ + `${repaired.restoredFindings.map((f) => `#${f.ordinal} ${f.mark}`).join(", ")}`
126
+ + (repaired.restoredKeys.length ? `; and ${repaired.restoredKeys.length} top-level register(s): ${repaired.restoredKeys.join(", ")}` : "")
127
+ + (repaired.restoredRows.length ? `; and ${repaired.restoredRows.length} row(s): ${repaired.restoredRows.map((r) => r.key).join(", ")}` : "")
128
+ + (repaired.leftRemoved.length ? `. ${repaired.leftRemoved.length} removal(s) the reviewer DID name stay removed.` : "")
129
+ + " The reviewer re-reads the repaired document before it ships.");
130
+ }
131
+ await enforceCorrectionsReachFindings(ctx, P, preCorrective, { synthesisKey, synthesisModel, synthesisThinking, correction }); // A1 freshness gate
132
+ }
133
+ // — WHAT THE DRIVER OBSERVED, flag by flag, written before the recheck is dispatched. The
134
+ // recheck's whole cost is re-reading two documents to work out whether its own corrections landed;
135
+ // the driver already holds the pre-corrective findings snapshot and the post-pass file, so it can
136
+ // answer that from evidence and leave the reviewer the part only it can do — judging whether what
137
+ // changed is RIGHT. NEVER-KILL: a table that cannot be built just means the recheck reads as it
138
+ // always did, which is today's behaviour exactly.
139
+ try {
140
+ const rows = correctionRows(P, readFileSync(P.seniorEyeReview, "utf8")); // the same reading of each flag as the correction's
141
+ const preDoc = preCorrective ? parseFindingsJsonLenient(preCorrective.model?.raw ?? preCorrective.raw) : null; // the flags name the model's ordinals, so both sides are the record the model wrote (record-fold.mjs)
142
+ let postDoc = null;
143
+ try { postDoc = parseFindingsJsonLenient(readFileSync(modelRecordPath(run.runDir, P.findings), "utf8")); } catch { /* shape defects ride the normal ladder */ }
144
+ correctionsApplied = buildCorrectionsApplied(rows, preDoc, postDoc);
145
+ recheckRecords = [preDoc, postDoc];
146
+ // — A CLAIM MAY NOT OUTLIVE ITS EVIDENCE, AND A DEMOTED STAMP MAY NOT COME BACK.
147
+ //
148
+ // Same two documents, one more question. The pass that fixes the reviewer's flags is the pass
149
+ // most likely to break the join between a claim and its support, and on the run this was found
150
+ // on it did both: four meters lost their basis while the band held (one with a byte-identical
151
+ // claim, one that GREW by 243 characters as its citation was deleted), and six stamps the
152
+ // driver had demoted minutes earlier as `record-on-disk-never-read` came back as
153
+ // `verified-from-record` with no register call in between.
154
+ //
155
+ // RECORDED, AND CARRIED TO THE RECHECK — never a refusal here, for the reason the table above
156
+ // is not one either: the reviewer is about to read both documents and is better placed than a
157
+ // diff to say whether a change was right. A gate here would also spend a dispatch on the stage
158
+ // this seam exists to make cheaper. ``'s correct-or-escalate is satisfied by escalating to
159
+ // the seat that can judge it.
160
+ try {
161
+ let demotions = [];
162
+ try { demotions = readJson(P.basisDerivation)?.rows ?? []; }
163
+ catch { /* no derivation record — stated below, never inferred as "clean" */ }
164
+ const ec = evidenceClaimViolations({ before: preDoc?.findings, after: postDoc?.findings, demotions });
165
+ evidenceViolations = ec.violations;
166
+ runLog(run.runDir, { event: "evidence-claim-invariant", violations: ec.violations.length,
167
+ byArm: ec.violations.reduce((a, v) => ({ ...a, [v.arm]: (a[v.arm] ?? 0) + 1 }), {}),
168
+ snapshots: ec.snapshots });
169
+ if (ec.violations.length) {
170
+ atomicWrite(P.evidenceClaimViolations,
171
+ JSON.stringify({ ts: new Date().toISOString(), ...ec }, null, 2) + "\n");
172
+ note(`#1557: ${ec.violations.length} claim(s) moved against their own evidence in the corrective pass — `
173
+ + ec.violations.slice(0, 3).map((v) => `${v.finding}/${v.meter} (${v.arm})`).join("; ")
174
+ + `${ec.violations.length > 3 ? ` …${ec.violations.length - 3} more` : ""}`);
175
+ }
176
+ } catch (e) {
177
+ runLog(run.runDir, { event: "evidence-claim-invariant", ok: false, why: String(e?.message ?? e).slice(0, 160) });
178
+ }
179
+ // — what the DECLARED scope was and whether the pass honoured it. Recorded, never refused:
180
+ // a gate here costs a whole extra dispatch on the stage this change exists to make cheaper, and
181
+ // the reviewer is about to read the table anyway — it is better placed than a diff to say
182
+ // whether a knock-on edit was right. `unbound` is the `cite_unbound` shape one gate over and
183
+ // would earn a refusal if it recurs; this round measures whether it does.
184
+ correctionsScope = scopeDrift(rows, preDoc, postDoc);
185
+ // The report's other parts and the narrative's sections, compared the same way, against the accepted call the pass
186
+ // started from. Recorded, never refused, as above.
187
+ let narrativeBefore = null;
188
+ try { narrativeBefore = preCorrective?.base?.accepted ? JSON.parse(preCorrective.base.accepted)?.params?.narrative ?? null : null; }
189
+ catch { narrativeBefore = null; }
190
+ correctionsScope = { ...correctionsScope,
191
+ lines: partsDrift(rows, preDoc, postDoc, { narratives: { before: narrativeBefore, after: lastAcceptedCall(run.runDir)?.narrative ?? null } }) };
192
+ atomicWrite(P.correctionsApplied, JSON.stringify({ ts: new Date().toISOString(), verdict,
193
+ scope: correctionsScope, rows: correctionsApplied }, null, 2) + "\n");
194
+ const by = correctionsApplied.reduce((a, r) => (a[r.outcome] = (a[r.outcome] ?? 0) + 1, a), {});
195
+ runLog(run.runDir, { event: "corrections-applied", flags: correctionsApplied.length, outcomes: by,
196
+ scoped: correctionsScope.scoped, named: correctionsScope.named.length,
197
+ movedOutsideScope: correctionsScope.moved.length, unboundOrdinals: correctionsScope.unbound.length,
198
+ partsMovedOutsideScope: correctionsScope.lines.moved.length, partsComparedWhole: correctionsScope.lines.complete });
199
+ // The basis for the delivery check each assembly makes (recordCorrectionsDelivered): what each flag
200
+ // changed in the fields a report prints from the record, from the same two records. Its own file.
201
+ try { recordCorrectionsBasis(run.runDir, correctionsApplied, preDoc, postDoc); }
202
+ catch (e) {
203
+ try { rmSync(driverDir(run.runDir, CORRECTIONS_DELIVERED_FILE), { force: true }); } catch { /* best-effort */ }
204
+ note(`[corrections] the delivery basis could not be kept (${String(e?.message ?? e).slice(0, 100)}) — this pass has no delivery record`);
205
+ }
206
+ } catch (e) {
207
+ // A basis from an earlier pass would be read against this pass's report as if it were this pass's.
208
+ try { rmSync(driverDir(run.runDir, CORRECTIONS_DELIVERED_FILE), { force: true }); } catch { /* best-effort */ }
209
+ correctionsApplied = null;
210
+ note(`[corrections] the applied table could not be built (${String(e?.message ?? e).slice(0, 100)}) — the recheck reads both files, as before`);
211
+ runLog(run.runDir, { event: "corrections-applied-failed", error: String(e?.message ?? e).slice(0, 160) });
212
+ }
213
+ }
214
+ // T3b — NO RECHECK AFTER A ROLLBACK. The document is byte-identical to the one the reviewer just
215
+ // read, so a recheck spends a dispatch to re-derive the verdict it already gave. The entry verdict
216
+ // stands, which is also the fail-safe direction this block uses everywhere else.
217
+ if (!correctiveRollback && !correctiveCycleSettled && (verdict === "CONDITIONAL" || verdict === "BLOCKING")) {
218
+ // A1: re-check after the corrective pass with a lean follow-up on the refutation's winning key and model —
219
+ // NOT a full re-run of the stage, and NOT the base model when another model won. The follow-up's first
220
+ // attempt starts fresh, and it never resumes the refutation's session (no engine resumes by key). (With no
221
+ // winning key, as on a crash-resume skip, a clean forced re-run on the same model.)
222
+ // A1: the recheck also runs on the CONDITIONAL path (the VENZY shipping path — previously the
223
+ // corrective output was never re-verified there) and reads the updated FINDINGS too, since the client
224
+ // surfaces render from findings.json, not the narrative. Failure falls back to the ENTRY verdict
225
+ // (CONDITIONAL stays CONDITIONAL; BLOCKING stays BLOCKING — the established fail-safe direction).
226
+ const entryVerdict = verdict;
227
+ // — the observed table rides as DATA. It never replaces the reviewer's judgement and it never
228
+ // asserts a correction was RIGHT; it says what moved, so the reviewer argues with evidence instead
229
+ // of with its own memory of two long documents.
230
+ const appliedTable = correctionsApplied ? correctionsAppliedTable(correctionsApplied) : "";
231
+ const restoredTable = restoredFindingsTable(correctiveRepair);
232
+ // — CARRIED, not merely recorded. The first cut of this feature wrote the violations to an
233
+ // artifact and said in its own comment that they were carried to the recheck; nothing read the
234
+ // file, the seat holds no tool that could, and the note beside the write is stderr. An escalation
235
+ // that reaches no reader is a log line.
236
+ const evidenceTable = evidenceClaimTable(evidenceViolations);
237
+ // T1 (J3): EVERY path that rewrites the review must re-demand the PLAN-EXECUTION CHECK
238
+ // section — the validator requires it whenever the receipt exists, and the copper-spire recheck
239
+ // rewrite dropped it (the reviewer complied with the lean followup, then failed the validator).
240
+ const planAuditCarry = (ctx.registerPlan && existsSync(P.planExecution))
241
+ ? `Your rewritten review MUST again contain the section titled exactly "PLAN-EXECUTION CHECK" — carry your prior section forward, updated for the corrected narrative/findings (the deterministic validator requires it whenever the plan-execution receipt exists).`
242
+ : "";
243
+ const recheckSeq0 = nextRefutationSeq(run.runDir);
244
+ const reviewShaBefore = shaOf(P.seniorEyeReview);
245
+ let reviewBefore = null;
246
+ try { reviewBefore = readFileSync(P.seniorEyeReview, "utf8"); } catch { reviewBefore = null; }
247
+ const rc = firstRef.key
248
+ ? await stage("narrative-refutation", ctx, {
249
+ force: true, sessionKey: firstRef.key, model: firstRef.model, thinking: firstRef.thinking, trigger: "verdict-recheck",
250
+ // The record its flags and the table above number, which is the writer's own while a fold is in force: a
251
+ // correction that saved nothing leaves the earlier pass's fold standing (record-fold.mjs).
252
+ followup: repairFollowup("narrative-refutation:verdict-recheck", {
253
+ narrative: P.narrative, findings: modelRecordPath(run.runDir, P.findings), seniorEyeReview: P.seniorEyeReview,
254
+ correctionsScope, appliedTable, restoredTable, evidenceTable, planAuditCarry,
255
+ writerExclusions: writerExclusionBlock(P, { review: "later", named: correctionsScope?.positions ?? [] }),
256
+ reviewAddresses: writeReviewAddresses(run.runDir, { records: [...recheckRecords, lastAcceptedCall(run.runDir)?.findings],
257
+ narratives: [lastAcceptedCall(run.runDir)?.narrative], seq0: recheckSeq0 }),
258
+ }),
259
+ })
260
+ : await stage("narrative-refutation", ctx, { force: true, model: firstRef.model, thinking: firstRef.thinking, trigger: "verdict-recheck", ...(planAuditExtra(ctx) ? { extra: planAuditExtra(ctx) } : {}) });
261
+ // A RECHECK COUNTS ONLY WHEN THIS DISPATCH SAVED A REVIEW. A reviewer whose every save was refused writes
262
+ // nothing, and the stage still reads ok on the review that stands from before the correction, so its verdict and
263
+ // its points would pass as the review of the corrected record, and the receipt would stop a resume from finishing
264
+ // a verification nobody made. Such a recheck is a failed one: the entry verdict stands, the record says the
265
+ // correction was not verified, no receipt is written, and the earlier review stays in place as the earlier review.
266
+ //
267
+ // TWO WAYS TO SAVE, BOTH COUNTED, UNDER ONE SET OF RULES. The message above orders the review file rewritten, and a
268
+ // seat may do that or record the review through its tool; both are seen on test runs. So a save is an accepted tool
269
+ // call made since this dispatch began, or review bytes that differ from the ones before it and that the tool's rules
270
+ // would accept (settleRecheckSave). A refused rewrite gives way to the accepted call or to the earlier review, and
271
+ // reads as no save. A byte-identical rewrite reads as no save, which costs only a cycle run again on a resume: the
272
+ // same bytes carry the same verdict.
273
+ const recheckSave = settleRecheckSave(run.runDir, { before: reviewBefore, stageOk: rc.ok === true, seq0: recheckSeq0 });
274
+ if (recheckSave.restore != null) {
275
+ try { atomicWrite(P.seniorEyeReview, recheckSave.restore); }
276
+ catch (e) { note(`[corrections] the review could not be put back after the recheck (${String(e?.message ?? e).slice(0, 100)})`); }
277
+ }
278
+ if (recheckSave.refused) runLog(run.runDir, { event: "verdict-recheck-file-save-refused", refused: recheckSave.refused, seq0: recheckSeq0, entryVerdict });
279
+ const recheckRead = recheckSave.read;
280
+ if (rc.ok && !recheckRead) {
281
+ runLog(run.runDir, { event: "verdict-recheck-unread", fail: recheckSave.fail, seq0: recheckSeq0, entryVerdict });
282
+ note(`[corrections] the recheck after the correction recorded no review it could accept (${recheckSave.fail}) — the correction is not verified, the entry verdict (${entryVerdict}) stands, and the review in place is the one from before the correction`);
283
+ }
284
+ // What stands is what was decided, so a put-back that could not be written never reads a refused verdict back.
285
+ verdict = recheckRead ? (parseVerdict(recheckSave.restore ?? readFileSync(P.seniorEyeReview, "utf8")) ?? entryVerdict) : entryVerdict;
286
+ correctiveRecheckOk = rc.ok === true && Boolean(recheckRead);
287
+ try {
288
+ atomicWrite(driverDir(run.runDir, CORRECTIVE_RECHECK_FILE), JSON.stringify({ ts: new Date().toISOString(),
289
+ status: correctiveRecheckOk ? "read" : "unread", by: recheckRead?.by ?? null, entryVerdict, verdict, seq0: recheckSeq0, seq: recheckRead?.seq ?? null,
290
+ reviewSha: reviewShaBefore, // the review this recheck found: earlierReviewNotRechecked tells it from any saved later
291
+ ...(correctiveRecheckOk ? {} : { fail: rc.ok ? recheckSave.fail : String(rc.fail ?? "failed").slice(0, 160) }) }, null, 2) + "\n");
292
+ } catch (e) { note(`[corrections] the recheck's record could not be written (${String(e?.message ?? e).slice(0, 100)}) — the run log still holds the outcome`); }
293
+ runLog(run.runDir, { event: "verdict-2", verdict, read: correctiveRecheckOk });
294
+ writeRunStatus(ctx, signoffPatch(verdict));
295
+ }
296
+ // AD-2 A1 — the completion receipt, written ONLY when the cycle finished with a verified recheck:
297
+ // a fallen-back recheck kept the entry verdict WITHOUT re-verifying, and cementing that would stop
298
+ // a resume from finishing the verification it still owes (so that path re-fires, exactly as today).
299
+ // Best-effort: a failed write just means the cycle may re-fire on a resume — never worse than today.
300
+ if (!correctiveCycleSettled && correctiveRecheckOk
301
+ && (correctiveEntryVerdict === "CONDITIONAL" || correctiveEntryVerdict === "BLOCKING")) {
302
+ try {
303
+ writeFileSync(`${correctiveCyclePath}.tmp`, JSON.stringify({
304
+ ts: new Date().toISOString(), entryVerdict: correctiveEntryVerdict, verdict, shas: correctiveCycleShas(),
305
+ }, null, 2) + "\n");
306
+ renameSync(`${correctiveCyclePath}.tmp`, correctiveCyclePath);
307
+ runLog(run.runDir, { event: "corrective-cycle-receipt", entryVerdict: correctiveEntryVerdict, verdict });
308
+ } catch (e) { note(`corrective-cycle receipt write failed (non-fatal — the cycle may re-fire on a resume): ${String(e?.message || e).slice(0, 100)}`); }
309
+ }
310
+ return { verdict, correctiveEntryVerdict, correctiveCycleSettled, correctiveRecheckOk };
311
+ }