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,1287 @@
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/delivery.mjs — the checks before delivery, the repairs they send back, and the publish that ends the run.
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 { atomicWrite, paths } from "../run-record.mjs";
9
+ import { runRecordLogPath } from "../../providers/_shared/ledger-path.mjs";
10
+ import { driverDir } from "../../shared/driver-dir.mjs";
11
+ import { readAnchors } from "../anchor-reader.mjs";
12
+ import { findCoverageLimitedCells, findSimilarListingSignals } from "../common-law-receipts.mjs";
13
+ import { coverageFormStamp, readCoverageForm } from "../coverage-form-io.mjs";
14
+ import { coverageAbsenceGaps, formLedgerRows } from "../coverage-form.mjs";
15
+ import { deriveCoverageStatus } from "../coverage-ledger.mjs";
16
+ import { findEngagementReceipts } from "../engagement-receipt.mjs";
17
+ import { bandBorderlineDeclarations, parseFindingsJson, parseFindingsJsonLenient } from "../findings-model.mjs";
18
+ import { frameResidualGaps } from "../frame-diff-model.mjs";
19
+ import { documentGrowth } from "../gate-metrics.mjs";
20
+ import { toolWrittenArtifact } from "../gateway.mjs";
21
+ import { readGoodsEvidence, readGoodsEvidenceAsWritten } from "../goods-evidence.mjs";
22
+ import { fileMeta, note, runLog } from "../log.mjs";
23
+ import { nextRefutationSeq, readAcceptedReviewSince } from "../narrative-refutation-record.mjs";
24
+ import { clearPartNotCompleted, readPartNotCompleted } from "../parts-not-completed.mjs";
25
+ import { rankedRecords, rankingFromJson, rankingNow, recordsReRanked } from "../placement-decisions.mjs";
26
+ import { parsePlacementsJson } from "../placement-model.mjs";
27
+ import { OVERVIEW_CITATION_ID, flagLines, goodsRepairLine, runLint } from "../predelivery-lint.mjs";
28
+ import { signoffPatch, writeRunStatus } from "../progress.mjs";
29
+ import { emailConditionsOfReport } from "../publish/email-conditions.mjs";
30
+ import { findDeadlineUrgencyMiss, findOrphanVerificationFlags, findProbativeGradingViolations, findRecallFloorViolations, findReviewFreshnessViolation, findSeedNeutralityViolations, findStatusHonestyViolation, findUncrossCheckedDemotions, findUnresolvedDisagreements } from "../reasoning-tripwires.mjs";
31
+ import { findingUris } from "../record-carry.mjs";
32
+ import { FOLD_FILE, citingModelOrdinal, keptModelOrdinal, modelRecordPath, readFold } from "../record-fold.mjs";
33
+ import { applyRegistryCorrections, assembleRunRecords, normalizeRecordUri } from "../registry-fidelity.mjs";
34
+ import { repairFollowup } from "../repair-composers.mjs";
35
+ import { abbrev } from "../repair-contract.mjs";
36
+ import { snapshotRepairBase, writePostRepairRecord } from "../repair-scope.mjs";
37
+ import { locateReportFaults, overviewCitationFault, reportPartsOf, writersCitationFaults } from "../repair-targets.mjs";
38
+ import { findRuleShapeFlags } from "../rule-shape.mjs";
39
+ import { projectStageInput, restamp, settleOneShotStamp, shaOf, staleOnPath } from "../stage-freshness.mjs";
40
+ import { dependencyOrder, lines, stageInputs, stageOutputs } from "../stages.mjs";
41
+ import { clauseForDefect } from "../terminal-clamp.mjs";
42
+ import { VERDICT_RANK, findReviewerCoherenceFlags, lateReviewAgainst, parseVerdict } from "../verify.mjs";
43
+ import { existsSync, mkdirSync, readFileSync, renameSync, writeFileSync } from "node:fs";
44
+ import { basename, join } from "node:path";
45
+
46
+ export async function runDelivery({ P, applyCoverageFloor, applyRatedUnderFrontMatter, applyScopeFrontMatter, applyVerdictFrontMatter, assembledOrdinals, byRight, cardOrdinals, checkLateBind, clampOnTheFloorDuty, clampOnTheWritersDuty, ctx, deliverAndClamp, findingsForCards, followTheRecordsActions, groupedMembers, job, opts, overviewOpen, publishAndDeliver, rebuildTheDeliveredRecord, restoreTheBrokenRecord, reviewOpen, rov, run, runState, saveTheLabel, saveTheOwedLabel, synthesisKey, synthesisModel, synthesisThinking, writeScopeFacts, writeUps, writeVerdictSidecar }, helpers) {
47
+ const { CITED_URI_RE, NO_CHANGE, REBUILDS_THE_DELIVERED_RECORD, StageFailure, UPSTREAM_STALE_REPAIR, assembleReportMd, cardsNeverBuilt, caseLawJoin, computeOpenFloors, defaultRecordFetcher, fullProseOrdinals, inScopeClassList, injectFrontMatter, keepRankingReadByWriter, lateRecordIds, loadCoverageLedger, owedCardOrdinals, ownerScreenForDelivery, partitionDeliveryStale, postRepairScope, queuedForTheRecordOnly, rankingReadByWriterPath, readFindingsForReport, readFloorAxes, readGoodsHanded, reassembleFromTheRecord, recordChangeOwesReview, recordGoodsHanded, relabelCoverageRows, retainStateBeforeReview, runPostRepairCorrection, runPostRepairReview, runWholeReviewForRecord, safeReadJson, settleDerivedBases, stage, stageCharter, stagesStaleOnPlacement, unreadRecordFindingOnly, unreadRecordReview, whatTheRepairLeftStale } = helpers;
48
+ // ── Spec A1 + A2: pre-delivery verification — pure code, before ANYTHING outward-facing. Per the
49
+ // user-amended design it NEVER withholds: every check lands in the receipt artifact; failing checks on a
50
+ // drafting surface get ONE warm named-correction redo (the model re-types, this code re-judges); whatever
51
+ // still fails ships as a visible plain-language flag at the top of the email + report. (Deviation from
52
+ // the spec's "blocks delivery", approved 2026-06-10: delivering nothing is worse than delivering good
53
+ // work with one clearly-labelled defect — and code-produced defects would deadlock a block.)
54
+ {
55
+ const lintPrefix = `clearance-${run.slug}-${run.codename}-`;
56
+ // V4-1: the gates evaluate the artifact set assembled for THIS delivery — run-dir _records/
57
+ // (inherited or prior-session) ∪ this-session ledger rows — never the session-prefixed ledger
58
+ // alone (empty on a fork ⇒ the vacuous registry pass that shipped a false citation).
59
+ let assembled = assembleRunRecords(run.runDir, lintPrefix);
60
+ runLog(run.runDir, { event: "record-artifacts", count: assembled.records.size,
61
+ fromRunDir: assembled.fromRunDir, fromLedgerThisSession: assembled.fromLedger,
62
+ ...(assembled.ledgerError ? { ledgerError: assembled.ledgerError } : {}),
63
+ ...(assembled.callLedgerError ? { callLedgerError: assembled.callLedgerError } : {}),
64
+ ...(assembled.fetchedWithoutRecord ? { fetchedWithoutRecord: assembled.fetchedWithoutRecord,
65
+ unrecordedFetches: assembled.unrecordedFetches.slice(0, 20) } : {}) });
66
+ // — AN UNREADABLE LEDGER IS A FINDING, NOT A ZERO. The record ledger outgrew Node's maximum
67
+ // string length and every read returned empty from a file that was present, readable and correct;
68
+ // the run then assembled no records at all and nothing downstream said so — the fetch-receipt join
69
+ // had an empty set and raised no flag, so a run with no records read exactly like a clean one.
70
+ if (assembled.ledgerError)
71
+ note(`[records] the fetch ledger could NOT be read (${assembled.ledgerError}) — this run's record set is EMPTY for that reason, `
72
+ + `not because nothing was fetched; every verified-from-record claim will be unprovable and #563 will demote it`);
73
+ // — THE RECORD LOG IS THIS RUN'S NOW, so an empty one is the ORDINARY state of a run before
74
+ // its first fetch and can no longer be read as "something is wrong". These two lines are what stop
75
+ // that from making an evidence hole invisible.
76
+ if (assembled.callLedgerError)
77
+ note(`[records] the CALL ledger could not be read (${assembled.callLedgerError}) — so this run cannot be checked for `
78
+ + `fetches whose record body is missing; treat a clean record set as unverified, not as proven`);
79
+ if (assembled.fetchedWithoutRecord)
80
+ note(`[records] ${assembled.fetchedWithoutRecord} record fetch(es) succeeded this run and their bodies are NOT in the run's `
81
+ + `record set (${assembled.unrecordedFetches.slice(0, 5).join(", ")}${assembled.fetchedWithoutRecord > 5 ? ", …" : ""}) — `
82
+ + `the bodies were written somewhere this run does not read; every verified-from-record claim resting on them is unprovable`);
83
+
84
+ // V4-2 — registry-evidence closure: every /mark/ URI cited on a delivered surface owes its record
85
+ // to this run's set. ONE bounded driver-code fetch pass for the absentees (no agent turn, no
86
+ // command lane); a record that cannot be fetched ships as the failing registry-record-coverage
87
+ // flag with its mechanical cause. The plugin chokepoint writes the record log, so re-assembly
88
+ // materializes _records/<id>.json for the auditor.
89
+ const recordFetchFailures = new Map();
90
+ {
91
+ const surfacesText = [P.report].filter(existsSync)
92
+ .map((f) => readFileSync(f, "utf8")).join("\n");
93
+ const cited = new Set((surfacesText.match(CITED_URI_RE) ?? []).map((u) => u.toLowerCase()));
94
+ // AND THE FINDINGS' OWN REGISTRATIONS, because the report is not a complete list of them. A
95
+ // register that publishes no page per record prints no record address at all, so on those runs
96
+ // the set built from the report above is EMPTY, this pass never runs, and bindFindingsToRecords
97
+ // and joinEvidenceStatus have nothing to compare the cards against — every card then prints the
98
+ // owner, status and dates as the model wrote them, and the only place that says so is the audit
99
+ // workbook's "Record retrieved?" column. Measured over 45 days of test runs: six of nine runs on
100
+ // such a register held no record at all, their findings citing 7 to 90 registrations each, while
101
+ // every run on a register that does publish pages held 112 to 5,038. The findings name the
102
+ // registrations whatever the register does. findingUris is the one derivation of that (it reads
103
+ // owner.registrations[].uri and normalizes to the same lowercased /mark/ path this set keys on),
104
+ // so this is the same question asked of a second source, not a second answer to it.
105
+ for (const uri of findingUris(parseFindingsJsonLenient(
106
+ existsSync(P.findings) ? readFileSync(P.findings, "utf8") : "").findings ?? []).keys()) cited.add(uri);
107
+ const missing = [...cited].filter((u) => !assembled.records.has(u)).sort();
108
+ if (missing.length) {
109
+ note(`registry-record closure: ${missing.length} cited record(s) absent from the run's set — targeted fetch`);
110
+ const fetcher = opts.recordFetcher ?? defaultRecordFetcher;
111
+ for (const uri of missing) {
112
+ const r = await fetcher(uri, { agentId: "clearotron-driver", sessionKey: `${lintPrefix}record-closure`, recordLog: runRecordLogPath(run.runDir) });
113
+ if (!r.ok) recordFetchFailures.set(uri, r.cause);
114
+ }
115
+ assembled = assembleRunRecords(run.runDir, lintPrefix); // pick up the closure fetches
116
+ runLog(run.runDir, { event: "registry-record-closure", cited: cited.size, missing,
117
+ fetched: missing.length - recordFetchFailures.size,
118
+ failed: [...recordFetchFailures.entries()].map(([uri, cause]) => ({ uri, cause })) });
119
+ }
120
+ }
121
+
122
+ const searchedNames = [...new Set([job.markName, job.name,
123
+ ...(Array.isArray(job.marks) ? job.marks.map((m) => m?.name) : [])].filter(Boolean))];
124
+ const lintNow = () => {
125
+ const reportMd = existsSync(P.report) ? readFileSync(P.report, "utf8") : "";
126
+ const narrativeMd = existsSync(P.narrative) ? readFileSync(P.narrative, "utf8") : ""; // R.1: narrative plumbing
127
+ // One resolution per claim: audit.md is built just above this block, so it is on disk here.
128
+ const auditMd = existsSync(P.audit) ? readFileSync(P.audit, "utf8") : "";
129
+ // Re-assemble per lint: a repair redo may have re-emitted surfaces and the closure pass may have
130
+ // grown the set — every re-lint must see the CURRENT record set, not a block-entry snapshot.
131
+ assembled = assembleRunRecords(run.runDir, lintPrefix);
132
+ // doc-31 counts-from-the-finding-set: pass the model's findings so the lint can flag a prose registration
133
+ // count that undershoots what the finding set lists. Malformed findings.json is already a validators.findings
134
+ // fail upstream — a parse miss here just skips the count check (never a double-throw).
135
+ // ION/copper-foundry (2026-07-22): the RAW text is kept as well as the parsed doc, so the
136
+ // permission-prose check can read coverage[] notes — the parsed findings array never carries them.
137
+ // The read happens before the parse, so a malformed findings.json is still scanned for the claim.
138
+ // ACCEPTED FLOOR, stated plainly because the opposite is easy to assume: on the incident run itself
139
+ // this surface was CLEAN. The false claim lived in register-units/*.json, _driver/register-plan.json,
140
+ // the register coverage ledger and skeptic-flags.md — none of which runLint scans. Guarding the four
141
+ // delivered surfaces is the scope here; widening it to the internal register surfaces is its own change.
142
+ let lintFindings = null, lintSv = 1, lintMarkAssessment = null, lintActions = null, lintFindingsRaw = "", lintAskAnswers = null, lintFourAnswers = null;
143
+ try {
144
+ if (existsSync(P.findings)) {
145
+ lintFindingsRaw = readFileSync(P.findings, "utf8");
146
+ const doc = parseFindingsJson(lintFindingsRaw);
147
+ lintFindings = doc.findings; lintSv = doc.schemaVersion ?? 1; lintMarkAssessment = doc.markAssessment ?? null;
148
+ lintActions = doc.actions ?? null; // spec 64 — the typed register joins the coherence checks
149
+ lintAskAnswers = doc.askAnswers ?? null; // PR-9 — the intake-ask lint judges the JOIN on v5 runs
150
+ lintFourAnswers = doc.fourAnswers ?? null; // P5 — the four answers join the content-model presence checks
151
+ }
152
+ } catch {
153
+ // — the strict parse throwing used to leave lintFindings null, and EVERY findings-based
154
+ // content-model check then emitted nothing at all. So on exactly the runs where the contract
155
+ // was missed — the ones that exhaust the corrective ladder and proceed on the lenient doc —
156
+ // the lint was silent about it, and silence read as a clean surface. Fall back to the same
157
+ // lenient parse the delivery path itself used: the checks judge the record that ships.
158
+ try { if (lintFindingsRaw) {
159
+ const soft = parseFindingsJsonLenient(lintFindingsRaw);
160
+ lintFindings = soft.findings; lintSv = soft.schemaVersion ?? 1; lintMarkAssessment = soft.markAssessment ?? null;
161
+ lintActions = soft.actions ?? null; lintAskAnswers = soft.askAnswers ?? null; lintFourAnswers = soft.fourAnswers ?? null;
162
+ } } catch { /* validators.findings owns the unparseable case */ }
163
+ }
164
+ // The narrative's finding headings are in the model's numbering: once the record is folded, its
165
+ // write-ups join the record the model wrote (record-fold.mjs).
166
+ let lintNarrativeFindings = null;
167
+ const lintModelAt = modelRecordPath(run.runDir, P.findings);
168
+ if (lintModelAt !== P.findings) {
169
+ try { lintNarrativeFindings = parseFindingsJsonLenient(readFileSync(lintModelAt, "utf8")).findings; } catch { lintNarrativeFindings = null; }
170
+ }
171
+ // wp50/wi2 — the sidecar tier joins the lint so overall-level prose can't contradict it.
172
+ let lintVerdict = null;
173
+ try { lintVerdict = JSON.parse(readFileSync(paths(run.runDir).verdict, "utf8")); } catch { /* legacy */ }
174
+ // B2 — placements.json joins the lint ONLY so an empty mirror surfaces as a flag (the parser no
175
+ // longer throws on it). Absent (every archived run) or malformed (validators.placement owns that
176
+ // case) ⇒ null ⇒ no check is emitted.
177
+ let lintPlacements = null;
178
+ try { lintPlacements = parsePlacementsJson(readFileSync(P.placementModel, "utf8")).placements; } catch { /* absent or malformed — not this lint's business */ }
179
+ // — the retrieval→findings trace joins the lint so an unreasoned drop, and a drop that is
180
+ // really an incomplete upstream stage, are both stated on the delivery surface a human reads.
181
+ // Read back from the artifact the run already wrote (unlike the doubt mint, which re-derives):
182
+ // this is the lint reporting what the run recorded, and re-reading a 10 MB band at the lint
183
+ // seam to restate it would buy nothing. Absent (every archived run) ⇒ null ⇒ no check emitted.
184
+ const lintRecordCarry = safeReadJson(P.recordCarry);
185
+ // — the common-law and jx slice traces, which nothing downstream read. The SAME pair the
186
+ // reconciliation siblings use at the derive seam, so a third list cannot drift from those two.
187
+ const lintCommonLawCarries = [P.commonLawCarry, P.jxZhCarry].map((f) => safeReadJson(f)).filter(Boolean);
188
+ return runLint({
189
+ // `clientSummaryMd` is deliberately NOT passed (2026-08-01): the stage is retired and a live
190
+ // run writes no client-summary.md. Every client-summary-capable check in predelivery-lint.mjs
191
+ // is presence-gated and simply emits nothing here; they stay alive for replay-archive.mjs,
192
+ // which passes the archived summary.
193
+ reportMd, narrativeMd, auditMd, recordsByUri: assembled.records, searchedNames,
194
+ // What each record's goods rested on when the writer wrote, and the records whose whole text a delivery repair
195
+ // was already handed: a finding written on goods the register cut, whose whole body the run holds now. The
196
+ // evidence is the copy kept when the writer was dispatched cold, which no later band merge rewrites; a run that
197
+ // kept none, written before the copy existed, is read on the evidence as it stands.
198
+ goodsEvidence: readGoodsEvidenceAsWritten(run.runDir) ?? readGoodsEvidence(run.runDir), goodsHanded: readGoodsHanded(run.runDir),
199
+ // The overview as its writer wrote it, read for a citation of a finding the report does not carry; and the
200
+ // conditions the email carries, as the email composes them.
201
+ overviewMd: (() => { try { return readFileSync(P.reportOverview, "utf8"); } catch { return null; } })(), emailConditions: emailConditionsOfReport(reportMd, lintVerdict?.verdict),
202
+ fetchFailures: recordFetchFailures, findings: lintFindings, narrativeFindings: lintNarrativeFindings, findingsRaw: lintFindingsRaw, actionsRegister: lintActions, verdictDoc: lintVerdict,
203
+ // WP-56 B2 — fresh v4 runs expect the standing mark-assessment (structural banner flag when
204
+ // absent). The replay harness's runLint call never passes this, so archived runs never flip.
205
+ markAssessment: lintMarkAssessment, markAssessmentExpected: lintSv >= 4,
206
+ // P5 — fresh v5 runs expect the content model (legal/practical split, manageable categories,
207
+ // four answers). Structural banner flags when absent; the replay harness never passes this.
208
+ fourAnswers: lintFourAnswers, contentModelExpected: lintSv >= 5,
209
+ // — the DECLARED version, so the lint can say when a fresh run is behind the dictated
210
+ // contract and the v6 parser gates never engaged. Live runs only: the replay harness passes
211
+ // nothing here, so archived runs never grow the check.
212
+ findingsSchemaVersion: lintSv,
213
+ placements: lintPlacements, // B2 — flag-only: an empty structured mirror is stated, never a validator kill
214
+ recordCarry: lintRecordCarry, // — flag-only: an unreasoned drop, and an upstream-absent one, are named on the delivery surface
215
+ commonLawCarries: lintCommonLawCarries, // — a lane that flagged its own trace wrong reaches the delivery surface
216
+ actionsExpected: lintSv >= 4, // spec 64 — a fresh v4 run without the register ships a visible structural flag
217
+ seniorRights: ctx.seniorRights?.rows ?? (() => { try { return JSON.parse(readFileSync(paths(run.runDir).seniorRights, "utf8")).rows; } catch { return null; } })(), // WP-receipts W4
218
+ seniorRightsExpected: ctx.seniorRightsExpected === true, // D1 — expected-but-absent is a failing structural check, never a silent pass
219
+ manifest: lintSv >= 4 ? ctx.framework : null, // doc 50: v4 tier words judged in the frozen framework's vocabulary
220
+ intakeAsks: ctx.intakeAsks ?? (() => { try { return JSON.parse(readFileSync(paths(run.runDir).intakeAsks, "utf8")).asks; } catch { return []; } })(), // A6
221
+ askAnswers: lintAskAnswers, // PR-9 — present ⇒ the intake-ask check judges the deterministic join, not fuzzy containment
222
+ cardFolds: (() => { try { return JSON.parse(readFileSync(paths(run.runDir).cardFolds, "utf8")).folds; } catch { return null; } })(), // PR-9 — fold observability (flag-only)
223
+ extraPlatformNames: ctx.profile?.platforms ?? [], // WS-B: profile marketplaces are run vocabulary
224
+ // the SAME structure the masthead's coverage_line is stamped from
225
+ // (scope-facts.json, written by writeScopeFacts). Passing the sidecar rather than re-deriving
226
+ // is the point of the issue: the stamped line and the prose check now answer to one searched
227
+ // set, so they cannot state two different answers about what was searched. Absent sidecar ⇒
228
+ // null ⇒ the check emits nothing at all, rather than a pass it cannot justify.
229
+ searchedJurisdictions: (() => {
230
+ try { return JSON.parse(readFileSync(P.scopeFacts, "utf8")).searched_jurisdictions ?? null; }
231
+ catch { return null; }
232
+ })(),
233
+ // compose guarantees the NAME(S) cell via the searched-name fallback, and code (not the model)
234
+ // builds the per-name rating rows — so these reflect the DELIVERED state (regressions are caught
235
+ // by the publish unit tests; the receipt still names every check).
236
+ // 2026-08-01: this used to read `shape.headerName || …`, where shape came from
237
+ // clientSummaryShape(csMd) — a model-authored header on the retired client summary. With that
238
+ // surface gone the fallback IS the value, and it is the better one: the searched names are
239
+ // code-carried, so templateChecks now judges against what the run actually searched.
240
+ headerName: searchedNames.join(" / "),
241
+ ratedNames: searchedNames,
242
+ // P2-B — the owner×element screen's receipt arms the named-competitor checks. Absent (a
243
+ // matter with no incumbent lane, or an archived run) ⇒ neither check is emitted at all.
244
+ ownerScreen: ownerScreenForDelivery(ctx),
245
+ depth: ctx.depth, // — the narrative depth rules are a per-product row; absent ⇒ no check
246
+ // — the corpora the party-fact rule partitions. The GRID is material about parties; the
247
+ // fetched records' goods wording is a claim about a registration's scope and is read only from
248
+ // `recordsByUri` above. Absent (an archived run, or a register-only matter with no grid) ⇒ the
249
+ // check emits nothing at all rather than a passing row, because there is nothing to test against.
250
+ commonLawGrid: safeReadJson(P.commonLawGrid),
251
+ matterContext: (() => { try { return readFileSync(P.matterContext, "utf8"); } catch { return ""; } })(),
252
+ clientPartyName: ctx.profile?.name ?? null,
253
+ });
254
+ };
255
+ // — the LAST settle, after refutation and the corrective pass. The audit this replaced ran
256
+ // ONCE, before refutation, and its own numbers prove that was too early: re-derived on the four
257
+ // delivered findings.json files it measured, the verified-stamp counts came out 35→37, 28→31,
258
+ // 37→38, 41→40. Two stamps entered R1's deliverable AFTER the only pass that checked
259
+ // them. A derivation is cheap enough to run at every seam, so it runs at the last one too.
260
+ settleDerivedBases(ctx, "pre-delivery");
261
+ let lint = lintNow();
262
+ // spec 64 — CODE-FIRST repair for a verdict/actions/statement incoherence: the defect is a
263
+ // derivation/staleness bug (the sidecar disagrees with the final findings), so the fix is to
264
+ // RE-DERIVE (applyCoverageFloor + writeVerdictSidecar) and re-lint — never an LLM redo, and never
265
+ // an edit to the actions. One attempt; a residual failure ships as the structural banner flag.
266
+ if (lint.failures.some((f) => f.id === "verdict-actions-coherence" || f.id === "verdict-actions-stale" || f.id === "statement-tier" || f.id === "statement-unconditional" || f.id === "statement-stance" || f.id === "statement-conditional-form")) {
267
+ const beforeVerdict = runState.verdict;
268
+ followTheRecordsActions("in the delivery check's re-derive"); // a stale step goes, as a missing one arrives
269
+ applyCoverageFloor();
270
+ try { writeVerdictSidecar(); }
271
+ catch (e) { throw new StageFailure("verdict", `verdict sidecar re-derive failed (spec-64 coherence repair): ${String(e.message).slice(0, 120)}`); }
272
+ if (runState.verdict !== beforeVerdict) writeRunStatus(ctx, signoffPatch(runState.verdict));
273
+ runLog(run.runDir, { event: "verdict-rederive-repair", from: beforeVerdict, to: runState.verdict });
274
+ lint = lintNow();
275
+ }
276
+ const initialFailures = lint.failures;
277
+ const repaired = [];
278
+ // doc-27 Item 1b ("close the loop"): deterministic registry auto-correction. The registry-record-match
279
+ // guard holds the fetched record's true value, so for numeric identifiers code overwrites the stated
280
+ // value FROM the record (and logs it) rather than relying on the model to re-type it. Run it (a) BEFORE
281
+ // the redo, so the redo only sees residuals (status/arithmetic/reference) and (b) AFTER the redo, since a
282
+ // redo re-emits the WHOLE file and could reintroduce a wrong identifier — the record-true value is the
283
+ // LAST word. PR-4: STATUS TOKENS joined the corrected set (label/parenthetical positions, polarity
284
+ // contradiction only — applyRegistryCorrections); free status prose stays redo territory.
285
+ // `registryCorrections` is DEDUPED on push so a revert→
286
+ // re-correct cycle does not double-count the audit trail; the re-lint fires whenever the file changed.
287
+ const registryCorrections = [];
288
+ const autoCorrectRegistry = () => {
289
+ if (!lint.failures.some((f) => f.id === "registry-record-match")) return;
290
+ let changed = false, newly = 0;
291
+ for (const [file, surface] of [[P.report, "report"]]) {
292
+ if (!existsSync(file)) continue;
293
+ const before = readFileSync(file, "utf8");
294
+ const { text: after, corrections } = applyRegistryCorrections(before, assembled.records);
295
+ if (corrections.length && after !== before) {
296
+ writeFileSync(file, after);
297
+ // THE CORRECTION MUST NOT READ AS STALENESS. `report.md` is watched by the freshness
298
+ // gate on the delivery path, so rewriting it here moves a sha the
299
+ // freshness gate is watching, and the gate then blocks delivery with "the report was
300
+ // assembled from material that has since changed". That is a deadlock rather than a delay:
301
+ // on resume assembleReportMd re-runs unconditionally from the UNCORRECTED card files, this
302
+ // corrector re-applies the byte-identical fix, the failure signature is identical, and the
303
+ // second occurrence is repeat-signature TERMINAL. The client gets nothing, after a fully
304
+ // paid search, because we fixed a registration number for them.
305
+ //
306
+ // restamp() exists for exactly this class and says so — "a post-stage mutator rewrote
307
+ // absPath — account for it everywhere it is recorded, so the change does not read as
308
+ // staleness no recompute could settle". The front-matter injectors already use it the same
309
+ // way (injectFrontMatter). Scoped to THIS file only: a blanket restamp would blind the gate
310
+ // to genuinely stale material, which is the failure it exists to catch.
311
+ restamp(run.runDir, file, { project: projectStageInput });
312
+ changed = true;
313
+ for (const c of corrections) {
314
+ const key = `${surface}|${c.field}|${c.uri}|${c.from}|${c.to}`;
315
+ if (!registryCorrections.some((e) => `${e.surface}|${e.field}|${e.uri}|${e.from}|${e.to}` === key)) {
316
+ registryCorrections.push({ ...c, surface });
317
+ newly++;
318
+ }
319
+ }
320
+ }
321
+ }
322
+ if (changed) {
323
+ if (newly) runLog(run.runDir, { event: "registry-auto-correct", count: newly,
324
+ corrections: registryCorrections.slice(-newly).map((c) => `${c.surface}/${c.field}: "${c.from}"→"${c.to}" (${c.uri})`) });
325
+ lint = lintNow(); // re-judge against the corrected surfaces (the file changed)
326
+ }
327
+ };
328
+ autoCorrectRegistry();
329
+ // RETIRED 2026-08-01 with the client-summary stage: the deterministic client-tier auto-correct
330
+ // ( A2 / F4), the recommendation-bound auto-bind ( T2 / H5) and the BOUNDARY
331
+ // LADDER above them — auto-correct → one forced cold re-emit with the verdict sidecar dictated
332
+ // → a hard deterministic StageFailure — are all DELETED. This is not a gate weakening: the
333
+ // ladder guarded a client-facing surface that no longer ships anywhere. What still guards the
334
+ // report the client actually reads is unchanged — the code-built verdict-bound row
335
+ // (composeEmailHtml opts.verdict, from _driver/verdict.json), the pre-delivery lint below, and
336
+ // the client gate. On the R2 evidence run this ladder was where the cost landed: three
337
+ // byte-identical failures before it exhausted.
338
+ // The writer's accepted record as it stood just before the delivery-check repair, kept only when that
339
+ // repair runs: the review after the repair is handed what changed between the two (repair-scope.mjs).
340
+ let repairBaseKept = false;
341
+ if (lint.failures.length) {
342
+ runLog(run.runDir, { event: "predelivery-lint-failed", failures: lint.failures.map((f) => f.id) });
343
+ const bySurface = (s) => lint.failures.filter((f) => f.surface === s || (s === "report" && f.surface === "all"));
344
+ // STRUCTURAL failures (a 404'd/un-fetchable cited record — registry-record-coverage marked `structural`
345
+ // by the lint) cannot be repaired by re-emitting a drafting surface, so they NEVER trigger a warm redo:
346
+ // they already ship as a visible flag (standing delivery philosophy), and a redo is doomed (the record
347
+ // does not exist). TONICA/ashen-keystone burned ~14 min re-emitting 35KB of report.md for a GB record that
348
+ // 404'd. modelFixable = the residue an LLM redo can actually fix; a structural-only surface skips the redo.
349
+ const modelFixable = (failures) => failures.filter((f) => !f.structural);
350
+ // CONVERSION 4 — THE LINT-REPAIR RUNG IS A REPAIR SURFACE, AND IT COMPOSES ITS OWN
351
+ // FOLLOWUP. gateway.mjs's warm patch and cold corrective both consult TOOL_WRITTEN_ARTIFACTS and
352
+ // turn a repair into a CALL; this ladder did not, so the first shell repair after the conversion
353
+ // would have handed a seat `editRepairTail`'s "TARGETED EDITS … using the Edit tool" for an
354
+ // artifact whose only writer is the driver — an order it cannot obey, because the conversion took
355
+ // `Write` and `Edit` out of its grant. Same class as the ten anchor sites and the max-tokens
356
+ // corrective before it: a retirement reaches the first-attempt surfaces and misses a correction
357
+ // surface. Keyed on the ARTIFACT rather than on the label, so conversions 5 and 6 inherit it.
358
+ const redo = async (label, failures, key, model, thinking, file, more = {}) => {
359
+ if (!failures.length || !key) return;
360
+ note(`pre-delivery lint: ${failures.length} failed check(s) on ${label} — one named-correction redo, sent as a follow-up`);
361
+ const toolWritten = file ? toolWrittenArtifact(file) : null;
362
+ const r = await stage(label, ctx, {
363
+ force: true, sessionKey: key, model, thinking, trigger: "lint-repair",
364
+ followup: repairFollowup("*:lint-repair", { label, file, toolWritten, failures, ...more })
365
+ + stageCharter(label, ctx.depth, ctx.framework),
366
+ });
367
+ if (r.ok) repaired.push(label);
368
+ };
369
+ // A citation of a withdrawn or absent finding in the overview's own prose is the overview's to remove, in the
370
+ // words its repair is given (repair-targets.mjs), so its check's failure is not placed a second time below.
371
+ const reportFixable = modelFixable(bySurface("report")).filter((f) => f.id !== OVERVIEW_CITATION_ID);
372
+ const reportParts = reportPartsOf(P, findingsForCards, writeUps);
373
+ const overviewCites = overviewCitationFault(lint.failures);
374
+ const reportStructuralOnly = bySurface("report").filter((f) => f.structural);
375
+ if (reportStructuralOnly.length && !reportFixable.length && !overviewCites) {
376
+ runLog(run.runDir, { event: "lint-redo-skipped-structural", surface: "report", failures: reportStructuralOnly.map((f) => f.id) });
377
+ note(`pre-delivery lint: report failure(s) are structural (un-fetchable record) — shipping as flags, no doomed redo`);
378
+ }
379
+ // B1 — report.md is ASSEMBLED, not one session: a failure keyed to a finding ordinal (e.g. a
380
+ // finding-provenance bleed) re-renders THAT card alone, FRESH (isolated from its own record, so the bleed
381
+ // cannot recur); a shell failure (no ordinal) re-runs report-overview. Then re-assemble. Bounded: one pass.
382
+ let reassembled = false;
383
+ // Each fault goes to the part that holds it (repair-targets.mjs): a card's to that card, with the detail its
384
+ // check gives on that card alone; the overview's to the overview; and a fault only the lines composed from the
385
+ // record hold to the writer's repair below, since the record is the writer's, and so does one a register of the
386
+ // record holds. One no single part holds keeps the overview's repair.
387
+ const targets = locateReportFaults(reportFixable, reportParts);
388
+ const shellFixable = [...targets.overview, ...(overviewCites ? [overviewCites] : [])];
389
+ if (reportFixable.length || overviewCites) runLog(run.runDir, { event: "report-repair-targets", cards: [...targets.cards.keys()],
390
+ overview: shellFixable.map((f) => f.id), stamped: targets.stamped.map((f) => f.id), record: targets.record.map((f) => f.id),
391
+ unlocated: targets.unlocated.map((f) => f.id) });
392
+ const badOrdinals = [...targets.cards.keys()];
393
+ for (const ord of badOrdinals) {
394
+ const f = findingsForCards.find((x) => x.ordinal === ord);
395
+ if (!f) continue;
396
+ // The card is re-rendered FRESH, and for a provenance bleed that IS the repair — isolation from the
397
+ // record it was contaminated by. For a PROSE defect (permission-prose) it is not: nothing about the
398
+ // finding changed, so a silent regeneration is free to write the same sentence again. Hand the card
399
+ // its own failing details, the way the retired client-summary re-emit handed over the verdict authority.
400
+ // Write mode: this stays a FULL WRITE, and not by omission. `extra` rides the card stage's OWN
401
+ // message (which carries its write mandate) on a cold session with no prior card in context, and
402
+ // isolation from the contaminated rendering is the entire point — patching the bad card would
403
+ // preserve exactly what the re-render exists to discard. The redo() ladder below is the opposite
404
+ // case (a follow-up to the stage that owns its file) and patches.
405
+ const why = targets.cards.get(ord).map((x) => x.detail).filter(Boolean);
406
+ const rc = await stage("report-card", { ...ctx, axis: String(ord), finding: f }, {
407
+ force: true, trigger: "lint-repair",
408
+ ...(why.length ? { extra: lines(
409
+ `The deterministic pre-delivery lint failed these checks on the previous rendering of THIS card:`,
410
+ ...why.map((d) => `- ${d}`),
411
+ `Fix ONLY what the checks name; change nothing else about the card.`,
412
+ ) } : {}),
413
+ });
414
+ if (rc.ok) { repaired.push(`report-card:${ord}`); reassembled = true; }
415
+ }
416
+ if (shellFixable.length && rov) { await redo("report-overview", shellFixable, rov.sessionKey, rov.model, rov.thinking, P.reportOverview); if (repaired.includes("report-overview")) reassembled = true; }
417
+ // — THE NARRATIVE REDO ROUTE. The same mechanism report-overview already has, re-aimed at
418
+ // the seat that wrote narrative.md. Without it a depth check could only FLAG, and a flag on a
419
+ // narrative that broke the rules is the run shipping the defect with a note attached. ONE followup
420
+ // pass, named violations; a second overrun ships and the lint row is the record.
421
+ //
422
+ // A FAULT IN A LINE COMPOSED FROM THE RECORD (a finding's own sentence, a short entry, a grouped line) is the
423
+ // writer's too: no card or overview repair can change what the renderer stamps from the record. It joins the
424
+ // narrative's faults in the writer's one repair, each named by the finding that owns it, in the numbering the
425
+ // writer's save takes. Its consumers then rebuild, and its change is reviewed, as for any repair of the record.
426
+ // A fault a register of the record holds (the four answers citing a finding the review withdrew) joins it, one
427
+ // line per withdrawn finding it cites, in that numbering.
428
+ const fold = readFold(run.runDir);
429
+ const sentenceFixable = targets.stamped.flatMap((f) => (f.parts ?? []).map((x) => ({ ...f, finding: keptModelOrdinal(fold, x.ordinal), detail: x.detail })));
430
+ const recordFixable = targets.record.flatMap((f) => writersCitationFaults(f, (o) => keptModelOrdinal(fold, o)));
431
+ // A finding named for goods the register cut, whose whole text the run holds now, is named in the writer's
432
+ // numbering, in the line's own words: it opens with the finding it names, so the list puts no "finding N:" before it.
433
+ // Under a fold the report displays the text of the member the fold kept, and the citation of the record can come
434
+ // from another member: the line then names both, so the repair reaches the text the report displays (design,
435
+ // 2026-11-04). Where the fold cannot be read, or no member is read citing the record, the line is not handed: a
436
+ // member is never guessed, and the run records each finding left unhanded.
437
+ const foldUnreadable = fold == null && existsSync(driverDir(run.runDir, FOLD_FILE));
438
+ let writersFindings = null; // the writer's record, read once and only for a goods line
439
+ const writersRecord = () => {
440
+ if (writersFindings) return writersFindings;
441
+ try { writersFindings = parseFindingsJsonLenient(readFileSync(modelRecordPath(run.runDir, P.findings), "utf8")).findings ?? []; }
442
+ catch { writersFindings = []; }
443
+ return writersFindings;
444
+ };
445
+ const citesRecord = (wf, uri) => (Array.isArray(wf?.owner?.registrations) ? wf.owner.registrations : [])
446
+ .some((reg) => normalizeRecordUri(reg?.uri ?? reg) === uri);
447
+ const goodsUnhanded = [];
448
+ const inWritersNumbering = (f) => {
449
+ if (!String(f.id).startsWith("goods-held-whole:")) return f;
450
+ const shown = foldUnreadable ? null : keptModelOrdinal(fold, f.ordinal);
451
+ const citing = shown == null ? null : citingModelOrdinal(fold, f.ordinal, f.uri, writersRecord(), citesRecord);
452
+ const detail = goodsRepairLine({ shown, citing, uri: f.uri, goods: f.goods, state: f.state });
453
+ if (detail == null) { goodsUnhanded.push({ id: f.id, why: shown == null ? "fold-not-read" : "no-member-read-citing" }); return null; }
454
+ return { ...f, detail };
455
+ };
456
+ const narrativeFixable = [...modelFixable(bySurface("narrative")).map(inWritersNumbering).filter(Boolean), ...sentenceFixable, ...recordFixable];
457
+ if (goodsUnhanded.length) runLog(run.runDir, { event: "goods-held-whole-not-handed", unhanded: goodsUnhanded });
458
+ if (narrativeFixable.length && synthesisKey) repairBaseKept = snapshotRepairBase(run.runDir);
459
+ // A writer fault with no writer session to repair it is not repaired, and the run says so.
460
+ if (narrativeFixable.length && !synthesisKey)
461
+ runLog(run.runDir, { event: "lint-redo-skipped", surface: "writer", why: "no-writer-session", failures: narrativeFixable.map((f) => f.id) });
462
+ if (narrativeFixable.length) await redo("synthesis", narrativeFixable, synthesisKey, synthesisModel, synthesisThinking, P.narrative,
463
+ { findings: modelRecordPath(run.runDir, P.findings), narrative: P.narrative });
464
+ // The records whose whole goods text this repair was handed, kept so the check after it does not name them again.
465
+ const goodsHandedNow = narrativeFixable.filter((f) => String(f.id).startsWith("goods-held-whole:")).map((f) => f.uri);
466
+ if (goodsHandedNow.length && repaired.includes("synthesis")) {
467
+ try {
468
+ recordGoodsHanded(run.runDir, goodsHandedNow);
469
+ runLog(run.runDir, { event: "goods-held-whole-handed", records: [...new Set(goodsHandedNow)].sort() });
470
+ } catch (e) { note(`pre-delivery lint: the records handed their whole goods text were not recorded: ${e?.message ?? e}`); }
471
+ }
472
+ if (reassembled) assembleReportMd(P, findingsForCards, assembledOrdinals, { grouped: groupedMembers, byRight });
473
+ // The client-summary redo arm is retired with the stage (2026-08-01). Its `email`-surface
474
+ // failures have not gone unowned: the `:email` reference check now runs over the report-derived
475
+ // cover text (predelivery-lint.mjs runLint), and those failures ship as visible flags on the
476
+ // cover note itself — the A10 enumeration block — exactly like every other unrepaired check.
477
+ if (repaired.length) {
478
+ // a redo/reassembly rewrote report.md — re-apply every driver-owned front-matter field
479
+ applyVerdictFrontMatter();
480
+ writeScopeFacts(); // compute-don't-author: re-derive (a repair pass may follow a coverage change) …
481
+ applyScopeFrontMatter(); // … and re-stamp the driver-owned scope line over the re-emitted masthead
482
+ applyRatedUnderFrontMatter(); // … and the profile/framework/project disclosure (PR-11: one closure, was a paste)
483
+ // T2: the derived label/badge/bound recommendation too
484
+ lint = lintNow();
485
+ autoCorrectRegistry(); // doc-27 Item 1b: a re-emission may have reintroduced a wrong identifier — overwrite from the record again
486
+ }
487
+ }
488
+ // THE GOODS REFRESH'S OUTCOME, kept in the run record whatever this pass did (predelivery-lint.mjs,
489
+ // goodsHeldWholeChecks): the findings named for the repair, those still saying their goods are cut or unread after
490
+ // it, and the check's own count of the ones that no longer say so.
491
+ try {
492
+ const rows = (lint?.checks ?? []).filter((c) => /^goods-held-whole(?::|-unresolved:|$)/.test(String(c.id)));
493
+ if (rows.some((c) => c.id !== "goods-held-whole") || readGoodsHanded(run.runDir).size)
494
+ runLog(run.runDir, { event: "goods-held-whole",
495
+ named: rows.filter((c) => c.id.startsWith("goods-held-whole:")).map((c) => c.id.slice("goods-held-whole:".length)),
496
+ unresolved: rows.filter((c) => c.id.startsWith("goods-held-whole-unresolved:")).map((c) => c.id.slice("goods-held-whole-unresolved:".length)),
497
+ summary: rows.find((c) => c.id === "goods-held-whole")?.detail ?? null });
498
+ } catch { /* the run record's row is best-effort; the check's own rows are in the receipt below */ }
499
+ // The receipt artifact — ALWAYS written, pass or fail (spec A2's auditor evidence).
500
+ // V4-1: the receipt states the ARTIFACT SET evaluated — surfaces, record set + sources, and the
501
+ // stage labels this session inherited via skip — so an auditor can see the gates ran over
502
+ // inherited content (check counts alone cannot betray a vacuous pass).
503
+ // P2 clause 3 — the DELIVERY PRECONDITION, computed here so it lands IN the receipt below.
504
+ // A report may only ship when nothing it was built from has moved underneath it. Computed before the
505
+ // receipt write (not after) because `gate-metrics.mjs` reads this sink POST-publish for the
506
+ // lint-repair-tax metric: recording the verdict here means no consumer can read the failure list of
507
+ // a stale-blocked run and mistake it for a delivery-quality signal. The receipt itself stays
508
+ // ALWAYS-WRITTEN (spec A2 auditor evidence) — blocking a run must not cost us the evidence of why.
509
+ // The cards on the path are the ones the record owes as it stands, read again each time the path is judged: a
510
+ // synthesis save after the cards can add a finding that is owed one, or withdraw one whose card is owed no longer.
511
+ const deliveryPathStages = () => [...new Set([
512
+ ...(ctx.skippedStages ?? []), "register-digest", "synthesis", "narrative-refutation",
513
+ "report-overview", ...owedCardOrdinals(P, ctx.depth).map((o) => `report-card:${o}`),
514
+ ])];
515
+ const deliveryInputsFor = (label) => {
516
+ const bare = label.replace(/:.*$/, "");
517
+ const axis = label.includes(":") ? label.slice(label.indexOf(":") + 1) : null;
518
+ try { return stageInputs(bare, P, { axes: ctx.axes, axis, registerOnly: ctx.registerOnly }); } catch { return []; }
519
+ };
520
+ // A part not completed has no stage to be stale: the overview's shell is the driver's own, the review is not run
521
+ // again, and nothing re-runs either.
522
+ const deliveryPathNow = () => deliveryPathStages().filter((l) => !(overviewOpen && l === "report-overview")
523
+ && !(reviewOpen && l === "narrative-refutation"));
524
+ runState.staleOnTheDeliveryPath = () => [...staleOnPath(run.runDir, deliveryPathNow(), deliveryInputsFor, { project: projectStageInput }),
525
+ ...cardsNeverBuilt(P, ctx.depth, cardOrdinals)]; // a finding a later save added is owed its one card call
526
+ runState.staleStages = runState.staleOnTheDeliveryPath();
527
+ // A DELIVERY-CHECK REPAIR THAT CHANGED ONLY THE FINDINGS RECORD leaves the narrative's bytes, and so the
528
+ // reviewer, fresh — the reviewer does not declare findings.json. The change is still content no review has
529
+ // read, so the reviewer is queued for the review after a repair, marked as the record's change.
530
+ if (repairBaseKept && !runState.staleStages.some((s2) => s2.label === "narrative-refutation")) {
531
+ if (recordChangeOwesReview(run.runDir)) {
532
+ // At the FRONT, so the dependency order below puts it after the writer and ahead of the overview and the
533
+ // cards, which then rebuild from whatever its correction changes.
534
+ runState.staleStages.unshift({ label: "narrative-refutation", changed: [{ name: basename(P.findings), via: "repair-record" }] });
535
+ runLog(run.runDir, { event: "post-repair-review-queued", why: "the repair changed the findings record only" });
536
+ }
537
+ }
538
+ // A RESUME AFTER SUCH A CHANGE WENT UNREVIEWED: its record queues the reviewer again, so this pass reviews it.
539
+ if (unreadRecordReview(run.runDir) && !runState.staleStages.some((s2) => s2.label === "narrative-refutation")) {
540
+ runState.staleStages.unshift({ label: "narrative-refutation", changed: [{ name: basename(P.findings), via: "repair-record" }] });
541
+ runLog(run.runDir, { event: "post-repair-review-queued", why: "a change to the findings record went unreviewed" });
542
+ }
543
+ // ── AD-2 A1 (E2E-R2, ordering) — repair-owned staleness is re-done IN-PASS, never parked. The
544
+ // pre-delivery repair can move an input under the tail this pass already built (the observed
545
+ // case: the report-overview lint redo rewrote findings.json, staling every report card + the
546
+ // client summary), and the only remedy used to be the stale throw below — a full park/resume
547
+ // cycle that re-drove the whole pipeline to re-render a handful of cards (34% of the E2E-R2
548
+ // run). The stale GUARD stays — it was RIGHT to block — but a staleness confined to the stages
549
+ // THIS pass generates (report-overview / report-card:N) is re-done here, from
550
+ // the CURRENT inputs, exactly once; whatever is still stale after the re-do falls through to
551
+ // the guard unchanged. Any upstream label in the set (register-digest, synthesis, …) keeps the
552
+ // park path untouched: those recomputes need pipeline order.
553
+ const staleRepaired = [];
554
+ // ── item 15a — REPAIR IN DEPENDENCY ORDER, never suppress all repair because one label is upstream ──
555
+ //
556
+ // This used to run only when EVERY stale label was in the delivery tail: one upstream label and the
557
+ // whole pass parked, re-driving the entire pipeline to rebuild a handful of surfaces. The ruling is
558
+ // that mixed staleness is repaired in dependency order — upstream first, then what depends on it,
559
+ // then the independent tails. The thing that must never happen is repairing a TAIL while its
560
+ // UPSTREAM is still stale, and ordering prevents that; suppressing everything does not, it just
561
+ // moves the same work into a resume.
562
+ //
563
+ // The order is derived from the two declaration maps (stages.mjs dependencyOrder over stageOutputs ×
564
+ // stageInputs), never hand-written — which is why 15c had to land first: without knowing who WROTE
565
+ // the artifact that moved there is no order to repair in.
566
+ //
567
+ // Still ONE bounded pass, exactly as before: each label is re-done at most once, and whatever is
568
+ // still stale afterwards blocks at the guard below. Nothing here weakens that guard.
569
+ if (runState.staleStages.length) {
570
+ const ordered = dependencyOrder(runState.staleStages.map((s2) => s2.label), P, { axes: ctx.axes });
571
+ runState.staleStages = ordered.map((l) => runState.staleStages.find((s2) => s2.label === l)).filter(Boolean);
572
+ const upstreamCount = partitionDeliveryStale(runState.staleStages).upstream.length;
573
+ runLog(run.runDir, { event: "delivery-stale-repair", stages: runState.staleStages.map((s2) => s2.label), upstream: upstreamCount, order: ordered });
574
+ note(`delivery: ${runState.staleStages.length} stale stage(s)${upstreamCount ? ` (${upstreamCount} upstream)` : ""} — re-doing them in-pass in DEPENDENCY ORDER (${ordered.join(" → ")}); what went stale, never a pipeline restart`);
575
+ // The whole point is that the staled consumers rebuild from the MOVED input: re-read the
576
+ // findings as they now stand — the pre-repair snapshot this pass rendered from is the past.
577
+ let readNow = readFindingsForReport(P);
578
+ let findingsNow = readNow.findings;
579
+ let ordinalsNow = fullProseOrdinals(findingsNow);
580
+ if (readNow.rejected) note(`stale-repair: findings.json is present and REJECTED by the strict parser (${readNow.rejected}) — ${findingsNow.length} finding(s) still join by ordinal; this rejection is the run's defect, not a missing finding`);
581
+ let caseLawNow = new Map();
582
+ try {
583
+ if (existsSync(P.caseLaw)) caseLawNow = caseLawJoin(P, findingsNow);
584
+ } catch { /* no case-law layer */ }
585
+ let reassemble = false;
586
+ // THE LATE VERDICT, ONE RULE FOR BOTH REVIEWS THIS LOOP CAN RUN — the whole review and the review after
587
+ // a delivery-check repair. A late review may only harden the run's verdict, and a softer one is logged,
588
+ // never adopted. Returns what it found, so the review after a repair can keep the review whose verdict
589
+ // the run carries in senior-eye-review.md.
590
+ const adoptLateReview = (reviewNow, stageLabel) => {
591
+ const { hardened, softened: reviewSays } = lateReviewAgainst(runState.verdict, reviewNow);
592
+ // A late review harsher than the assessment is a ground of its own: a gap closed later never lifts it.
593
+ const says = parseVerdict(reviewNow);
594
+ if ((VERDICT_RANK[says] ?? -1) > (VERDICT_RANK[runState.assessed] ?? -1)) runState.assessed = says;
595
+ // A REVIEW THAT SOFTENED IS NOT ADOPTED, AND THE RUN SAYS SO. The ratchet below only
596
+ // tightens, so a re-review that comes back softer leaves the settled verdict in force while
597
+ // senior-eye-review.md, rewritten by this repair, opens with the softer word. That is the
598
+ // design; recording nothing was the defect: a reader of the run found two answers and no
599
+ // line saying which one governs (measured in testing, 2026-09-23: BLOCKING recorded, CONDITIONAL on disk).
600
+ if (reviewSays) {
601
+ runLog(run.runDir, { event: "verdict-softening-not-adopted", was: runState.verdict, reviewSays, stage: stageLabel });
602
+ note(`stale-repair: the reviewer now returns ${reviewSays}; the run keeps ${runState.verdict}, because a late re-review may only harden the verdict — senior-eye-review.md now disagrees with verdict.json, and verdict.json governs`);
603
+ }
604
+ if (hardened) {
605
+ // ── T3a — THE LATE VERDICT IS ADOPTED, NOT THROWN, AND ADOPTION IS THE WHOLE JOB ──
606
+ //
607
+ // built the throw here because a late hardening was an input the gate had been
608
+ // DENIED: the verdict settles thousands of lines earlier, nothing re-reads the review,
609
+ // so a reviewer refusing to sign DURING this repair "is written to disk and never
610
+ // heard". Measured on `bf21580e` — the narrative printed a registration date of
611
+ // 1 March 2011 against a record reading 25 February 2011, the reviewer said so, and
612
+ // the run delivered anyway.
613
+ //
614
+ // DELETING THE THROW WITHOUT A DESTINATION RE-OPENS EXACTLY THAT HOLE, and that is
615
+ // why this branch is not the same edit as the gate's. The owner's ruling removes the
616
+ // REFUSAL; it does not say the reviewer stops being heard. So the late verdict is
617
+ // adopted as the run's own and everything derived from it is rebuilt:
618
+ //
619
+ // · `verdict` and status.json — the run's own record
620
+ // · verdict.json — "the single label authority" (its words)
621
+ // · `reassemble` — assembleReportMd re-runs, so the open-points
622
+ // section is built from THIS review, and
623
+ // applyVerdictFrontMatter re-reads the sidecar
624
+ // and re-stamps overall_label / overall_badge
625
+ //
626
+ // Without the sidecar write the report would ship BADGED WITH THE VERDICT SETTLED
627
+ // BEFORE THE REVIEWER HARDENED — refused by the reviewer, labelled CONDITIONAL. That
628
+ // is worse than either behaviour this replaces, and it is `bf21580e`'s shape one
629
+ // layer up: the reviewer's word on disk and the client's document disagreeing.
630
+ //
631
+ // `verdictHardenedTo` still ratchets ONE WAY, so a review that SOFTENED during the
632
+ // repair still cannot lift a clamp. This branch only ever tightens.
633
+ runLog(run.runDir, { event: "verdict-hardened-by-repair", was: runState.verdict, now: hardened, stage: stageLabel, adopted: true });
634
+ note(`stale-repair: the reviewer returned ${hardened} — adopting it as the run's verdict (the one settled earlier was decided against a review this repair has since rewritten) and rebuilding the label from it`);
635
+ runState.verdict = hardened;
636
+ writeRunStatus(ctx, signoffPatch(runState.verdict));
637
+ try { writeVerdictSidecar(); }
638
+ catch (e) { throw new StageFailure("verdict", `verdict sidecar write failed (the single label authority): ${String(e.message).slice(0, 120)}`); }
639
+ reassemble = true;
640
+ }
641
+ return { hardened, softened: reviewSays };
642
+ };
643
+ const processedLabels = new Set(); // the labels this loop has re-done, for the re-queue after a correction
644
+ const requeuedLabels = new Set();
645
+ const repairFailed = new Map(); // label → why its re-run in this loop did not complete
646
+ // A CHANGED DECISION IS READ AGAIN IN THIS PASS. A repeated placement pass whose decisions moved leaves the reading
647
+ // step, the writer and the review stale, and each of them leaves what reads it stale in turn. They are queued here,
648
+ // in dependency order after the stage that moved them, each re-done at most once more; one already queued runs where
649
+ // it stands, and a stage stale before the repair for the same reasons is not the repair's. The reviewer gets the whole
650
+ // review and its one correction, and the writer is judged again against its duty and the recall gate. The pass
651
+ // then ends with all of them rebuilt from the decision that stands. The guard below used to park the run on them,
652
+ // and the resume re-ran them, until the owner's ruling of 2026-10-19 that a run is never held. A stage still stale
653
+ // after its re-run still falls to the guard: no approved sentence states that case yet.
654
+ const chain = new Set();
655
+ const staleNow = () => staleOnPath(run.runDir, deliveryPathStages(), deliveryInputsFor, { project: projectStageInput });
656
+ const queueWhatItLeftStale = (s2, before) => {
657
+ const at = runState.staleStages.indexOf(s2) + 1;
658
+ const left = whatTheRepairLeftStale({ before, after: staleNow(), repaired: s2.label,
659
+ ahead: new Set(runState.staleStages.slice(at).map((x) => x.label)), processed: processedLabels, requeued: requeuedLabels });
660
+ for (const l of left.chain) chain.add(l);
661
+ for (const l of left.requeue) requeuedLabels.add(l);
662
+ if (!left.queue.length) return;
663
+ const rest = [...runState.staleStages.slice(at), ...left.queue];
664
+ const order = [...new Set(dependencyOrder(rest.map((x) => x.label), P, { axes: ctx.axes }))]; // each label once
665
+ runState.staleStages.splice(at, runState.staleStages.length - at, ...order.map((l) => rest.find((x) => x.label === l)).filter(Boolean));
666
+ runLog(run.runDir, { event: "delivery-stale-requeued", after: s2.label, stages: left.queue.map((x) => x.label) });
667
+ };
668
+ // A STAGE STALE ON WHAT PLACEMENT WROTE IS THE CHAIN'S FROM THE START, whoever moved it: the decisions written
669
+ // again when the shape is derived again, or a late pass whose readers had already run, as much as this check's
670
+ // own repeat. Its re-run is followed, and a re-run that does not complete delivers.
671
+ const placementWrote = new Set([...stageOutputs("placement-inquiry", P, { axes: ctx.axes }).map((f) => basename(f)), basename(P.placementDecisions)]);
672
+ for (const l of stagesStaleOnPlacement(runState.staleStages, placementWrote)) chain.add(l);
673
+ for (const s2 of runState.staleStages) {
674
+ processedLabels.add(s2.label);
675
+ if (s2.label === "report-overview") {
676
+ const r = await stage("report-overview", { ...ctx, displayVerdict: runState.displayVerdict }, { force: true, trigger: "stale-repair" });
677
+ if (r.ok) { staleRepaired.push(s2.label); reassemble = true; }
678
+ else note(`stale-repair: report-overview re-emit failed (${r.fail}) — stays stale, the guard below decides`);
679
+ } else if (s2.label === "narrative-refutation"
680
+ && (chain.has(s2.label) || postRepairScope(run.runDir, P, s2, { staleRepaired, baseKept: repairBaseKept }).mode !== "whole"
681
+ || queuedForTheRecordOnly(s2) || unreadRecordReview(run.runDir))) {
682
+ // A REVIEWER A CHANGED DECISION QUEUED is given the whole review and its one correction here, as the pass that
683
+ // re-ran it on a resume gave it a review and a correction.
684
+ // THE REVIEW AFTER A DELIVERY-CHECK REPAIR (see runPostRepairReview). Reached where the scope is certain, and
685
+ // where a change to the record, or one an earlier review could not read, is reviewed whole: that review's
686
+ // flags go to the same one correction. Every other staleness of the reviewer takes the arm below, as before.
687
+ // A CHANGE NO REVIEW READ IS REVIEWED WHOLE, whatever this pass's own repair changed: the base this pass
688
+ // kept follows the earlier change, so a narrowed review would read only the later one, and saving the same
689
+ // values again would settle a stamp over a change nobody read.
690
+ const unreadOnEntry = unreadRecordReview(run.runDir);
691
+ const narrowedScope = postRepairScope(run.runDir, P, s2, { staleRepaired, baseKept: repairBaseKept });
692
+ const scope = unreadOnEntry && narrowedScope.mode !== "whole" ? { mode: "whole", why: "an earlier change went unreviewed" } : narrowedScope;
693
+ if (scope.mode === "none") {
694
+ // A FILE WRITTEN AGAIN WITH THE SAME VALUES IS NOT A CHANGE: no review runs, and the reviewer's stamp
695
+ // takes the rewrite as accounted for, so the delivery guard does not block on it.
696
+ settleOneShotStamp(run.runDir, "narrative-refutation", [P.narrative], "repair-changed-no-content");
697
+ runLog(run.runDir, { event: "post-repair-review-not-needed", why: scope.why });
698
+ note(`[post-repair] the repair saved the same values again — no review needed`);
699
+ staleRepaired.push(s2.label);
700
+ continue;
701
+ }
702
+ const rerun = () => UPSTREAM_STALE_REPAIR[s2.label](ctx, { displayVerdict: runState.displayVerdict });
703
+ // THE STATE THIS REVIEW READS IS KEPT WHOLE before it runs, so a correction that fails after it has a trusted
704
+ // state to come back to even where the record itself is lost meanwhile.
705
+ retainStateBeforeReview(run.runDir, P);
706
+ // A scope that cannot be narrowed is reviewed whole at once, and its record lists no change it could compare.
707
+ let review = scope.mode === "whole"
708
+ // A resume reviews the change its earlier record names, so that record says what the change was.
709
+ ? await runWholeReviewForRecord(ctx, P, run, { ...scope, changed: scope.changed ?? NO_CHANGE,
710
+ findingOnly: unreadRecordFindingOnly(run.runDir) ?? queuedForTheRecordOnly(s2) }, rerun)
711
+ : await runPostRepairReview(ctx, P, run, scope);
712
+ // A narrowed review that could not be read falls back to the whole review, whose points go to the same one
713
+ // correction below: neither the stamp of a findings-only change nor that of a stage that ends ok on the
714
+ // earlier review's file can show the change unread. When the whole review cannot be read either, its
715
+ // record keeps the change no review read; the record holds nothing (see `unreadRecordReview`).
716
+ if (!review.reviewed && scope.mode !== "whole") review = await runWholeReviewForRecord(ctx, P, run, scope, rerun);
717
+ if (!review.reviewed) continue;
718
+ staleRepaired.push(s2.label);
719
+ reassemble = true;
720
+ // senior-eye-review.md HOLDS THE REVIEW WHOSE VERDICT THE RUN CARRIES. A narrowed review that hardened
721
+ // the verdict stays in place, so the open questions print its grounds; otherwise the whole review goes
722
+ // back, and the narrowed one is kept under _driver/.
723
+ const { hardened } = adoptLateReview(review.reviewText, s2.label);
724
+ if (!hardened) review.putBack();
725
+ if (review.rec.flags.length) {
726
+ const pass = await runPostRepairCorrection(ctx, P, run, { rec: review.rec, items: review.items, points: review.points,
727
+ grounds: Boolean(hardened), whole: review.base?.whole === true, synthesisRef: { key: synthesisKey, model: synthesisModel, thinking: synthesisThinking } });
728
+ if (!pass.ok) runState.correctionRejectedAt = new Date().toISOString(); // a rejected correction gives no result back
729
+ // NOTHING REVIEWS THE CORRECTION: the reviewer's stamp takes what it changed as accounted for, and so
730
+ // does the first cycle's receipt, so a resume re-fires neither.
731
+ settleOneShotStamp(run.runDir, "narrative-refutation", [P.narrative], "post-repair-fix");
732
+ try {
733
+ const at = paths(run.runDir).correctiveCycle;
734
+ let receipt = null;
735
+ try { receipt = JSON.parse(readFileSync(at, "utf8")); } catch { receipt = null; }
736
+ atomicWrite(at, JSON.stringify({ ...(receipt ?? { entryVerdict: runState.verdict }), ts: new Date().toISOString(), verdict: runState.verdict,
737
+ shas: { review: shaOf(P.seniorEyeReview), narrative: shaOf(P.narrative) }, settledBy: "post-repair-cycle" }, null, 2) + "\n");
738
+ } catch (e) { note(`[post-repair] the cycle receipt could not be rewritten (${String(e?.message ?? e).slice(0, 100)}) — a resume may re-fire the first correction`); }
739
+ // ITS CONSUMERS REBUILD FROM WHAT IT WROTE: re-read the findings, and queue the overview and any card it
740
+ // left stale that this loop has not queued already.
741
+ readNow = readFindingsForReport(P);
742
+ findingsNow = readNow.findings;
743
+ ordinalsNow = fullProseOrdinals(findingsNow);
744
+ try {
745
+ if (existsSync(P.caseLaw)) caseLawNow = caseLawJoin(P, findingsNow);
746
+ } catch { /* no case-law layer */ }
747
+ // After a correction, and after a rollback that rebuilt the record from a save, what reads the record is
748
+ // rebuilt from it; a rollback that put the same bytes back leaves nothing stale, and queues nothing.
749
+ if (pass.ok || pass.rollback) {
750
+ // A label not queued yet is appended; one this loop already re-done is re-queued ONCE, so the
751
+ // pass stays bounded and still ends with every surface rebuilt from the corrected record.
752
+ const queued = new Set(runState.staleStages.map((x) => x.label));
753
+ // A finding the correction's save added is owed its one card call, as after any later save.
754
+ for (const x of [...staleOnPath(run.runDir, deliveryPathStages(), deliveryInputsFor, { project: projectStageInput }),
755
+ ...cardsNeverBuilt(P, ctx.depth, cardOrdinals)]) {
756
+ if (!(x.label === "report-overview" || x.label.startsWith("report-card:"))) continue;
757
+ if (!queued.has(x.label)) { runState.staleStages.push(x); queued.add(x.label); }
758
+ else if (processedLabels.has(x.label) && !requeuedLabels.has(x.label)) { requeuedLabels.add(x.label); runState.staleStages.push(x); }
759
+ }
760
+ }
761
+ // THE WRITER'S DUTY, JUDGED AGAIN ONCE THE CORRECTION HAS SETTLED, rollback included. The terminal guards judged
762
+ // it on the record before this correction. A correction that rolled back restores a record that the duty as it
763
+ // now stands may not be met by: a save restored as accepted work, or records owed since the save was made. The
764
+ // approved clause names what it leaves unaccounted, and a gap it closed withdraws its clause, as after the
765
+ // writer's re-run in this loop; the label is saved again before anything is published.
766
+ {
767
+ const was = runState.verdict, stood = JSON.stringify(runState.clampReasons);
768
+ const judged = clampOnTheWritersDuty({ again: true });
769
+ if (runState.restoredClear && runState.verdict === "CLEAR") applyCoverageFloor();
770
+ if (JSON.stringify(runState.clampReasons) !== stood || runState.verdict !== was) saveTheLabel("after the correction after a post-repair review");
771
+ runLog(run.runDir, { event: "writer-duty-after-correction", was, now: runState.verdict, rolledBack: Boolean(pass.rollback),
772
+ owed: judged.duty?.computable === true ? judged.duty.totals?.owed ?? null : null,
773
+ unaccounted: judged.duty?.computable === true ? judged.duty.unaccounted.length : null, recall: judged.recall });
774
+ }
775
+ }
776
+ continue;
777
+ } else if (UPSTREAM_STALE_REPAIR[s2.label]) {
778
+ // The upstream arm (item 15a). Each of these re-runs the SAME stage the pipeline would have
779
+ // run, forced, with a `stale-repair` trigger so the telemetry says why. Dependency order put
780
+ // it ahead of anything that reads what it writes, so the tail arms below rebuild from the
781
+ // repaired artifact rather than from the one that moved.
782
+ const reviewSeq0 = s2.label === "narrative-refutation" ? nextRefutationSeq(run.runDir) : null;
783
+ const staleBefore = s2.label === "placement-inquiry" || chain.has(s2.label) ? staleNow() : null; // what was stale before this one
784
+ if (s2.label === "placement-inquiry" && !runState.rankingBeforeRepeat) runState.rankingBeforeRepeat = rankingNow(P); // as the writer last read it
785
+ const r = await UPSTREAM_STALE_REPAIR[s2.label](ctx, { displayVerdict: runState.displayVerdict });
786
+ // NOT A PASS: a reviewer that ends with no accepted call reads ok whenever the earlier review's file
787
+ // stands, and its stamp is refreshed over the change it never read. The record says so, the run delivers,
788
+ // and a resume for any other cause reviews the change whole.
789
+ if (r?.ok && s2.label === "narrative-refutation" && !readAcceptedReviewSince(run.runDir, reviewSeq0)) {
790
+ writePostRepairRecord(run.runDir, { status: "unread", whole: true, findingOnly: queuedForTheRecordOnly(s2), by: "stale-repair", fail: "no-accepted-call" });
791
+ runLog(run.runDir, { event: "post-repair-review", read: false, whole: true, fail: "no-accepted-call" });
792
+ note(`stale-repair: the reviewer's re-run recorded no review — the change it was queued for is unreviewed; the run's record says so, and the run delivers`);
793
+ } else if (r?.ok) {
794
+ staleRepaired.push(s2.label);
795
+ reassemble = true;
796
+ // THE FLOOR, APPLIED AGAIN TO THE PLACEMENT THE REPORT IS NOW BUILT FROM. The delivery floor was judged on
797
+ // the placement account before this repair; the repeated pass has recorded its own floor duty, and the
798
+ // stages after it rebuild from it in this loop. The same rule is applied to that account, through the
799
+ // same clamp, so the delivered verdict, its floor and its record describe one pass. It only tightens.
800
+ if (s2.label === "placement-inquiry") {
801
+ const was = runState.verdict, stood = JSON.stringify(runState.clampReasons);
802
+ clampOnTheFloorDuty({ again: true });
803
+ clampOnTheWritersDuty({ again: true }); // the recall gate leaves out the floor that now stands
804
+ // A save that fails here is tried again, then owed, never the end of the run: see saveTheLabel.
805
+ if (JSON.stringify(runState.clampReasons) !== stood || runState.verdict !== was) saveTheLabel("after the repeated placement pass");
806
+ runLog(run.runDir, { event: "floor-duty-after-repair", was, now: runState.verdict });
807
+ }
808
+ // A whole review that is read reviews the change an earlier unread one left: its record says so, and
809
+ // its points stand under the late-review rule below, as any whole review's do. (The arm above has
810
+ // already set aside a stage that read ok without an accepted review.)
811
+ if (s2.label === "narrative-refutation" && unreadRecordReview(run.runDir))
812
+ writePostRepairRecord(run.runDir, { status: "read", whole: true, by: "stale-repair" });
813
+ // its consumers rebuild from what it JUST wrote — re-read, do not carry the pre-repair copy
814
+ readNow = readFindingsForReport(P);
815
+ findingsNow = readNow.findings;
816
+ ordinalsNow = fullProseOrdinals(findingsNow);
817
+ try {
818
+ if (existsSync(P.caseLaw)) caseLawNow = caseLawJoin(P, findingsNow);
819
+ } catch { /* no case-law layer */ }
820
+ for (const owed of cardsNeverBuilt(P, ctx.depth, cardOrdinals)) if (!runState.staleStages.some((x) => x.label === owed.label)) runState.staleStages.push(owed);
821
+ // — AND THE REVIEW IS ALSO SOMETHING THIS PASS JUST WROTE.
822
+ //
823
+ // The re-reads above are the artifacts a repaired stage's CONSUMERS need. narrative-refutation
824
+ // has no consumer here: what it authors is senior-eye-review.md, whose first line is the
825
+ // verdict that decides whether this run may deliver at all — and that verdict was settled
826
+ // thousands of lines earlier, at the gate. Nothing re-reads it, so a reviewer that refuses to
827
+ // sign DURING this repair is written to disk and never heard.
828
+ //
829
+ // Measured on `bf21580e` (round of 2026-08-23): verdict-2 CONDITIONAL at 00:22:11;
830
+ // `delivery-stale-repair` at 00:38:35 naming narrative-refutation; the review landing BLOCKING
831
+ // at 00:52:01; delivered. The narrative printed a registration date of 1 March 2011 against a
832
+ // fetched record reading 25 February 2011 — the reviewer said so, in the document nobody read.
833
+ //
834
+ // NOT a "stop on BLOCKING" check bolted beside the gate. The gate's own terminal is correct and
835
+ // stays where it is; this restores the input it was denied. `verdictHardenedTo` ratchets one
836
+ // way, so a review that softened during the repair cannot lift a clamp.
837
+ if (s2.label === "narrative-refutation") {
838
+ adoptLateReview(existsSync(P.seniorEyeReview) ? readFileSync(P.seniorEyeReview, "utf8") : "", s2.label);
839
+ }
840
+ // THE WRITER, JUDGED AGAIN WHEN A CHANGED DECISION RE-RAN IT. Its duty and the recall gate were judged on the
841
+ // writer before it; a gap this one opens is named through the same clamps, and one already named stays named.
842
+ // The label is saved again as the floor's is above, through saveTheLabel.
843
+ if (s2.label === "synthesis") keepRankingReadByWriter(P); // where each record stood as this writer read it
844
+ if (s2.label === "synthesis" && chain.has(s2.label)) {
845
+ const was = runState.verdict, stood = JSON.stringify(runState.clampReasons);
846
+ const judged = clampOnTheWritersDuty({ again: true });
847
+ // A CLEAR a closed gap gave back meets the floor again on what this writer now says: its forward actions
848
+ // are a ground of their own.
849
+ if (runState.restoredClear && runState.verdict === "CLEAR") applyCoverageFloor();
850
+ if (JSON.stringify(runState.clampReasons) !== stood || runState.verdict !== was) saveTheLabel("after the writer's re-run");
851
+ runLog(run.runDir, { event: "writer-duty-after-repair", was, now: runState.verdict,
852
+ owed: judged.duty?.computable === true ? judged.duty.totals?.owed ?? null : null,
853
+ unaccounted: judged.duty?.computable === true ? judged.duty.unaccounted.length : null, recall: judged.recall });
854
+ }
855
+ if (staleBefore) queueWhatItLeftStale(s2, staleBefore);
856
+ } else {
857
+ repairFailed.set(s2.label, String(r?.fail ?? "failed").slice(0, 200));
858
+ note(`stale-repair: ${s2.label} re-run failed (${r?.fail}) — stays stale, the guard below decides`);
859
+ }
860
+ } else if (s2.label.startsWith("report-card:")) {
861
+ const ord = Number(s2.label.slice("report-card:".length));
862
+ const f = findingsNow.find((x) => x.ordinal === ord);
863
+ if (!f || !ordinalsNow.includes(ord)) {
864
+ // — name the CAUSE, not the symptom. This line ran 26 times on R1 while all 26 findings
865
+ // sat in the file, because the strict parser's rejection had been converted into zero
866
+ // findings upstream. A card with no finding and a file that was refused are different
867
+ // problems with different fixes, and the run must not describe one as the other.
868
+ note(readNow.rejected
869
+ ? `stale-repair: ${s2.label} cannot be repaired because findings.json was REJECTED (${readNow.rejected}) — the finding may well be present; fix the rejection, not the card`
870
+ : `stale-repair: ${s2.label} has no full-prose finding in the current findings.json — stays stale, the guard below decides`);
871
+ continue;
872
+ }
873
+ const rc2 = await stage("report-card", { ...ctx, axis: String(ord), finding: f, caseLawProfile: caseLawNow.get(ord) ?? null }, { force: true, trigger: "stale-repair" });
874
+ if (rc2.ok) { staleRepaired.push(s2.label); reassemble = true; }
875
+ else note(`stale-repair: ${s2.label} re-render failed (${rc2.fail}) — stays stale, the guard below decides`);
876
+ }
877
+ }
878
+ if (reassemble) {
879
+ reassembleFromTheRecord(P, findingsNow, ctx.depth); // the plan the first assembly used, made from the record as it stands
880
+ applyVerdictFrontMatter(); // the reassembly rewrote report.md — re-apply every driver-owned
881
+ // field, exactly as the lint-repair branch above does
882
+ writeScopeFacts();
883
+ applyScopeFrontMatter();
884
+ applyRatedUnderFrontMatter();
885
+ // A repair that re-ran a stage the trace and the Audit Trail report has both written again, before the lint
886
+ // below reads the trace. A rebuild that fails withdraws the audit written before the repair, as a failed first
887
+ // build ships none.
888
+ if (rebuildTheDeliveredRecord && staleRepaired.some((l) => REBUILDS_THE_DELIVERED_RECORD.has(l))) {
889
+ const rebuilt = rebuildTheDeliveredRecord("stale-repair");
890
+ if (!rebuilt.ok) note(`stale-repair: the audit could not be written again (${String(rebuilt.reason).slice(0, 100)}) — the one written before the repair is withdrawn and kept under _history; the report ships without an audit`);
891
+ }
892
+ }
893
+ // The AD-2 in-pass stale-repair arm for client-summary is retired with the stage
894
+ // (2026-08-01): nothing generates that label, so it can never turn up stale here.
895
+ // Re-judge the repaired surfaces exactly as the lint-repair branch does, then RE-ASK the
896
+ // freshness question — one bounded pass; anything still stale blocks below, exactly as before.
897
+ lint = lintNow();
898
+ autoCorrectRegistry();
899
+ runState.staleStages = staleOnPath(run.runDir, deliveryPathNow(), deliveryInputsFor, { project: projectStageInput });
900
+ // A REPAIR WHOSE REVIEW COULD NOT BE READ IS NOT REVIEWED, and its record says so (`unreadRecordReview`). The guard
901
+ // is never handed that record: a run is not held on an unread review (owner's ruling, 2026-10-19). What the guard
902
+ // reads here is staleness alone, as in the released engine.
903
+ // A CHANGED DECISION STILL UNREAD AFTER ITS RE-RUN IS DELIVERED, NOT HELD (the owner's ruling of 2026-10-19 that a
904
+ // run is never held). When every stage still stale is one the changed decision left stale and whose re-run in
905
+ // this pass did not complete, the run delivers what it has. The writer's duty and the recall gate are judged
906
+ // again on the writer delivered, and name in their approved sentences what they find. Staleness for any other
907
+ // reason still falls to the guard.
908
+ // LATE RECORDS NO PLACEMENT PASS COULD ASSESS ARE DELIVERED, NOT HELD (ruled 2026-10-19). The band gained records
909
+ // after placement's last pass, and neither the pass that would have assessed them nor the delivery check's repeat
910
+ // of placement completed. The report stands as the last accepted passes built it. An account from before the late
911
+ // records cannot show they were assessed, so the floor and the recall gate are judged again on the band as it
912
+ // stands, and the late records the report does not address are counted in the approved sentence for records
913
+ // neither addressed nor set aside. The attempts and the records are kept in the run record.
914
+ const unassessed = repairFailed.has("placement-inquiry") ? lateRecordIds(P) : [];
915
+ if (unassessed.length && runState.staleStages.some((x) => x.label === "placement-inquiry")
916
+ && runState.staleStages.every((x) => x.label === "placement-inquiry" || chain.has(x.label))) {
917
+ const was = runState.verdict, stood = JSON.stringify(runState.clampReasons);
918
+ clampOnTheFloorDuty({ again: true });
919
+ const judged = clampOnTheWritersDuty({ again: true });
920
+ if ((JSON.stringify(runState.clampReasons) !== stood || runState.verdict !== was) && saveTheLabel("after late records went unassessed")) applyVerdictFrontMatter();
921
+ runLog(run.runDir, { event: "late-evidence-unassessed-delivered", was, now: runState.verdict, records: unassessed.length, ids: unassessed.slice(0, 20),
922
+ stated: judged.recall, latePass: ctx.latePassFailed ?? null, repeat: repairFailed.get("placement-inquiry") });
923
+ note(`late evidence: ${unassessed.length} record(s) reached the band after placement's last pass, and neither its pass for them nor the delivery check's repeat completed — the run delivers what the last accepted passes built, and the approved clauses state what is open`);
924
+ runState.staleStages = runState.staleStages.filter((x) => x.label !== "placement-inquiry");
925
+ }
926
+ if (runState.staleStages.length && runState.staleStages.every((x) => chain.has(x.label))) {
927
+ const was = runState.verdict, named = runState.clampReasons.length, stood = JSON.stringify(runState.clampReasons);
928
+ clampOnTheWritersDuty({ again: true });
929
+ // THE RECORDS RE-RANKED SINCE THE WRITER LAST WROTE, in the owner's words of 2026-10-19. The report states the
930
+ // ranking the writer last read; the audit trail, written again after the repeat, states the one that stands.
931
+ const readByWriter = rankingFromJson(safeReadJson(rankingReadByWriterPath(P))) ?? runState.rankingBeforeRepeat;
932
+ if (readByWriter && runState.staleStages.some((x) => x.label === "synthesis")) {
933
+ const now = rankingNow(P), n = recordsReRanked(readByWriter, now);
934
+ const m = Math.max(rankedRecords(readByWriter), rankedRecords(now), n);
935
+ if (n > 0) deliverAndClamp({
936
+ event: "ranking-changed-unread-delivered",
937
+ defect: `ranking_changed_unread:${n}`,
938
+ detail: { records: n, of: m },
939
+ reason: `ranking_changed_unread:${n} of ${m} record(s) — the delivery check's repeat of placement changed where these records stand, and the writer's re-run for the change did not complete, so the report gives the ranking it last read and the audit trail the one that stands. The report ships with this named rather than being withheld.`,
940
+ clause: clauseForDefect("ranking_changed_unread", n, m),
941
+ });
942
+ }
943
+ if ((JSON.stringify(runState.clampReasons) !== stood || runState.verdict !== was) && saveTheLabel("after a changed decision went unread")) applyVerdictFrontMatter();
944
+ runLog(run.runDir, { event: "changed-decision-unread-delivered", was, now: runState.verdict, named: runState.clampReasons.length - named,
945
+ stages: runState.staleStages.map((x) => ({ label: x.label, changed: (x.changed ?? []).map((c) => c.name) })) });
946
+ note(`stale-repair: ${runState.staleStages.map((x) => x.label).join(", ")} could not be re-run for the changed decision — the run delivers, and the approved clauses name what they find`);
947
+ runState.staleStages = [];
948
+ }
949
+ saveTheOwedLabel(); // before anything is published from it
950
+ note(`stale-repair: re-did ${staleRepaired.length} stage(s) in-pass (${staleRepaired.join(", ") || "none"}) — ${runState.staleStages.length ? `${runState.staleStages.length} still stale, the delivery guard blocks` : "the delivery path is fresh"}`);
951
+ }
952
+ // THE CONDITIONS FOLLOW THE RECORD AS IT IS DELIVERED, whichever repair above moved it last, and the label owed is
953
+ // saved before the receipt below and anything published from it. A list that moved is judged again.
954
+ if (followTheRecordsActions("as the record is delivered")) {
955
+ saveTheLabel("as the record is delivered");
956
+ applyVerdictFrontMatter();
957
+ lint = lintNow();
958
+ }
959
+ saveTheOwedLabel();
960
+ // P2 — record the delivery-BLOCKING stale labels the moment they are known (not only at the throw
961
+ // below), so ANY later exit from this pass — the staleness throw, a core-artifact throw between here
962
+ // and it, an auto-recovery park — carries the set into reconcilePassStamps. Reconcile must leave these
963
+ // stamps stale (see reconcileStamps' `exclude`), else it erases the block and the resume ships stale.
964
+ if (runState.staleStages.length) ctx.deliveryBlockingStale = new Set(runState.staleStages.map((s2) => s2.label));
965
+ try {
966
+ writeFileSync(paths(run.runDir).predeliveryLint, JSON.stringify({
967
+ ts: new Date().toISOString(),
968
+ checks: lint.checks, failures: lint.failures.map((f) => f.id),
969
+ staleStages: runState.staleStages, // P2: non-empty ⇒ this run was blocked on freshness, not on lint quality
970
+ staleRepaired, // AD-2 A1: delivery-tail stages re-done IN-PASS after a repair moved their input
971
+
972
+ initialFailures: initialFailures.map((f) => f.id), repaired,
973
+ registryCorrections, // doc-27 Item 1b: deterministic record-true overwrites applied before/after the redo
974
+ artifactSet: {
975
+ surfaces: [P.report].filter(existsSync).map(fileMeta), // client-summary retired 2026-08-01 — one delivered surface
976
+ recordUris: [...assembled.records.keys()].sort(),
977
+ recordSources: { fromRunDir: assembled.fromRunDir, fromLedgerThisSession: assembled.fromLedger },
978
+ recordFetchFailures: [...recordFetchFailures.entries()].map(([uri, cause]) => ({ uri, cause })),
979
+ skippedStages: ctx.skippedStages ?? [],
980
+ },
981
+ }, null, 2) + "\n");
982
+ } catch (e) { note(`lint receipt write failed (non-fatal): ${e.message}`); }
983
+ // F1 + F2 — reasoning-integrity OBSERVABILITY: per-finding engagement receipts (does
984
+ // each Composite≥3 finding cite any of its own field anchors?) + rule-shape flags (a rating decided
985
+ // by a cutoff/blanket rule), written to an INTERNAL sidecar and surfaced on the INTERNAL report only
986
+ // (publishReport → opts.integrityFlags). GOODHART GUARD: this is observability the reviewer reads while
987
+ // curating, NEVER a gate — nothing retries or blocks on it (§0(a)/§6).
988
+ try {
989
+ const narrativeMd = existsSync(P.narrative) ? readFileSync(P.narrative, "utf8") : "";
990
+ const reportMd = existsSync(P.report) ? readFileSync(P.report, "utf8") : "";
991
+ const anchors = readAnchors({
992
+ registerFindingsMd: existsSync(P.registerFindings) ? readFileSync(P.registerFindings, "utf8") : "",
993
+ matterContextMd: existsSync(P.matterContext) ? readFileSync(P.matterContext, "utf8") : "",
994
+ variantManifestMd: existsSync(P.variantManifest) ? readFileSync(P.variantManifest, "utf8") : "",
995
+ });
996
+ const receipts = findEngagementReceipts(narrativeMd, anchors);
997
+ const bland = receipts.filter((r) => !r.citesOwnAnchor);
998
+ const ruleShape = findRuleShapeFlags(`${narrativeMd}\n${reportMd}`, { disputeTypes: (ctx.frameworkMethod?.inputs ?? []).flatMap((i) => i.values) }); // the run's own dispute types, where its framework states a method
999
+ const reviewMd = existsSync(P.seniorEyeReview) ? readFileSync(P.seniorEyeReview, "utf8") : "";
1000
+ // B2b — reviewer self-coherence over senior-eye-review.md (same internal sidecar/banner).
1001
+ const reviewerCoherence = findReviewerCoherenceFlags(reviewMd);
1002
+
1003
+ // v5 Appendix-A reasoning tripwire net — the thin MECHANICAL catch under the recall / coverage /
1004
+ // honesty PRINCIPLES (skills/*). Same INTERNAL-observability posture as F1/F2/B2: a staff lawyer curates, it
1005
+ // never blind-redoes a surface, and each reads ONLY mechanical artifacts — never the noisy reviewer
1006
+ // verdict. (The U1 status-FORCING already happened at the verdict clamp above; here it is the
1007
+ // surface-honesty backstop + the recorded receipt.) Flag-and-deliver: a trip is surfaced, never withheld.
1008
+ const registerFindingsMd = existsSync(P.registerFindings) ? readFileSync(P.registerFindings, "utf8") : "";
1009
+ const commonLawMd = existsSync(P.commonLaw) ? readFileSync(P.commonLaw, "utf8") : "";
1010
+ const matterContextMd = existsSync(P.matterContext) ? readFileSync(P.matterContext, "utf8") : "";
1011
+ const placementMd = existsSync(P.placement) ? readFileSync(P.placement, "utf8") : "";
1012
+ let parsedFindings = null;
1013
+ try { if (existsSync(P.findings)) parsedFindings = parseFindingsJson(readFileSync(P.findings, "utf8")); }
1014
+ catch { /* malformed findings.json is already a validators.findings fail upstream — don't double-throw here */ }
1015
+ // AD-4 (instrumentation house rule) — record WHICH inputs this pass could actually read. Every
1016
+ // "" fallback above makes a missing file indistinguishable from an empty one, which is exactly how
1017
+ // the R2 evidence run's engagement total flapped 13→0 between two emissions (tripwires 9 both
1018
+ // times) with nothing saying the second pass simply could not see the narrative. A zero with
1019
+ // inputs.narrative:false is "not recorded"; a zero with inputs.narrative:true is "did not happen".
1020
+ const inputsRead = {
1021
+ narrative: existsSync(P.narrative), report: existsSync(P.report),
1022
+ review: existsSync(P.seniorEyeReview), registerFindings: existsSync(P.registerFindings),
1023
+ commonLaw: existsSync(P.commonLaw), matterContext: existsSync(P.matterContext),
1024
+ placement: existsSync(P.placement),
1025
+ findings: parsedFindings != null,
1026
+ };
1027
+ const inScopeClasses = inScopeClassList(job, ctx.profile); // #2 — full Nice set (top-level + per-mark), incl. services
1028
+ const carriedMarks = (parsedFindings?.findings ?? []).map((f) => f.mark);
1029
+ // A3 — the frame residual (an unclosed dominant-element crowd + every deferred frame directive) joins
1030
+ // the coverage gaps fed to the status-honesty signal, so the delivered headline cannot read clean while
1031
+ // the dominant-element crowd is unfinished (and the caption is promoted to disclose it, below).
1032
+ let frameReopenReceipt = null;
1033
+ try { const rp = paths(run.runDir).frameReopenReceipt; frameReopenReceipt = existsSync(rp) ? JSON.parse(readFileSync(rp, "utf8")) : null; } catch { /* best-effort */ }
1034
+ // copper-lattice net #3 — the cross-check tripwire's substrate (only-if-present)
1035
+ let xcheckReceipt = null;
1036
+ try { const xp = paths(run.runDir).registerXcheck; xcheckReceipt = existsSync(xp) ? JSON.parse(readFileSync(xp, "utf8")) : null; } catch { /* best-effort */ }
1037
+ const carriedOwners = (parsedFindings?.findings ?? []).flatMap((f) => [f?.owner, f?.owner_name, f?.owner?.name]).filter((x) => typeof x === "string" && x);
1038
+ const executedQids = (ctx.planExecution?.executed ?? []).map((x) => x.qid);
1039
+ const regLedgerRows = loadCoverageLedger(run.runDir).rows;
1040
+ // judgment-relocation (2026-06-23): the search-shape gate (findFloorShapeGaps) was DELETED here too —
1041
+ // sufficiency is judgment's call (coverage_judgment), not a re-parse of the ledger at the surface. This
1042
+ // status-honesty tripwire stays an INTERNAL observability backstop over the genuine ledger gaps
1043
+ // (deferred / coverage-limited rows) + the structural frame residual + an unsearched in-scope jurisdiction
1044
+ // — it never clamps the verdict (the verdict clamp above is retired); it only flags the reviewer.
1045
+ const materialGaps = deriveCoverageStatus([
1046
+ ...regLedgerRows,
1047
+ ...(commonLawMd ? findCoverageLimitedCells(commonLawMd).map((c) => ({ axis: "common-law", status: "coverage-limited", unit: `${c.variant} × ${c.platform}` })) : []),
1048
+ ]).materialGaps.concat(frameResidualGaps(frameReopenReceipt))
1049
+ // Round 2 Change 1d — an in-scope jurisdiction the run never searched is a recall gap: it joins the
1050
+ // status-honesty signal + the disclosed caption (escalate + disclose, never withhold), like the frame residual.
1051
+ .concat((ctx.jurisdictionScope?.underCoverage ?? []).map((j) => ({ unit: `in-scope jurisdiction unsearched: ${j}`, status: "frame-gap", reason: "an instructed / effective-in-scope territory was not searched this run" })))
1052
+ // M6 — A DECLARED ABSENCE IS A MATERIAL GAP, and it has to be added HERE because it is
1053
+ // invisible everywhere else: the form carries no rows, so `deriveCoverageStatus` above returns
1054
+ // `{complete: true}` over it and the status-honesty surface would see a run with nothing
1055
+ // outstanding. The declaration reads correctly to the lawyer and says nothing to the machine
1056
+ // unless this line exists.
1057
+ .concat(coverageAbsenceGaps(readCoverageForm(run.runDir, coverageFormStamp(run.runDir).formName).parsed));
1058
+ const tripwires = {
1059
+ recallFloor: findRecallFloorViolations(registerFindingsMd, { carriedMarks, searchedNames, inScopeClasses }), // S1
1060
+ reviewFreshness: findReviewFreshnessViolation(reviewMd, { upstreamTexts: [registerFindingsMd, commonLawMd, placementMd] }), // U2
1061
+ seedNeutrality: findSeedNeutralityViolations([{ name: "matter-context", text: matterContextMd }, { name: "placements", text: placementMd }]), // S2
1062
+ probativeGrading: parsedFindings ? findProbativeGradingViolations(parsedFindings) : [], // U3
1063
+ // The matrix-ceiling tripwire is retired: a framework that states a table now holds each rating to it (framework-method.mjs).
1064
+ // U1 (surface backstop). The scan surface NARROWS to report.md on 2026-08-01: client-summary.md
1065
+ // was the second half of this concat and no longer exists. The report is the one delivered
1066
+ // document, so nothing a reader sees escapes the check — it just has one surface to read now.
1067
+ statusHonesty: findStatusHonestyViolation(materialGaps, reportMd),
1068
+ // #6/#7/#8 grading tripwires (non-blocking, escalate-and-disclose): a near-term client deadline that
1069
+ // must surface as an ACTION; a placement disagreement the digest left unresolved; a register finding
1070
+ // with no grounding record (orphan). All read STRUCTURED artifacts (findings.json / the digest table).
1071
+ deadlineUrgency: parsedFindings ? findDeadlineUrgencyMiss(parsedFindings, { nowMs: Date.now() }) : [], // #6
1072
+ unresolvedDisagreements: findUnresolvedDisagreements(registerFindingsMd), // #7
1073
+ orphanFindings: parsedFindings ? findOrphanVerificationFlags(parsedFindings) : [], // #8
1074
+ // copper-lattice net #3 — a same-field in-use common-law hit demoted without an executed
1075
+ // register cross-check receipt (S1 sibling; receipt-gated ⇒ replay-pure).
1076
+ crosscheckMissing: findUncrossCheckedDemotions(commonLawMd ? findSimilarListingSignals(commonLawMd) : [],
1077
+ { carriedOwners, carriedMarks, xcheckReceipt, executedQids }),
1078
+ // PR-4 — document-growth trips off the append-only spine (the stage choke point logs them; both
1079
+ // the lint-repair and corrective loops are covered because the trip keys on TRIGGER). Internal
1080
+ // observability like every tripwire: the reviewer sees which repair pass ADDED material.
1081
+ documentGrowth: documentGrowth(run.runDir)?.trips ?? [],
1082
+ };
1083
+ const tripFlags = [
1084
+ ...tripwires.recallFloor.map((v) => `recall-floor: ${v.why}`),
1085
+ ...tripwires.crosscheckMissing.map((v) => `crosscheck-missing: ${v.why.replace(/^crosscheck-missing:\s*/, "")}`),
1086
+ // doc-35 T4: review-freshness (U2) grades the engine's own QC RITUAL ("the review re-read its own
1087
+ // inputs"), a process metric not a matter fact — dropped from the reviewer surface.
1088
+ ...tripwires.seedNeutrality.map((v) => `seed-neutrality: ${v.where} carries ${v.why}`),
1089
+ ...tripwires.probativeGrading.map((v) => `probative-grading: ${v.why}`),
1090
+ ...(tripwires.statusHonesty && !tripwires.statusHonesty.pass ? [`status-honesty: ${tripwires.statusHonesty.detail}`] : []),
1091
+ ...tripwires.deadlineUrgency.map((v) => `deadline-urgency: ${v.why}`),
1092
+ ...tripwires.unresolvedDisagreements.map((v) => `disagreement-unresolved: ${v.why}`),
1093
+ ...tripwires.orphanFindings.map((v) => `orphan-finding: ${v.why}`),
1094
+ ...tripwires.documentGrowth.map((t) => `document-growth: ${t.stage} grew ${t.growthPct}% (${t.before} → ${t.after} bytes) under trigger "${t.trigger}" — a repair defends or corrects, it does not add; review what the pass appended`),
1095
+ ];
1096
+
1097
+ writeFileSync(paths(run.runDir).reasoningIntegrity, JSON.stringify({
1098
+ ts: new Date().toISOString(),
1099
+ inputs: inputsRead, // AD-4: which substrates this pass could read — a 0 below is only a 0 when its input was true
1100
+ engagement: { total: receipts.length, blandCount: bland.length, bland: bland.map((r) => r.finding), receipts },
1101
+ ruleShape, reviewerCoherence, tripwires, tripFlags,
1102
+ registryCorrections, // doc-27 Item 1b: surfaced on the INTERNAL banner so the reviewer sees what code fixed from the record
1103
+ }, null, 2) + "\n");
1104
+ // AD-4: the run.jsonl event is UNCONDITIONAL (it used to fire only when something flagged, so a
1105
+ // clean pass and a never-ran pass looked identical to a run.jsonl reader) and carries the
1106
+ // inputs-read map, so the 13→0 flap shape self-explains on the row that shows the 0.
1107
+ runLog(run.runDir, { event: "reasoning-integrity", ok: true, bland: bland.length, total: receipts.length, ruleShape: ruleShape.length, reviewerCoherence: reviewerCoherence.length, tripwires: tripFlags.length, inputs: inputsRead });
1108
+ if (bland.length || ruleShape.length || reviewerCoherence.length || tripFlags.length) {
1109
+ note(`reasoning-integrity (observability, non-blocking — for the reviewer to eyeball): ${bland.length}/${receipts.length} finding(s) cite no field anchor; ${ruleShape.length} rule-shape; ${reviewerCoherence.length} reviewer-coherence; ${tripFlags.length} v5 tripwire(s)${tripFlags.length ? ` — ${tripFlags.map((f) => f.split(":")[0]).join(", ")}` : ""}.`);
1110
+ }
1111
+ } catch (e) {
1112
+ // AD-4: a failed integrity pass is a recorded fact, not a stderr aside — the old note-only catch is
1113
+ // exactly the "not recorded reads as clean" shape this package retires.
1114
+ try { runLog(run.runDir, { event: "reasoning-integrity", ok: false, error: String(e?.message ?? e).slice(0, 160) }); } catch { /* best-effort */ }
1115
+ note(`reasoning-integrity (non-fatal): ${e.message}`);
1116
+ }
1117
+ // Surviving failures + any unclosed envelope gap ride the report front-matter as code-built flags —
1118
+ // rendered as the banner at the top of the email and the report page. Single-line, length-capped.
1119
+ const flags = flagLines(lint.failures);
1120
+ const fmFields = {};
1121
+ // A1 (residual leak closed): lint_flags must NOT ride report.md front-matter — report.md is copied
1122
+ // verbatim into the client-reachable pool dir (publish/index.mjs copyRO), so a front-matter lint
1123
+ // flag is a latent client leak even though the rendered client HTML strips it. The flags live ONLY
1124
+ // in the internal _driver/predelivery-lint.json sink (written just above); publishReport reads that
1125
+ // sink and surfaces them on the INTERNAL report render alone (opts.lintFlags), never the client one.
1126
+ // B5b checkpoint 4: a customer named after the narrative existed binds as a DELIVERY NOTE, never silently.
1127
+ await checkLateBind("pre-delivery");
1128
+ if (ctx.lateBindNote) fmFields.late_bind_note = ctx.lateBindNote;
1129
+ // V4-4: surviving coverage gaps ship as the attempted-and-unreachable note with the priced offer.
1130
+ if (ctx.coverageNote) fmFields.coverage_note = ctx.coverageNote.slice(0, 600);
1131
+ // T4 (H1/H2): the screen_gate_note / frame_reopen_note / machine_ledger_note front-matter
1132
+ // injections are DEAD — their only renderer was the retired review bar, and their SUBSTANCE
1133
+ // already reaches the reader honestly: the verdict clamp reasons (hero bound line + email
1134
+ // conditions row) carry the screen-gate and frame residues, injectDeferralCoverage puts the
1135
+ // unclosed directives in the coverage rows, and the machine-ledger degrade rides status.json /
1136
+ // the run log / the audit workbook's Review-receipts sheet.
1137
+ // Doc-17 C-2: open floors at delivery = deferred rows ∪ surviving ⭐-floor breaches (the label
1138
+ // never demotes floor work). Stated with the mechanical cause, never silently shipped.
1139
+ const ledgerLoadFinal = loadCoverageLedger(run.runDir); // WS-A: third gate consumer — same source as the other two
1140
+ let ledgerFinal = ledgerLoadFinal.rows;
1141
+ // T3 (H3, the owner-refined line): the machine-ledger DEGRADE is
1142
+ // sanctioned only while the gates could actually READ coverage — the prose table is the source
1143
+ // of truth and its rows kept every gate functioning. A run whose coverage-honesty floor had
1144
+ // ZERO usable rows (machine mirror unavailable AND the prose parse yielded nothing) has no
1145
+ // functioning coverage receipts at all — it FAILS instead of stamping a verdict over unread
1146
+ // coverage (the retired D1 clamp used to ship this as a finished-looking CONDITIONAL).
1147
+ // THE FORM BOTH LEDGERS ARE RENDERED FROM, BEFORE THE RUN IS ENDED FOR WANT OF EITHER. The machine ledger
1148
+ // and the prose table are renders of the driver's coverage form, whose statuses the write-up recorded. With both
1149
+ // renders unreadable, the form's ruled rows still let the coverage-honesty floor run, through the same relabels,
1150
+ // so the run is not ended with no report over a render it lost. With no ruled row there either, see below.
1151
+ if (ctx.machineLedgerNote && ledgerLoadFinal.source !== "machine" && ledgerFinal.length === 0 && existsSync(P.registerFindings)) {
1152
+ const formRows = formLedgerRows(readCoverageForm(run.runDir).rows ?? []);
1153
+ if (formRows.length) {
1154
+ ledgerFinal = relabelCoverageRows(run.runDir, formRows);
1155
+ runLog(run.runDir, { event: "coverage-ledger-from-form", rows: ledgerFinal.length, note: abbrev(String(ctx.machineLedgerNote), 200) });
1156
+ note(`coverage ledger: the machine ledger and the prose table are unreadable — the coverage floor reads the coverage form's ${formRows.length} ruled row(s)`);
1157
+ } else
1158
+ // With no ruled row anywhere, no verdict can ship over coverage nobody read (spec-49 T3), and the run is not
1159
+ // ended for it either: the failure is the assessment's, recorded as not completed and delivered without it.
1160
+ throw Object.assign(new StageFailure("coverage-ledger", `no readable coverage ledger — ${abbrev(String(ctx.machineLedgerNote), 200)}; the prose table yielded zero rows${ledgerLoadFinal.dropped?.length ? ` (${ledgerLoadFinal.dropped.length} unclassifiable)` : ""} — the coverage-honesty floor cannot run, so no verdict can ship`), { notCompletedPart: "assessment" });
1161
+ }
1162
+ // — the designation comes from the VALIDATED model, not the rendered manifest. `manifestFinal`
1163
+ // is gone from this call: it was the retired mechanism's text-scanning input and reading it here
1164
+ // again would be the token matching that made the original impossible to carry forward.
1165
+ const openFloors = computeOpenFloors(ledgerFinal, readFloorAxes(P));
1166
+ if (openFloors.length) {
1167
+ fmFields.envelope_note = ctx.envelopeNote
1168
+ ?? `floor work still open at delivery: ${openFloors.join("; ")} — still recorded open after the in-loop close attempt (see envelope events in the run log)`;
1169
+ }
1170
+ // WS-A machine-ledger degrade: the receipt stays on the AUDIT lane (status.json via writeRunStatus,
1171
+ // the run log, and the workbook's Review-receipts sheet) — no longer a report front-matter caveat.
1172
+ // Disk backstop: a quarantined .invalid.json with no live note (crash-resume edge) still records.
1173
+ if (!ctx.machineLedgerNote && ledgerLoadFinal.source !== "machine"
1174
+ && existsSync(P.registerCoverageLedger.replace(/\.json$/, ".invalid.json"))) {
1175
+ ctx.machineLedgerNote = "machine coverage ledger was quarantined earlier in this run (register-coverage-ledger.invalid.json) — coverage gates read the prose table";
1176
+ writeRunStatus(ctx, { machineLedgerNote: ctx.machineLedgerNote });
1177
+ }
1178
+ if (Object.keys(fmFields).length) {
1179
+ injectFrontMatter(P.report, fmFields, run.runDir);
1180
+ runLog(run.runDir, { event: "delivery-flags", lint: flags.length, envelope: Boolean(fmFields.envelope_note), machineLedger: Boolean(ctx.machineLedgerNote) });
1181
+ }
1182
+ note(`pre-delivery lint: ${lint.checks.length} checks, ${lint.failures.length} failing${repaired.length ? ` (repaired: ${repaired.join(", ")})` : ""}${fmFields.envelope_note ? " + envelope gap stated" : ""}`);
1183
+ }
1184
+
1185
+ // item 10 — the band declarations this run made, recorded once against the SETTLED findings (after
1186
+ // every deterministic mutator has run, so the ordinals are the delivered ones). Same shape and same
1187
+ // discipline as the placement-borderline row: COUNT AND MARKS ONLY — the two readings live in the
1188
+ // finding's own prose, and a declaration has no more business in a log row than in the report. Silent
1189
+ // when nothing is declared, and on every archived / pre-field run. Its first reader is the round's own
1190
+ // revert criterion: "a record the framework decides clearly" only means something once the records it
1191
+ // does NOT decide are marked as such. Best-effort — observability never blocks a delivery.
1192
+ try {
1193
+ const settled = parseFindingsJsonLenient(readFileSync(P.findings, "utf8")).findings ?? [];
1194
+ const declared = bandBorderlineDeclarations(settled);
1195
+ if (declared.length)
1196
+ runLog(run.runDir, {
1197
+ event: "band-borderline", count: declared.length,
1198
+ marks: declared.slice(0, 8).map((f) => f.mark),
1199
+ between: [...new Set(declared.map((f) => f.borderline_between.join("|")))].slice(0, 8),
1200
+ });
1201
+ } catch { /* absent or malformed — the core-artifact gate immediately below is what owns that */ }
1202
+
1203
+ // doc-44 Fix C — machine-file DELIVERY gate (mechanism + a pluggable core-artifact seam). A top-level-invalid
1204
+ // CORE machine artifact must NOT ship: it is repaired UPSTREAM (the synthesis quarantine + the corrective
1205
+ // must() re-synthesis already fail a top-level-invalid findings.json), and THIS is the final backstop before
1206
+ // publish so nothing invalid slips through a post-synthesis mutation. Never quarantine-and-ship: a broken
1207
+ // findings.json is restored from the last save that passed (restoreTheRecordThatPassed), and with none to restore
1208
+ // the failure is the assessment not completed. We validate with the LENIENT parser so a legitimate PER-FINDING quarantine
1209
+ // (one bad finding dropped, the rest shipped) still passes — THAT (whether a dropped finding is a core failure)
1210
+ // is a POLICY call the definition-of-done (spec 45) owns, not this gate. The CORE_ARTIFACTS list is the SEAM:
1211
+ // spec 45 owns its contents; it is seeded with the machine findings file doc-44 names. This enforces machine-
1212
+ // file INTEGRITY only — it does NOT set the completed/conditional/failed verdict rule (spec 45 owns that).
1213
+ const CORE_ARTIFACTS = [
1214
+ { name: "findings.json", path: P.findings, validate: (raw) => { parseFindingsJsonLenient(raw); } }, // ← spec 45 owns this list
1215
+ ];
1216
+ const coreInvalid = [];
1217
+ for (const art of CORE_ARTIFACTS) {
1218
+ if (!existsSync(art.path)) continue; // absent ≠ invalid (a degraded/legacy run legitimately has no machine file)
1219
+ try { art.validate(readFileSync(art.path, "utf8")); }
1220
+ catch (e) { coreInvalid.push(`${art.name} — ${String(e.message).replace(/\s+/g, " ").slice(0, 140)}`); }
1221
+ }
1222
+ if (coreInvalid.length) {
1223
+ runLog(run.runDir, { event: "core-artifact-invalid", failures: coreInvalid });
1224
+ // The record, broken after the delivery checks first read it, is restored as it is there (restoreTheBrokenRecord),
1225
+ // and what was built from it is judged again against the record that stands: the freshness check below parks a
1226
+ // stage it left stale, and the resumed pass rebuilds it.
1227
+ const failure = new StageFailure("core-artifact-gate", `a core machine artifact is invalid and cannot ship: ${coreInvalid.join("; ")}`);
1228
+ if (!coreInvalid.every((f) => f.startsWith("findings.json "))) throw failure; // only the findings record is the assessment's
1229
+ if (!(await restoreTheBrokenRecord(coreInvalid, "delivery-gate"))) throw Object.assign(failure, { notCompletedPart: "assessment" });
1230
+ runState.staleStages = runState.staleOnTheDeliveryPath();
1231
+ }
1232
+
1233
+ // P2 clause 3 — FRESHNESS PRECONDITION, immediately before the client gate. copper-vault's gate
1234
+ // passed a byte-identical client summary an hour after rejecting it, because its OTHER input moved
1235
+ // underneath a frozen deliverable. A gate whose subject can change without the deliverable changing
1236
+ // is not a gate — so nothing is asked of the gate until every stage on the delivery path is fresh
1237
+ // with respect to its declared inputs. Deterministic; same failure shape as the other delivery gates.
1238
+ if (runState.staleStages.length) {
1239
+ const detail = runState.staleStages.map((s2) => `${s2.label} (${s2.changed.map((c) => c.name).join(", ")})`).join("; ");
1240
+ runLog(run.runDir, { event: "delivery-stale-blocked", stages: runState.staleStages });
1241
+ note(`delivery: ${runState.staleStages.length} stage(s) on the delivery path are stale w.r.t. their inputs — ${detail}`);
1242
+ // item 15b — WRITE DOWN WHAT IS STALE, so the recovery has something to aim at.
1243
+ //
1244
+ // A `stale` failClass parks and the resume re-enters the pipeline from the top. That is correct and
1245
+ // safe, and it is also the whole 34% recovery phase: the run walks every stage to discover, one skip
1246
+ // at a time, what this pass already knew by name. The set is recorded here — in dependency order, so
1247
+ // the reader and the repair agree about what has to happen first — and `repairStale()` below runs
1248
+ // exactly it. Best-effort: the sidecar is an accelerator, never the authority. Absent or unreadable,
1249
+ // the ordinary resume does what it has always done.
1250
+ try {
1251
+ const dir = driverDir(run.runDir);
1252
+ mkdirSync(dir, { recursive: true });
1253
+ const tmp = join(dir, "delivery-stale.json.tmp");
1254
+ writeFileSync(tmp, JSON.stringify({
1255
+ ts: new Date().toISOString(),
1256
+ labels: dependencyOrder(runState.staleStages.map((s2) => s2.label), P, { axes: ctx.axes }),
1257
+ changed: Object.fromEntries(runState.staleStages.map((s2) => [s2.label, (s2.changed ?? []).map((c) => c.name)])),
1258
+ }, null, 2));
1259
+ renameSync(tmp, join(dir, "delivery-stale.json"));
1260
+ } catch { /* accelerator only — the resume stands without it */ }
1261
+ // failClass "stale": the remedy is a DETERMINISTIC recompute of the stale stage(s) (a resume recomputes
1262
+ // them — the stamps were left stale for exactly this, see reconcileStamps' exclude), so this must not be
1263
+ // starved by the shared one-park "unknown" budget. The repeat-signature backstop still caps it.
1264
+ // THE REPEAT IS GIVEN ONE MORE ASSEMBLY, NOT THE STOP NOTICE. A first staleness parks and the resume repairs
1265
+ // it, as always. Where the repeat would end the run, the check is named as its own part: the run parks once more,
1266
+ // and the resumed pass repairs and checks again from the material as it then stands. Still stale then, it ends as
1267
+ // it always did; this check never delivers past staleness.
1268
+ throw Object.assign(new StageFailure("delivery", `the report was assembled from material that has since changed: ${detail} — re-run needed (nothing published)`, undefined, { failClass: "stale" }), { notCompletedPart: "delivery" });
1269
+ }
1270
+
1271
+ // The changed-material check passed: a record the last pass left for it is answered.
1272
+ if (readPartNotCompleted(run.runDir, "delivery")) {
1273
+ clearPartNotCompleted(run.runDir, "delivery");
1274
+ runLog(run.runDir, { event: "part-completed", part: "delivery" });
1275
+ }
1276
+
1277
+ // ONE report (spec 2026-07-30 §5) — the client gate's preflight is gone with the readiness state it
1278
+ // chose. publishReport still runs the evaluateClientGate machine checks (they are real: arithmetic,
1279
+ // record fidelity, stale corrections) but their result lands on the AUDIT WORKBOOK + meta.json + the
1280
+ // machine-qc-failed telemetry event below — it decides nothing about who may read, and there is no
1281
+ // client export to withhold. A defect that changes the LEGAL ANSWER is the verdict clamp's job and
1282
+ // rides the report as a fact about the mark (a CONDITIONAL/BLOCKING verdict), never as a warning
1283
+ // about the document.
1284
+ // B — publish: DETERMINISTIC CODE → cannot hang. The durable deliverable: the report ships even if the audit
1285
+ // failed above (publishReport renders report.html regardless; the xlsx is best-effort inside it).
1286
+ return await publishAndDeliver(runState.verdict);
1287
+ }