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
@@ -7,16 +7,16 @@
7
7
  // self-reported trail), meta.json batch stamps, and the email composer. Deliberately separate from publishReport (single-clearance-shaped); shares the exported
8
8
  // palette (TONE_TIER, resolved against the run's FROZEN framework) so driver and interactive output
9
9
  // can never drift and a knockout never reads the clearance composer's module state.
10
- import { readFileSync, writeFileSync, copyFileSync, mkdirSync, chmodSync, existsSync } from 'node:fs';
10
+ import { readFileSync, writeFileSync, existsSync } from 'node:fs';
11
+ import { finishPoolRun, openPoolRun, refreshStaffPages } from './shell.mjs';
11
12
  import { plainDeferralReason, plainCause } from '../deferral-row.mjs'; import { knockoutStepFailures, PART_NAMES, RULED_WORDS, NOT_COMPLETED, linkNotOnRegisterSite } from '../degraded-parts.mjs'; import { ownersOwedACheck, composeOwnerQuery } from '../owner-use-check.mjs'; import { KNOCKOUT_WEB } from '../stages-knockout.mjs'; // — the reader's words for a search left open; and the parts that failed as a whole
12
13
  import { join } from 'node:path';
13
- import { driverDir, ensureDriverDir, RUN_DIR_MODE } from '../../shared/driver-dir.mjs'; //
14
14
  import { riskTier, TONE_TIER, regenIndex, regenSurfaces, auditRouteFor, markReportRouteFor, reportRouteFor } from './index.mjs';
15
15
  import { runKnockoutLint, deliveryFlagLines } from '../predelivery-lint.mjs';
16
16
  import { note } from '../log.mjs';
17
17
  import { addSheet } from './xlsx.mjs';
18
18
  import { COUNT_PREDICATES, COUNT_BASIS, countsForMark, countLine, countedMarks, variantFormsLine, disclosedFloor, moreThan, countNote } from '../register-count.mjs';
19
- import { RECORD_BASIS, noneCarriedForward, recordsForMark, recordsLine, listedMarks, normalizeRegisterRecordLinks } from '../register-records.mjs';
19
+ import { noneCarriedForward, recordsForMark, recordsLine, normalizeRegisterRecordLinks } from '../register-records.mjs';
20
20
  import { reportIdentityFor, productCoverageNote, kebab } from '../search-policy.mjs';
21
21
  import { batchMarkName } from '../mark-name.mjs';
22
22
  import { renderKnockoutHtml, knockoutReportData } from './render-knockout.mjs';
@@ -27,7 +27,6 @@ import { servedModels } from '../tokens.mjs';
27
27
  import { knockoutFindingViews, knockoutFindingRange } from '../findings-model.mjs';
28
28
  import { knockoutReceipts, worstBand } from '../verify-knockout.mjs';
29
29
 
30
- const grpRead = (p, mode) => { try { chmodSync(p, mode); } catch { /* best-effort */ } };
31
30
  const esc = (s) => String(s ?? '').replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/"/g, '&quot;');
32
31
  // The http(s)-only link helpers that used to live here went with the MSO review table (2026-07-28) and
33
32
  // had no caller left: this module writes workbook CELLS and a cover note that links the report, never a
@@ -380,7 +379,19 @@ export async function buildKnockoutWorkbook(findings, receipts, outPath, registe
380
379
  // The audit link used to be `url.replace(/report\.html$/, auditFile)`, a second derivation of a URL that
381
380
  // silently produced nothing the moment a report stopped being called `report.html`; a batch's documents
382
381
  // are `report-<slug>.html`, so that surgery would have shipped a broken workbook link on every batch.
383
- export function composeKnockoutEmail({ findings, framework, overall, reports = [], auditUrl = null, job, registerCounts = null, qcFlags = [] }) {
382
+ /**
383
+ * THE NAME A KNOCKOUT'S EMAIL AND RECORD GIVE THE PRODUCT: the product's own, read from the run's frozen policy, as its report
384
+ * page and the staff list read it (owner's ruling, 2026-11-10). The subject, the email's first line and the pool's report.md
385
+ * title all take it from here. Null where the registry no longer names the level: each surface then says less, as a
386
+ * clearance's does, and never names a product the run may not have been.
387
+ */
388
+ export const knockoutName = (searchPolicy) => reportIdentityFor(searchPolicy ?? null).identity || null;
389
+
390
+ /** The pool's report.md title: the product's name in capitals where it has one, then the run. Staff read it. */
391
+ export const knockoutRecordTitle = (searchPolicy, runId) =>
392
+ `${[knockoutName(searchPolicy)?.toUpperCase(), 'REPORT'].filter(Boolean).join(' ')} — ${runId}`;
393
+
394
+ export function composeKnockoutEmail({ findings, framework, overall, reports = [], auditUrl = null, job, registerCounts = null, qcFlags = [], productName = null }) {
384
395
  const t = bandTier(framework, overall);
385
396
  const n = (findings.marks ?? []).length;
386
397
  const urlByMark = new Map((reports ?? []).map((r) => [r.mark, r.url]).filter(([, u]) => u));
@@ -388,7 +399,9 @@ export function composeKnockoutEmail({ findings, framework, overall, reports = [
388
399
  // says how to read the list instead: a "full report" link on a batch could only be one name standing
389
400
  // for all of them. A single-mark run keeps its head link exactly as before — same bytes, same place.
390
401
  const only = n === 1 ? urlByMark.get((findings.marks ?? [])[0]?.name) ?? null : null;
391
- const head = `<p style="${FONT}">Knockout trademark review${job?.ref ? ` — ${esc(job.ref)}` : ''}: <b>${n} mark${n === 1 ? '' : 's'}</b>, ${n === 1 ? 'rating' : 'highest rating'} <b style="color:${t.txt}">${esc(overall ?? '')}</b>.`
402
+ // The product's name and the reference, each where there is one: a part left out leaves no dash or colon behind it.
403
+ const lead = [productName, job?.ref].filter(Boolean).map((p) => esc(p)).join(' — ');
404
+ const head = `<p style="${FONT}">${lead ? `${lead}: ` : ''}<b>${n} mark${n === 1 ? '' : 's'}</b>, ${n === 1 ? 'rating' : 'highest rating'} <b style="color:${t.txt}">${esc(overall ?? '')}</b>.`
392
405
  + (only ? ` <a href="${esc(only)}">Open the full report</a>${auditUrl ? ` · <a href="${esc(auditUrl)}">audit workbook</a>` : ''}.` : '')
393
406
  + (!only && n > 1 ? ` One report per name below${auditUrl ? `, and one <a href="${esc(auditUrl)}">audit workbook</a> for the batch` : ''}.` : '') + `</p>`;
394
407
  // — THE FIRST NON-BLANK, never element 0. `?? fallback` catches null and undefined
@@ -421,11 +434,15 @@ export function composeKnockoutEmail({ findings, framework, overall, reports = [
421
434
  }
422
435
 
423
436
  // ── The publisher ────────────────────────────────────────────────────────────────────────────────────
424
- // `delivery`: the run's frozen delivery overlay, threaded to the template so the knockout obeys the
425
- // SAME three-state confidentiality rule the clearance does. It defaults to null — the no-opinion state,
426
- // which renders the plain marking this template always printed — so the ~15 fixtures in
427
- // knockout-units.test.mjs that call this without one are unaffected by its arrival.
428
- export async function publishKnockout({ runId, codename, runDir, findings, plan, framework, overall, poolRoot, poolUrl, customerKey, searchPolicy, tokens, registerCounts = null, skipRegen = false, delivery = null }) {
437
+ /**
438
+ * THE REPORT DOCUMENT FOR A KNOCKOUT: every fact the batch's surfaces print, read from the run once.
439
+ *
440
+ * It is read before anything is written to the pool, and each surface prints from it: the workbook, each name's page
441
+ * and data file, the pool's `report.md` and `meta.json`. It refuses a batch whose citations cannot be traced (the
442
+ * receipts door below), and it writes the run's own lint receipt, as the publisher always did. It writes nothing to
443
+ * the pool.
444
+ */
445
+ export async function readKnockoutDocument({ runId, runDir, findings, plan, framework, overall, poolRoot, poolUrl, customerKey, searchPolicy, registerCounts = null }) {
429
446
  // ── THE RECEIPTS DOOR ───────────────────────────────────────────────────────────────────────
430
447
  // BEFORE anything is written, and it can refuse. The live lane already gates the merged artifact
431
448
  // (pipeline-knockout.mjs → validateMergedFindings), so on that path this is belt-and-braces; the path
@@ -451,36 +468,8 @@ export async function publishKnockout({ runId, codename, runDir, findings, plan,
451
468
  // A pass with nothing to check is not the same answer as a pass, so it is recorded rather than
452
469
  // assumed: `urls: 0` in the receipt below means no finding cited anything.
453
470
  note(`knockout receipts: ${receipts.checked.urls} citation(s) across ${receipts.checked.findings} finding(s) on ${receipts.checked.citing}/${receipts.checked.marks} mark(s) traced to held evidence`);
454
- const poolRunDir = join(poolRoot, runId);
455
- // Owner and group only: a mode given to mkdir, which keeps the set-GID the pool root passes down.
456
- mkdirSync(poolRunDir, { recursive: true, mode: RUN_DIR_MODE });
457
- const writeRO = (name, data) => { const p = join(poolRunDir, name); writeFileSync(p, data); grpRead(p, 0o640); };
458
-
459
- // ── THE RUN'S WORKING RECORD TRAVELS WITH THE REPORT ──────────────────────────────────────────────
460
- //
461
- // The delivered directory held the report, its data and the workbook, and nothing the engine itself
462
- // wrote. That is what the acceptance read needs to tell a line the ENGINE wrote from a line the
463
- // RENDERER invented: without it the check can still place a line as report text or as a sanctioned
464
- // label, so it passes — and cannot fail in the way it exists to fail. A clearance run's record is
465
- // `audit.md` and `findings.json`; this lane's own names are these two, and they are copied rather
466
- // than rebuilt so the pool carries the bytes the stages wrote.
467
- //
468
- // AN ABSENT ONE IS SAID, NOT SKIPPED. A run whose stage never wrote its assessment is a different
469
- // thing from a run that wrote one, and a publisher that copies what it finds and says nothing about
470
- // what it does not makes the two look identical to the next reader — which is the whole defect this
471
- // closes, one directory along.
472
- for (const name of ['knockout-findings.json', 'knockout-assessment.md']) {
473
- const src = join(runDir, name);
474
- if (existsSync(src)) {
475
- const dest = join(poolRunDir, name);
476
- copyFileSync(src, dest);
477
- grpRead(dest, 0o640);
478
- } else {
479
- note(`knockout working record: ${name} is not in the run directory, so the delivered report has no engine text to be checked against`);
480
- }
481
- }
482
471
  // WHAT THE RECORD SAYS, NOT THE CLOCK (report-dates.mjs): a republish is neither a new search nor a new issue.
483
- const dates = reportDates({ runDir, poolRunDir });
472
+ const dates = reportDates({ runDir, poolRunDir: join(poolRoot, runId) });
484
473
  const issued = zurichStamp(dates.issuedAt);
485
474
  const searched = zurichStamp(dates.searchedAt);
486
475
 
@@ -488,7 +477,7 @@ export async function publishKnockout({ runId, codename, runDir, findings, plan,
488
477
  // is the record of what the driver called, the other is the check that the findings cite what it held.
489
478
  let sweepReceipts = [];
490
479
  try {
491
- sweepReceipts = readFileSync(driverDir(runDir, 'knockout-sweep.jsonl'), 'utf8').split('\n').filter(Boolean)
480
+ sweepReceipts = readFileSync(paths(runDir).knockoutSweep, 'utf8').split('\n').filter(Boolean)
492
481
  .map((l) => { try { return JSON.parse(l); } catch { return null; } }).filter(Boolean);
493
482
  } catch { /* fixture/degenerate runs may have none */ }
494
483
 
@@ -506,27 +495,27 @@ export async function publishKnockout({ runId, codename, runDir, findings, plan,
506
495
  // here so the decision has something to key on when it is made.
507
496
  let registerCountsUnreadable = false;
508
497
  if (!registerCounts) {
509
- try { registerCounts = JSON.parse(readFileSync(driverDir(runDir, 'register-counts.json'), 'utf8')); }
510
- catch { registerCounts = null; registerCountsUnreadable = existsSync(driverDir(runDir, 'register-counts.json')); }
498
+ try { registerCounts = readJson(paths(runDir).registerCounts); }
499
+ catch { registerCounts = null; registerCountsUnreadable = existsSync(paths(runDir).registerCounts); }
511
500
  }
512
501
  // part 5 — the filings sidecar, read the same way and for the same reason: the publisher renders
513
502
  // what the driver measured and wrote, and a republish of an archived run picks up the same file. An
514
503
  // absent sidecar publishes exactly the counts-only knockout, with no filings section anywhere.
515
504
  let registerRecords = null, registerRecordsUnreadable = false;
516
- try { registerRecords = JSON.parse(readFileSync(driverDir(runDir, 'register-records.json'), 'utf8')); }
517
- catch { registerRecords = null; registerRecordsUnreadable = existsSync(driverDir(runDir, 'register-records.json')); }
505
+ try { registerRecords = readJson(paths(runDir).registerRecords); }
506
+ catch { registerRecords = null; registerRecordsUnreadable = existsSync(paths(runDir).registerRecords); }
518
507
  // The owner lookups this run made, read the same tolerant way as the records above:
519
508
  // an archived run that predates the lane has no file, and its cards then render exactly as they were
520
509
  // delivered. The source line the report prints comes from HERE, not from anything the seat typed.
521
510
  let ownerChecks = [];
522
- try { ownerChecks = JSON.parse(readFileSync(driverDir(runDir, 'owner-checks.json'), 'utf8')).checks ?? []; }
511
+ try { ownerChecks = readJson(paths(runDir).ownerChecks).checks ?? []; }
523
512
  catch { ownerChecks = []; }
524
513
  // The request the run was given, read the same tolerant way as the sidecars above and for the same
525
514
  // reason (A.1). It is what "About this request" states; a run archived before the
526
515
  // sidecar existed has none, and its page renders exactly as it was delivered.
527
516
  let instructedScope = null, scopeUnreadable = false;
528
- try { instructedScope = JSON.parse(readFileSync(driverDir(runDir, 'instructed-scope.json'), 'utf8')); }
529
- catch { instructedScope = null; scopeUnreadable = existsSync(driverDir(runDir, 'instructed-scope.json')); }
517
+ try { instructedScope = readJson(paths(runDir).instructedScope); }
518
+ catch { instructedScope = null; scopeUnreadable = existsSync(paths(runDir).instructedScope); }
530
519
  // The run's frozen method, where its framework states one (framework-method.mjs): the report card and
531
520
  // the workbook's band cell show the framework's inputs beside the band. A run that froze none — every
532
521
  // run before the method existed among them — renders the band alone, as it was delivered.
@@ -583,7 +572,7 @@ export async function publishKnockout({ runId, codename, runDir, findings, plan,
583
572
  qcFlags = deliveryFlagLines(lint.failures.filter((c) => c.surface === 'report'));
584
573
  try {
585
574
  ensureDriverDir(runDir);
586
- writeFileSync(driverDir(runDir, 'predelivery-lint.json'), JSON.stringify({
575
+ writeFileSync(paths(runDir).predeliveryLint, JSON.stringify({
587
576
  ts: new Date().toISOString(),
588
577
  lane: 'knockout',
589
578
  checks: lint.checks, failures: lint.failures.map((f) => f.id),
@@ -616,19 +605,12 @@ export async function publishKnockout({ runId, codename, runDir, findings, plan,
616
605
  // A first web question whose answer is on disk and whose trail entry is not. Only the first question is
617
606
  // read: a second question's missing entry cannot be told from one that got no answer. A run with no
618
607
  // trail file at all was delivered before the trail existed, and republishes as it was delivered.
619
- const keptATrail = existsSync(driverDir(runDir, 'knockout-sweep.jsonl'));
608
+ const keptATrail = existsSync(paths(runDir).knockoutSweep);
620
609
  const recordsNotKept = (keptATrail ? (plan?.marks ?? []) : []).map((m) => String(m?.name ?? '')).filter((name) => name
621
610
  && existsSync(join(runDir, 'research', `${kebab(name)}.md`))
622
611
  && !sweepReceipts.some((r) => r?.mark === name && !r.question))
623
612
  .map((mark) => ({ mark, preset: koPreset }));
624
- const openPoints = (() => { try { return JSON.parse(readFileSync(driverDir(runDir, 'knockout-corrections.json'), 'utf8')).open ?? []; } catch { return []; } })();
625
- const auditFile = `knockout-audit-${codename ?? runId}.xlsx`;
626
- await buildKnockoutWorkbook(findings, sweepReceipts, join(poolRunDir, auditFile), registerCounts, qcFlags, framework, registerRecords, frameworkMethod, [...ownerChecks, ...lookupsNotRun], {
627
- listing: registerRecords ? null : steps.listing, reading: steps.reading, review: steps.review, machineChecks: machineChecksFailed,
628
- aboutThisRequest: scopeUnreadable ? { reason: NOT_COMPLETED } : null, droppedLinks: recordLinksDropped, recordsNotKept, openPoints,
629
- });
630
- grpRead(join(poolRunDir, auditFile), 0o640);
631
-
613
+ const openPoints = (() => { try { return readJson(paths(runDir).knockoutCorrections).open ?? []; } catch { return []; } })();
632
614
  // The run's report identity, off the SAME registry row that chose its machinery (search-policy.mjs
633
615
  // PRODUCT_POLICIES). Resolved from the frozen policy sidecar so an archived run re-renders under the
634
616
  // stage it was sold as, not under whatever today's registry calls that level.
@@ -700,10 +682,99 @@ export async function publishKnockout({ runId, codename, runDir, findings, plan,
700
682
  // because it is a property of the run. A read that throws records nothing rather than failing a publish.
701
683
  let served = null;
702
684
  try { served = runDir ? servedModels(runDir) : null; } catch { served = null; }
685
+ const statement = knockoutStatement(framework, findings.marks ?? []);
686
+ // THE NAME THE RUN IS ABOUT. This object carried `title` and no `markName` key at all, so the
687
+ // portal's displayName() fell through to `title` exactly as designed, and every delivered knockout row
688
+ // read "Knockout review — N marks" in a column whose whole job is to name a mark. A batch of them is a
689
+ // list of identical rows distinguishable only by run codename — two of them can be different marks for
690
+ // different purposes, and nothing on the page says which is which.
691
+ //
692
+ // The data was always there — status.json carries markName and marks[0].name sits in this very object.
693
+ // It was simply never lifted to the field the UI reads. This is NOT the documented back-fill case: that
694
+ // comment says null means "delivered before the stamp existed" and must never render as "no mark", but
695
+ // for the knockout lane null was not staleness, it was permanent.
696
+ //
697
+ // One rule, both shapes: one mark is the mark, several is the first plus a count. Never the run type.
698
+ // The rule itself now lives in mark-name.mjs, because this was one of TWO spellings of it — the live
699
+ // lane wrote "(+N marks)" onto status.json for the same batch, so a run changed its name at delivery
700
+ // and the browser, which threads reads on the name string, listed one batch as two different marks.
701
+ const markNames = (findings.marks ?? []).map((m) => m.name).filter(Boolean);
702
+ // WHICH ORGANISATION'S GENERIC this batch was filed under, read from the frozen sidecar exactly as the clearance
703
+ // publisher reads it. Absent on a company's batch and on one filed before organisations existed.
704
+ const organisation = (() => { try { const f = readJson(paths(runDir).profile); return typeof f?.organisation === 'string' && f.organisation ? f.organisation : undefined; } catch { return undefined; } })();
705
+ return {
706
+ receipts, dates, issued, searched, sweepReceipts, registerCounts, registerCountsUnreadable, registerRecords,
707
+ registerRecordsUnreadable, ownerChecks, instructedScope, scopeUnreadable, frameworkMethod, recordLinksDropped,
708
+ officeLinks, qcFlags, machineChecksFailed, steps, lookupsNotRun, recordsNotKept, openPoints, identity, probeRan,
709
+ markRows, single, origin, reportUrlFor, demoData, served, statement, markNames, organisation,
710
+ // WHICH BUILD produced this, read once for every surface that records it. null off a git checkout.
711
+ engineCommit: engineCommit(),
712
+ // FACTS THE SURFACES STATE TWO WAYS, each way named, so every surface prints what it printed before. Which way is
713
+ // right is for the owner to rule; nothing here chooses.
714
+ // The issue date: `issued` above is the firm's date and time (Europe/Zurich), which each name's page prints;
715
+ // meta.json keeps the date of the UTC instant, which differs from it near midnight.
716
+ issuedDateUtc: dates.issuedAt.slice(0, 10),
717
+ // The product's name in the run's record, with how many names, which meta.json and the staff index print; the
718
+ // pool's report.md and the email print fixed Knockout wording instead.
719
+ // The plural bug lived on this line: `${n} marks` with no guard, so every one-mark batch said
720
+ // "1 marks". The sibling statement writer above has always guarded it; this never did.
721
+ //
722
+ // AND IT SPELT THE PRODUCT BY HAND. The literal was "Knockout review" — a product
723
+ // retired — so every batch published under the live "Knockout search" stamped a name the offering
724
+ // no longer sells into its own record, and the staff pool index rendered it in the Mark column
725
+ // (publish/index.mjs anonMark(r.title)) on every knockout row, past and future. The identity is
726
+ // resolved twenty lines up from the run's own frozen policy; this is that same string. A level the
727
+ // registry cannot name says only how many marks, because a wrong product name is worse than none.
728
+ title: [identity.identity, `${markNames.length} mark${markNames.length === 1 ? '' : 's'}`]
729
+ .filter(Boolean).join(' — '),
730
+ // The batch's badge, read once for report.md's front matter and meta.json.
731
+ overallBadge: bandBadge(framework, overall),
732
+ };
733
+ }
734
+
735
+ // `delivery`: the run's frozen delivery overlay, threaded to the template so the knockout obeys the
736
+ // SAME three-state confidentiality rule the clearance does. It defaults to null — the no-opinion state,
737
+ // which renders the plain marking this template always printed — so the ~15 fixtures in
738
+ // knockout-units.test.mjs that call this without one are unaffected by its arrival.
739
+ export async function publishKnockout({ runId, codename, runDir, findings, plan, framework, overall, poolRoot, poolUrl, customerKey, searchPolicy, tokens, registerCounts: givenCounts = null, skipRegen = false, delivery = null }) {
740
+ // `givenCounts`: counts the lane already holds; the document reads the run's own when none are given.
741
+ const doc = await readKnockoutDocument({ runId, runDir, findings, plan, framework, overall, poolRoot, poolUrl, customerKey, searchPolicy, registerCounts: givenCounts });
742
+ const { receipts, dates, issued, searched, sweepReceipts, registerCounts, registerRecords, registerRecordsUnreadable,
743
+ ownerChecks, instructedScope, scopeUnreadable, frameworkMethod, recordLinksDropped, officeLinks, qcFlags,
744
+ machineChecksFailed, steps, lookupsNotRun, recordsNotKept, openPoints, identity, probeRan, markRows, single, origin,
745
+ reportUrlFor, demoData, served, statement, markNames, organisation, issuedDateUtc, title, overallBadge } = doc;
746
+ const { poolRunDir, writeRO, copyRO, buildWorkbook, writeDataFile } = openPoolRun(poolRoot, runId, { runDir });
747
+
748
+ // ── THE RUN'S WORKING RECORD TRAVELS WITH THE REPORT ──────────────────────────────────────────────
749
+ //
750
+ // The delivered directory held the report, its data and the workbook, and nothing the engine itself
751
+ // wrote. That is what the acceptance read needs to tell a line the ENGINE wrote from a line the
752
+ // RENDERER invented: without it the check can still place a line as report text or as a sanctioned
753
+ // label, so it passes — and cannot fail in the way it exists to fail. A clearance run's record is
754
+ // `audit.md` and `findings.json`; this lane's own names are these two, and they are copied rather
755
+ // than rebuilt so the pool carries the bytes the stages wrote.
756
+ //
757
+ // AN ABSENT ONE IS SAID, NOT SKIPPED. A run whose stage never wrote its assessment is a different
758
+ // thing from a run that wrote one, and a publisher that copies what it finds and says nothing about
759
+ // what it does not makes the two look identical to the next reader — which is the whole defect this
760
+ // closes, one directory along.
761
+ for (const name of ['knockout-findings.json', 'knockout-assessment.md']) {
762
+ const src = join(runDir, name);
763
+ if (existsSync(src)) {
764
+ copyRO(src, name);
765
+ } else {
766
+ note(`knockout working record: ${name} is not in the run directory, so the delivered report has no engine text to be checked against`);
767
+ }
768
+ }
769
+ // A workbook that cannot be built no longer stops the batch: every name's report ships, and nothing names the workbook.
770
+ const { auditFile, auditError } = await buildWorkbook(`knockout-audit-${codename ?? runId}.xlsx`, (at) => buildKnockoutWorkbook(findings, sweepReceipts, at, registerCounts, qcFlags, framework, registerRecords, frameworkMethod, [...ownerChecks, ...lookupsNotRun], {
771
+ listing: registerRecords ? null : steps.listing, reading: steps.reading, review: steps.review, machineChecks: machineChecksFailed,
772
+ aboutThisRequest: scopeUnreadable ? { reason: NOT_COMPLETED } : null, droppedLinks: recordLinksDropped, recordsNotKept, openPoints,
773
+ }));
774
+
703
775
  const reports = markRows.map((m) => {
704
776
  const slug = kebab(m.name);
705
777
  const file = single ? 'report.html' : `report-${slug}.html`;
706
- const dataFile = single ? 'report-data.json' : `report-data-${slug}.json`;
707
778
  // The mark's own slice. Its band is the document's band — `overall` on a one-mark document is that
708
779
  // mark's rating, never the batch's worst, or a clean name would inherit a blocking name's colour.
709
780
  const one = {
@@ -748,25 +819,26 @@ export async function publishKnockout({ runId, codename, runDir, findings, plan,
748
819
  }));
749
820
  // The run as data — what the assistant drafts client-facing mail from, and the shape the portal's
750
821
  // native-render path has been reading for since before anything wrote it. One per report, so the
751
- // native render of a per-mark document is that mark's data and not the batch's.
752
- writeRO(dataFile, JSON.stringify(knockoutReportData(one, framework, {
822
+ // native render of a per-mark document is that mark's data and not the batch's. A data file that
823
+ // cannot be written leaves this name's report in place and the other names publishing; `dataFile`
824
+ // is null for it, so nothing points at a file that is not there.
825
+ const dataFile = writeDataFile(single ? 'report-data.json' : `report-data-${slug}.json`, () => knockoutReportData(one, framework, {
753
826
  runId, codename, overall: markBand, issued, registerCounts, registerRecords, ownerChecks, auditFile, customerKey, matter: runId, servedModels: served,
754
827
  identity: { ...identity, level: searchPolicy?.level ?? null },
755
828
  url: reportUrlFor(slug),
756
- }), null, 2));
829
+ }));
757
830
  return { mark: m.name, slug, file, dataFile, url: reportUrlFor(slug), band: markBand ?? null };
758
831
  });
759
- const statement = knockoutStatement(framework, findings.marks ?? []);
760
832
  // report.md — front-matter compatible with archive greps (title/matter/overall_label)
761
833
  //
762
834
  // — AND IT NAMES THE DOCUMENTS (knockoutDocumentRoutes, below).
763
835
  const routes = knockoutDocumentRoutes(reports, { auditFile });
764
836
  writeRO('report.md', [
765
837
  '---',
766
- `title: "KNOCKOUT TRADEMARK REVIEW REPORT — ${runId}"`,
838
+ `title: "${knockoutRecordTitle(searchPolicy, runId)}"`,
767
839
  `matter: "${runId}"`,
768
840
  `overall_label: "${overall ?? ''}"`,
769
- `overall_badge: "${bandBadge(framework, overall)}"`,
841
+ `overall_badge: "${overallBadge}"`,
770
842
  '---',
771
843
  '',
772
844
  // — THE CROSS-MARK SURFACE, MARKED. Acceptance 3 asks for the banner on "the
@@ -781,45 +853,17 @@ export async function publishKnockout({ runId, codename, runDir, findings, plan,
781
853
  String(findings.batch?.executiveSummary ?? ''),
782
854
  ...routes,
783
855
  ].join('\n'));
784
- // THE NAME THE RUN IS ABOUT. This object carried `title` and no `markName` key at all, so the
785
- // portal's displayName() fell through to `title` exactly as designed, and every delivered knockout row
786
- // read "Knockout review — N marks" in a column whose whole job is to name a mark. A batch of them is a
787
- // list of identical rows distinguishable only by run codename — two of them can be different marks for
788
- // different purposes, and nothing on the page says which is which.
789
- //
790
- // The data was always there — status.json carries markName and marks[0].name sits in this very object.
791
- // It was simply never lifted to the field the UI reads. This is NOT the documented back-fill case: that
792
- // comment says null means "delivered before the stamp existed" and must never render as "no mark", but
793
- // for the knockout lane null was not staleness, it was permanent.
794
- //
795
- // One rule, both shapes: one mark is the mark, several is the first plus a count. Never the run type.
796
- // The rule itself now lives in mark-name.mjs, because this was one of TWO spellings of it — the live
797
- // lane wrote "(+N marks)" onto status.json for the same batch, so a run changed its name at delivery
798
- // and the browser, which threads reads on the name string, listed one batch as two different marks.
799
- const markNames = (findings.marks ?? []).map((m) => m.name).filter(Boolean);
800
- writeRO('meta.json', JSON.stringify({
856
+ const total = finishPoolRun({ writeRO, poolRoot, skipRegen, regenIndex, meta: {
801
857
  runId, codename: codename ?? '', matter: runId,
802
- // The plural bug lived on this line: `${n} marks` with no guard, so every one-mark batch said
803
- // "1 marks". The sibling statement writer above has always guarded it; this never did.
804
- //
805
- // AND IT SPELT THE PRODUCT BY HAND. The literal was "Knockout review" — a product
806
- // retired — so every batch published under the live "Knockout search" stamped a name the offering
807
- // no longer sells into its own record, and the staff pool index rendered it in the Mark column
808
- // (publish/index.mjs anonMark(r.title)) on every knockout row, past and future. The identity is
809
- // resolved twenty lines up from the run's own frozen policy; this is that same string. A level the
810
- // registry cannot name says only how many marks, because a wrong product name is worse than none.
811
- title: [identity.identity, `${markNames.length} mark${markNames.length === 1 ? '' : 's'}`]
812
- .filter(Boolean).join(' — '),
858
+ title, // the product's name and how many names (readKnockoutDocument)
813
859
  markName: batchMarkName(markNames) ?? undefined,
814
- engineCommit: engineCommit(),
860
+ engineCommit: doc.engineCommit,
815
861
  // The models that served the batch, named as a client may read them (tokens.mjs servedModels). Absent when
816
862
  // nothing was read, so a meta from before the record keeps its shape; [] when turns ran and named none a client may read.
817
863
  servedModels: served ?? undefined,
818
864
  client: null, customerKey: customerKey || 'generic',
819
- // WHICH ORGANISATION'S GENERIC this batch was filed under, read from the frozen sidecar exactly as
820
- // the clearance publisher reads it. Absent on a company's batch and on one filed before
821
- // organisations existed.
822
- organisation: (() => { try { const f = JSON.parse(readFileSync(driverDir(runDir, 'profile.json'), 'utf8')); return typeof f?.organisation === 'string' && f.organisation ? f.organisation : undefined; } catch { return undefined; } })(),
865
+ // WHICH ORGANISATION'S GENERIC this batch was filed under (readKnockoutDocument).
866
+ organisation,
823
867
  issuedAt: dates.issuedAt,
824
868
  renderedAt: dates.renderedAt,
825
869
  kind: 'knockout-batch',
@@ -850,12 +894,15 @@ export async function publishKnockout({ runId, codename, runDir, findings, plan,
850
894
  // read it. The one `.run` reader in the tree parses report.html front matter and uses it as a DATE
851
895
  // fallback, so had this field ever been joined to that one it would have printed a product name where
852
896
  // a date belongs. The product is `meta.product`, written from the run's own frozen policy.
853
- overall: overall ?? '', badge: bandBadge(framework, overall), date: dates.issuedAt.slice(0, 10),
897
+ overall: overall ?? '', badge: overallBadge, date: issuedDateUtc,
854
898
  auditFile, statement,
899
+ // WHY THERE IS NO WORKBOOK, when the build threw. Absent when it built, so such a meta is unchanged.
900
+ auditError: auditError ?? undefined,
855
901
  framework: framework ? { key: framework.framework_key, title: framework.title, custom: framework.framework_key !== 'house-triage', bands: framework.bands.map((b) => ({ label: b.label, tone: b.tone })) } : undefined,
856
902
  // Present ⇒ this run has a report-data.json beside its report. The portal reads this to tell a run it
857
903
  // could render natively from a legacy one; the field had readers long before it had a writer.
858
- reportSchema: 'report-data/1',
904
+ // Stamped only when every name's data file wrote, as the clearance stamps it only when its one file wrote.
905
+ reportSchema: reports.every((r) => r.dataFile) ? 'report-data/1' : undefined,
859
906
  // WHICH DOCUMENTS THIS RUN PUBLISHED, and for which name. Every reader that has to open,
860
907
  // serve or link a knockout's reports takes the list from here rather than deriving a filename: the
861
908
  // naming rule (one mark ⇒ `report.html`, several ⇒ `report-<slug>.html`) is written ONCE, above, and
@@ -868,11 +915,9 @@ export async function publishKnockout({ runId, codename, runDir, findings, plan,
868
915
  // it BOTH marks of a batch resolved to the run-level URL, which resolveReportFile answers null
869
916
  // for by design (a batch has no run-level document) — so every per-mark link 404'd, and the
870
917
  // clearances row printed a fallback saying the report was with us for a final read.
871
- reports: reports.map(({ mark, slug, file, dataFile, band }) => ({ mark, slug, file, dataFile, band })),
872
- }, null, 2));
873
-
874
- const total = skipRegen ? null : regenIndex(poolRoot);
875
- if (!skipRegen) { try { await regenSurfaces(poolRoot); } catch { /* best-effort */ } }
918
+ reports: reports.map(({ mark, slug, file, dataFile, band, url }) => ({ mark, slug, file, dataFile, band, url })),
919
+ } });
920
+ await refreshStaffPages({ regenSurfaces, poolRoot, skipRegen, runDir });
876
921
  // `url` IS NULL FOR A BATCH, and that is the honest answer rather than a convenient one. A multi-name
877
922
  // knockout has no single report, so any one URL here would be the first name standing for all of them —
878
923
  // the defect exists to end, re-entering through the delivery packet. Readers take `reports`; a
@@ -888,8 +933,8 @@ export async function publishKnockout({ runId, codename, runDir, findings, plan,
888
933
  // DESTINATION exactly as dead — `<pool>/<runId>/<auditFile>` reaches no handler, on a batch and on a
889
934
  // single alike, which is every knockout ever delivered. `audit.xlsx` is the route literal; the portal
890
935
  // reads the run's real filename out of meta.json and sends it as the download name.
891
- const auditUrl = auditRouteFor(origin, runId);
892
- return { runId, auditFile, auditUrl, url, reports, poolRunDir, statement, total, qcFlags, receipts: receipts.checked };
936
+ const auditUrl = auditFile ? auditRouteFor(origin, runId) : null;
937
+ return { runId, auditFile, auditError, auditUrl, url, reports, poolRunDir, statement, total, qcFlags, receipts: receipts.checked };
893
938
  }
894
939
 
895
940
  /**
@@ -947,3 +992,4 @@ export function knockoutDocumentRoutes(reports, { auditFile = null } = {}) {
947
992
  import { addressListedFilings, reasonCellFor } from './office-record-links.mjs';
948
993
  import { reportDates, zurichStamp } from './report-dates.mjs'; // the dates a report prints, from its record
949
994
  import { declaredRecordOrigins } from '../record-origins.mjs';
995
+ import { driverDir, ensureDriverDir, paths, readJson } from "../run-record.mjs";
@@ -49,6 +49,9 @@ export const OFFICE_RECORD_PAGES = Object.freeze({
49
49
  au: { name: "Australia", address: (r) => addressFrom([r.applicationNumber, r.registrationNumber], /^(\d{1,8})$/, (m) => ({
50
50
  number: m[1], href: `https://search.ipaustralia.gov.au/trademarks/search/view/${m[1]}` })) },
51
51
  // Opened a real record. `-00` is the extension CIPO gives the base application.
52
+ // INPI opens a record only inside a search session that starts at its sign-in page, at an internal id that is
53
+ // not the process number, so there is no address for one record. Checked 2026-11-10.
54
+ br: { name: "Brazil", address: null },
52
55
  ca: { name: "Canada", address: (r) => addressFrom([r.applicationNumber], /^([1-9]\d{0,6})(?:-(\d{2}))?$/, (m) => ({
53
56
  number: m[2] ? `${m[1]}-${m[2]}` : m[1], href: `https://ised-isde.canada.ca/cipo/trademark-search/${m[1]}-${m[2] ?? "00"}?lang=eng` })) },
54
57
  // Rendered in a browser: a real number draws the record, and one that does not exist draws the bare
@@ -58,6 +61,12 @@ export const OFFICE_RECORD_PAGES = Object.freeze({
58
61
  return { number: n, href: `https://www.swissreg.ch/database-client/register/detail?type=trademark&lang=en&no=${encodeURIComponent(n)}` };
59
62
  }) },
60
63
  // The address the EUIPO provider already links (providers/euipo/src/row.js).
64
+ // OEPM's file lookup, at this host since 2025-06-03. The office writes the modality letter before the seven digits;
65
+ // the vendor writes it after them, sometimes with the office's check digit, which the address does not take.
66
+ // Only a national mark (M) is addressed: no other modality was checked. Opened a real record on 2026-11-10: the
67
+ // page draws it with JavaScript, and the data request the page makes returned that record.
68
+ es: { name: "Spain", address: (r) => addressFrom([r.applicationNumber, r.registrationNumber], /^(\d{7})\s*M\d?$/i, (m) => ({
69
+ number: `M${m[1]}`, href: `https://ceo.oepm.es/detalleExpediente?numExp=M${m[1]}` })) },
61
70
  eu: { name: "European Union", address: (r) => addressFrom([r.applicationNumber], /^(\d{1,9})$/, (m) => {
62
71
  const n = pad(m[1], 9);
63
72
  return { number: n, href: `https://euipo.europa.eu/eSearch/#details/trademarks/${n}` };
@@ -77,6 +86,19 @@ export const OFFICE_RECORD_PAGES = Object.freeze({
77
86
  // The register's own search opens records at exactly this address: the application number, then the
78
87
  // registration number when there is one. Opened a real record. The older search.patentstyret.no
79
88
  // addresses now answer 410 Gone.
89
+ // UIBM shows a record only as the answer to a submitted search form; the same request as a link finds nothing, so
90
+ // there is no address for one record. Checked 2026-11-10.
91
+ it: { name: "Italy", address: null },
92
+ // IMPI's MARCia. The address is RM, the year the application was filed, and the application's file number in eight
93
+ // digits: a wrong year finds nothing, so a record with no filing date gets no link, and the registration number is
94
+ // never used, because it is a different number. RM is the prefix for a mark; the vendor's records carry marks, and
95
+ // say nothing of a slogan's or a trade name's prefix. Opened real records on 2026-11-10, filed in 1923, 1968 and
96
+ // 2021: the page draws each with JavaScript, and the data request the page makes returned it.
97
+ mx: { name: "Mexico", address: (r) => {
98
+ const year = /^(\d{4})-\d{2}-\d{2}/.exec(clean(r.applicationDate))?.[1];
99
+ return year ? addressFrom([r.applicationNumber], /^(\d{1,8})$/, (m) => ({
100
+ number: m[1], href: `https://marcia.impi.gob.mx/marcas/search/details/RM${year}${pad(m[1], 8)}` })) : null;
101
+ } },
80
102
  no: { name: "Norway", address: (r) => addressFrom([r.applicationNumber], /^((?:19|20)\d{7})$/, (m) => {
81
103
  const reg = /^\d{1,7}$/.test(clean(r.registrationNumber)) ? clean(r.registrationNumber) : null;
82
104
  return { number: m[1], href: `https://services.patentstyret.no/search-details/trademark/${m[1]}${reg ? `-${reg}` : ""}?lang=en` };
@@ -365,14 +365,29 @@ export function parseCaseLawProfiles(mdText) {
365
365
  });
366
366
  }
367
367
 
368
- // Join parsed profiles to findings: exact ordinal first, then normalized mark+owner containment.
369
- export function joinCaseLawProfiles(profiles, findings) {
368
+ // Join parsed profiles to findings: exact ordinal first, across every finding, then normalized mark+owner containment
369
+ // for the findings still without one, so a name match never takes a profile stamped for a later finding. A profile
370
+ // carries the number in the writer's record; `modelToFolded` (record-fold.mjs) is the map to the delivered record when
371
+ // findings were grouped. A number the map does not know is treated as no number. Two filings grouped into one finding
372
+ // can each have a profile: the finding takes one, a decision over a "no precedent", and neither is left for another.
373
+ export function joinCaseLawProfiles(profiles, findings, modelToFolded = null) {
370
374
  const norm = (s) => String(s ?? '').toLowerCase().replace(/[^a-z0-9]+/g, ' ').trim();
375
+ const delivered = (ord) => {
376
+ if (ord == null || !modelToFolded) return ord;
377
+ const folded = modelToFolded[String(ord)];
378
+ return folded == null ? null : Number(folded);
379
+ };
371
380
  const byOrdinal = new Map();
372
- const unclaimed = [...(profiles ?? [])];
381
+ let unclaimed = (profiles ?? []).map((p) => ({ ...p, ord: delivered(p.ord) }));
382
+ for (const f of (findings ?? [])) {
383
+ const stamped = unclaimed.filter((p) => p.ord != null && p.ord === f.ordinal);
384
+ if (!stamped.length) continue;
385
+ byOrdinal.set(f.ordinal, stamped.find((p) => !p.none) ?? stamped[0]);
386
+ unclaimed = unclaimed.filter((p) => !stamped.includes(p));
387
+ }
373
388
  for (const f of (findings ?? [])) {
374
- let ix = unclaimed.findIndex((p) => p.ord != null && p.ord === f.ordinal);
375
- if (ix < 0) ix = unclaimed.findIndex((p) => {
389
+ if (byOrdinal.has(f.ordinal)) continue;
390
+ const ix = unclaimed.findIndex((p) => {
376
391
  const pm = norm(p.mark), fm2 = norm(f.mark), po = norm(p.owner), fo = norm(f.owner?.name);
377
392
  const markHit = pm && fm2 && (pm.includes(fm2) || fm2.includes(pm));
378
393
  const ownerHit = po && fo && (po.includes(fo) || fo.includes(po));
@@ -57,6 +57,8 @@ import { republishRun } from './report-registry.mjs';
57
57
  import { config } from '../driver.config.mjs';
58
58
  import { isEntrypoint } from "../../shared/is-entrypoint.mjs"; // — one entry-point test, all spellings
59
59
  import { envFrom } from "../../shared/env-aliases.mjs"; // — resolves EITHER spelling; names the retired one because that is the live-writable half
60
+ import { readJson } from "../run-record.mjs";
61
+ import { crossBuildRepublishRefusal } from "../one-build-per-run.mjs";
60
62
 
61
63
  // One derivation, not a second copy of the literal: config.poolRoot IS the answer, and it refuses when
62
64
  // CLEAROTRON_REPORTS_DIR is unset. This file used to spell `|| '/srv/trademark-archive'` itself, which
@@ -68,7 +70,7 @@ const POOL = config.poolRoot;
68
70
  function listRuns(poolDir) {
69
71
  return readdirSync(poolDir, { withFileTypes: true })
70
72
  .filter(d => d.isDirectory() && d.name !== 'customer' && existsSync(join(poolDir, d.name, 'meta.json')))
71
- .map(d => JSON.parse(readFileSync(join(poolDir, d.name, 'meta.json'), 'utf8')))
73
+ .map(d => readJson(join(poolDir, d.name, 'meta.json')))
72
74
  .sort(runOrder);
73
75
  }
74
76
 
@@ -165,6 +167,10 @@ async function doRepublish({ runId, meta, pool, runDir, skipRegen = false }) {
165
167
  if (found.length > 1) throw new Error(`ambiguous archives for ${runId}: ${found.join(', ')} — pass --run-dir.`);
166
168
  runDir = found[0];
167
169
  }
170
+ // A REPORT IS RE-RENDERED ONLY BY THE BUILD THAT MADE IT (one-build-per-run.mjs). rerender-all lists a refused run
171
+ // as skipped, and its stored page stands.
172
+ const refused = crossBuildRepublishRefusal(runDir);
173
+ if (refused) throw new Error(refused);
168
174
  // Which publisher this run's shape calls for is republishRun's decision, read off the run's own meta —
169
175
  // NOT an assumption made here. This function used to call publishReport unconditionally, which meant a
170
176
  // knockout run could not be re-rendered at all: it has no report.md, so it died on the shape check with
@@ -248,7 +254,7 @@ async function main(argv) {
248
254
  const st = statSync(dir);
249
255
  const ms = (st.birthtimeMs && st.birthtimeMs > 0) ? st.birthtimeMs : st.mtimeMs;
250
256
  const metaPath = join(dir, 'meta.json');
251
- const meta = JSON.parse(readFileSync(metaPath, 'utf8'));
257
+ const meta = readJson(metaPath);
252
258
  meta.issuedAt = new Date(ms).toISOString();
253
259
  writeFileSync(metaPath, JSON.stringify(meta, null, 2));
254
260
  try { chmodSync(metaPath, 0o640); } catch { /* best-effort; group-read via set-gid pool */ }
@@ -300,7 +306,7 @@ async function main(argv) {
300
306
  const runs = listRuns(POOL);
301
307
  const id = resolveId(token, runs);
302
308
  const metaPath = join(POOL, id, 'meta.json');
303
- const meta = JSON.parse(readFileSync(metaPath, 'utf8'));
309
+ const meta = readJson(metaPath);
304
310
  const from = meta.customerKey || 'generic';
305
311
  if (from === target) {
306
312
  console.log(`reassign: ${id} is already owned by "${target}" — nothing to do.`);
@@ -291,11 +291,11 @@ function frameworkGauge(fm, findings, coverage = [], fourAnswers = null, opts =
291
291
  // a vocabulary ("Manageable", "Moderate") that is meaningless without the framework in force, and the
292
292
  // one place that named it sat several screens down at the end of a long document. The footer line stays:
293
293
  // it is the printed page's provenance, and the complaint was that the framework was named ONLY there.
294
- // Styling is in report.css (.gauge .label .gauge-fw), which is not frozen — only this text had to move.
294
+ // Styling is in report.css (.gauge .gauge-head); the name is its own block so a copied page keeps it apart from the heading.
295
295
  // frameworkGauge ONLY: the legacy `gauge()` branch below has no manifest to name, so it stays
296
296
  // byte-identical for every archived run that has no framework sidecar.
297
297
  return `<div class="panel gauge">
298
- <div class="label">Overall risk<span class="gauge-fw">${esc(FRAMEWORK.title)}</span></div>
298
+ <div class="gauge-head"><div class="label">Overall risk</div><div class="gauge-fw">${esc(FRAMEWORK.title)}</div></div>
299
299
  <div class="scale" style="background:${grad}">${marker}</div>
300
300
  <div class="ticks">${ticks}</div>
301
301
  <div class="gconc">${conc}</div>
@@ -1088,12 +1088,20 @@ function clearedGroupsHtml(searchDepth, auditFile) {
1088
1088
  }).join('');
1089
1089
  }
1090
1090
 
1091
+ // THE RUN'S OWN COMMON-LAW SEARCH RECORD, named in words. A row the assessing model backed with the run's own search
1092
+ // ledger carries that file's name where a web address would be, and the page printed it as a link to nowhere. Only a
1093
+ // reference positively identified as that ledger is renamed; any other source keeps its exact reference until a
1094
+ // truthful label exists for it. The run's record and the audit keep the original reference.
1095
+ const RUN_COMMON_LAW_RECORD = /^(?:\.\/)?(?:_driver\/)?common-law-grid(?:\.half-[a-z0-9]+)?\.json$/i;
1096
+ const RUN_COMMON_LAW_RECORD_LABEL = "the run's own common-law search record";
1097
+
1091
1098
  function webNamesHtml(searchDepth) {
1092
1099
  const web = (searchDepth && searchDepth.cleared && searchDepth.cleared.web) || [];
1093
1100
  if (!web.length) return '';
1094
1101
  const shown = web.slice(0, NAMES_CAP);
1095
1102
  const rows = shown.map((w) => `<div class="crow"><span class="cm-mark">${esc(w.title || '')}</span>${
1096
- w.url ? `<a class="curl" href="${escAttr(w.url)}">${esc(String(w.url).replace(/^https?:\/\//, '').replace(/\/$/, ''))}</a>` : '<span class="cwho"></span>'}</div>`).join('');
1103
+ w.url && RUN_COMMON_LAW_RECORD.test(String(w.url).trim()) ? `<span class="curl">${esc(RUN_COMMON_LAW_RECORD_LABEL)}</span>`
1104
+ : w.url ? `<a class="curl" href="${escAttr(w.url)}">${esc(String(w.url).replace(/^https?:\/\//, '').replace(/\/$/, ''))}</a>` : '<span class="cwho"></span>'}</div>`).join('');
1097
1105
  return `<details class="cgroup"><summary><span class="gname">Web and marketplace names</span><span class="gcount">${
1098
1106
  web.length.toLocaleString('en-GB')} ${web.length === 1 ? 'name' : 'names'}</span></summary><div class="gbody">${rows}</div></details>`;
1099
1107
  }