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,163 @@
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
+ // review-addresses.mjs — the parts of a report a review was handed, each with the address a flag about it carries.
4
+ //
5
+ // A review flag names the findings it is about in `on`, and nothing checked that each ordinal names a finding the
6
+ // review was handed. The report's other parts had no address at all, so a correction bound a flag to them by matching
7
+ // its prose against their text. This module builds the list a review dispatch writes beside its exclusions, and
8
+ // resolves what a flag declares against it, so a declaration that names nothing the review was handed can be refused
9
+ // in the reviewer's own turn.
10
+ //
11
+ // Findings are addressed by ordinal, taken from every record handed in together: a recheck reads the record before
12
+ // and after a correction, so it can still name a finding the correction removed. Each coverage line, action and mark
13
+ // assessment read is addressed by the key a correction already gives it (REPORT_LINE_KEY), and each narrative section
14
+ // that has content by its name. A key two rows of one record share would bind a flag to either of them, so it is not
15
+ // offered, and neither is one holding a comma or a bracket, which the review line's `[lines: …]` token cannot carry
16
+ // back. PURE, apart from `writeReviewAddresses`, which writes the list into the run.
17
+ import { REPORT_LINE_KEY, REPORT_LINE_LABEL } from "./corrections-feedforward.mjs";
18
+ import { NARRATIVE_SECTIONS } from "./synthesis-record.mjs";
19
+ import { atomicWrite, driverDir, ensureDriverDir } from "./run-record.mjs";
20
+ import { rmSync } from "node:fs";
21
+
22
+ export const REVIEW_ADDRESSES_FILE = "review-addresses.json";
23
+
24
+ const MARK_ASSESSMENT_READS = ["distinctiveness", "connotation"];
25
+ const hasContent = (v) => (typeof v === "string" ? v.trim() !== ""
26
+ : Array.isArray(v) ? v.length > 0
27
+ : v && typeof v === "object" ? Object.values(v).some(hasContent) : false);
28
+
29
+ /** Every part of one record that is not a finding, as [address, label] pairs, in the record's own order. */
30
+ function partsOf(doc) {
31
+ const out = [];
32
+ for (const c of Array.isArray(doc?.coverage) ? doc.coverage : []) out.push([REPORT_LINE_KEY.coverage(c), REPORT_LINE_LABEL.coverage(c)]);
33
+ for (const a of Array.isArray(doc?.actions) ? doc.actions : []) out.push([REPORT_LINE_KEY.actions(a), REPORT_LINE_LABEL.actions(a)]);
34
+ const ma = doc?.markAssessment ?? doc?.mark_assessment;
35
+ for (const k of MARK_ASSESSMENT_READS) if (hasContent(ma?.[k])) out.push([`mark-assessment:${k}`, `the mark assessment's ${k}`]);
36
+ return out;
37
+ }
38
+
39
+ /**
40
+ * Every part of one record that is not a finding, by address, with the value a reader is given for it, and whether any
41
+ * address is held by two rows: such a record cannot say which of the two moved.
42
+ */
43
+ function partValues(doc) {
44
+ const out = new Map();
45
+ let ambiguous = false;
46
+ const put = (address, label, value) => {
47
+ if (!address.slice(address.indexOf(":") + 1).trim()) return;
48
+ if (out.has(address)) ambiguous = true;
49
+ out.set(address, { label, value: JSON.stringify(value ?? null) });
50
+ };
51
+ for (const c of Array.isArray(doc?.coverage) ? doc.coverage : []) put(REPORT_LINE_KEY.coverage(c), REPORT_LINE_LABEL.coverage(c), c);
52
+ for (const a of Array.isArray(doc?.actions) ? doc.actions : []) put(REPORT_LINE_KEY.actions(a), REPORT_LINE_LABEL.actions(a), a);
53
+ const ma = doc?.markAssessment ?? doc?.mark_assessment;
54
+ for (const k of MARK_ASSESSMENT_READS) put(`mark-assessment:${k}`, `the mark assessment's ${k}`, ma?.[k]);
55
+ return { values: out, ambiguous };
56
+ }
57
+
58
+ /**
59
+ * The parts of the report other than findings that a correction changed and no flag named: `{ named, moved, complete }`,
60
+ * each `moved` entry `{ address, label }`. A part added, removed or rewritten counts as moved.
61
+ *
62
+ * `complete` says whether every coverage line, action, mark assessment read and narrative section was compared. It is
63
+ * false when either record or either narrative is missing, or when one address is held by two rows of a record: then
64
+ * "none moved" is not known, and the recheck must not be told it (repair-composers.mjs reads it). Recorded, never
65
+ * refused: the clearance's correction policy (scopeDrift in corrections-feedforward.mjs). PURE.
66
+ */
67
+ export function partsDrift(rows, preDoc, postDoc, { narratives = null } = {}) {
68
+ const named = [...new Set((rows ?? []).flatMap((r) => (Array.isArray(r?.lines) ? r.lines : [])))];
69
+ if (!preDoc || !postDoc) return { named, moved: [], complete: false };
70
+ const a = partValues(preDoc), b = partValues(postDoc);
71
+ const pre = a.values, post = b.values;
72
+ const sectionsHeld = Boolean(narratives?.before && narratives?.after);
73
+ if (sectionsHeld) {
74
+ for (const k of NARRATIVE_SECTIONS) {
75
+ pre.set(`section:${k}`, { label: `the narrative's ${k} section`, value: JSON.stringify(narratives.before[k] ?? null) });
76
+ post.set(`section:${k}`, { label: `the narrative's ${k} section`, value: JSON.stringify(narratives.after[k] ?? null) });
77
+ }
78
+ }
79
+ const isNamed = new Set(named);
80
+ const moved = [];
81
+ for (const address of new Set([...pre.keys(), ...post.keys()])) {
82
+ if (isNamed.has(address)) continue;
83
+ if (pre.get(address)?.value !== post.get(address)?.value) moved.push({ address, label: (post.get(address) ?? pre.get(address)).label });
84
+ }
85
+ return { named, moved, complete: sectionsHeld && !a.ambiguous && !b.ambiguous };
86
+ }
87
+
88
+ /**
89
+ * The address list for one review dispatch: `{ schema, ordinals, lines: [{ address, label }] }`.
90
+ *
91
+ * `records` are the findings documents the review reads (one at a first review; the record before and after the
92
+ * correction at a recheck). `narratives` are the narrative's typed sections, keyed as NARRATIVE_SECTIONS names them.
93
+ * An address with nothing after its colon, which a row with no area or id would make, is never offered.
94
+ */
95
+ export function reviewAddresses({ records = [], narratives = [] } = {}) {
96
+ const ordinals = new Set();
97
+ const lines = new Map();
98
+ const shared = new Set();
99
+ for (const doc of records) {
100
+ for (const f of Array.isArray(doc?.findings) ? doc.findings : []) if (Number.isInteger(f?.ordinal) && f.ordinal > 0) ordinals.add(f.ordinal);
101
+ const inThisRecord = new Set();
102
+ for (const [address, label] of partsOf(doc)) {
103
+ if (!address.slice(address.indexOf(":") + 1).trim() || /[,[\]]/.test(address)) continue;
104
+ if (inThisRecord.has(address)) shared.add(address);
105
+ inThisRecord.add(address);
106
+ lines.set(address, label);
107
+ }
108
+ }
109
+ for (const n of narratives) for (const k of NARRATIVE_SECTIONS) if (hasContent(n?.[k])) lines.set(`section:${k}`, `the narrative's ${k} section`);
110
+ for (const a of shared) lines.delete(a);
111
+ return { schema: 1, ordinals: [...ordinals].sort((x, y) => x - y), lines: [...lines].map(([address, label]) => ({ address, label })) };
112
+ }
113
+
114
+ const loose = (s) => String(s ?? "").toLowerCase().replace(/\s+/g, " ").trim();
115
+
116
+ /**
117
+ * What a flag declares, resolved against the list. Returns `{ ok: true }`, or the first thing that does not
118
+ * resolve: `{ ok: false, kind: "ordinal", value }` for an ordinal no finding handed in carries, `{ ok: false,
119
+ * kind: "lines-shape" }` when `lines` is not an array of strings, or `{ ok: false, kind: "line", value, near }` for
120
+ * an address not on the list. `near` is the listed address it matches when spacing and case are ignored, else null.
121
+ * `on` is assumed already checked as positive integers, as acceptRefutation checks it today.
122
+ */
123
+ export function resolveDeclared(list, { on = null, lines = null } = {}) {
124
+ const ordinals = new Set(list?.ordinals ?? []);
125
+ for (const n of Array.isArray(on) ? on : []) if (!ordinals.has(n)) return { ok: false, kind: "ordinal", value: n };
126
+ if (lines == null) return { ok: true };
127
+ if (!Array.isArray(lines) || lines.some((l) => typeof l !== "string")) return { ok: false, kind: "lines-shape" };
128
+ const listed = (list?.lines ?? []).map((l) => l.address);
129
+ const exact = new Set(listed);
130
+ for (const value of lines) {
131
+ if (exact.has(value)) continue;
132
+ const near = listed.find((a) => loose(a) === loose(value)) ?? null;
133
+ return { ok: false, kind: "line", value, near };
134
+ }
135
+ return { ok: true };
136
+ }
137
+
138
+ /**
139
+ * Build the list and write it beside the review's exclusions, where the review's recording tool reads it. `seq0` is the
140
+ * sequence the dispatch's first review call will take (nextRefutationSeq), so the list, and the accepted call the
141
+ * correction reads, belong to this dispatch and no earlier one. Returns the list, or null when it could not be written:
142
+ * the dispatch then shows no address block, and an older list is removed rather than left for this dispatch to read.
143
+ * IMPURE.
144
+ */
145
+ export function writeReviewAddresses(runDir, { records = [], narratives = [], seq0 = null } = {}) {
146
+ const at = driverDir(runDir, REVIEW_ADDRESSES_FILE);
147
+ try {
148
+ const list = { ...reviewAddresses({ records: records.filter(Boolean), narratives: narratives.filter(Boolean) }), seq0 };
149
+ ensureDriverDir(runDir);
150
+ atomicWrite(at, JSON.stringify({ ts: new Date().toISOString(), ...list }, null, 2) + "\n");
151
+ return list;
152
+ } catch {
153
+ try { rmSync(at, { force: true }); } catch { /* nothing more can be done; the list stays as it was */ }
154
+ return null;
155
+ }
156
+ }
157
+
158
+ // What the review dispatch shows the reviewer: the block's heading, then one row per address. No block for a list with
159
+ // no parts beyond the findings, whose ordinals the reviewer already reads off the report.
160
+ export const ADDRESS_LIST_HEADING = "THE ADDRESS LIST: each part of the report below is not a finding. A flag about one carries its address in `lines`, copied exactly; an address not on this list is refused.";
161
+ export const addressListLines = (list) => (Array.isArray(list?.lines) && list.lines.length
162
+ ? [ADDRESS_LIST_HEADING, ...list.lines.map((l) => `- ${l.label} — address ${l.address}`)]
163
+ : []);
@@ -9,7 +9,7 @@
9
9
  // the sidecar and moves on; nothing gates on it. PURE (no node imports, tests offline); empty input → [].
10
10
  //
11
11
  // DELIBERATELY NARROW — near-zero false positives. It does NOT flag bare percentages or counts: the
12
- // engine ENCOURAGES base-rate counts ("640 of 3,060 filings claim gaming", "545 live JELLY filings",
12
+ // engine ENCOURAGES base-rate counts ("640 of 3,060 filings claim gaming",
13
13
  // "127k reviews") over adjectives. It flags ONLY the shape of a RULE that DECIDES the rating: a
14
14
  // Level/Composite cutoff ("Level C or above", "Composite 3+"), an explicit "threshold", or a blanket
15
15
  // "always/automatically/any X is <rating>". The real target (a rule injected into a customer context
@@ -0,0 +1,340 @@
1
+ // SPDX-License-Identifier: AGPL-3.0-only
2
+ // Copyright 2026 Cordillera Sàrl. Additional terms under section 7 of the AGPL-3.0 apply — see ADDITIONAL-TERMS.md
3
+ //
4
+ // run-delivered.mjs — how a run ends delivered: the publish, the packet, the delivered state and the archive,
5
+ // whether or not the overall assessment completed.
6
+ //
7
+ // The clearance pipeline's delivery end state, moved out of pipelineInner unchanged. It hands back the two ways a run
8
+ // delivers. `helpers` are functions still held in pipeline.mjs, handed in because this module must not import that
9
+ // one back.
10
+ import { assessmentNotCompletedNote } from "../shared/client-failure-note.mjs";
11
+ import { driverDir } from "../shared/driver-dir.mjs";
12
+ import { assertNotCancelledBeforePublish } from "./cancel.mjs";
13
+ import { recordRunConsumption } from "./consumption-ledger.mjs";
14
+ import { degradedParts, writeDegradedParts } from "./degraded-parts.mjs";
15
+ import { config } from "./driver.config.mjs";
16
+ import { registerAdapter } from "./engine/run-choices.mjs"; // the run's register adapter, from ctx.register
17
+ import { note, runLog } from "./log.mjs";
18
+ import { NOT_COMPLETED_DIR } from "./parts-not-completed.mjs";
19
+ import { deliveryForRun } from "./profiles.mjs";
20
+ import { finalStepFields, readRunStatus, recordTransition, signoffPatch, writeRunStatus } from "./progress.mjs";
21
+ import { DEFAULT_LEDGER_PATH, tallyRegisterCalls } from "./provider-usage.mjs";
22
+ import { composeEmailHtml, coverNoteOptions, deliverySubject, publishReport } from "./publish/index.mjs";
23
+ import { noteRegisterServed, providerUsageCaveat, registersServedFrom } from "./register-served.mjs";
24
+ import { renderReportOverview } from "./report-overview-record.mjs";
25
+ import { atomicWrite } from "./run-record.mjs";
26
+ import { logTurnaroundReconciliation } from "./run-quote.mjs";
27
+ import { endTheDeliveredRun } from "./run-shell.mjs";
28
+ import { reportIdentityFor } from "./search-policy.mjs";
29
+ import { paths, whatsappRouting } from "./stages.mjs";
30
+ import { stampTokenRollup } from "./tokens.mjs";
31
+ import { existsSync, mkdirSync, readFileSync, rmSync, writeFileSync } from "node:fs";
32
+ import { join } from "node:path";
33
+
34
+ export async function deliveryEndState({ P, agent, ctx, job, run }, helpers) {
35
+ const { applyScopeFrontMatterOf, archive, assessmentCoverageOfRun, localLanguageStateOf, reportIdentityRecord, searchLogAuditMd, sentinel, setAsideTheAssessment, writeScopeFactsOf } = helpers;
36
+ // ── PUBLISHING AND DELIVERING: ONE PATH, FOR EVERY RUN THAT DELIVERS ─────────────────────────────────
37
+ //
38
+ // The run's last steps, from publishing the report to the delivered state, the packet and the archive. A run whose
39
+ // overall assessment completed reaches them at the end of the stage sequence. A run whose assessment could not be
40
+ // completed reaches them from deliverWithoutTheAssessment below, with no verdict: the same publish, the same packet
41
+ // and the same terminal, so the two deliveries cannot drift apart. `verdict` is the review's sign-off word, or null.
42
+ async function publishAndDeliver(verdict) {
43
+ let published;
44
+ // PUBLISHED ONCE, and a resume delivers what was published. `.published` holds the whole publish result, as the
45
+ // Knockout's does, because the delivery below reads more of it than the link: the workbook's file name for the
46
+ // covering email's download link, the report's caption for the run record, and the pool folder the delivered state
47
+ // is stamped on. It used to keep four fields, so a run stopped between the publish and its delivered status sent
48
+ // its covering email without the workbook link, kept no caption and left its pool copy unstamped.
49
+ if (existsSync(join(run.runDir, ".published"))) {
50
+ const { ts: _publishedAt, ...stored } = JSON.parse(readFileSync(join(run.runDir, ".published"), "utf8"));
51
+ published = stored;
52
+ note(`publish skip — already published → ${published.url}`);
53
+ } else {
54
+ // THE LAST READ OF THE STOP FLAG, and it sits HERE rather than above the branch: a run that has
55
+ // already published has delivered, and refusing at that point would record a delivered run as
56
+ // cancelled — the same defect pointed the other way.
57
+ assertNotCancelledBeforePublish(run.runDir, "clearance");
58
+ // Same fact, same moment, same words as the knockout lane: past this line a stop cannot prevent
59
+ // delivery, and the screen is told so rather than working it out.
60
+ writeRunStatus(ctx, { stoppable: false });
61
+ // THE PARTS THAT FAILED AND STILL SHIP (ruling 498): read from the run as it stands now, so a failure a
62
+ // retry or a resume recovered writes nothing, and written for the audit workbook in the shipped
63
+ // deferral row's words. The run's record keeps each raw cause; the reader's cell never carries one.
64
+ try {
65
+ const localLanguage = await localLanguageStateOf(run.runDir);
66
+ const degraded = writeDegradedParts(run.runDir, degradedParts(run.runDir, { localLanguage }));
67
+ runLog(run.runDir, { event: "degraded-parts", parts: degraded.parts.map((d) => ({ part: d.part, cause: d.cause })) });
68
+ } catch (e) { runLog(run.runDir, { event: "degraded-parts-failed", cause: String(e?.message ?? e).slice(0, 200) }); }
69
+ published = await publishReport({
70
+ runId: `${run.slug}-${run.date}-${run.codename}`, codename: run.codename,
71
+ reportMd: P.report, auditMd: P.audit, findingsJson: P.findings, poolRoot: config.poolRoot, poolUrl: config.poolUrl,
72
+ // WS-B/D3: the resolved account key (frozen sidecar) buckets the per-customer portal index and
73
+ // stamps meta.json; delivery selects the render/banner variant. Both default safe for old sidecars.
74
+ customerKey: ctx.profile?.profileKey ?? "generic", delivery: deliveryForRun(ctx),
75
+ // Instance #6 — the source run dir whose _records/ the render reads identifiers from (records were
76
+ // materialized into run.runDir/_records by the lint-pass assembleRunRecords). NOT the pool dir.
77
+ runDir: run.runDir,
78
+ });
79
+ sentinel(run.runDir, ".published", published);
80
+ // WHAT THE TWO GATES EACH SAID, in the run's own log, under names that say whose they are.
81
+ // `.published` carries `clientGate.released` beside `counts.gateViolations`, which are the verdicts
82
+ // of DIFFERENT gates: the first is the client-export refusal (evaluateClientGate), the second is the
83
+ // audit workbook's own build check (validateAudit), which is advisory by design and decides nothing
84
+ // about the release. Read as one gate they contradict each other — released, with a list of
85
+ // violations beside it — and a delivered run shipped looking exactly like that. Named separately
86
+ // here, with the advisory COUNT and the absences the gate did not close on, so the log a person
87
+ // reads after a run answers "what did the checks say" without opening the sentinel and knowing
88
+ // which field belongs to which gate.
89
+ runLog(run.runDir, { event: "publish-gates",
90
+ clientExport: published.clientGate?.released === false ? "closed" : "released",
91
+ clientExportReasons: published.clientGate?.reasons ?? [],
92
+ releasedDespiteAbsentInputs: (published.clientGate?.notClosing ?? []).map((n) => n.input),
93
+ auditWorkbookAdvisory: published.counts?.gateViolations?.length ?? 0,
94
+ // A workbook that failed to build cannot say so itself, so its failure is recorded here. Without
95
+ // these two fields the advisory's 0 read as a clean workbook when there was none.
96
+ auditWorkbook: published.auditFile ? "built" : published.auditError ? "failed" : "not built",
97
+ auditWorkbookError: published.auditError ? String(published.auditError).slice(0, 300) : null });
98
+ note(`published → ${published.url}`);
99
+ }
100
+ // Lifecycle honesty (charter P1 §4): publish is CODE, not a stage() call, so nothing ever advanced the
101
+ // displayed step past "Drafting the report" — advance it here (monotonic; the delivered terminal below
102
+ // completes the stepper). The skip branch advances too: a resumed run with .published is equally at 8/9.
103
+ recordTransition(ctx, "publish");
104
+ // ONE report: the two-bit delivery (clientReady/defects) is deleted. The machine-QC result is
105
+ // telemetry — the reviewer reads it on the audit workbook. A4: the
106
+ // stable reason codes still ride the event, so a classifier reading the spine never hashes prose.
107
+ if (published.clientGate && published.clientGate.released === false) {
108
+ runLog(run.runDir, { event: "machine-qc-failed", reasons: (published.clientGate.reasons ?? []).map(String), ...(published.clientGate.reasonCodes?.length ? { reasonCodes: published.clientGate.reasonCodes } : {}),
109
+ ...(published.clientGate.evaluationError ? { evaluationError: published.clientGate.evaluationError } : {}) });
110
+ note(`machine QC failed (${(published.clientGate.reasons ?? []).length} check(s)) — recorded on the audit workbook; the report is delivered as usual: ${(published.clientGate.reasons ?? []).join("; ")}`);
111
+ }
112
+ ctx.publishedUrl = published.url;
113
+ writeRunStatus(ctx, { url: published.url });
114
+
115
+ // Provider-usage rollup — billing-grade per-run Corsearch call counts from the plugin chokepoint
116
+ // ledger (every API call flows through it; all of a run's calls are done by the time we publish).
117
+ // Best-effort: a telemetry rollup must never affect a delivered run. `duplicate_fetches[_same/cross]`
118
+ // measures the Workstream-B dedup opportunity (and which scope matters) directly from data.
119
+ let providerTally = null;
120
+ try {
121
+ const provider = registerAdapter(ctx.register).id;
122
+ const usage = tallyRegisterCalls(DEFAULT_LEDGER_PATH, `clearance-${run.slug}-${run.codename}-`);
123
+ // ── A WHOLE-RUN TALLY FILED UNDER ONE REGISTER SAYS SO WHEN THE RUN SERVED MORE THAN ONE ──────
124
+ //
125
+ // This label is resolved HERE, at publish, while the tally it labels spans the whole run. On a run
126
+ // whose register changed part-way that key is whichever register happened to be active at publish,
127
+ // and every call is filed under it — the confident-and-wrong shape the served field exists to end.
128
+ //
129
+ // The key's SHAPE is untouched because a ledger reads this map. What is added is the caveat, in the
130
+ // same record, so the two register fields in one status cannot silently disagree: the served list
131
+ // says two, and this says the tally covers both and could only be filed under one. Splitting the
132
+ // tally by register is a second question and is not answered here.
133
+ // ── THE LEDGER IS WHAT KNOWS, SO ASK IT BEFORE READING THE RECORD ───────────────────────────
134
+ //
135
+ // `registersServed` was written from ONE place: the adapter wrapper the record fetcher, the record
136
+ // lister and a gated plan executor pass through. A clearance that takes counts and never fetches a
137
+ // record went through none of them and recorded no register at all — the run could not say which
138
+ // vendor answered it, and `registersServedFrom` returned [] for a run that had called a register
139
+ // hundreds of times.
140
+ //
141
+ // Every one of those calls wrote a ledger row, and every row carries the vendor that produced it, so
142
+ // the tally just computed already holds the answer per call. Noting them here is not a second source
143
+ // of truth competing with the first: it is the same memoised setter, which unions and writes only on
144
+ // change, so the eager note during the run and this reconciliation at publish cannot disagree.
145
+ //
146
+ // WHY NOT `activeProvider()` HERE. That resolves the register active at publish, which is the
147
+ // confident-and-wrong answer this whole field exists to end — and on a run that changed register it
148
+ // would name one vendor while the rows name two. The rows are per call; the resolver is per moment.
149
+ for (const id of usage.providers) noteRegisterServed(run.runDir, id);
150
+ const served = registersServedFrom(readRunStatus(run.runDir));
151
+ const spans = providerUsageCaveat(served);
152
+ runLog(run.runDir, { event: "provider-usage", provider, ...(served.length > 1 ? { spans: served } : {}), ...usage });
153
+ writeRunStatus(ctx, { providerUsage: { [provider]: usage }, ...spans });
154
+ providerTally = { [provider]: usage };
155
+ // AD-4: the line prints the complete by_tool census, not a hand-picked subset — the R2 run printed
156
+ // "search=0" while 286 execute_plan calls carried the whole register workload, and the subset read
157
+ // as "no searches happened". An unclassified count is called out loudly: it means the KINDS list in
158
+ // provider-usage.mjs has fallen behind a tool name again.
159
+ const byTool = Object.entries(usage.by_tool ?? {}).map(([k, v]) => `${k}=${v}`).join(" ") || "(none)";
160
+ // …and the LEDGER's own state rides the same line (post-merge audit, problem 4). A missing or
161
+ // mis-pointed call ledger used to print `total=0 ((none))` — a clean-looking measurement of a
162
+ // measurement that never happened. `total=0` is only believable when the ledger was read.
163
+ // The PATH is named here and only here: note() is the driver's own stderr, internal by construction,
164
+ // while the tally itself rides status.json and the MCP tool responses (see emptyTally's ledger note).
165
+ const led = usage.ledger ?? null;
166
+ const ledgerNote = !led ? ""
167
+ : !led.configured ? " ledger=NOT-CONFIGURED — the zeros above are NOT a measurement"
168
+ : !led.present ? ` ledger=MISSING (${DEFAULT_LEDGER_PATH}) — the zeros above are NOT a measurement`
169
+ : !led.readable ? ` ledger=UNREADABLE (${DEFAULT_LEDGER_PATH}) — the zeros above are NOT a measurement`
170
+ : ` ledger=read ${led.rowsScanned} row(s)`;
171
+ note(`${provider} calls: total=${usage.total} (${byTool})${usage.unclassified ? ` UNCLASSIFIED=${usage.unclassified} — a tool name the KINDS list doesn't know` : ""} retries=${usage.retries} errors=${usage.errors} dup_fetch=${usage.duplicate_fetches} [same=${usage.duplicate_fetches_same_session} cross=${usage.duplicate_fetches_cross_session}]${ledgerNote}`);
172
+ } catch (e) {
173
+ note(`provider-usage rollup failed (non-fatal): ${e.message}`);
174
+ }
175
+
176
+ // Register calls are the SECOND cost axis and may dominate the LLM one at some depths, so the ledger
177
+ // row carries both or it cannot answer "what did this run cost us" on its own.
178
+ recordRunConsumption(ctx, { phase: "delivered", tokens: stampTokenRollup(run.runDir, "delivered"), providerUsage: providerTally });
179
+
180
+ // AD-4 — quoted-vs-actual turnaround. The consumption row already pairs the two figures on one line
181
+ // (quote + wallSec); nothing ever computed the comparison, which is how "quoted 1.5h, took 5.68h"
182
+ // stayed a forensic discovery instead of a logged fact. Unconditional: a missing quote is recorded as
183
+ // quotedHours:null (the run was never sized), never as silence. Every OTHER terminal writes the same
184
+ // row with its own `state` — see logTurnaroundReconciliation.
185
+ logTurnaroundReconciliation(run.runDir, ctx.quote, "delivered");
186
+
187
+ // C — compose the email body in CODE: a single inline-HTML fragment (the cover note — headline
188
+ // tier, the report link, and any surviving machine-check/scope/verdict flags). The mail tool passes
189
+ // a fully-HTML body through unchanged. The notify leaf only sends it
190
+ // verbatim. Non-fatal: the report is already published.
191
+ const emailNames = [...new Set([job.markName, job.name,
192
+ ...(Array.isArray(job.marks) ? job.marks.map((m) => m?.name) : [])].filter(Boolean))];
193
+ // — THE PRODUCT NAME, off the run's own frozen policy row, for the cover note and the subject.
194
+ // The same resolver the report itself renders from, so the covering email and the document cannot
195
+ // name two different products. Null on a run with no sidecar ⇒ both surfaces say nothing rather
196
+ // than asserting one.
197
+ const emailProductName = reportIdentityFor(ctx.searchPolicy ?? null).identity;
198
+ // The email's options, read from the run's frozen files by the publisher's one function (coverNoteOptions), which the
199
+ // report document carries too: the verdict record as written and the band ladder. Read from the files rather than from
200
+ // `published`, because a resume that finds the run already published has no document. The product's name stays the one
201
+ // the subject takes, which names a run with no frozen policy as the legacy clearance it was.
202
+ const emailVerdictOpts = { ...coverNoteOptions(run.runDir), productName: emailProductName ?? undefined };
203
+ // ONE report (spec 2026-07-30 §6): the cover note is a cover note — verdict, one-line summary, link.
204
+ // A10 (addendum, 2026-07-30) NARROWS the old "machine-QC never on the email" rule rather than
205
+ // restating it: surviving predelivery machine-check failures are enumerated on BOTH delivery
206
+ // surfaces — the workbook Summary and this cover note — because deleted the closed-gate block
207
+ // that used to carry them and they were left living only in a _driver sink nobody reads. What the
208
+ // rule still forbids is the ENGINE'S OWN WORDS getting there: composeEmailHtml enumerates
209
+ // predelivery-lint's code-owned projection (deliveryFlagLines), never the checks' raw `detail` —
210
+ // this mail is addressed to job.forwarderEmail, which on a client-principal run is the client.
211
+ // THE REVIEWER'S OPEN POINTS NO LONGER RIDE THE EMAIL (owner ruling, 2026-10-01). This line read them
212
+ // out of the run record and handed them to the cover, which is how the sentence naming the independent
213
+ // reviewer reached a client after the 2026-09-24 ruling had already taken it off the report page: the
214
+ // section stopped being spliced into the body and started being posted to the email instead. Measured
215
+ // on the last thirty days of production, the report carries neither the heading nor that sentence since
216
+ // that ruling, and the email carries both. The record is still written beside the report for the
217
+ // reviewing lawyer; nothing reads it onto a client surface.
218
+ writeFileSync(P.emailBody, composeEmailHtml(P.report, published.url, published.auditFile, emailNames, deliveryForRun(ctx), emailVerdictOpts));
219
+ // ctx.verdict is set BEFORE the packet is composed, because the packet's copy reads it.
220
+ ctx.verdict = verdict;
221
+ // DELIVERY (Phase 2). The driver writes a self-contained delivery packet and leaves
222
+ // status.sendPending; the integrator sends off it. The report is ALREADY published by this point,
223
+ // so nothing here can lose it. There is no second delivery mode and no send stage: what used to sit
224
+ // behind `CLEAROTRON_DELIVERY=stage` asked a gateway agent to send the mail and a chat ping, and that
225
+ // gateway is not part of this product.
226
+ {
227
+ const mark = job.markName ?? job.name ?? job.ref ?? "the matter";
228
+ const ref = job.ref ? ` (${job.ref})` : "";
229
+ const vtag = emailVerdictOpts.tier ? ` Overall risk: ${emailVerdictOpts.tier}.` : ""; // the rating, never the reviewer's sign-off word (ruled 2026-09-22)
230
+ // self-contained packet (the email body HTML is embedded so the courier needs no path resolution
231
+ // across the archive move). The courier sends EXACTLY this — same subject, text and recipient the
232
+ // deleted send stages composed, now composed in code.
233
+ // ONE report: the packet carries no readiness bits — every delivered run routes the same way.
234
+ const packet = {
235
+ // ONE canonical runId form (charter P1 §3): `<slug>-<date>-<codename>` — the same id status.json,
236
+ // the pool and the knockout lane carry ("one format across every consumer"). The packet's runId
237
+ // NAMES the outbox marker below, and the dateless `<slug>-<codename>` form this lane used to mint
238
+ // is what split one delivery into TWO markers two minutes apart (the outbox rescan re-drops from
239
+ // status.runId, saw no marker under the dated name, and minted a second one — the 2026-07-19
240
+ // runId-form split recurring). resolveRun still accepts the dateless legacy form for historical
241
+ // packets; the .sent orphan guard (outbox-backoff.mjs) stays as defence and matches both forms.
242
+ runId: `${run.slug}-${run.date}-${run.codename}`, agent,
243
+ forwarder: job.forwarder, forwarderEmail: job.forwarderEmail, msgId: job.msgId,
244
+ conversationId: job.conversationId ?? null, // reply-lane fallback when msgId is not a Graph id
245
+ subject: deliverySubject(emailProductName, job),
246
+ emailBodyHtml: readFileSync(P.emailBody, "utf8"),
247
+ // — the notice goes to whoever ASKED, with the operator's copy beside it and a
248
+ // stated reason when no number is held. It used to go to AGENT_WHATSAPP[agent], which is the
249
+ // operator on every run because every user shares one agent id.
250
+ ...whatsappRouting(job, agent),
251
+ whatsappText: `✅ Clearotron search for ${mark}${ref} is done.${vtag} Report: ${published.url}`,
252
+ url: published.url, verdict, markName: job.markName ?? job.name ?? null,
253
+ };
254
+ // A NEW send supersedes any previous one: .sent is PER-SEND idempotence, not per-run-lifetime.
255
+ // A run that terminally failed (notice sent → .sent written) and was then resumed to success
256
+ // would otherwise be SKIPPED by clearotron-deliver's .sent guard — the report would never send.
257
+ // The stale failure packet goes too, so the run dir tells exactly one delivery story. B4: the
258
+ // per-channel send receipts are per-SEND state exactly like .sent — a stale email receipt from
259
+ // the superseded send would make clearotron-deliver skip THIS packet's email, so they reset together.
260
+ try { rmSync(join(run.runDir, ".sent")); } catch { /* none */ }
261
+ try { rmSync(paths(run.runDir).sendReceipts, { force: true }); } catch { /* none */ }
262
+ try { rmSync(paths(run.runDir).failure); } catch { /* none */ }
263
+ writeFileSync(paths(run.runDir).delivery, JSON.stringify(packet, null, 2) + "\n");
264
+ note(`delivery: handoff → wrote _driver/delivery.json (the forwarding agent's completion-watch sends email${packet.whatsappTo ? " + WhatsApp" : ""})`);
265
+ // Workstream B — instant delivery: drop a marker in the fixed outbox so the prelim-outbox.path unit
266
+ // wakes the forwarder agent NOW (vs ≤55m on the HEARTBEAT completion-watch, which stays as the
267
+ // backstop). The marker only names the agent to wake; status.sendPending + the run's .sent guard
268
+ // remain the source of truth, so a lost/cleared marker never double-sends nor loses a delivery.
269
+ // Best-effort — a marker-write failure must never break the run (the backstop still delivers).
270
+ try {
271
+ mkdirSync(config.outboxDir, { recursive: true });
272
+ writeFileSync(join(config.outboxDir, `${packet.runId}.pending`), `${agent}\n`);
273
+ note(`delivery: outbox marker → ${join(config.outboxDir, `${packet.runId}.pending`)} (instant wake)`);
274
+ } catch (e) {
275
+ note(`delivery: outbox marker write skipped (${String(e.message).slice(0, 100)}) — HEARTBEAT backstop still delivers`);
276
+ }
277
+ }
278
+
279
+ // Final status BEFORE archive so the renamed status.json carries the delivered state into the archive;
280
+ // then rebuild STATUS.md (which scans the archive too).
281
+ // spec 64 — the delivered status carries THE one risk statement too, so the run-status surface can
282
+ // speak the same sentence as every other surface (never a bare "CLEAR" beside an index "High").
283
+ // ONE report: the terminal state is "delivered", full stop — the delivery.{clientReady,defects}
284
+ // second bit is deleted with the split it narrated (machine QC lives on the workbook + telemetry).
285
+ // Lifecycle honesty (charter P1 §4): the terminal state advances the stepper — a delivered run with
286
+ // .published + .delivered on disk must never read "7/9" on any status surface (nothing runs after
287
+ // the packet, so no stage transition would ever finish the display sequence). finalStepFields ⇒ 9/9.
288
+ const deliveredAt = new Date().toISOString();
289
+ // `notified: "pending"` and `sendPending: true` unconditionally, which is what the KNOCKOUT lane has
290
+ // always written one file over. They used to be three-valued because a send STAGE could report
291
+ // success, failure or "no chat binding" here; with the packet as the only lane the integrator owns
292
+ // the outcome, and a field that can hold exactly one value is not evidence of anything. `notifiedChat`
293
+ // is gone for the same reason rather than pinned to false — a key that is always there and always
294
+ // says no reads as a measurement.
295
+ const archived = endTheDeliveredRun({ ctx, run, published, archive, sentinel }, {
296
+ status: { state: "delivered", ...signoffPatch(verdict), statement: emailVerdictOpts.statement ?? undefined, caption: published.caption ?? undefined, url: published.url, deliveredAt, sendPending: true, ...finalStepFields() },
297
+ settle: { state: "delivered", signoff: verdict, deliveredAt, runId: published.runId ?? run.runId, lane: "clearance" },
298
+ delivered: (archivedAt) => ({ verdict, url: published.url, notified: "pending", archived: archivedAt, sendPending: true }),
299
+ });
300
+ note(`=== DELIVERED (verdict ${verdict}) → ${published.url}${archived ? ` — archived → ${archived}` : ""} ===\n`);
301
+ return { ok: true, verdict, url: published.url, runDir: archived ?? run.runDir };
302
+ }
303
+
304
+ // ── WHEN THE OVERALL ASSESSMENT COULD NOT BE COMPLETED, THE RUN DELIVERS WHAT IT HOLDS ──────────────────────
305
+ //
306
+ // Reached from the synthesis site on the pass that resumes a run whose synthesis failed once its recovery was spent:
307
+ // the catch recorded the assessment as not completed and parked the run (parts-not-completed.mjs). The run holds
308
+ // everything except the assessment, and delivers the same page, workbook and email, built from that:
309
+ // · every assessment artifact an earlier pass left is set aside, so no rejected draft and no earlier verdict can
310
+ // reach a surface, and the run's status drops the rating it may still carry;
311
+ // · the audit is the search log the run holds, without the records the assessment would have rated and without
312
+ // placement's set-asides, which beside no finding would read as a list of only dismissals;
313
+ // · the coverage rows are the register's own coverage ledger, each with its recorded status;
314
+ // · report.md carries the run's identity and, as its conclusion, the one sentence for this state and the shipped
315
+ // action line, which the page, the email and the run list all read;
316
+ // · the workbook's "Findings" row says the part was not completed (degraded-parts.mjs).
317
+ // Then it publishes and delivers as every run does. A failure from here on is an ordinary failure: the record exists,
318
+ // so the catch does not route it again, and the run ends with the stop notice.
319
+ async function deliverWithoutTheAssessment(open) {
320
+ note(`[assessment] the overall assessment was not completed at ${open.stage ?? "an unrecorded stage"} — delivering what the run holds, with the gap stated`);
321
+ const setAside = setAsideTheAssessment(P, run.runDir);
322
+ writeRunStatus(ctx, { tier: null, statement: null, ...signoffPatch(null) });
323
+ let audit = null;
324
+ try {
325
+ const a = searchLogAuditMd(P);
326
+ writeFileSync(P.audit, a.md);
327
+ audit = a.counts;
328
+ } catch (e) { runLog(run.runDir, { event: "audit-build-failed", reason: String(e?.message ?? e).slice(0, 160) }); }
329
+ const coverageRows = assessmentCoverageOfRun(run.runDir);
330
+ atomicWrite(driverDir(run.runDir, NOT_COMPLETED_DIR, "assessment-coverage.json"), JSON.stringify({ rows: coverageRows }, null, 2) + "\n");
331
+ writeFileSync(P.report, renderReportOverview({ overall_caption: assessmentNotCompletedNote(), handling_note: null, actions: [], methodology: null },
332
+ reportIdentityRecord(job, ctx, run.runDir, null)));
333
+ writeScopeFactsOf(ctx, P, run.runDir);
334
+ applyScopeFrontMatterOf(P, run.runDir);
335
+ runLog(run.runDir, { event: "assessment-not-completed-delivery", stage: open.stage ?? null, sig: open.sig ?? null,
336
+ setAside, coverageRows: coverageRows.length, audit });
337
+ return await publishAndDeliver(null);
338
+ }
339
+ return { deliverWithoutTheAssessment, publishAndDeliver };
340
+ }
@@ -102,12 +102,13 @@
102
102
 
103
103
  import { readdirSync, readFileSync, writeFileSync } from "node:fs";
104
104
  import { join } from "node:path";
105
- import { driverDir, labelOfDriverFile } from "../shared/driver-dir.mjs"; //
106
105
  import { runLog, note } from "./log.mjs";
107
106
  import { writeRunStatus } from "./progress.mjs";
108
107
  // tokens.mjs imports this module too (isCodeSide, stampRunEconomics). The cycle is safe because each side
109
108
  // reads the other's bindings only inside functions, never while the module is loading.
110
- import { isAttemptRow, modelKey } from "./tokens.mjs";
109
+ import { isAttemptRow, modelKey } from "./attempt-rows.mjs";
110
+ import { vendorOf } from "./engine/stamps.mjs";
111
+ import { driverDir, labelOfDriverFile, paths, readJson } from "./run-record.mjs";
111
112
 
112
113
  /**
113
114
  * The provider's separately-priced token kinds, in the driver's own `usage` vocabulary (gateway.mjs /
@@ -232,26 +233,7 @@ function foldBilling(bucketMap, rec, cls) {
232
233
  // what was stamped; `vendors` carries who was billed; `mixedVendors` flags the second, which is the one
233
234
  // the owner rules on.
234
235
  //
235
- // A CLOSED TABLE, NOT A PREFIX RULE. `anthropic-*` → anthropic is shorter and would silently adopt any
236
- // future engine whose name began that way, which is how a vendor claim becomes a guess. An engine this
237
- // table does not know is reported BY NAME and blocks the single-vendor claim, because "I do not know who
238
- // billed this" and "one vendor" are different answers and only one of them is safe to print.
239
- //
240
- // THE NATIVE-LANGUAGE ROWS STAMP THE VENDOR ITSELF. jxBillingStamp (jx-lanes.mjs) writes as the row's
241
- // engine the provider the engine door resolved, `anthropic` or `openai` (engine/auth.mjs), so those two
242
- // names are engines this table must place. Without them an Anthropic-only run with a native-language turn
243
- // named `anthropic` as an engine that bills to no vendor, in the same sentence that named anthropic as its
244
- // one vendor. Two exact names, still a closed table.
245
- export const ENGINE_VENDORS = Object.freeze({
246
- "anthropic-agent": "anthropic",
247
- "anthropic-direct": "anthropic",
248
- "anthropic-completions": "anthropic",
249
- "openai-agent": "openai",
250
- "anthropic": "anthropic",
251
- "openai": "openai",
252
- });
253
- /** The vendor an engine bills to, or null when the table does not name one. */
254
- export const vendorOf = (engine) => ENGINE_VENDORS[String(engine ?? "")] ?? null;
236
+ // THE ENGINE-TO-VENDOR TABLE is `vendorOf` in engine/stamps.mjs, with what else each stamp means.
255
237
 
256
238
  // ── WHAT THE RUN CANNOT SAY ABOUT ITSELF ──────────────────────────────────────────────────
257
239
  //
@@ -364,7 +346,7 @@ function readRows(path) {
364
346
  // recomputed weeks later reads the same number the requester was shown. The knockout lane computes no
365
347
  // quote at all and legitimately has no row.
366
348
  function readQuote(runDir) {
367
- const rows = readRows(driverDir(runDir, "run.jsonl"));
349
+ const rows = readRows(paths(runDir).run);
368
350
  if (!rows) return null;
369
351
  for (let i = rows.length - 1; i >= 0; i--) if (rows[i]?.event === "quote") {
370
352
  const { event, ts, ...q } = rows[i];
@@ -374,7 +356,7 @@ function readQuote(runDir) {
374
356
  }
375
357
 
376
358
  function readStatus(runDir) {
377
- try { return JSON.parse(readFileSync(join(runDir, "status.json"), "utf8")) ?? null; }
359
+ try { return readJson(join(runDir, "status.json")) ?? null; }
378
360
  catch { return null; }
379
361
  }
380
362
 
@@ -589,7 +571,7 @@ export function runEconomics(runDir, { now = null, bytesPerOutputToken = BYTES_P
589
571
  runDir,
590
572
  // The instrument's own weakness, on every record it writes. See the header.
591
573
  modelBasis: "requested",
592
- modelBasisNote: "this record's billing classes key on the dispatch row's `modelUsed`, which is resolved from the REQUESTED alias. Since #238 the rows ALSO carry `modelActual`/`modelBasis`/`modelMismatch` — the provider's own answer, or an explicit unknown — and an unhonoured override now fails the turn instead of being billed here silently. Switching this module to a per-record actual basis is #240's work",
574
+ modelBasisNote: "this record's billing classes key on the dispatch row's `modelUsed`, which is resolved from the REQUESTED alias. The rows ALSO carry `modelActual`/`modelBasis`/`modelMismatch` — the provider's own answer, or an explicit unknown — and an unhonoured override now fails the turn instead of being billed here silently. Switching this module to a per-record actual basis is still to do",
593
575
  billingClasses: BILLING_CLASSES,
594
576
  telemetryPresent: files != null,
595
577
  dispatchCensus: census,
@@ -621,7 +603,7 @@ export function stampRunEconomics(runDir, phase, { now = Date.now() } = {}) {
621
603
  if (!runDir) return null;
622
604
  try {
623
605
  const econ = runEconomics(runDir, { now });
624
- try { writeFileSync(driverDir(runDir, "economics.json"), JSON.stringify({ phase, ...econ }, null, 2) + "\n"); }
606
+ try { writeFileSync(paths(runDir).economics, JSON.stringify({ phase, ...econ }, null, 2) + "\n"); }
625
607
  catch { /* best-effort */ }
626
608
  const summary = {
627
609
  phase,