clearotron 0.5.1-beta.2 → 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 +147 -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 +8 -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 +8 -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,899 @@
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/overview-and-cards.mjs — the report's overview and its cards, and the front matter the driver stamps on them.
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 { ensureDriverDir } from "../../shared/driver-dir.mjs";
10
+ import { applyAskClosure, deriveAsks, finalizeOpenHandoffs, summarizeAsks } from "../ask-ledger.mjs";
11
+ import { mintCommonLawCarryDoubts } from "../commonlaw-carry.mjs";
12
+ import { readDeclinations } from "../declination-tool.mjs";
13
+ import { CLOSURE_EVIDENCE_FILES } from "../doubt-closure-call.mjs";
14
+ import { readAcceptedClosures } from "../doubt-closure-tool.mjs";
15
+ import { applyClosure, mintContradictionDoubts, mintCrossCheckDoubts, stitchDoubts } from "../doubt-ledger.mjs";
16
+ import { doubtSelectionNote, doubtsForClosure } from "../doubt-selection.mjs";
17
+ import { config } from "../driver.config.mjs";
18
+ import { resolveTerritories } from "../effective-scope.mjs";
19
+ import { bindRecommendation, parseFindingsJsonLenient } from "../findings-model.mjs";
20
+ import { exitsForLog, notesExits, pickingExits } from "../hand-off-exits.mjs";
21
+ import { note, runLog } from "../log.mjs";
22
+ import { lastAcceptedMatterFrame } from "../matter-frame-record.mjs";
23
+ import { fallbackNoteFor } from "../numeric-setting.mjs";
24
+ import { readPartNotCompleted } from "../parts-not-completed.mjs";
25
+ import { mintPlacementCarryDoubts, reconcilePlacementCarry } from "../placement-carry.mjs";
26
+ import { placementAuditRows } from "../placement-decisions.mjs";
27
+ import { parsePlacementsJson } from "../placement-model.mjs";
28
+ import { mintPresenceDoubts } from "../presence-reconciliation.mjs";
29
+ import { buildAuditMd, parseSpineFindingBlocks } from "../publish/audit-from-spine.mjs";
30
+ import { deriveRegisterPresence } from "../publish/register-presence.mjs";
31
+ import { recallReceiptForOwnCompany } from "../recall-receipt.mjs";
32
+ import { mintRecordCarryDoubts, silentlyLostFindings, statedDivergenceFindings } from "../record-carry.mjs";
33
+ import { recordedFindingUris } from "../register-digest-record.mjs";
34
+ import { SETTLED_CLASSES, mintRemedyAccountingDoubts } from "../remedy-accounting.mjs";
35
+ import { IDENTITY_FILE as REPORT_IDENTITY_FILE, renderReportOverview } from "../report-overview-record.mjs";
36
+ import { parseVariantManifestModel } from "../variant-manifest-model.mjs";
37
+ import { readWithheldFamilies } from "../withheld-families.mjs";
38
+ import { gradedWriteUpRung } from "../write-up-form.mjs";
39
+ import { existsSync, mkdirSync, readFileSync, readdirSync, writeFileSync } from "node:fs";
40
+ import { basename, join } from "node:path";
41
+
42
+ export async function runOverviewAndCards({ P, applyCoverageFloor, clampOnTheWritersDuty, ctx, followTheRecordsActions, job, run, runState, saveTheLabel, writeVerdictSidecar }, helpers) {
43
+ const { StageFailure, applyScopeFrontMatterOf, asPartNotCompleted, assembleReportMd, caseLawJoin, consolidateFindingsFile, correctionsTheRestoreLacks, deriveCommonLawCarry, deriveRecordCarry, inScopeClassList, injectDeferralCoverage, injectFrontMatter, injectLaneDepthCoverage, injectMeaningGapCoverage, injectScreenGateCoverage, injectScriptScopeCoverage, keepDeliveredRecordAsHistory, localLanguageStateOf, must, openAskForClosure, originRowsForReport, planWriteUps, readFindingsForReport, readReadingLog, rebuildDeliveredRecord, reportIdentityRecord, restoreTheRecordThatPassed, rewriteFromBeforeTheSeam, runBatched, safeReadJson, settleDerivedBases, stage, stampCoverageJudgmentRows, withdrawSupersededAudit, writeScopeFactsOf, writeShortEntries } = helpers;
44
+ // Phase 3 — delivery (v14 post-mortem fix). One LLM step curates the report; the audit, the page render,
45
+ // and the email body are deterministic CODE; a tiny LLM step only SENDS. Each step is independent — a
46
+ // failure in the audit or the email never loses the report.
47
+
48
+ // B1 — the report is rendered in TWO isolated parts, then ASSEMBLED by the driver (was ONE pass over every
49
+ // card → the ashen-lattice cross-contamination). (1) report-overview: the cross-finding shell (front-matter +
50
+ // Actions/Coverage/Methodology). (2) report-card per full-prose finding, each from ITS OWN record only — so a
51
+ // card can never carry another finding's body. Then deterministic assembly (render.mjs fills any gap
52
+ // structured-only). Each stage is file-gated/resumable; per-card sessions feed the lint repair below.
53
+ // C2 — fold same-owner+same-mark duplicate filings into one finding BEFORE the overview + cards read
54
+ // findings.json, so the whole delivery phase (and the published copy) sees the single consolidated set.
55
+ // THE SEAM'S WRITES ARE ONE CLOSURE, so they can run again: a synthesis save after this point rewrites
56
+ // findings.json from the seat's own call, and every write below went with it (`stage()` re-runs them).
57
+ const seamWrites = async () => {
58
+ // A pass follows each rewrite of findings.json and adds the rows below again, so delivery reads only the adders
59
+ // that failed since the last of these.
60
+ runLog(run.runDir, { event: "coverage-rows-pass" });
61
+ injectDeferralCoverage(P, run.runDir, note); injectMeaningGapCoverage(P, run.runDir, note); // A3: unclosed reopen directives, and meaning searches that did not complete, become reader-visible coverage rows first
62
+ // qw/cn-scope-honesty — the sibling injection: a CN-family-scope run whose zh lane did not run
63
+ // discloses what the native-language investigation would have searched, and where it is offered
64
+ // (coverage-limited: never clamps, never gates).
65
+ // — every candidate lane in LANGUAGE_LANES, not zh alone. A JP- or KR-scoped run without the
66
+ // investigation now states the Japanese/Korean-script equivalents it did not search, exactly as a
67
+ // CN-scoped one has always stated the Chinese ones.
68
+ // — the run STATES which jx slices it executed, derived from the per-unit records and the
69
+ // frozen lane decision. Minted HERE and not at the fold, because the fold runs before both retrieval
70
+ // slices (grid at ~:5857, nativeread at ~:8503) and a writer inside it could only ever say
71
+ // "candidates". This is the first point after slice 3 that every resume reaches. Never-kill.
72
+ // GUARDED on the SAME condition as every other jx site (:5833, :5870, :8515). Without it this ran on
73
+ // every clearance, including the ones that never had a jx lane — and both R2 runs of the 2026-08-09
74
+ // round carry no _driver/jx-lanes.json at all. On those the writer would reach its absent arm and
75
+ // print "NOT writing one", which reads as a withheld action on a run where absence is simply normal.
76
+ // That is the absent-vs-failed conflation this tranche exists to remove; a lazy import also keeps a
77
+ // plain clearotron byte-identical, which is why the sibling sites are shaped this way.
78
+ let localLanguage = null;
79
+ if (ctx.searchPolicy?.components?.jxLanes) {
80
+ try {
81
+ const { stateJxSlices } = await import("../jx.mjs");
82
+ stateJxSlices(run.runDir, { note, runLog });
83
+ } catch (e) { note(`jx slice statement skipped (${String(e?.message ?? e).slice(0, 100)}) — never-kill`); }
84
+ try { localLanguage = await localLanguageStateOf(run.runDir); } catch { localLanguage = null; }
85
+ }
86
+ injectScriptScopeCoverage(P, run.runDir, note, { searchPolicy: ctx.searchPolicy, job, profile: ctx.profile, localLanguage });
87
+ // — AFTER stateJxSlices, and the order is load-bearing: this reads `fold.depth`, which the call
88
+ // above mints. Before it, every run would look like one that never stated a verdict. Its sibling one
89
+ // line up covers the lane that did not run; this covers the lane that ran short of what was bought.
90
+ injectLaneDepthCoverage(P, run.runDir, note);
91
+ // The third sibling: each mark the screen-gate disclosed as unexamined
92
+ // gets its own reader-visible coverage row (guarded on the ctx/sidecar unresolved set; idempotent by
93
+ // mark+uri). The CONDITIONAL clamp came from applyCoverageFloor's screenGateGap arm above, never
94
+ // from these coverage-limited rows.
95
+ injectScreenGateCoverage(P, run.runDir, note, ctx);
96
+ // — the fourth sibling, and the one that REPLACES rather than adds: coverage_judgment.rows
97
+ // is derived from the machine ledger and the plan-execution receipt instead of retyped by the seat.
98
+ // Same seam and same reason as injectDeferralCoverage above — every synthesis re-run has settled, so
99
+ // a re-emit cannot clobber it; and it lands before report-overview and the cards, which are stamped
100
+ // afterwards and therefore never read it as staleness.
101
+ stampCoverageJudgmentRows(P, run.runDir, note, ctx);
102
+ consolidateFindingsFile(P, note, ctx.framework);
103
+ // The conditions too: a save that rewrote, withdrew or added a forward legal step moves the list with it.
104
+ followTheRecordsActions("after a save of the record");
105
+ // T2: consolidation can change the live composite set — re-derive the sidecar so every
106
+ // surface joins the FINAL findings (the sidecar must never describe a superseded set).
107
+ // review fix: consolidation can also surface CONDITIONS the floor never saw (a lenient-
108
+ // quarantined action healed by the strict rewrite, or a transient read failure at floor time) —
109
+ // the sidecar's CLEAR-with-conditions throw then re-runs the FLOOR once instead of bricking a
110
+ // delivery the later lint repair was built to heal.
111
+ try { writeVerdictSidecar(); }
112
+ catch (e) {
113
+ note(`verdict sidecar refresh: ${String(e.message).slice(0, 100)} — re-deriving the floor once`);
114
+ applyCoverageFloor();
115
+ try { writeVerdictSidecar(); }
116
+ catch (e2) { throw new StageFailure("verdict", `verdict sidecar refresh failed after consolidation: ${String(e2.message).slice(0, 120)}`); }
117
+ }
118
+ };
119
+ // THE RECORD THE CARDS ARE BUILT ON CARRIES EVERY DEMOTION. The derivation settled the record after the first
120
+ // synthesis save; a corrective pass saves again before this seam, and a whole re-send brings back every stamp it had
121
+ // demoted. Built on those, every card whose finding carried one read as stale after the derivation before delivery
122
+ // demoted them again, and was rebuilt with the overview for a finding nothing had changed. Settled here, once more,
123
+ // before the overview and the cards; idempotent on a record that already carries every demotion.
124
+ settleDerivedBases(ctx, "seam");
125
+ await seamWrites();
126
+ // Every write above is idempotent: each injection skips a row the record already carries, the stamp
127
+ // replaces its rows, and the fold leaves a folded record as it is.
128
+ ctx.afterSynthesisSave = async () => {
129
+ note(`[seam] a synthesis save after the seam rewrote findings.json — re-applying the seam's writes`);
130
+ runLog(run.runDir, { event: "seam-reapplied", after: "synthesis-save" });
131
+ rewriteFromBeforeTheSeam(ctx); // the basis derivation and the deadline enrichment, as the pass made them
132
+ await seamWrites();
133
+ };
134
+ // wp50/wi2 — the overview PROSE must speak the derived tier (VENZY: caption said "High risk" while
135
+ // every code surface said VERY HIGH). Thread the just-refreshed sidecar into the stage prompt; the
136
+ // deterministic backstop is predelivery-lint's overallTierChecks.
137
+ runState.displayVerdict = null;
138
+ try { runState.displayVerdict = JSON.parse(readFileSync(paths(run.runDir).verdict, "utf8")); } catch { /* legacy — prompt line omitted */ }
139
+ // ── CONVERSION 4 — THE DRIVER'S OWN FRONT-MATTER RECORD ──────────────────────────────────────
140
+ //
141
+ // Nine of report-overview.md's ten front-matter keys are values the driver already holds and used to
142
+ // hand the seat in the dispatch so the seat could type them back into a file the driver then parsed.
143
+ // They are written here, from the same `job` object `frontMatterIdentity` read, at the same point in
144
+ // the run — so the record and the old dictation cannot disagree about what the values were.
145
+ //
146
+ // NOT added to `_driver/instructed-scope.json`, and that is a live guard rather than a preference:
147
+ // `validators.matterContext` compares the matter frame against EVERY VALUE in that file, so a key
148
+ // added there becomes a value the FRAME must quote verbatim. Conversion 4 would have failed a
149
+ // different stage's validator, on a field neither stage is about.
150
+ //
151
+ // `classes` is the INSTRUCTED list, which is what the seat typed too. applyScopeFrontMatter still
152
+ // stamps the authoritative `classes_line` from _driver/scope-facts.json at assembly (that sidecar is
153
+ // written after this stage runs, so it cannot be read here), and applyVerdictFrontMatter still stamps
154
+ // overall_label/overall_badge. This removes the SEAT from those keys; it does not touch the driver's
155
+ // own authority over them.
156
+ try {
157
+ ensureDriverDir(run.runDir);
158
+ writeFileSync(join(run.runDir, REPORT_IDENTITY_FILE), JSON.stringify(reportIdentityRecord(job, ctx, run.runDir, runState.displayVerdict), null, 2) + "\n");
159
+ } catch (e) { note(`report identity write failed (non-fatal — the shell renders the keys it has): ${e.message}`); }
160
+ // THE REPORT OVERVIEW, WHERE IT COULD NOT BE COMPLETED (parts-not-completed.mjs). Its recovery was spent, so the report
161
+ // delivers its rating and its cards without the overview's conclusion, and the workbook's shipped "Summary" row says
162
+ // so. The shell the overview would have written is the driver's own, with the run's identity and no conclusion, and
163
+ // no overview is dispatched again on this pass: not here, not by the lint's redo, not by the delivery check's repair.
164
+ const overviewOpen = readPartNotCompleted(run.runDir, "overview");
165
+ if (overviewOpen) {
166
+ writeFileSync(P.reportOverview, renderReportOverview({ overall_caption: null, handling_note: null, actions: [], methodology: null },
167
+ reportIdentityRecord(job, ctx, run.runDir, runState.displayVerdict)));
168
+ runLog(run.runDir, { event: "overview-not-completed-delivery", stage: overviewOpen.stage ?? null });
169
+ }
170
+ const rov = overviewOpen ? null
171
+ : await asPartNotCompleted("overview", async () => must(await stage("report-overview", { ...ctx, displayVerdict: runState.displayVerdict }, {}), "report-overview")); // T3a: a BLOCKING run now DELIVERS; its open points are rendered at assembly, not dispatched here
172
+ const findingsRead = readFindingsForReport(P);
173
+ const findingsForCards = findingsRead.findings;
174
+ //: a rejected findings.json is a defect, not an emptiness. Say so HERE, where the file was read,
175
+ // with the validator's own token — the card loop below can only observe the consequence.
176
+ if (findingsRead.rejected) note(`findings.json is present and REJECTED by the strict parser (${findingsRead.rejected}) — joining ${findingsForCards.length} finding(s) leniently for the card match; the delivery guard still refuses`);
177
+ // P2 clause 3 — assigned in the lint block below, consumed by the freshness precondition before the
178
+ // client gate. Declared here so both live in the same scope regardless of the lint block's nesting.
179
+ runState.staleStages = [];
180
+ runState.staleOnTheDeliveryPath = () => runState.staleStages; // the same question, asked again: set where the lint block asks it
181
+ // ── §9 — THE CARD SET IS `fullProseOrdinals ∧ form === "full"` ───────────────────────────
182
+ //
183
+ // On one country every form is `full`, so this reduces to `fullProseOrdinals` — the same list, in the
184
+ // same order, dispatching the same cards. That is the byte-identical argument in its structural form
185
+ // rather than as a diff someone has to re-run.
186
+ //
187
+ // On a graded product the findings that drop out are NOT lost: they render as a short entry or a
188
+ // grouped line, built code-side from the typed `net` already in findings.json. What they stop costing
189
+ // is a card DISPATCH — a paid model turn per mark — which is the whole saving §8 claims.
190
+ //
191
+ // The floor tier joins on `mark_text` (see floorTierByMark): joining on `mark` returns a clean,
192
+ // plausible zero, and a zero here means every floor row quietly loses the full card the owner made
193
+ // non-negotiable. An absent band-shape yields an empty map and every finding reads as holding no
194
+ // floor — which is what it did before this existed.
195
+ // The plan is made in one place (planWriteUps), the same way here and wherever a later save changes the record:
196
+ // the full cards in the record's order, then the remainder, in the same order, for the short-entry and grouped-row
197
+ // render below.
198
+ const writeUps = planWriteUps(findingsForCards, ctx.depth, safeReadJson(P.bandShape));
199
+ const { cardOrdinals, entryOrdinals } = writeUps;
200
+ // §9 — WRITTEN ON EVERY GRADED PRODUCT, INCLUDING ONE WHOSE ENTRY COUNT IS 0. The old gate was
201
+ // `entryOrdinals.length`, which conflated two different empties: one country is empty BY CONSTRUCTION
202
+ // (every form is `full`, so the row would report the product's own definition back), while a graded run
203
+ // where every finding earned a card is empty AS A MEASUREMENT — a fact about that run's population, and
204
+ // the exact shape the ladder is asked to justify. Under the old gate that measurement was indistinguishable
205
+ // from a run predating the gauge. Gate on the rung, never on the count. My defect, from this section.
206
+ if (gradedWriteUpRung(ctx.depth))
207
+ runLog(run.runDir, { event: "write-up-forms", full: cardOrdinals.length, entry: entryOrdinals.length,
208
+ depth: ctx.depth?.source ?? null });
209
+ if (cardOrdinals.length) mkdirSync(P.reportCardsDir, { recursive: true });
210
+ // T7 (E5): each card gets ITS matched grounded case-law profile INLINE — the old
211
+ // "if the file exists, fish in it" instruction was model-discretionary and missed cards.
212
+ let caseLawByOrd = new Map();
213
+ try {
214
+ if (existsSync(P.caseLaw)) caseLawByOrd = caseLawJoin(P, findingsForCards);
215
+ } catch { /* no case-law layer */ }
216
+ // A2 — cards are isolated BY DESIGN (each sees ONLY its own finding and writes its own
217
+ // P.reportCard(ord) file), so they fan out like the gather members instead of paying 8–14 serial
218
+ // LLM walls. The first card runs alone to warm the shared prompt-prefix cache; the rest batch at
219
+ // gatherConcurrency. A failed card stays non-fatal (render shows it structured-only) and never
220
+ // fails a sibling — renderCard resolves on rc.fail, it never throws. assembleReportMd runs
221
+ // strictly after every card settles; the lint-repair re-render loop below stays serial.
222
+ const cardFindings = findingsForCards.filter((f) => cardOrdinals.includes(f.ordinal)); // secondary findings render structured-only (no LLM call)
223
+ // A CONTENT failure stays non-fatal: the render shows that finding structured-only, which is a
224
+ // thinner card, not a missing one. A RATE LIMIT is not a content failure — it is the engine's
225
+ // session cap, and swallowing it ships a report whose cards are thin because we were throttled,
226
+ // with nothing saying so. Every other stage routes that to the postpone lane and delivers complete
227
+ // later; cards were the exception only because the fan-out was too narrow to hit it often. Collected
228
+ // here and raised after the fan-out settles, so one throttled card cannot abandon its siblings.
229
+ const cardRateLimited = [];
230
+ const renderCard = async (f) => {
231
+ const rc = await stage("report-card", { ...ctx, axis: String(f.ordinal), finding: f, caseLawProfile: caseLawByOrd.get(f.ordinal) ?? null }, {});
232
+ if (rc.ok) return;
233
+ if (rc.fail === "rate_limited" && !existsSync(P.reportCard(String(f.ordinal)))) {
234
+ cardRateLimited.push({ ordinal: f.ordinal, resetsAt: rc.resetsAt ?? null });
235
+ return;
236
+ }
237
+ note(`report-card[${f.ordinal}] failed (non-fatal — render shows it structured-only): ${rc.fail}`);
238
+ };
239
+ if (cardFindings.length) await renderCard(cardFindings[0]);
240
+ // — THE ONE SETTING ALLOWED TO FALL BACK IS NOT ALLOWED TO DO IT QUIETLY. Every
241
+ // other numeric setting refuses a value it cannot parse, by name, at the read. This one is read
242
+ // mid-run and is not grade-moving, so refusing would turn a delivering search into a refusal over an
243
+ // operator's typo — the run continues on the default instead. It says so here, once, in the run's own
244
+ // record: a fallback nobody can see is how a deployment ends up running on a number nobody chose,
245
+ // which is the same defect one register quieter.
246
+ const cardCapNote = fallbackNoteFor("CLEAROTRON_CARD_CONCURRENCY");
247
+ if (cardCapNote) note(`[config] ${cardCapNote}`);
248
+ await runBatched(cardFindings.slice(1), config.cardConcurrency, renderCard);
249
+ if (cardRateLimited.length) {
250
+ const earliest = cardRateLimited.map((c) => c.resetsAt).filter(Boolean).sort()[0] ?? null;
251
+ runLog(run.runDir, { event: "report-cards-rate-limited", count: cardRateLimited.length,
252
+ ordinals: cardRateLimited.map((c) => c.ordinal), resetsAt: earliest });
253
+ // Resumable by construction: the cards that DID land are file-gated and skip on the resume, so
254
+ // the postpone costs only what the cap actually blocked.
255
+ throw new StageFailure("report-card", "rate_limited", earliest);
256
+ }
257
+ // ── §8 — THE TWO GRADED FORMS, WRITTEN CODE-SIDE ────────────────────────────────────────
258
+ //
259
+ // Every entry finding is either a SHORT ENTRY (its own card file, composed from the typed `net` — no
260
+ // dispatch) or a member of a GROUP (a line in the sibling section below). §8 sets the minimum group
261
+ // size at two and renders the remainder as short entries, so `singles` is exactly that remainder.
262
+ //
263
+ // WORLDWIDE GROUPS BY THE RIGHT, multi-country by territory. The flag is derived from the depth row
264
+ // rather than a product name so the two cannot drift: the worldwide row is the one whose prose rung
265
+ // is `adversarial`, multi-country's is `adversarial+floors`, and both come from the same table.
266
+ //
267
+ // The bodies are written to the SAME card files a dispatched card would use, so `assembleReportMd`
268
+ // frames them with the same composer and the ordinal binding is untouched. What they never get is a
269
+ // model turn — the whole saving.
270
+ const { entryFindings, byRight, entrySingles } = writeUps;
271
+ writeShortEntries(P, entrySingles);
272
+ // Assembly sees full cards AND short entries; the DISPATCH set and the freshness stage list stay
273
+ // `cardOrdinals`, because a short entry has no stage and never had one.
274
+ const { assembledOrdinals, groupedMembers } = writeUps;
275
+ if (entryFindings.length)
276
+ note(`write-up forms: ${cardOrdinals.length} full card(s), ${entrySingles.length} short entr(y/ies), ${groupedMembers.length} grouped line(s)`);
277
+ assembleReportMd(P, findingsForCards, assembledOrdinals, { grouped: groupedMembers, byRight });
278
+ // The client-summary inclusion scope (WP-56 A4) and its _driver/client-summary-scope.json sidecar
279
+ // are DELETED with the stage (2026-08-01) — they existed only to dictate which cards that stage
280
+ // had to carry. verify.mjs's checkClientSummaryJoin still reads the sidecar when replaying an
281
+ // archived run that has one; a live run writes none, and that check already skips when it is absent.
282
+
283
+ // The WS1c failover-transparency stamp (`failoverModel` + `failover_note` into report.md front-matter,
284
+ // rendered by composeEmailHtml as a "Model failover:" line) stood here and is DELETED. It could
285
+ // never fire: it read ctx.failovers, which only a fired chain rung ever wrote, and the chain had exactly
286
+ // one rung. No code path can put a failover note in a report now — that is the point of the issue.
287
+
288
+ // T2 (H5) — the report's overall label/badge/recommendation are DRIVER-OWNED, derived from
289
+ // the verdict sidecar: the model-authored fm.overall_label was the second verdict authority that let
290
+ // the hero contradict the reviewer verdict AND the client tier. Kept as a closure because a lint-repair
291
+ // redo re-emits report.md, so every driver-owned front-matter field is re-applied after it.
292
+ const applyVerdictFrontMatter = () => {
293
+ let v = null;
294
+ try { v = JSON.parse(readFileSync(paths(run.runDir).verdict, "utf8")); } catch { return; }
295
+ if (!v?.tier) return;
296
+ const fields = { overall_label: v.tier, overall_badge: v.badge };
297
+ try {
298
+ const fmBlock = readFileSync(P.report, "utf8").match(/^---\n([\s\S]*?)\n---\n/)?.[1] ?? "";
299
+ const rec = fmBlock.match(/^recommendation:\s*(.+)$/m)?.[1];
300
+ if (rec != null) {
301
+ const bound = bindRecommendation(rec, v.verdict, v.reasons);
302
+ if (bound !== rec.trim()) fields.recommendation = bound;
303
+ }
304
+ } catch { /* report absent — injectFrontMatter no-ops anyway */ }
305
+ const wrote = injectFrontMatter(P.report, fields, run.runDir);
306
+ if (wrote) runLog(run.runDir, { event: "verdict-frontmatter", tier: v.tier, badge: v.badge, verdict: v.verdict });
307
+ };
308
+ applyVerdictFrontMatter();
309
+ // compute-don't-author (PR-4) — the masthead's SCOPE line is DRIVER-OWNED, like the verdict labels
310
+ // above: the model-typed `classes:` value was the second scope authority that let the masthead say
311
+ // "searched" over a class three machine stores called dispatched-but-not-enumerated (the 2026-07-28 postmortem run).
312
+ // writeScopeFacts derives _driver/scope-facts.json (pure join: instructed-scope × frozen plan ×
313
+ // band states × coverage ledger — scope-facts.mjs); applyScopeFrontMatter overwrites `classes:`
314
+ // and injects `coverage_line:` from it. Recomputed + re-applied after every lint-repair
315
+ // reassembly (same discipline as applyVerdictFrontMatter); ZERO render.mjs change — the frozen
316
+ // renderer keeps rendering fm.classes verbatim, we changed WHO AUTHORS the value.
317
+ const writeScopeFacts = () => writeScopeFactsOf(ctx, P, run.runDir);
318
+ const applyScopeFrontMatter = () => applyScopeFrontMatterOf(P, run.runDir);
319
+ writeScopeFacts();
320
+ applyScopeFrontMatter();
321
+ // T9 (K3) — DISCLOSE which profile/framework rated this run (+ the verifiable sha).
322
+ // Methodology identity, not QC — it renders on the internal report, the client summary footer
323
+ // and the email ( F7: nothing disclosed which framework rated a run, so K1 was untestable).
324
+ // PR-11: ONE closure, like its applyVerdictFrontMatter / applyScopeFrontMatter
325
+ // siblings. The lint-repair reassembly branch below re-applies the same driver-owned front matter, and
326
+ // it used to do it from a VERBATIM PASTE of this block ~500 lines away — two copies that had to be
327
+ // edited in lockstep forever, with nothing to catch a drift.
328
+ const applyRatedUnderFrontMatter = () => {
329
+ const pr = ctx.profile;
330
+ if (pr?.name || pr?.profileKey) {
331
+ // doc 50 — say WHICH of the two is in force in words a human notices: the customer's own
332
+ // framework (title + file) or the Generic default. The manifest title comes from the frozen
333
+ // framework sidecar, so the disclosure can never drift from what actually rated the run.
334
+ // — THIS LINE IS READ BY A LAWYER, AND IT SHIPPED A HASH AND A FILENAME. It rendered as
335
+ // "… · custom framework: <title> (risk-framework-<slug>.md) · profile e186ce0adbfc". The sha is
336
+ // telemetry — it identifies a config revision to us and nothing at all to the reader — and the
337
+ // filename is the title again in machine form. Both are DROPPED from the client surface; both
338
+ // are still recorded, in `run.jsonl`'s methodology-witness and `_driver/methodology-read.json`,
339
+ // which is where anyone asking "which revision rated this run" is actually looking.
340
+ injectFrontMatter(P.report, { rated_under: ratedUnderLine(pr, ctx.framework) }, run.runDir);
341
+ // spec 62 — beside the framework disclosure, name WHICH PROJECT rated this run (the customer's own
342
+ // display name in parentheses), plus the per-field configuration-provenance rows (rendered internal-only
343
+ // in the scope fold). Omitted entirely for a no-project run (pr.projectKey absent).
344
+ if (pr.projectKey) {
345
+ injectFrontMatter(P.report, { run_under_project: `${pr.projectName ?? pr.projectKey} (${pr.name ?? pr.profileKey})` }, run.runDir);
346
+ const originRows = originRowsForReport(pr);
347
+ if (originRows.length) injectFrontMatter(P.report, { origins_json: JSON.stringify(originRows) }, run.runDir);
348
+ }
349
+ }
350
+ };
351
+ applyRatedUnderFrontMatter();
352
+
353
+ // A1b (the client-summary stage dispatch) is RETIRED 2026-08-01. Its output reached no reader
354
+ // after the one-report collapse, and it was not free: on the R2 evidence run it burned 931s over
355
+ // five dispatches, three of them failing identically until the ladder exhausted.
356
+ // composeEmailHtml now takes its headline tier from the verdict sidecar and its conditions from
357
+ // the report's own `# Actions`.
358
+
359
+ // A FINDINGS RECORD BROKEN AFTER SYNTHESIS PASSED IT IS RESTORED, NOT ENDED ON. It is checked as the delivery
360
+ // gate checks it, before the audit and the delivery checks are built from it, and again at that gate. A broken record
361
+ // comes back from the last save that passed (restoreTheRecordThatPassed). A save rebuilt with the duty set aside is
362
+ // judged again here, as after a rollback, and the corrections a save from before the repair lacks close the client
363
+ // export (correctionsTheRestoreLacks). With no save to restore, the failure is the assessment not completed: its
364
+ // recovery re-runs synthesis, which a broken record does not let skip, and once that is spent the run delivers
365
+ // without the assessment. Returns the restore, or null where no save passes.
366
+ const restoreTheBrokenRecord = async (failures, where) => {
367
+ const restored = await restoreTheRecordThatPassed(ctx, P, run.runDir, (raw) => { parseFindingsJsonLenient(raw); });
368
+ if (!restored) {
369
+ note(`core-artifact (${where}): ${failures.join("; ")} — no save passes either, so the assessment is not completed`);
370
+ return null;
371
+ }
372
+ const lacks = correctionsTheRestoreLacks(run.runDir, restored.from);
373
+ if (lacks.length) {
374
+ // Joined to what the state already holds: an earlier correction's names stay in the reason.
375
+ const at = paths(run.runDir).correctionsState;
376
+ const held = (() => { try { const s = JSON.parse(readFileSync(at, "utf8"))?.stale; return Array.isArray(s) ? s : []; } catch { return []; } })();
377
+ try { atomicWrite(at, JSON.stringify({ ts: new Date().toISOString(), stale: [...new Set([...held, ...lacks])] }, null, 2)); }
378
+ catch { /* the event below records it */ }
379
+ }
380
+ runLog(run.runDir, { event: "core-artifact-restored", where, from: restored.from, duty: restored.duty, ...(lacks.length ? { correctionsLacked: lacks.length } : {}) });
381
+ note(`core-artifact (${where}): ${failures.join("; ")} — the record is restored from the ${restored.from}, and the run delivers from it`);
382
+ if (restored.duty === "relaxed") {
383
+ const was = runState.verdict, stood = JSON.stringify(runState.clampReasons);
384
+ clampOnTheWritersDuty({ again: true });
385
+ if ((JSON.stringify(runState.clampReasons) !== stood || runState.verdict !== was) && saveTheLabel("after the record was restored")) applyVerdictFrontMatter();
386
+ }
387
+ return restored;
388
+ };
389
+ if (existsSync(P.findings)) {
390
+ let broken = null;
391
+ try { parseFindingsJsonLenient(readFileSync(P.findings, "utf8")); } catch (e) { broken = `findings.json — ${String(e.message).replace(/\s+/g, " ").slice(0, 140)}`; }
392
+ if (broken) {
393
+ runLog(run.runDir, { event: "core-artifact-invalid", failures: [broken], where: "delivery-checks" });
394
+ if (!(await restoreTheBrokenRecord([broken], "delivery-checks")))
395
+ throw Object.assign(new StageFailure("core-artifact-gate", `a core machine artifact is invalid and cannot ship: ${broken}`), { notCompletedPart: "assessment" });
396
+ }
397
+ }
398
+
399
+ // A2 — full audit: DETERMINISTIC CODE (parse the spine tables → audit.md, count-guarded). Replaces the LLM
400
+ // audit-emit (output varied 47↔69 on identical input). NON-FATAL: if it fails, the report still ships (publish
401
+ // renders the report with no xlsx when audit.md is absent), and the audit self-recovers on a re-run.
402
+ // `rebuildTheDeliveredRecord` is set by the block once the audit is written: the delivery check calls it after a repair.
403
+ let rebuildTheDeliveredRecord = null;
404
+ let auditWrittenThisPass = false, earlierPairKept = null;
405
+ try {
406
+ // One resolution per claim: hand the builder the run's OWN dispositions so a withdrawn conflict reads
407
+ // as withdrawn on the audit surface too (it already does on report + client summary). Best-effort —
408
+ // a malformed findings.json is validators.findings' business and must never cost us the audit.
409
+ let auditRunFindings = null, auditRunActions = [], auditRunCoverage = [];
410
+ try {
411
+ if (existsSync(P.findings)) {
412
+ const parsed = parseFindingsJsonLenient(readFileSync(P.findings, "utf8"));
413
+ auditRunFindings = parsed.findings;
414
+ auditRunActions = parsed.actions ?? [];
415
+ auditRunCoverage = parsed.coverage ?? []; // presence-or-reason: coverage-row areas join the delivered set
416
+ }
417
+ } catch { /* stamping is skipped; the audit still builds */ }
418
+
419
+ // HALF TWO, and the ONLY place this artifact is authored. Here because `auditRunFindings` is
420
+ // parsed immediately above, so the findings this joins against demonstrably exist — the property
421
+ // the digest-time derivation could not have and did not check. Everything downstream (the doubt
422
+ // mint below, the predelivery lint's `recordCarry` arms) reads THIS artifact rather than deriving
423
+ // its own: two derivations from different inputs is what let the doubt ledger be roughly right
424
+ // while the artifact and every lint arm were inverted.
425
+ // A resumed pass writes both again: what the earlier pass wrote is kept under _history first.
426
+ earlierPairKept = keepDeliveredRecordAsHistory(P, "earlier-pass");
427
+ deriveRecordCarry(ctx, "publish", { findings: auditRunFindings ?? [] });
428
+ // ── — AND NOW THE JOIN BETWEEN THE TWO ARTIFACTS THAT WERE EACH RIGHT ────────
429
+ //
430
+ // `recall-reconciliation.json` measured the DIGEST and reported `unended: 0`; the artifact written
431
+ // one line above measured REASONS and reported `unreasoned: 0`. Both true. Between them a position
432
+ // the digest ended as a FINDING was dropped at placement with `reason_source: "step-silent"` and
433
+ // the client lost the mark. Nothing read one against the other, so nothing could see it.
434
+ //
435
+ // HERE, for the same reason moved the carry here: this is where the findings demonstrably
436
+ // exist and where the artifact it joins has just been authored. Best-effort and never fatal — this
437
+ // seam does not gate delivery (that is the pre-verdict floor's job), it makes the loss SAYABLE.
438
+ try {
439
+ const silent = silentlyLostFindings({
440
+ reconciliation: safeReadJson(P.recallReconciliation),
441
+ carryRows: safeReadJson(P.recordCarry)?.rows ?? null,
442
+ // — the INDEPENDENT population, read from the typed calls by other code.
443
+ // Without it a reconciliation looking at an entirely different set answers "clean".
444
+ digestFindingUris: recordedFindingUris(P.runDir),
445
+ });
446
+ runLog(P.runDir, { event: "silently-lost-findings", computable: silent.computable,
447
+ reason: silent.reason, population_empty: silent.population_empty === true,
448
+ checked: silent.checked, matched: silent.matched, lost: silent.lost.length,
449
+ marks: silent.lost.map((l) => l.mark).filter(Boolean).slice(0, 10) });
450
+ if (silent.lost.length) {
451
+ note(`recall: ${silent.lost.length} position(s) the digest ended as FINDINGS reached no client `
452
+ + `surface and no step said why — ${silent.lost.map((l) => `${l.mark ?? l.uri} (${l.reason})`).join("; ")}`);
453
+ }
454
+ // ── AND THE STATED CASE, WHICH IS THE ONE THAT REACHED A CLIENT ────────────────────────────
455
+ //
456
+ // Same inputs, same seam, same best-effort contract — a second call rather than a widened first
457
+ // one, because the sibling's population boundary is deliberate and correct. It covers a
458
+ // finding-ending followed by SILENCE; this covers one followed by a SENTENCE.
459
+ //
460
+ // On a delivered R2 run the sibling logged `checked:5 matched:5 lost:0` — correctly — on a
461
+ // delivery missing two marks from the lawyer's final list, one rated HIGH. They were dropped with
462
+ // a reason, so they were outside its population by design. A drop with a reason nobody verifies
463
+ // is not accounted for; it is unexamined with a paper trail, and that delivery carried 66 of them.
464
+ const stated = statedDivergenceFindings({
465
+ reconciliation: safeReadJson(P.recallReconciliation),
466
+ carryRows: safeReadJson(P.recordCarry)?.rows ?? null,
467
+ digestFindingUris: recordedFindingUris(P.runDir),
468
+ });
469
+ runLog(P.runDir, { event: "stated-divergence-findings", computable: stated.computable,
470
+ reason: stated.reason, population_empty: stated.population_empty === true,
471
+ checked: stated.checked, matched: stated.matched, diverged: stated.diverged.length,
472
+ marks: stated.diverged.map((d) => d.mark).filter(Boolean).slice(0, 10) });
473
+ if (stated.diverged.length) {
474
+ note(`recall: ${stated.diverged.length} position(s) the digest ended as FINDINGS are absent from `
475
+ + "the findings and were dropped with a STATED reason pointing at another artifact — "
476
+ + stated.diverged.map((d) => `${d.mark ?? d.uri} (${d.reason}${d.cites_artifact ? ` → ${d.cites_artifact.join(", ")}` : ""})`).join("; "));
477
+ }
478
+ } catch (e) { /* never mask a delivery */ }
479
+ // — the common-law path, and the jx zh slice on the same tracer. `consumed` used to read
480
+ // CLEAROTRON_JX_CONSUME, which decided whether a zh candidate could reach a finding at all: with it
481
+ // off every candidate was `shadow:not-consumed`, a configuration boundary rather than a judgment.
482
+ // item 8 deleted the switch, and had already recorded production running with it ON —
483
+ // so `consumed` is now unconditionally true, which is the state that comment said we were leaving
484
+ // for. An armed slice flows through the ordinary reason classes with no second code path, and
485
+ // `shadow:not-consumed` becomes unreachable rather than merely unused.
486
+ deriveCommonLawCarry(ctx, "publish");
487
+ if (existsSync(P.jxZhGrid)) {
488
+ deriveCommonLawCarry(ctx, "publish", {
489
+ slice: "jx-zh-grid", gridPath: P.jxZhGrid, outPath: P.jxZhCarry,
490
+ consumed: true,
491
+ });
492
+ }
493
+ // THE HAND-OFFS' EXITS WITH NO GROUND, read off the record trace written just above and the findings
494
+ // parsed before them: a record that left the picking step, and a page the web notes marked as a
495
+ // candidate or conflict that no delivered finding cites, each with nothing saying why. A page the web
496
+ // step only read is not owed a ground, so the grid's rows are not counted here. It reports and never
497
+ // gates, and a missing trace says so by name rather than counting zero.
498
+ try {
499
+ const exits = { picking: pickingExits(safeReadJson(P.recordCarry)),
500
+ notes: notesExits(existsSync(P.commonLaw) ? readFileSync(P.commonLaw, "utf8") : null, auditRunFindings, readDeclinations(P.runDir).byPage) };
501
+ runLog(P.runDir, { event: "reasonless-exits", lane: "clearance", ...exitsForLog(exits) });
502
+ if (exits.picking.exits || exits.notes.exits) {
503
+ note(`hand-offs: ${exits.picking.exits} record(s) of ${exits.picking.owners ?? 0} owner(s) left the picking step `
504
+ + `with no ground; ${exits.notes.exits} page(s) the web notes marked as candidates or conflicts reached no delivered `
505
+ + `finding and no step said why`);
506
+ }
507
+ } catch { /* never mask a delivery */ }
508
+
509
+ const registerFindingsText = readFileSync(P.registerFindings, "utf8");
510
+ const commonLawText = existsSync(P.commonLaw) ? readFileSync(P.commonLaw, "utf8") : "";
511
+
512
+ // Doubt stitching (2026-07-22 — the copper-gantry defect): mint every doubt the run RAISED (the
513
+ // gathers' dictated `CROSS-CHECK REQUIRED:` hand-off lines; asserted⇄refuted contradiction pairs
514
+ // among the audit's own Findings blocks) and stitch each to a resolution the run ALREADY produced
515
+ // (a findings.json disposition/action, a coverage-ledger row, a register-findings answer/watchlist
516
+ // line). Pure join-and-record: nothing re-searches, nothing retries, and an unstitchable doubt
517
+ // ships VISIBLY as OPEN in the audit's # Doubt Ledger — delivery is never gated on a doubt.
518
+ // NON-FATAL end to end: a failure here logs `doubts-failed` and the audit builds without a ledger.
519
+ let runDoubts = null;
520
+ // — one row per mint that actually dropped something: {source, minted, omitted}. Empty on
521
+ // the overwhelming majority of runs, and an empty array renders nothing at all.
522
+ const doubtTruncations = [];
523
+ // ── PR-6: the ASK LEDGER (2026-07-29) — every question the run asked ITSELF ends: executed
524
+ // (COMPUTED from the plan-execution join, never asserted), judged-immaterial with reasons, or
525
+ // recovery (loudly handed over). Derived HERE, at the audit seam, as a deterministic join over
526
+ // the ten birth-places' own receipts (ask-ledger.mjs documents the list). Open rows ride the
527
+ // SAME doubt-closure stage below (dictated ASK line-form; IMMATERIAL always available — the
528
+ // terminating move); still-open rows ship VISIBLY OPEN. Never a gate, no count thresholds, and
529
+ // no cost figure anywhere near closure. NON-FATAL end to end (`asks-failed`).
530
+ let runAsks = null;
531
+ const askTs = new Date().toISOString();
532
+ try {
533
+ const readJson = (p) => { try { return existsSync(p) ? JSON.parse(readFileSync(p, "utf8")) : null; } catch { return null; } };
534
+ const runEvents = (() => {
535
+ try {
536
+ return readFileSync(paths(run.runDir).run, "utf8").split("\n")
537
+ .filter(Boolean).map((l) => { try { return JSON.parse(l); } catch { return null; } }).filter(Boolean);
538
+ } catch { return []; }
539
+ })();
540
+ const unitsDirForAsks = join(run.runDir, "register-units");
541
+ const supplementalPlans = existsSync(unitsDirForAsks)
542
+ ? readdirSync(unitsDirForAsks).filter((n) => n.endsWith("-supplemental-plan.json")).sort().map((n) => {
543
+ const doc = readJson(join(unitsDirForAsks, n));
544
+ return { axis: n.replace(/-supplemental-plan\.json$/, ""), entries: doc?.entries ?? [], rejected: doc?.rejected ?? [] };
545
+ })
546
+ : [];
547
+ runAsks = deriveAsks({
548
+ intakeAsks: ctx.intakeAsks ?? readJson(paths(run.runDir).intakeAsks)?.asks ?? [],
549
+ reportMd: existsSync(P.report) ? readFileSync(P.report, "utf8") : "",
550
+ escalationState: readJson(paths(run.runDir).escalationState),
551
+ events: runEvents,
552
+ frameReopen: readJson(paths(run.runDir).frameReopenReceipt),
553
+ screenGateUnresolved: readJson(paths(run.runDir).screenGateUnresolved)?.unresolved ?? null,
554
+ supplementalPlans,
555
+ xcheck: readJson(paths(run.runDir).registerXcheck),
556
+ recall: recallReceiptForOwnCompany(readJson(paths(run.runDir).registerRecall)), // never another company's recall line
557
+ withheldFamilies: readWithheldFamilies(run.runDir), // the reading turn's reasons, for a frame ask its judgment settled
558
+ planExecution: ctx.planExecution ?? readJson(P.planExecution),
559
+ }, { ts: askTs });
560
+ } catch (e) {
561
+ runAsks = null; // the audit builds ask-less, exactly like a legacy caller
562
+ runLog(run.runDir, { event: "asks-failed", error: e.message });
563
+ }
564
+ try {
565
+ const doubts = [
566
+ ...mintCrossCheckDoubts(commonLawText, basename(P.commonLaw)),
567
+ ...mintContradictionDoubts(parseSpineFindingBlocks(registerFindingsText, commonLawText)),
568
+ ];
569
+ // register unit digests carry the register-side hand-off lines (one file per axis)
570
+ const unitsDir = join(run.runDir, "register-units");
571
+ if (existsSync(unitsDir)) {
572
+ for (const f of readdirSync(unitsDir).filter((n) => n.endsWith(".md")).sort()) {
573
+ doubts.push(...mintCrossCheckDoubts(readFileSync(join(unitsDir, f), "utf8"), `register-units/${f}`));
574
+ }
575
+ }
576
+ // coverage rows: the machine mirror when it survived (best-effort — a missing/invalid ledger
577
+ // just means one fewer resolution source, never a failed stitch pass)
578
+ let coverageRows = [];
579
+ try {
580
+ if (existsSync(P.registerCoverageLedger)) {
581
+ const rows = JSON.parse(readFileSync(P.registerCoverageLedger, "utf8"));
582
+ if (Array.isArray(rows)) coverageRows = rows;
583
+ }
584
+ } catch { /* prose-only run — findings + register-findings joins still stitch */ }
585
+ // Presence-or-reason (2026-07-22 — the unjoined-Sheet-2 leak): every digest row the funnel
586
+ // rated on-field (the Risk-relevant / Incumbent-context sheets) must end in PRESENCE on a
587
+ // delivered surface or a RECORDED reason; synthesis's drop stands, but a silent drop mints a
588
+ // doubt into the same stitch → doubt-closure → # Doubt Ledger chain as every other family.
589
+ doubts.push(...mintPresenceDoubts(registerFindingsText, {
590
+ findings: { findings: auditRunFindings ?? [], actions: auditRunActions, coverage: auditRunCoverage },
591
+ coverageRows, sourceName: basename(P.registerFindings),
592
+ }));
593
+ // — the placement→digest carry join's two unanswered classes. Derived HERE against
594
+ // `registerFindingsText`, the findings file that actually shipped, NOT read back from
595
+ // _driver/placement-carry.json. The artifact is a per-PASS record and register-findings.md is
596
+ // rewritten after the last digest pass by the corrective and lint-repair paths, so minting
597
+ // from it would put losses in the Doubt Ledger of a run that closed them — a false loss on a
598
+ // clean delivery, which is worse than the silence this whole join replaces. The artifact stays
599
+ // the history; the doubt is decided against the delivered text. Both classes mint and they stay
600
+ // APART: `uncarried` is a loss, `unclassified` is the join saying it cannot tell — folding the
601
+ // second into the first, or dropping it, would rebuild the silent drop one level up. A run with
602
+ // no placements.json mints nothing, exactly as before.
603
+ try {
604
+ const placedNow = parsePlacementsJson(readFileSync(P.placementModel, "utf8")).placements;
605
+ doubts.push(...mintPlacementCarryDoubts(
606
+ reconcilePlacementCarry({ placements: placedNow, registerFindingsText }),
607
+ { sourceName: basename(P.placementModel) },
608
+ ));
609
+ } catch { /* absent, pre-B2 or malformed — validators.placement's business, not this mint's */ }
610
+ // — the seam before that one: a RETRIEVED record that reached a step obliged to speak
611
+ // about it and got no ground from anybody. Re-derived against the delivered findings text for
612
+ // exactly the reason the carry mint above is, and capped, because this list is unbounded by
613
+ // construction (a wholly failed digest could put every placed record in it and drown the
614
+ // ledger) — the artifact always carries the full list, and the cap reports what it omitted so
615
+ // the truncation is itself visible. `stage-incomplete` drops mint NOTHING here: those carry a
616
+ // structural reason already, and the run.jsonl row plus the note carry that fact.
617
+ // — READ, no longer re-derived. This mint used to build its own trace from `auditRunFindings`,
618
+ // which made it correct-by-construction while `_driver/record-carry.json` — written back at
619
+ // register-digest time, before findings.json existed — was inverted, and the predelivery lint reads
620
+ // the artifact. So the doubt ledger has been roughly right and every lint arm wrong on the same
621
+ // run. One derivation, written once above, consumed by both.
622
+ try {
623
+ const rc = safeReadJson(P.recordCarry);
624
+ if (rc?.computable === true) {
625
+ const minted = mintRecordCarryDoubts(rc);
626
+ doubts.push(...minted.doubts);
627
+ // — the note STAYS (it is the live operator's line) and it is no longer the only
628
+ // record. `note` writes the run log, which is purged with the run dir, so on a delivered
629
+ // run a ledger sitting at exactly the cap read as a complete one. The row below travels
630
+ // to the audit, which is retained.
631
+ if (minted.omitted) {
632
+ doubtTruncations.push({ source: "record-carry", minted: minted.minted, omitted: minted.omitted });
633
+ note(`record-carry: ${minted.omitted} further unreasoned drop(s) beyond the ${minted.minted} minted are in _driver/record-carry.json .unreasoned but NOT in the doubt ledger`);
634
+ }
635
+ }
636
+ } catch { /* no band this run — a register-less matter mints nothing, exactly as before */ }
637
+ // — the same, one path over. Read from the artifact for the same reason: two derivations
638
+ // from different inputs is how the register half came to have a right doubt ledger and a wrong
639
+ // artifact on the same run.
640
+ for (const p of [P.commonLawCarry, P.jxZhCarry]) {
641
+ try {
642
+ const cc = safeReadJson(p);
643
+ if (cc?.computable !== true) continue;
644
+ const minted = mintCommonLawCarryDoubts(cc);
645
+ doubts.push(...minted.doubts);
646
+ //, one path over — and the SLICE is carried, because this mint runs per slice and a
647
+ // reader told "12 omitted" twice with no slice cannot tell two truncations from one.
648
+ if (minted.omitted) {
649
+ doubtTruncations.push({ source: `commonlaw-carry (${cc.slice})`, minted: minted.minted, omitted: minted.omitted });
650
+ note(`commonlaw-carry (${cc.slice}): ${minted.omitted} further unreasoned drop(s) beyond the ${minted.minted} minted are in ${basename(p)} .unreasoned but NOT in the doubt ledger`);
651
+ }
652
+ } catch { /* no common-law pass this run — a register-only matter mints nothing */ }
653
+ }
654
+ // — the remedy terms the reopen could not put on the record. Read back from the receipt
655
+ // (unlike the placement carry, which re-derives against the delivered findings): this ledger is
656
+ // a record of what the EXECUTOR did, and nothing after the reopen can retroactively make an
657
+ // undispatched term dispatched, so the receipt is the authority and re-deriving would need band
658
+ // blocks the audit seam has no reason to hold. A `searched-empty` term mints nothing — it is
659
+ // answered — and nor does one the reading turn's recorded judgment settled (SETTLED_CLASSES). A run
660
+ // with no reopen, or a legacy receipt with no term rows, mints nothing.
661
+ try {
662
+ const fr = JSON.parse(readFileSync(paths(run.runDir).frameReopenReceipt, "utf8"));
663
+ if (Array.isArray(fr?.remedy_terms)) {
664
+ doubts.push(...mintRemedyAccountingDoubts(
665
+ { not_accounted: fr.remedy_terms.filter((r) => !SETTLED_CLASSES.includes(r?.class)) },
666
+ { sourceName: "_driver/frame-reopen.json" },
667
+ ));
668
+ }
669
+ } catch { /* no reopen this run, or an unreadable receipt — the reopen's own arms already disclosed */ }
670
+ runDoubts = stitchDoubts(doubts, {
671
+ findings: { findings: auditRunFindings ?? [], actions: auditRunActions },
672
+ coverageRows, registerFindingsText,
673
+ });
674
+
675
+ // T2c — settle-by-citation (doubt-closure): ONE bounded sonnet/low pass over the doubts the
676
+ // stitch left OPEN. Unconditional (kill switch deleted post-E2E 2026-07-22) — deliberately: it fires
677
+ // only when opens exist, costs one cheap non-looping call, gates nothing, and offline evidence
678
+ // (6 archived runs) says ~75% of stitch-open doubts had an on-disk answer the deterministic
679
+ // join could not reach — while a genuinely unresolved doubt still ships OPEN, which is exactly
680
+ // what OPEN should mean. The stage may only POINT: every SETTLED citation is re-verified
681
+ // VERBATIM by code (applyClosure) against the three files it was allowed to cite; an
682
+ // unverifiable quote leaves its doubt OPEN + a LOUD `doubt-closure-unverified` event. Stage
683
+ // failure/timeout ⇒ doubts ship open exactly as without the stage (never a delivery gate).
684
+ let closureStats = null;
685
+ const openAfterStitch = runDoubts.filter((d) => d.status === "open");
686
+ // PR-6: still-open ASK rows ride the SAME closure pass — one stage, two dictated line-forms.
687
+ // The stage can never assert "executed" (that is computed from the plan-execution join); it
688
+ // may only end an ask as IMMATERIAL by pointing at a verbatim on-disk quote, or leave it
689
+ // OPEN with a one-line recovery recommendation the ledger records as the handoff.
690
+ const openAsksForStage = (runAsks ?? []).filter((a) => !a.ending);
691
+ if (openAfterStitch.length || openAsksForStage.length) {
692
+ try {
693
+ // — DRIVER SELECTION, on the PLACEMENT TIER both mints already hold. Inert today:
694
+ // every product row still reads `every-doubt`, so `ids` is null and every open doubt is
695
+ // dispatched exactly as before — byte-identical, not merely equivalent.
696
+ //
697
+ // The key is the tier and NOT the band of the finding the doubt is about, because that
698
+ // second key cannot bind: stitchDoubts settles every finding-joining doubt before this
699
+ // stage, so what arrives here has no finding and no band. That is asserted in
700
+ // doubt-closure-grading-cannot-bind.test.mjs and measured at 0 of 420 open doubts on 28
701
+ // delivered runs. The tier comes from the carry artifact instead, which the stitch cannot
702
+ // have consumed — 199 of the same 420 carry one.
703
+ const doubtSel = doubtsForClosure({
704
+ doubts: openAfterStitch,
705
+ doubtClosure: ctx.depth?.doubtClosure ?? null,
706
+ });
707
+ // RECORDED ON EVERY RUN, cut or no cut. The keyless count is what says whether this
708
+ // selection is worth having: if most doubts carry no tier, the cut saves nothing and should
709
+ // not be given a value. A count written only when the cut is live could never answer that —
710
+ // it would need the cut to exist to measure whether the cut is worth existing.
711
+ runLog(run.runDir, { event: "doubt-selection", of: doubtSel.total, selected: doubtSel.ids?.length ?? doubtSel.total,
712
+ keyed: doubtSel.keyed, keyless: doubtSel.keyless, dropped: doubtSel.dropped,
713
+ cut: ctx.depth?.doubtClosure ?? null, cutState: doubtSel.cutState });
714
+ const noteLine = doubtSelectionNote(doubtSel);
715
+ if (noteLine) note(`[pipeline] ${noteLine}`);
716
+ const dispatchDoubts = doubtSel.ids
717
+ ? openAfterStitch.filter((d) => doubtSel.ids.includes(d.id))
718
+ : openAfterStitch;
719
+ ctx.openDoubts = dispatchDoubts.map((d) => ({ id: d.id, birth: d.birth, subject: d.subject }));
720
+ ctx.openAsks = openAsksForStage.map(openAskForClosure);
721
+ // THE SPEC SIDECAR, WRITTEN BEFORE THE DISPATCH. The seat supplies none of its own context:
722
+ // the ids it may speak about and the files it may cite are the driver's, so a doubt it was not
723
+ // given is refused by name and a file it was not given cannot be expressed at all. Both
724
+ // ledgers' ids ride ONE list because one call answers both — the row's `kind` says which.
725
+ // CLOSURE_EVIDENCE_FILES is imported, never re-listed here: `file_index` is a POSITION, so a
726
+ // second copy of this array drifting would verify every citation against the wrong file.
727
+ // `bornIn` carries each DOUBT's birth artifact so the tool can refuse a circular citation
728
+ // inside the seat's own turn (doubt-ledger.applyClosure refuses it again either way). Asks
729
+ // are absent from the map on purpose: an ask is a question about a probe or directive, not
730
+ // a claim lifted out of an artifact, so it has no source to be circular with.
731
+ writeFileSync(paths(run.runDir).doubtClosureSpec, `${JSON.stringify({
732
+ // The SAME set the dispatch carries. Listing openAfterStitch here while dispatching a
733
+ // subset would tell the seat it may speak about ids it was never shown.
734
+ openIds: [...dispatchDoubts.map((d) => d.id), ...openAsksForStage.map((a) => a.ask_id)],
735
+ allowedFiles: CLOSURE_EVIDENCE_FILES,
736
+ bornIn: Object.fromEntries(dispatchDoubts
737
+ .filter((d) => d?.birth?.artifact)
738
+ .map((d) => [d.id, d.birth.artifact])),
739
+ }, null, 2)}\n`);
740
+ const dc = await stage("doubt-closure", ctx);
741
+ if (dc.ok) {
742
+ // the citable set is CLOSED: exactly the three files the stage message named — a line
743
+ // citing any other file simply never verifies (and is logged unverified, never followed).
744
+ const fileTexts = {
745
+ "findings.json": existsSync(P.findings) ? readFileSync(P.findings, "utf8") : "",
746
+ "register-findings.md": registerFindingsText,
747
+ "register-coverage-ledger.json": existsSync(P.registerCoverageLedger) ? readFileSync(P.registerCoverageLedger, "utf8") : "",
748
+ };
749
+ // APPLIED FROM THE RECORDED ROWS, not from a re-read of the artifact. The rows are what the
750
+ // tool accepted — already checked against these same files at call time — so the parse that
751
+ // used to sit here is gone, and with it the failure mode that made this conversion worth
752
+ // doing: `parseClosureLines` was STRICT, and a line it could not match produced NOTHING and
753
+ // left its doubt open, byte-identical to a doubt the seat looked at and honestly left open.
754
+ // Nothing counted it and nothing could. The union is over every accepted file, so a batch
755
+ // split across calls or a repair re-dispatch is one ledger, not the last call's slice.
756
+ const acc = readAcceptedClosures(run.runDir);
757
+ if (acc.unreadable) note(`doubt-closure: ${acc.unreadable} recorded call file(s) unreadable — their rows are NOT applied; the doubts they answered ship OPEN`);
758
+ const applied = applyClosure(runDoubts, acc.doubt, fileTexts);
759
+ runDoubts = applied.doubts;
760
+ closureStats = { settledByStage: applied.settledByStage, unverified: applied.unverified.length };
761
+ for (const u of applied.unverified) runLog(run.runDir, { event: "doubt-closure-unverified", ...u });
762
+ if (runAsks) {
763
+ const askApplied = applyAskClosure(runAsks, acc.ask, fileTexts, { ts: askTs });
764
+ runAsks = askApplied.asks;
765
+ for (const u of askApplied.unverified) runLog(run.runDir, { event: "ask-closure-unverified", ...u });
766
+ // Option A: a recall ask whose mark is not in the delivered findings
767
+ // did NOT close. Each one is a mark the run found and the client was not shown, so it is
768
+ // recorded by name rather than left to be inferred from an ask that merely stayed open.
769
+ // ✕ NOT written into findings.json here. See the sidecar's own note: a row appended after
770
+ // the drafting stage would carry no band and no reasoning.
771
+ for (const c of askApplied.carryIntoFindings ?? [])
772
+ runLog(run.runDir, { event: "ask-closure-mark-owed", ...c });
773
+ if (askApplied.carryIntoFindings?.length)
774
+ writeFileSync(paths(run.runDir).marksOwedAFinding,
775
+ JSON.stringify({
776
+ _provenance: "recall asks that could not close because the mark they found is absent from findings.json — owner ruling 2026-09-07, Option A, worded about the MARK",
777
+ _notWritten: "these are NOT appended to findings.json: a finding carries a band, a net line and a legal position, and a row minted here would carry none of them. The repair belongs where the findings are authored.",
778
+ count: askApplied.carryIntoFindings.length,
779
+ marks: askApplied.carryIntoFindings,
780
+ }, null, 2) + "\n");
781
+ }
782
+ } else {
783
+ note(`doubt-closure failed (non-fatal — the open doubts/asks ship OPEN, as without the stage): ${dc.fail}`);
784
+ }
785
+ } catch (e) {
786
+ note(`doubt-closure errored (non-fatal — the open doubts/asks ship OPEN, as without the stage): ${e.message}`);
787
+ }
788
+ }
789
+
790
+ const settled = runDoubts.filter((d) => d.status === "checked-and-settled").length;
791
+ writeFileSync(paths(run.runDir).doubts,
792
+ JSON.stringify({ minted: runDoubts.length, settled, open: runDoubts.length - settled,
793
+ // — recorded here too so the live sidecar and the delivered audit cannot disagree
794
+ // about whether the mint truncated. Omitted entirely when nothing was dropped.
795
+ ...(doubtTruncations.length ? { truncated: doubtTruncations } : {}),
796
+ ...(closureStats ?? {}), doubts: runDoubts }, null, 2));
797
+ runLog(run.runDir, { event: "doubts", minted: runDoubts.length, settled, open: runDoubts.length - settled, ...(closureStats ?? {}) });
798
+ } catch (e) {
799
+ runDoubts = null; // the audit builds ledger-less, exactly like a legacy caller
800
+ runLog(run.runDir, { event: "doubts-failed", error: e.message });
801
+ }
802
+
803
+ // PR-6: persist the ask ledger (its own try — a doubts failure above must not cost the asks,
804
+ // and vice versa; open rows just skipped closure and ship OPEN with their handoffs).
805
+ if (runAsks) {
806
+ try {
807
+ runAsks = finalizeOpenHandoffs(runAsks);
808
+ const askSummary = summarizeAsks(runAsks);
809
+ writeFileSync(paths(run.runDir).asks,
810
+ JSON.stringify({ ...askSummary, asks: runAsks }, null, 2) + "\n");
811
+ runLog(run.runDir, { event: "asks", ...askSummary });
812
+ note(`ask ledger: ${askSummary.total} ask(s) — ${askSummary.executed} executed, ${askSummary.immaterial} judged immaterial, ${askSummary.recovery} handed over, ${askSummary.open} OPEN`);
813
+ } catch (e) {
814
+ runAsks = null;
815
+ runLog(run.runDir, { event: "asks-failed", error: e.message });
816
+ }
817
+ }
818
+
819
+ // PR-8 — the reading audit: what judgment actually looked up (band-server appends every lookup to
820
+ // _driver/reading-log.jsonl). Passed on any run that derived a band shape — an EMPTY array renders
821
+ // the honest zero ("no lookups recorded"), because a band-consuming stage that read nothing is a
822
+ // fact the audit must show, not hide. Legacy runs (no shape) pass null → no section, byte-identical.
823
+ const readingLog = readReadingLog(P);
824
+ // item 33 — hand the builder the machine grid so the common-law search log is derived from the
825
+ // tool-written per-term cells rather than from a heading the tagger has to match. Absent (pre-grid
826
+ // archive, register-only run) it falls back to the prose tables, which is honest: those runs have
827
+ // no machine record. Read here rather than inside the builder to keep that module IO-free.
828
+ let commonLawGrid = null;
829
+ try { commonLawGrid = existsSync(P.commonLawGrid) ? readFileSync(P.commonLawGrid, "utf8") : null; } catch { /* no grid — prose path */ }
830
+ // — the Register Presence store: every live, matter-in-scope enumerated record,
831
+ // whatever its screen verdict, into the one artifact that survives the purge. Derived, not fatal:
832
+ // a run with no band (register-less, legacy) legitimately builds its audit without the section, and
833
+ // the run log says which happened rather than letting the absence read as a pass.
834
+ let registerPresence = null;
835
+ if (existsSync(P.registerNamedBand)) {
836
+ try {
837
+ let dominantElement = null;
838
+ try { dominantElement = parseVariantManifestModel(readFileSync(P.variantManifestModel, "utf8")).dominant_element; }
839
+ catch { /* prose-only manifest — the store still derives, the dominant column reads null */ }
840
+ let scopeClasses = [];
841
+ try { scopeClasses = inScopeClassList(ctx.job, ctx.profile).map(String); }
842
+ catch { scopeClasses = (ctx.job?.classes ?? []).map(String); }
843
+ // The matter's territories: the resolved ladder when it answers (worldwide = NO restriction,
844
+ // never a fallback), else the frame's own recorded scope — R14's shape: nothing instructed,
845
+ // scope inferred by the frame — else no restriction (the inclusive direction for a store).
846
+ const resolved = resolveTerritories(ctx.job, ctx.profile);
847
+ let scopeTerritories = null;
848
+ if (resolved.geographyMode !== "worldwide") {
849
+ scopeTerritories = resolved.jurisdictions?.length ? resolved.jurisdictions
850
+ : (lastAcceptedMatterFrame(run.runDir)?.scope_jurisdictions ?? null);
851
+ }
852
+ registerPresence = deriveRegisterPresence(JSON.parse(readFileSync(P.registerNamedBand, "utf8")),
853
+ { dominantElement, scopeClasses, scopeTerritories });
854
+ runLog(run.runDir, { event: "register-presence", rows: registerPresence.rows.length,
855
+ territories: registerPresence.scope.territories, classes: registerPresence.scope.classes,
856
+ dominantElement: registerPresence.dominant_element });
857
+ } catch (e) {
858
+ registerPresence = null;
859
+ runLog(run.runDir, { event: "register-presence-failed", error: String(e?.message ?? e).slice(0, 200) });
860
+ }
861
+ } else {
862
+ runLog(run.runDir, { event: "register-presence-skipped", reason: "no register-named-band.json" });
863
+ }
864
+ const a = buildAuditMd(registerFindingsText, commonLawText,
865
+ { findings: auditRunFindings, doubts: runDoubts, asks: runAsks, readingLog, commonLawGrid, doubtTruncations, registerPresence,
866
+ placementRows: placementAuditRows(P) });
867
+ if (!a.counts.findings) throw new Error("0 findings parsed from the spine tables"); // count-guard
868
+ writeFileSync(P.audit, a.md);
869
+ auditWrittenThisPass = true;
870
+ runLog(run.runDir, { event: "audit", ...a.counts }); // — counts now carry doubtsOmitted
871
+ // The trace and the Audit Trail, written again over a repair (`rebuildDeliveredRecord`), from the inputs this
872
+ // pass built them from; the doubts minted from the trace follow the trace written again.
873
+ rebuildTheDeliveredRecord = (trigger) => rebuildDeliveredRecord(ctx,
874
+ { commonLawText, doubts: runDoubts, asks: runAsks, commonLawGrid, doubtTruncations, registerPresence }, trigger);
875
+ note(`audit (code): ${a.counts.findings} findings, ${a.counts.negatives} negatives, ${a.counts.audit} audit-trail${a.counts.withdrawnStamped ? `, ${a.counts.withdrawnStamped} withdrawn-stamped` : ""}${a.counts.resolutionStamped ? `, ${a.counts.resolutionStamped} resolution-stamped` : ""}${runDoubts ? `, doubts ${a.counts.doubtsSettled} settled / ${a.counts.doubtsOpen} open` : ""}${a.counts.presenceRows != null ? `, register presence ${a.counts.presenceRows} row(s)` : ""}`);
876
+ } catch (e) {
877
+ note(`audit build failed (NON-FATAL — report still ships, audit will regenerate on re-run): ${e.message}`);
878
+ // A findings record with no finding row trips the count guard, and on a clean run it can: that is recorded apart,
879
+ // as a note on the run's content, and only a build that broke is recorded as a failure.
880
+ const noFindings = /^0 findings parsed from the spine tables/.test(String(e?.message ?? ""));
881
+ runLog(run.runDir, { event: noFindings ? "audit-not-built-no-findings" : "audit-build-failed", reason: String(e?.message ?? e).slice(0, 160) });
882
+ // An audit an earlier pass wrote describes that pass, not this one: the report ships without it, kept under _history.
883
+ if (!auditWrittenThisPass) withdrawSupersededAudit(P, "audit-build-failed", { keep: !earlierPairKept });
884
+ }
885
+ return { applyRatedUnderFrontMatter, applyScopeFrontMatter, applyVerdictFrontMatter, assembledOrdinals, byRight, cardOrdinals, findingsForCards, groupedMembers, overviewOpen, rebuildTheDeliveredRecord, restoreTheBrokenRecord, rov, writeScopeFacts, writeUps };
886
+ }
887
+
888
+ /**
889
+ * The footer's "Rated under" line: the company, then the scale that rated the run. A customer's own scale is named as
890
+ * its own. The house scale is named by the title the run froze, as the gauge names it: a new run says "Standard risk
891
+ * scale", and a run frozen under an older title keeps that title. With no frozen title the earlier words stand. PURE.
892
+ */
893
+ export function ratedUnderLine(profile, framework) {
894
+ const title = typeof framework?.title === "string" && framework.title.trim() ? framework.title.trim() : null;
895
+ const scale = profile?.frameworkPath
896
+ ? `custom framework: ${framework?.title ?? basename(String(profile.frameworkPath))}`
897
+ : title ?? "generic default framework";
898
+ return `${profile?.name ?? profile?.profileKey} · ${scale}`;
899
+ }