clearotron 0.5.1 → 0.6.0-beta.1

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 (390) 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 +88 -33
  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 +69 -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/band-shape.mjs +21 -3
  37. package/driver/best-draft.mjs +3 -3
  38. package/driver/blind-frame-record.mjs +2 -2
  39. package/driver/cancel.mjs +3 -2
  40. package/driver/carry-through.mjs +2 -2
  41. package/driver/citation-census.json +3 -3
  42. package/driver/clearance-variants-record.mjs +4 -10
  43. package/driver/common-law-coverage-status.mjs +3 -3
  44. package/driver/common-law-receipts.mjs +2 -2
  45. package/driver/commonlaw-carry-floor.json +3 -3
  46. package/driver/compare.mjs +1 -1
  47. package/driver/config-inventory.mjs +6 -79
  48. package/driver/consumption-ledger.mjs +2 -1
  49. package/driver/contract-arm2-baseline.json +2 -3
  50. package/driver/contract-dictation-registry.mjs +5 -0
  51. package/driver/contract-e3-backlog.mjs +45 -66
  52. package/driver/contract-e3-baseline.json +16 -16
  53. package/driver/contract-vocabulary.mjs +8 -6
  54. package/driver/corrections-feedforward.mjs +3 -1
  55. package/driver/coverage-form-io.mjs +7 -8
  56. package/driver/coverage-tool.mjs +1 -1
  57. package/driver/declination-tool.mjs +2 -2
  58. package/driver/degraded-parts.mjs +9 -9
  59. package/driver/demo-container.mjs +5 -4
  60. package/driver/demo-posture.mjs +17 -0
  61. package/driver/deploy-live-run-guard.mjs +19 -7
  62. package/driver/derived-state.mjs +2 -2
  63. package/driver/dev-portal.mjs +2 -1
  64. package/driver/dispatch-record.mjs +1 -1
  65. package/driver/disposition-tool.mjs +2 -1
  66. package/driver/doubt-closure-tool.mjs +2 -2
  67. package/driver/driver.config.mjs +35 -724
  68. package/driver/e2e-rounds.mjs +3 -4
  69. package/driver/engine/CONTRACT.md +3 -0
  70. package/driver/engine/README.md +2 -0
  71. package/driver/engine/anthropic-agent.mjs +13 -42
  72. package/driver/engine/auth.mjs +74 -0
  73. package/driver/engine/child-record.mjs +1 -1
  74. package/driver/engine/deny-authority-write.mjs +2 -2
  75. package/driver/engine/jx-turn.mjs +10 -2
  76. package/driver/engine/mcp/README.md +1 -1
  77. package/driver/engine/mcp/band-server.mjs +20 -13
  78. package/driver/engine/mcp/codex-config.mjs +1 -1
  79. package/driver/engine/mcp/declination-server.mjs +2 -3
  80. package/driver/engine/mcp/dispositions-server.mjs +3 -3
  81. package/driver/engine/mcp/gather-config.mjs +24 -19
  82. package/driver/engine/mcp/grid-provenance.mjs +1 -1
  83. package/driver/engine/mcp/held-answers.mjs +5 -5
  84. package/driver/engine/mcp/perplexity-server.mjs +16 -7
  85. package/driver/engine/mcp/recording-server.mjs +7 -6
  86. package/driver/engine/mcp/register-server.mjs +29 -0
  87. package/driver/engine/mcp/stdio-server.mjs +5 -5
  88. package/driver/engine/mcp/supplemental.mjs +9 -9
  89. package/driver/engine/openai-agent.mjs +5 -2
  90. package/driver/engine/registry.mjs +103 -0
  91. package/driver/engine/run-choices.mjs +162 -0
  92. package/driver/engine/stamps.mjs +35 -0
  93. package/driver/enqueue-schema.mjs +4 -4
  94. package/driver/envelope-settle.mjs +3 -2
  95. package/driver/feedback-issues.mjs +1 -1
  96. package/driver/feedback-mint.mjs +3 -2
  97. package/driver/feedback-store.mjs +3 -2
  98. package/driver/findings-model.mjs +1 -1
  99. package/driver/flag-snapshot.mjs +5 -4
  100. package/driver/floor-duty.mjs +3 -3
  101. package/driver/foreign-record-links.mjs +1 -1
  102. package/driver/frame-diff-record.mjs +2 -8
  103. package/driver/framework.mjs +1 -1
  104. package/driver/gate-metrics.mjs +10 -11
  105. package/driver/gateway.mjs +220 -839
  106. package/driver/goods-evidence.mjs +26 -14
  107. package/driver/jx-lanes.mjs +3 -3
  108. package/driver/jx-units.mjs +31 -37
  109. package/driver/jx.mjs +44 -59
  110. package/driver/knockout-assess-record.mjs +3 -3
  111. package/driver/knockout-caveats.mjs +21 -0
  112. package/driver/knockout-correction-record.mjs +58 -28
  113. package/driver/knockout-frame-record.mjs +2 -2
  114. package/driver/knockout-register-read.mjs +38 -21
  115. package/driver/knockout-register-record.mjs +5 -6
  116. package/driver/knockout-review-record.mjs +12 -11
  117. package/driver/ladder/model-gauge.mjs +88 -0
  118. package/driver/ladder/next-rung.mjs +296 -0
  119. package/driver/ladder/rescue.mjs +146 -0
  120. package/driver/ladder/stage-tools.mjs +57 -0
  121. package/driver/ladder/turn-failure.mjs +166 -0
  122. package/driver/log.mjs +2 -2
  123. package/driver/matter-frame-record.mjs +4 -4
  124. package/driver/methodology-witness.mjs +2 -2
  125. package/driver/named-band.mjs +60 -3
  126. package/driver/narrative-refutation-record.mjs +145 -42
  127. package/driver/one-build-per-run.mjs +62 -0
  128. package/driver/outbox-backoff.mjs +4 -4
  129. package/driver/owner-screen.mjs +0 -10
  130. package/driver/owner-use-check.mjs +2 -28
  131. package/driver/package.json +1 -1
  132. package/driver/partial-payload-baseline.json +1 -1
  133. package/driver/parts-not-completed.mjs +1 -1
  134. package/driver/pipeline-knockout.mjs +1015 -1001
  135. package/driver/pipeline.mjs +714 -9351
  136. package/driver/placement-decisions.mjs +2 -2
  137. package/driver/placement-form-io.mjs +7 -9
  138. package/driver/placement-union.mjs +0 -6
  139. package/driver/plan-stability.mjs +7 -10
  140. package/driver/portal-acks.mjs +3 -2
  141. package/driver/portal-confirmation.mjs +48 -0
  142. package/driver/portal-families.mjs +3 -2
  143. package/driver/portal-local-auth.mjs +1 -2
  144. package/driver/portal-routes/README.md +24 -0
  145. package/driver/portal-routes/admin.mjs +425 -0
  146. package/driver/portal-routes/compose.mjs +66 -0
  147. package/driver/portal-routes/config.mjs +118 -0
  148. package/driver/portal-routes/connect.mjs +283 -0
  149. package/driver/portal-routes/feedback.mjs +178 -0
  150. package/driver/portal-routes/me.mjs +165 -0
  151. package/driver/portal-routes/queue.mjs +64 -0
  152. package/driver/portal-routes/report.mjs +106 -0
  153. package/driver/portal-routes/run.mjs +508 -0
  154. package/driver/portal-routes/runs.mjs +127 -0
  155. package/driver/portal-routes/usage.mjs +82 -0
  156. package/driver/portal-runs.mjs +588 -0
  157. package/driver/portal-service.mjs +82 -2593
  158. package/driver/portal-static.mjs +3 -1
  159. package/driver/predelivery-lint.mjs +101 -9
  160. package/driver/production-pool-guard.mjs +1 -1
  161. package/driver/profiles.mjs +5 -4
  162. package/driver/progress.mjs +29 -24
  163. package/driver/publish/README.md +10 -5
  164. package/driver/publish/archive-tags.mjs +3 -2
  165. package/driver/publish/demo-marking.mjs +2 -2
  166. package/driver/publish/index.mjs +215 -140
  167. package/driver/publish/knockout.mjs +153 -107
  168. package/driver/publish/office-record-links.mjs +22 -0
  169. package/driver/publish/parse.mjs +20 -5
  170. package/driver/publish/pool-admin.mjs +9 -3
  171. package/driver/publish/render.mjs +11 -3
  172. package/driver/publish/report-dates.mjs +3 -4
  173. package/driver/publish/report-registry.mjs +7 -10
  174. package/driver/publish/seed-pool.mjs +3 -2
  175. package/driver/publish/shell.mjs +106 -0
  176. package/driver/publish/templates/report.css +9 -7
  177. package/driver/queue-order.mjs +4 -3
  178. package/driver/record-carry.mjs +0 -9
  179. package/driver/record-discard.mjs +1 -4
  180. package/driver/record-fold.mjs +3 -3
  181. package/driver/record-goods.mjs +79 -23
  182. package/driver/reference-score.mjs +2 -3
  183. package/driver/register-capabilities.mjs +0 -6
  184. package/driver/register-count.mjs +3 -2
  185. package/driver/register-digest-record.mjs +7 -7
  186. package/driver/register-fixture-marker.mjs +3 -3
  187. package/driver/register-plan.mjs +2 -2
  188. package/driver/register-records.mjs +2 -2
  189. package/driver/register-taint.mjs +3 -3
  190. package/driver/register-unit-record.mjs +48 -9
  191. package/driver/register-unreachable.mjs +4 -3
  192. package/driver/registry-fidelity.mjs +79 -34
  193. package/driver/repair-composers.mjs +14 -9
  194. package/driver/repair-digest.mjs +4 -6
  195. package/driver/repair-scope.mjs +3 -3
  196. package/driver/repair-targets.mjs +24 -9
  197. package/driver/repairs.mjs +44 -58
  198. package/driver/replay-archive.mjs +7 -7
  199. package/driver/report-card-record.mjs +3 -3
  200. package/driver/report-overview-record.mjs +4 -4
  201. package/driver/research-answers.mjs +38 -6
  202. package/driver/research-checks.mjs +4 -4
  203. package/driver/result-noun-fields.mjs +28 -11
  204. package/driver/review-addresses.mjs +163 -0
  205. package/driver/rule-shape.mjs +1 -1
  206. package/driver/run-delivered.mjs +340 -0
  207. package/driver/run-economics.mjs +8 -26
  208. package/driver/run-failed.mjs +545 -0
  209. package/driver/run-integrity.mjs +1 -1
  210. package/driver/run-outcome.mjs +314 -0
  211. package/driver/run-park.mjs +23 -0
  212. package/driver/run-quote.mjs +32 -0
  213. package/driver/run-record.mjs +352 -0
  214. package/driver/run-requirements.mjs +22 -0
  215. package/driver/run-shell.mjs +55 -0
  216. package/driver/runner.mjs +71 -33
  217. package/driver/saved-register-pages.mjs +4 -4
  218. package/driver/score-redaction.mjs +2 -2
  219. package/driver/search-policy.mjs +12 -13
  220. package/driver/settle-stamp.mjs +4 -3
  221. package/driver/skeptic-record.mjs +2 -2
  222. package/driver/skeptic-search.mjs +1 -1
  223. package/driver/skills/README.md +7 -7
  224. package/driver/skills/blind-frame/SKILL.md +1 -2
  225. package/driver/skills/case-law-citation/SKILL.md +9 -37
  226. package/driver/skills/case-law-citation/sources/courtlistener.md +1 -3
  227. package/driver/skills/case-law-citation/sources/eurlex.md +8 -11
  228. package/driver/skills/case-law-citation/sources/legaldatahunter.md +1 -1
  229. package/driver/skills/clearance-common-law/SKILL.md +45 -111
  230. package/driver/skills/clearance-common-law/perplexity-prompts.md +7 -79
  231. package/driver/skills/clearance-register/SKILL.md +15 -33
  232. package/driver/skills/clearance-register/digest.md +35 -96
  233. package/driver/skills/clearance-register/providers/clarivate.md +2 -2
  234. package/driver/skills/clearance-register/providers/corsearch.md +5 -5
  235. package/driver/skills/clearance-register/providers/euipo.md +1 -2
  236. package/driver/skills/clearance-register/providers/free-tier.md +0 -19
  237. package/driver/skills/clearance-register/providers/signa.md +6 -25
  238. package/driver/skills/clearance-register/providers/uspto-local.md +0 -24
  239. package/driver/skills/clearance-register/register-recipes.md +8 -15
  240. package/driver/skills/clearance-register/status-rules.md +6 -24
  241. package/driver/skills/clearance-register/unit.md +11 -20
  242. package/driver/skills/clearance-search/delivery-contract.md +24 -120
  243. package/driver/skills/clearance-search/field-doctrine-pharma.md +1 -5
  244. package/driver/skills/clearance-search/firm-wide-reasoning.md +24 -43
  245. package/driver/skills/clearance-search/phase2-execution.md +29 -77
  246. package/driver/skills/clearance-search/report-prose.md +3 -4
  247. package/driver/skills/clearance-search/risk-framework-demo.md +1 -1
  248. package/driver/skills/clearance-search/risk-framework-triage.manifest.json +3 -3
  249. package/driver/skills/clearance-search/risk-framework-triage.md +7 -9
  250. package/driver/skills/clearance-search/risk-framework.manifest.json +1 -1
  251. package/driver/skills/clearance-search/risk-framework.md +1 -1
  252. package/driver/skills/clearance-search/synthesis-rules.md +30 -107
  253. package/driver/skills/clearance-search/worked-examples.md +5 -5
  254. package/driver/skills/clearance-variants/SKILL.md +46 -45
  255. package/driver/skills/clearance-variants/transliteration-scripts.md +4 -4
  256. package/driver/skills/frame-diff/SKILL.md +1 -1
  257. package/driver/skills/knockout-assess/SKILL.md +6 -14
  258. package/driver/skills/knockout-frame/SKILL.md +1 -1
  259. package/driver/skills/matter-frame/SKILL.md +7 -12
  260. package/driver/skills/matter-frame/watchlist-reference.md +1 -4
  261. package/driver/skills/narrative-refutation/SKILL.md +20 -30
  262. package/driver/skills/placement-inquiry/SKILL.md +10 -20
  263. package/driver/skills-store-provenance.mjs +1 -1
  264. package/driver/stage-context.mjs +32 -35
  265. package/driver/stage-freshness.mjs +127 -11
  266. package/driver/stages-knockout.mjs +49 -22
  267. package/driver/stages.mjs +89 -288
  268. package/driver/status-snapshot.mjs +2 -1
  269. package/driver/steps/correction-cycle.mjs +311 -0
  270. package/driver/steps/corrections.mjs +644 -0
  271. package/driver/steps/delivery.mjs +1287 -0
  272. package/driver/steps/frame-comparison.mjs +927 -0
  273. package/driver/steps/intake.mjs +84 -0
  274. package/driver/steps/open-run.mjs +419 -0
  275. package/driver/steps/overview-and-cards.mjs +899 -0
  276. package/driver/steps/placement-and-digest.mjs +23 -0
  277. package/driver/steps/register-sweep.mjs +1563 -0
  278. package/driver/steps/skeptic-and-follow-up.mjs +836 -0
  279. package/driver/steps/synthesis.mjs +261 -0
  280. package/driver/steps/verdict-gate.mjs +968 -0
  281. package/driver/suite-census.json +456 -96
  282. package/driver/surface-exit-verdict.mjs +0 -8
  283. package/driver/synthesis-record.mjs +72 -6
  284. package/driver/terminal-clamp.mjs +10 -0
  285. package/driver/tokens.mjs +8 -62
  286. package/driver/tool-calls.mjs +2 -2
  287. package/driver/unexecuted-asserts.json +2 -2
  288. package/driver/unit-state-verdict.mjs +1 -1
  289. package/driver/usage-ledger.mjs +2 -1
  290. package/driver/verify-knockout.mjs +20 -35
  291. package/driver/verify.mjs +47 -36
  292. package/driver/web-grid.mjs +3 -4
  293. package/driver/whatif-memo-run.mjs +2 -2
  294. package/driver/whatif-queue.mjs +4 -3
  295. package/driver/withheld-families.mjs +14 -15
  296. package/driver/worker-heartbeat.mjs +3 -2
  297. package/driver/write-up-form.mjs +0 -3
  298. package/mcp-server/CHANGELOG.md +8 -0
  299. package/mcp-server/http-server.mjs +11 -12
  300. package/mcp-server/lib/brief.mjs +22 -4
  301. package/mcp-server/lib/events.mjs +2 -2
  302. package/mcp-server/lib/evidence.mjs +3 -2
  303. package/mcp-server/lib/findings.mjs +2 -1
  304. package/mcp-server/lib/knockout.mjs +9 -10
  305. package/mcp-server/lib/ops.mjs +9 -9
  306. package/mcp-server/lib/runs.mjs +9 -10
  307. package/mcp-server/lib/trace.mjs +1 -1
  308. package/mcp-server/lib/whatif.mjs +2 -3
  309. package/mcp-server/package.json +1 -1
  310. package/mcp-server/server.mjs +5 -5
  311. package/node_modules/buffers/package.json +1 -1
  312. package/package.json +2 -1
  313. package/portal-ui/dist/assets/{index-fPqAU0sx.js → index-CYaO2ygd.js} +26 -14
  314. package/portal-ui/dist/assets/{index-AtB9ZpDH.css → index-izLa9apq.css} +2 -2
  315. package/portal-ui/dist/index.html +4 -4
  316. package/portal-ui/package.json +3 -3
  317. package/providers/README.md +1 -1
  318. package/providers/_shared/answer-memory.mjs +4 -5
  319. package/providers/_shared/execute-plan.mjs +48 -1
  320. package/providers/_shared/records-from-search.mjs +46 -0
  321. package/providers/clarivate/README.md +2 -2
  322. package/providers/clarivate/src/adapter.js +147 -0
  323. package/providers/clarivate/src/core.js +1 -14
  324. package/{driver/engine/mcp/clarivate-server.mjs → providers/clarivate/src/mount.js} +5 -10
  325. package/providers/corsearch/README.md +3 -3
  326. package/providers/corsearch/src/adapter.js +80 -0
  327. package/providers/corsearch/src/core.js +14 -11
  328. package/{driver/engine/mcp/corsearch-server.mjs → providers/corsearch/src/mount.js} +5 -10
  329. package/providers/euipo/README.md +2 -2
  330. package/providers/euipo/src/adapter.js +85 -0
  331. package/providers/euipo/src/core.js +1 -1
  332. package/providers/euipo/src/euipo-client.js +1 -2
  333. package/{driver/engine/mcp/euipo-server.mjs → providers/euipo/src/mount.js} +5 -10
  334. package/providers/free-tier/README.md +2 -2
  335. package/providers/free-tier/src/adapter.js +127 -0
  336. package/{driver/engine/mcp/free-tier-server.mjs → providers/free-tier/src/mount.js} +5 -10
  337. package/providers/jx-subclass/coverage.mjs +1 -6
  338. package/providers/jx-subclass/score-truth.mjs +2 -1
  339. package/providers/oauth-mcp-bridge/CHANGELOG.md +8 -0
  340. package/providers/oauth-mcp-bridge/package.json +1 -1
  341. package/providers/perplexity/src/core.js +2 -2
  342. package/providers/signa/README.md +2 -2
  343. package/providers/signa/src/adapter.js +157 -0
  344. package/providers/signa/src/capabilities.js +0 -3
  345. package/providers/signa/src/core.js +2 -2
  346. package/{driver/engine/mcp/signa-server.mjs → providers/signa/src/mount.js} +7 -12
  347. package/providers/signa/src/offices.generated.js +17 -15
  348. package/providers/uspto-local/README.md +1 -1
  349. package/providers/uspto-local/bin/verify-index.mjs +1 -1
  350. package/providers/uspto-local/src/adapter.js +75 -0
  351. package/{driver/engine/mcp/uspto-local-server.mjs → providers/uspto-local/src/mount.js} +5 -10
  352. package/scripts/band-shape-probe.mjs +2 -2
  353. package/scripts/citation-line-check.mjs +7 -7
  354. package/scripts/compare.mjs +1 -1
  355. package/scripts/dead-names.mjs +2 -2
  356. package/scripts/e2e-first-time.mjs +19 -7
  357. package/scripts/e2e.mjs +13 -13
  358. package/scripts/engine-probe.mjs +1 -1
  359. package/scripts/env-audit.mjs +7 -4
  360. package/scripts/env-classify.mjs +5 -1
  361. package/scripts/feedback-mint.mjs +1 -1
  362. package/scripts/freeze-example-run.mjs +7 -7
  363. package/scripts/mint-suite-census.mjs +2 -2
  364. package/scripts/nightly-notice.mjs +1 -1
  365. package/scripts/release-cut-decision.mjs +7 -2
  366. package/scripts/release-note-required.mjs +26 -9
  367. package/scripts/release-notes-lint.mjs +3 -2
  368. package/scripts/release-version-pr-checks.mjs +1 -1
  369. package/scripts/render-check.mjs +1 -1
  370. package/scripts/settings-render-check.mjs +23 -3
  371. package/scripts/test-run.mjs +5 -5
  372. package/scripts/travelling-predicates.mjs +1 -1
  373. package/scripts/undeclared-field-census.mjs +1 -1
  374. package/scripts/unexecuted-asserts.mjs +3 -3
  375. package/scripts/verify-publishable.mjs +1 -1
  376. package/shared/client-door.mjs +1 -1
  377. package/shared/connect-clients.mjs +1 -1
  378. package/shared/connector-signin-probe.mjs +1 -1
  379. package/shared/customer-store.mjs +3 -2
  380. package/shared/env-aliases.mjs +1 -1
  381. package/shared/invocation.mjs +14 -2
  382. package/shared/names-in-force.mjs +2 -0
  383. package/shared/register-selection.mjs +2 -2
  384. package/shared/store-in-repo.mjs +3 -3
  385. package/shared/summary-blocks.mjs +0 -3
  386. package/shared/trigger-lane.mjs +1 -1
  387. package/shared/vacuous-pass.mjs +2 -2
  388. package/shared/verb-shim.mjs +4 -2
  389. package/vendor/buffers/package.json +1 -1
  390. package/node_modules/exceljs/README.md +0 -3023
@@ -0,0 +1,588 @@
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
+ // portal-runs.mjs — the runs a portal reader can see: delivered runs from the pool's records, live and queued ones from the
5
+ // workspace, and the account a run belongs to. Moved out of portal-service.mjs unchanged; the service exports it as before.
6
+ import { existsSync, readdirSync, statSync } from "node:fs";
7
+ import { basename, join, resolve as pathResolve } from "node:path";
8
+ import { clientFailureNote } from "../shared/client-failure-note.mjs";
9
+ import { studioDirFor } from "../shared/pre-rename-spellings.mjs";
10
+ import { batchMarkName } from "./mark-name.mjs";
11
+ import { resolveNumericSetting } from "./numeric-setting.mjs";
12
+ import { seesEverything } from "./portal-access.mjs";
13
+ import { reportsOf } from "./portal-report.mjs";
14
+ import { stageNow } from "./progress.mjs";
15
+ import { readArchivedSet } from "./publish/archive-tags.mjs";
16
+ import { orderedQueueFiles } from "./queue-order.mjs";
17
+ import { paths, readJson } from "./run-record.mjs";
18
+ import { policyFor, reportIdentityFor } from "./search-policy.mjs";
19
+ import { drainingState } from "./worker-heartbeat.mjs";
20
+
21
+ // A run in one of these has finished; its step is the one its terminal write set, not the stage it last entered.
22
+ const TERMINAL_STATES = new Set(["delivered", "failed", "cancelled"]);
23
+
24
+ // The band ladder a run was rated against, and the tone of the band it landed on.
25
+ //
26
+ // Tone, not label, is what the UI colours and sorts by, and the join has to happen HERE because the
27
+ // server is the only side that knows the framework. Ladders are framework-scoped: house-default has four
28
+ // stops and says "Moderate" where house-triage says "Medium". A client that mapped labels to colours
29
+ // itself would mis-colour every customer whose framework is not the one it was written against.
30
+ //
31
+ // A run with no framework (every run archived before doc-50) yields an empty ladder and a null tone. That
32
+ // is honest — it was not rated against a ladder — and the UI renders the label alone, uncoloured.
33
+ function ladderOf(meta) {
34
+ const bands = Array.isArray(meta.framework?.bands)
35
+ ? meta.framework.bands.filter((b) => b && typeof b.label === "string" && typeof b.tone === "string")
36
+ .map((b) => ({ label: b.label, tone: b.tone }))
37
+ : [];
38
+ const toneFor = (label) => bands.find((b) => b.label === label)?.tone ?? null;
39
+ return { bands, toneFor };
40
+ }
41
+
42
+ // ── run listing: delivered (pool metas) + live (workspace status + frozen profile sidecar) ─────────
43
+ //
44
+ // `account` null means EVERY account — the staff "All brand owners" view. Every row carries its own
45
+ // `account` either way, so the caller never has to infer ownership from the request it made.
46
+ /** The registry's display face for a stored product key, or null for one it does not know. It answers for
47
+ * a RETIRED key too — a delivered run keeps the name it was sold under, which is the whole reason those
48
+ * rows still exist (search-policy.mjs RETIRED_POLICIES). */
49
+ const stageLabelOf = (product) => (typeof product === "string" ? policyFor(product)?.stageLabel ?? null : null);
50
+
51
+ /** THE PRODUCT'S CLIENT-FACING NAME for a run row — the same resolver, and the same field, the
52
+ * delivered report's masthead prints. The browser used to hold its own switch from product key to label
53
+ * (`home.ts depthLabel`), which is a mapping table in a second place: it drifted once already, listing
54
+ * only the five retired slugs so every run this build creates rendered a blank chip.
55
+ *
56
+ * `.identity`, never `.banner` or `stageLabel` — on a RETIRED row those carry "Depth 4", and a depth
57
+ * number must never reach a client's screen. Null for a level the registry has forgotten: the chip goes
58
+ * blank rather than naming a search the run may not have been. */
59
+ const productNameOf = (product) => (typeof product === "string" ? reportIdentityFor(product).identity ?? null : null);
60
+
61
+ // `account` accepts one key, or an ARRAY of keys for an identity that holds several — the multi-brand
62
+ // client asking for all of its own work at once. An array is exactly the union of what that caller can
63
+ // already fetch one key at a time, so it widens no boundary; it just spares the browser one request per
64
+ // brand owner against a 120/min limit. It is NOT a wildcard: an empty array matches nothing, which is
65
+ // the safe direction, and `null` (every account) stays reachable only from scanAllRuns.
66
+ export function scanAccountRuns({ poolRoot, workspaceRoot, account = null, generic = null, includeRetired = false,
67
+ // — THE QUEUES THE RUNNER ACTUALLY DRAINS, which is not the same set as the
68
+ // directories under `workspaceRoot`. Defaults to [] so a caller that passes none keeps exactly the
69
+ // behaviour it had; the service passes `config.queueDirs`, the same getter the allowance counter reads.
70
+ queueDirs = [] }) {
71
+ const out = [];
72
+ const only = Array.isArray(account) ? new Set(account) : null;
73
+ // GENERIC IS MATCHED BY ORGANISATION when the caller says which. `generic` is `{ all: true }` or
74
+ // `{ orgs, unfiled }`: a Generic run matches when it was filed under one of `orgs`, or was filed under
75
+ // none and `unfiled` asks for those too. Without it, `account` alone decides, exactly as before.
76
+ const mine = (owner, organisation = null) => {
77
+ if (owner === "generic" && generic) return generic.all === true
78
+ || (organisation != null ? (generic.orgs ?? []).includes(organisation) : generic.unfiled === true);
79
+ return only ? only.has(owner) : account === null || owner === account;
80
+ };
81
+ // RETIRED RUNS ARE NOT LISTED HERE — unless the caller is the staff retired view, and asks.
82
+ //
83
+ // `pool-admin archive` has always written this sidecar, and until now the ONLY reader was the old
84
+ // static index — the surface the edge stopped serving at the portal cutover. So the command reported
85
+ // success, the staff index it re-rendered was unreachable, and the run stayed in full view on the one
86
+ // page anybody actually opens. A curation verb that silently does nothing to the live surface is worse
87
+ // than not having one: it is a control that lies about having worked.
88
+ //
89
+ // Retired for EVERY reader, staff included: that has not changed, and `includeRetired` does not widen
90
+ // it. What changed is where the CONTROL lives. This comment used to argue that a portal fold
91
+ // would be "a second place to look, out of step with the CLI" — true while retiring was only a CLI
92
+ // act, and wrong the moment staff could retire from the screen they are already on. A control whose
93
+ // inverse lives in a terminal on another host is a one-way door. So the portal now carries both, and
94
+ // `includeRetired` is what the staff-only "Show retired" route reads. The default is unchanged, every
95
+ // client-facing caller takes it, and nothing a client can request reaches this flag.
96
+ //
97
+ // Read once per scan rather than per run: a scan is a directory walk over the whole pool and this is
98
+ // one small file, so re-reading it per entry would be the only O(n) sidecar read in the function.
99
+ //
100
+ // THE REPORT ROUTE IS DELIBERATELY NOT GATED ON THIS. Retiring a run takes it off the list; it does
101
+ // not revoke a link. Report URLs are in email we have already sent, and the Caddyfile's legacy-report
102
+ // rewrite exists precisely so those keep resolving — 404ing them here would rot them from a curation
103
+ // command, which is not what "archive" means to the person typing it. Ownership is still enforced at
104
+ // that route, unchanged; retirement is about what the pool ADVERTISES, not about who may read what.
105
+ const retired = readArchivedSet(poolRoot);
106
+ try {
107
+ for (const name of readdirSync(poolRoot)) {
108
+ const metaPath = join(poolRoot, name, "meta.json");
109
+ if (!existsSync(metaPath)) continue;
110
+ try {
111
+ const meta = readJson(metaPath);
112
+ const owner = meta.customerKey || "generic";
113
+ if (!mine(owner, meta.organisation ?? null)) continue;
114
+ // Tagged by runId — the same key pool-admin writes, which is the pool DIRECTORY name. Checking
115
+ // both guards the one case where they differ: a meta whose runId was rewritten by a republish.
116
+ const isRetired = retired.has(meta.runId ?? name) || retired.has(name);
117
+ if (isRetired && !includeRetired) continue;
118
+ // The retired view is EXCLUSIVELY retired runs, not the whole pool with a flag: it is the fold
119
+ // you open to find something you filed, and mixing the live list into it would make "Show
120
+ // retired" a second copy of the page you are already looking at.
121
+ if (!isRetired && includeRetired) continue;
122
+ // ONE report, one audience rule: a run you have rights to is always listed and served (spec
123
+ // 2026-07-30 §5). The client gate's "held" state is retired — the machine-QC record lives in
124
+ // meta.clientGate for the workbook/staff-index surfaces and decides nothing here.
125
+ // WHICH DOCUMENTS THIS RUN HAS, off its own meta. `existsSync("report.html")` was the
126
+ // test, and a knockout batch no longer publishes that file — every batch would have listed as
127
+ // having no report at all while carrying three. reportsOf() reads the published list and answers
128
+ // `report.html` for a run that predates it, which is every archived run and every clearance.
129
+ const docs = reportsOf(meta).filter((r) => existsSync(join(poolRoot, name, r.file)));
130
+ const { bands, toneFor } = ladderOf(meta);
131
+ const band = meta.overall ?? null; // the rating; a meta's retired `verdict` held the reviewer's sign-off on the full-search lane
132
+ out.push({ runId: meta.runId ?? name, account: owner, ...(owner === "generic" ? { organisation: meta.organisation ?? null } : {}),
133
+ title: meta.title ?? meta.matter ?? name, kind: meta.kind ?? "clearance",
134
+ // THE MARK, separate from the report's headline.
135
+ //
136
+ // `title` is model-authored front matter: a real run carries "AquaPlus — US Preliminary
137
+ // Trademark Clearance" as its title while the typed mark is "AquaPlus". The UI needs the mark
138
+ // to name a row and to group reads; it needs the headline for nothing. Written into meta at
139
+ // publish, so runs delivered before that carry null and consumers fall back to title.
140
+ markName: typeof meta.markName === "string" ? meta.markName : null,
141
+ // WHICH PROJECT (engagement) THIS RAN UNDER.
142
+ //
143
+ // Stamped into meta at publish from the run's frozen profile sidecar. Absent on every run
144
+ // delivered before that stamp, and deliberately not back-filled: the sidecar is the only
145
+ // honest source and it does not travel with a pool dir. Null therefore means "we do not know",
146
+ // never "no project" — so nothing downstream may render it as "no project".
147
+ projectKey: typeof meta.projectKey === "string" ? meta.projectKey : null,
148
+ projectName: typeof meta.projectName === "string" ? meta.projectName : null,
149
+ // Which read this is, for the Stages cell.
150
+ //
151
+ // THE REGISTRY FIRST, the frozen stamp only as a last resort — the same rule reportIdentityFor
152
+ // follows, and it has to be the same rule or the product has two names on one screen. This read
153
+ // the stamp FIRST, so after the Depth 1-5 renumbering a run's report banner said "Depth 2" while
154
+ // its own row in this list still said "Stage 0.5". One system: the label is a pure function of
155
+ // the level, so deriving it from the level names every run the way the product is named today.
156
+ //
157
+ // `meta.stageLabel` survives as the fallback for a run whose LEVEL the registry no longer knows
158
+ // (a retired row) — there is no current answer there and the stamp beats a blank. A run older
159
+ // than the level registry carries neither and stays null: the cell goes blank rather than
160
+ // inventing a depth that never ran.
161
+ // `meta.searchLevel` is the STORED key on a delivered run's meta.json and keeps its name on
162
+ // disk — an archived run's record is not this build's to rewrite. What the wire carries is
163
+ // `product`, because that is the word every client-facing surface uses now.
164
+ product: meta.searchLevel ?? null,
165
+ stageLabel: stageLabelOf(meta.searchLevel) ?? meta.stageLabel ?? null,
166
+ productName: productNameOf(meta.searchLevel),
167
+ state: "delivered", date: meta.date ?? null,
168
+ // WHEN IT FINISHED, to the second. `date` is DAY precision and always was — it is
169
+ // parsed out of the run directory name. Two reads of one mark delivered on the same day
170
+ // therefore TIE, Array.prototype.sort is stable, and which one the parent row spoke for was
171
+ // decided by readdirSync order rather than by recency.
172
+ //
173
+ // `issuedAt` has been written full-ISO into meta.json at every publish for as long as there
174
+ // has been a publisher; it simply never crossed the wire. Measured on the test instance
175
+ // 2026-08-04, the two House-default reads differ by 2m08s in this field and in nothing else
176
+ // the page renders — which is the whole.
177
+ issuedAt: typeof meta.issuedAt === "string" ? meta.issuedAt : null,
178
+ // `overall` stays for the existing consumers; `band` is the same value under the name the UI
179
+ // uses, alongside the ladder it belongs to.
180
+ overall: band, band, tone: toneFor(band), bands,
181
+ // Knockout batches summarise per name — the list renders "N names, worst: <band>" from this.
182
+ // Each mark's band is resolved against the SAME ladder, so a batch cannot mix vocabularies.
183
+ marks: Array.isArray(meta.marks)
184
+ ? meta.marks.filter((m) => m && typeof m.name === "string")
185
+ .map((m) => ({ name: m.name, band: m.band ?? null, tone: toneFor(m.band ?? null) }))
186
+ : [],
187
+ // Present ⇒ the run has a report-data.json and can render natively. Absent ⇒ legacy: the Result
188
+ // screen iframes the baked file. Legacy is identified by ABSENCE, so this must stay undefined
189
+ // rather than defaulting to 0 or 1.
190
+ // BOTH writers (publish/knockout.mjs and the clearance producer) stamp the STRING
191
+ // 'report-data/1' — gating on `typeof === "number"` alone meant the native-render flag NEVER
192
+ // armed, even for runs with a report-data.json on disk (2026-07-29, filed during PR-9). The
193
+ // string form maps to its numeric version; a bare number is honoured; anything else is legacy.
194
+ reportSchema: typeof meta.reportSchema === "number" ? meta.reportSchema
195
+ : typeof meta.reportSchema === "string" && /^report-data\/(\d+)$/.test(meta.reportSchema)
196
+ ? Number(meta.reportSchema.slice("report-data/".length)) : null,
197
+ // `report` is the run-level link and it is NULL for a batch — there is no run-level document
198
+ // to open. `reports` is the list, one entry per name, and it is what a batch's row renders.
199
+ // A single-document run carries both, pointing at the same place, so nothing that reads
200
+ // `report` today changes shape.
201
+ //
202
+ // BOTH ARE DOCUMENT URLS, and `path` STAYS one. The obvious repair for "the per-mark
203
+ // links open outside the portal" is to point `path` at the portal route instead — and it is
204
+ // wrong twice. `report` is consumed as an IFRAME SOURCE, not as a link, so making its sibling
205
+ // mean something else leaves two fields of the same name-shape with different kinds, and the
206
+ // client that framed one would frame the other and load the shell inside itself. The client
207
+ // needs to build a route; what it lacks for that is the NAME of the document, not a second
208
+ // spelling of its address. That is `slug`, below.
209
+ //
210
+ // `slug` is null on a single-document run: there is one document and no name to pick between,
211
+ // which is the same thing `report` being non-null already says.
212
+ report: docs.length === 1 ? `/portal/report/${encodeURIComponent(name)}/` : null,
213
+ reports: docs.map((r) => ({
214
+ mark: r.mark,
215
+ slug: r.slug ?? null,
216
+ path: r.slug
217
+ ? `/portal/report/${encodeURIComponent(name)}/${encodeURIComponent(r.slug)}/`
218
+ : `/portal/report/${encodeURIComponent(name)}/`,
219
+ })),
220
+ // — stamped only where it is true. A row that says nothing about retirement is a live
221
+ // row, on every surface that has ever consumed this listing; a `retired: false` on all of
222
+ // them would be a new field for every reader to ignore.
223
+ ...(isRetired ? { retired: true } : {}) });
224
+ } catch { /* unreadable meta — skip */ }
225
+ }
226
+ } catch { /* no pool yet */ }
227
+ // live runs: status.json + the frozen profile sidecar (freezeProfile writes `profileKey`)
228
+ const readRun = (dir) => {
229
+ try {
230
+ const s = readJson(join(dir, "status.json"));
231
+ const p = readJson(paths(dir).profile);
232
+ const owner = p.profileKey ?? p.key ?? "generic";
233
+ if (!mine(owner, p.organisation ?? null)) return;
234
+ if (s.state === "delivered") return; // the pool row is the delivered face
235
+ // ── — RETIREMENT REACHES A RUN THAT NEVER PUBLISHED ──────────────────
236
+ //
237
+ // The pool branch above has honoured the sidecar since; this branch never did, so a tag
238
+ // written for a run that ended without publishing sat in the file doing nothing and the run
239
+ // stayed on the list. That is worse than the refusal it replaces: a control that reports success
240
+ // and changes nothing is the failure `scanAccountRuns`'s own retirement comment is about.
241
+ //
242
+ // The failed and abandoned runs are exactly the ones a reader most wants off the list, so this is
243
+ // the population the control was wanted for, not an edge of it. Same key as the pool branch —
244
+ // the runId — and the same two-way filter, so "Show retired" stays exclusively retired.
245
+ const liveRetired = retired.has(s.runId) || retired.has(basename(dir));
246
+ if (liveRetired && !includeRetired) return;
247
+ if (!liveRetired && includeRetired) return;
248
+ // A live run already HAS the typed mark — status.json is where it has always lived. The frozen
249
+ // search-policy sidecar carries the stage. Both are read here so a run does not change identity
250
+ // when it crosses from live to delivered: same mark, same stage, same thread.
251
+ let sp = null;
252
+ try { sp = readJson(paths(dir).searchPolicy); } catch { /* legacy/early run */ }
253
+ // A PAUSE IS NOT A RUN. The engine writes `postponed` (a rate-limit park, auto-resuming at
254
+ // `resetsAt`) and `recovering` (an auto-retry backing off), and the portal contract knows neither
255
+ // — its coercion treats anything unrecognised as `running`. So a run parked for five hours showed
256
+ // "Running", with the step it had reached before it stopped, and the customer had no way to tell a
257
+ // pause from work. The UI has had a `paused` state and a `.dot.paused` rule the whole time, and
258
+ // nothing on the wire could ever reach them.
259
+ //
260
+ // Mapped here rather than in the browser: the run listing is the one place that already turns
261
+ // engine vocabulary into the words a client reads, and a second translation in the UI is a second
262
+ // thing to keep in step. `pausedKind` keeps the two apart, because they say different things to
263
+ // the person waiting — one has a time, the other is the system retrying itself.
264
+ // `parked-for-human` (A5): the engine's grace-exit park — the runner was stopped (deploy restart)
265
+ // with the run in flight. Mapped HERE, like the other two, so the wire NEVER carries the raw
266
+ // value: the portal contract would coerce an unknown state to "running", which is exactly the
267
+ // zombie face this state exists to end. pausedKind "operator" tells the UI which words to use.
268
+ const paused = s.state === "postponed" || s.state === "recovering" || s.state === "parked-for-human";
269
+ out.push({ ...(liveRetired ? { retired: true } : {}),
270
+ runId: s.runId, account: owner, ...(owner === "generic" ? { organisation: p.organisation ?? null } : {}), title: s.markName ?? s.slug,
271
+ // THE RUN’S OWN PIPELINE, off the frozen policy sidecar this branch already reads — the same
272
+ // source the `product` field two lines down takes, so a row cannot contradict its own product.
273
+ // `s.lane` is the runner’s queue directory and it is not that: a knockout claimed from any other
274
+ // lane arrived here as a clearance, and Home then quoted it the clearance turnaround — hours,
275
+ // against a search that finishes in minutes. The queued rows below were fixed for exactly this
276
+ // and this row was left on the weaker field. The lane stays as the fallback for a run whose
277
+ // sidecar predates the stamp, and an unplaceable product stays a clearance, which is what every
278
+ // listing has always shown for something it could not identify.
279
+ kind: (policyFor(sp?.level)?.pipeline ?? (s.lane === "knockout" ? "knockout" : null)) === "knockout" ? "knockout-batch" : "clearance",
280
+ markName: typeof s.markName === "string" ? s.markName : null,
281
+ // The project, straight off the frozen sidecar this branch already reads as `p`. A LIVE run needs
282
+ // no publish stamp and no back-fill — the sidecar is right there, and freezeProfile has written
283
+ // both fields since spec 62.
284
+ projectKey: typeof p.projectKey === "string" ? p.projectKey : null,
285
+ projectName: typeof p.projectName === "string" ? p.projectName : null,
286
+ // Registry first here too — a live run's frozen policy sidecar names WHICH level is running; what
287
+ // that level is CALLED comes from the registry, so an in-flight run and a delivered one agree.
288
+ product: sp?.level ?? null, stageLabel: stageLabelOf(sp?.level) ?? sp?.stageLabel ?? null,
289
+ productName: productNameOf(sp?.level),
290
+ state: paused ? "paused" : (s.state ?? "running"),
291
+ pausedKind: paused ? (s.state === "recovering" ? "recovering" : s.state === "parked-for-human" ? "operator" : "rate-limit") : null,
292
+ // The ONE honest ETA this system possesses. The engine computes it from the provider's own
293
+ // reset header and has always written it; it reached the ops surface and stopped one hop short
294
+ // of the browser. Absent for a recovery park, which backs off on a schedule rather than to a
295
+ // stated time — so the UI must not promise a clock it does not have.
296
+ resetsAt: typeof s.resetsAt === "string" ? s.resetsAt : null,
297
+ // Elapsed, so a card can say how long this has been going without inventing a finish time.
298
+ startedAt: typeof s.startedAt === "string" ? s.startedAt : null,
299
+ // THE STAGE IT IS IN NOW, a step back into an earlier stage included (owner, 2026-09-19): see
300
+ // stageNow. Only while it is live; a run that has finished keeps the step its terminal write set.
301
+ ...(TERMINAL_STATES.has(s.state)
302
+ ? { step: s.stepLabel ?? null, stepN: s.stepN ?? null, stepTotal: s.stepTotal ?? null }
303
+ : stageNow(s)),
304
+ // — a requested stop is a state the screen shows. Stamped by stop_run,
305
+ // preserved by writeRunStatus's spread-merge, replaced by the terminal when the honour check
306
+ // fires. The UI derives "Stopping…" from this beside a non-terminal state.
307
+ stopRequestedAt: typeof s.stopRequestedAt === "string" ? s.stopRequestedAt : null,
308
+ // — whether a stop can still prevent delivery. FALSE only once a lane has written it, at the
309
+ // moment it commits to publishing. Absent means the run has not reached that point, which is
310
+ // the truthful reading on this build: both lanes write it immediately after their last cancel
311
+ // read. The screen shows its promise on true and withdraws it on false.
312
+ stoppable: s.stoppable === false ? false : true,
313
+ // A failed run with no reason on screen is a run the user has to phone somebody about. Both
314
+ // fields are already written by every failure path (pipeline-knockout.mjs, the driver's
315
+ // writeRunStatus); the listing simply used to drop them.
316
+ reason: s.reason ?? null, failedStage: s.failedStage ?? null,
317
+ // — the engine's OPEN-SET payload, its own field so the portal can show the sentence and
318
+ // hide this. Staff only: the client redaction below replaces `reason` and must drop this too,
319
+ // or the redaction would be defeated by the field that carries the raw words.
320
+ reasonDetail: s.reasonDetail ?? null,
321
+ date: (s.updatedAt ?? "").slice(0, 10), overall: s.tier ?? null, // the rating, never the reviewer's sign-off word
322
+ // A live run has not been issued, so its last progress write is the honest ordering key — the
323
+ // same role issuedAt plays for a delivered one, never presented as a finish time.
324
+ issuedAt: typeof s.updatedAt === "string" ? s.updatedAt : null,
325
+ // A live run has not been rated yet, so it has no band and no ladder. The UI shows an em-dash.
326
+ //
327
+ // `marks` IS NOT THE BAND LADDER. One array answered two questions and the second answer was a
328
+ // false one: the Result screen reads its LENGTH as a name count, so an empty array told the
329
+ // customer a three-name knockout batch had "0 names" for the entire run — on a row whose own mark
330
+ // string beside it said the batch had three. The names are known from the moment the batch is
331
+ // planned; the BANDS are what a live run does not have, and they stay null here.
332
+ band: null, tone: null, bands: [],
333
+ marks: Array.isArray(s.marks)
334
+ ? s.marks.filter((m) => m && typeof m.name === "string").map((m) => ({ name: m.name, band: null, tone: null }))
335
+ : [],
336
+ reportSchema: null, report: null });
337
+ } catch { /* not a run dir */ }
338
+ };
339
+ // QUEUED BUT NOT YET PICKED UP — the gap between pressing Start and the driver writing a status.json.
340
+ //
341
+ // The queue directory used to be skipped outright, so for that window a started clearance appeared in
342
+ // NOTHING: not the pool, not the live list. The screen that had just promised "it will appear in
343
+ // Clearances" was, for those seconds, wrong — and to anyone who pressed Start and went straight to
344
+ // the list, indistinguishable from a run that never started at all. That ambiguity is the whole
345
+ // reason this exists; the window itself is short (prelim-driver.path fires on the file landing).
346
+ //
347
+ // A PENDING job is `<id>.json` with no suffix — the runner renames to `.done`/`.failed` when it is
348
+ // through, and those are history the pool and live scans already own. Reading only the bare `.json`
349
+ // is therefore what keeps a finished run from appearing twice.
350
+ //
351
+ // ── AND THE TERMINAL MARKERS STAY OUT. THIS IS A DEAD-LETTER STORE, NOT A WORK SURFACE. ────────────
352
+ //
353
+ // 2026-07-28: this scan was briefly widened to also read `<id>.failed` / `.duplicate` /
354
+ // `.manifest.failed`, reasoning that a job refused at the runner's intake gate never gets a run dir,
355
+ // never gets a status.json, and so appears in no surface at all — the row says "Queued · Waiting to
356
+ // start" and then silently disappears. The reasoning was sound. The inference from the data was not.
357
+ //
358
+ // The evidence offered for it was "the live queue is holding thirty of these". What that actually
359
+ // meant is that THIS DIRECTORY HAS NO RETENTION AND NOBODY EVER CLEANS IT. The thirty spanned six
360
+ // weeks and were test artefacts, raw Outlook message ids from the email door, and `mcp-*` dev runs;
361
+ // twenty-six had no `.reason` sidecar at all, so each rendered as a row saying, in effect, something
362
+ // stopped and we cannot say what or why. Twelve carried no `profileKey` and fell through to `generic`.
363
+ // Home and Clearances both read this scan, so both filled with six weeks of dead letters on a morning
364
+ // when nothing was running.
365
+ //
366
+ // A job refused at intake deserves an answer. That answer belongs AT SUBMISSION — the door that
367
+ // refused it knows why, immediately, and can say so to the person standing there. It does not belong
368
+ // to a directory that never forgets. Narrowing this by age or by owner would only make the junk
369
+ // smaller: the source would still be a store with no retention, one policy change away from returning.
370
+ //
371
+ // So: a PENDING job is `<id>.json` with no suffix. The runner renames to `.done`/`.failed` when it is
372
+ // through, and those are history the pool and live scans already own. Reading only the bare `.json` is
373
+ // what keeps a finished run from appearing twice — and what keeps this list about work in progress.
374
+ //
375
+ // ORDER. The rows come back in the order the runner will ADMIT them (queue-order.mjs — the same
376
+ // function drainQueue sorts with, so the list and the engine can never disagree), and each carries
377
+ // a dense 1-based `queuePos`.
378
+ //
379
+ // Dense over the rows THIS CALLER CAN SEE, not the raw index in the lane. A client whose two jobs
380
+ // sit at lane positions 4 and 9 must not be told "4" and "9" — that publishes how much work other
381
+ // tenants have queued, which is the same thing the 404-never-403 rule exists to prevent. Staff
382
+ // reading across every account see the true lane depth anyway, because for them every row is visible.
383
+ const queuedRows = []; // { row, lane, laneIdx } — positions assigned once the whole scan is in
384
+ // — READ ONCE per scan, not per row: every row of one response must agree about whether a worker
385
+ // exists, and a boundary crossed mid-scan would otherwise put "waiting its turn" and "waiting for a
386
+ // worker" in the same list. A queued job cannot answer this itself — it has no claim and no sidecar, so
387
+ // claim liveness is silent on precisely the rows that need it.
388
+ //
389
+ // `null` means NOT KNOWN, and that is the default EVERYWHERE except a local install. A deployed instance
390
+ // drains through the systemd path/timer units, which run `main({once:true})` and write no heartbeat — so
391
+ // a service that read a missing heartbeat as "no worker" would put a false alarm on every queued row in
392
+ // production. Only the launcher that actually supervises a worker claims to know, and it is the same
393
+ // launcher that sets the lock dir, so the two can never be set without each other.
394
+ const draining = drainingState();
395
+ const readQueued = (dir) => {
396
+ let files = []; try { files = readdirSync(dir); } catch { return; }
397
+ const ordered = orderedQueueFiles(dir, files.filter((f) => f.endsWith(".json") && !f.startsWith(".")));
398
+ for (const [laneIdx, f] of ordered.entries()) {
399
+ try {
400
+ const j = readJson(join(dir, f));
401
+ const owner = j.profileKey ?? "generic";
402
+ if (!mine(owner, j.tenant ?? null)) continue;
403
+ // ALL the names, spelled the way the run's own status.json and its delivered meta.json spell
404
+ // them — this took `marks[0].name` and named ONE mark of N, so a client who had just ordered a
405
+ // three-name knockout screen saw a single name on the row that tells them it went in.
406
+ const mark = batchMarkName(j.marks, typeof j.markName === "string" && j.markName ? j.markName : undefined);
407
+ queuedRows.push({ lane: dir, laneIdx, row: { runId: j.id ?? f.replace(/\.json$/, ""), account: owner, ...(owner === "generic" ? { organisation: j.tenant ?? null } : {}), title: mark ?? (j.id ?? "Queued"),
408
+ // THE JOB'S OWN PIPELINE, not the literal "clearance". The row already carried
409
+ // `product: "knockout-search"` and still called itself a clearance, so it was the one row in
410
+ // the listing that contradicted its own product field — and Result.tsx gates the names line on
411
+ // this, so a queued batch showed no names at all. A product the registry cannot place stays a
412
+ // clearance: that is what the listing has always shown for anything it could not identify.
413
+ kind: policyFor(j.product)?.pipeline === "knockout" ? "knockout-batch" : "clearance",
414
+ markName: mark,
415
+ // The job carries the KEY (portal-service stamps it from the composer) but no name — the name
416
+ // is resolved by the engine when the run starts, and this job has not started. Null name, real
417
+ // key: a consumer that wants a label falls back to the key rather than being told the run has
418
+ // no project when it has one.
419
+ projectKey: typeof j.projectKey === "string" && j.projectKey ? j.projectKey : null,
420
+ projectName: null,
421
+ // The ORDER's product, and its name off the same resolver every other row uses. The name was
422
+ // missing here alone, and the browser covered for it by joining `product` against the composer
423
+ // menu; with that join deleted a queued row would have degraded to a bare date — the one
424
+ // row a client looks at straight after pressing Start. `stageLabel` stays null: nothing is
425
+ // frozen until the run starts, and the registry answers for every product this door accepts.
426
+ product: j.product ?? null, stageLabel: null,
427
+ productName: productNameOf(j.product),
428
+ // — "Waiting to start" is true of both a job behind other work and a job nothing will
429
+ // ever pick up, and those are not the same thing to whoever just pressed Start. The position
430
+ // still says where it sits in the line; this says whether the line is moving at all.
431
+ state: "queued", step: draining === false ? "Waiting for a worker" : "Waiting to start", stepN: null, stepTotal: null,
432
+ reason: null, failedStage: null,
433
+ // Part of the row contract now; a job that has not started has none of them.
434
+ pausedKind: null, resetsAt: null, startedAt: null,
435
+ // A job file has no updatedAt — it has not run. Its MTIME is when it was queued, which is a
436
+ // real fact rather than a fabricated one, sorts a just-queued run to the top where the
437
+ // person who pressed Start will look, and is deterministic under test.
438
+ date: new Date(statSync(join(dir, f)).mtimeMs).toISOString().slice(0, 10), overall: null,
439
+ // Queued: its mtime, at full precision, for the same reason the day-level `date` uses it.
440
+ issuedAt: new Date(statSync(join(dir, f)).mtimeMs).toISOString(),
441
+ // The names the job was submitted with — no bands, because nothing has been rated. Same rule as
442
+ // the live row: this array answers "which names", and only the delivered row can answer "at
443
+ // what band".
444
+ band: null, tone: null, bands: [],
445
+ marks: (Array.isArray(j.marks) ? j.marks : [])
446
+ .filter((m) => m && typeof m.name === "string" && m.name.trim())
447
+ .map((m) => ({ name: m.name, band: null, tone: null })),
448
+ reportSchema: null, report: null,
449
+ queuePos: null } }); // filled below, once every lane has been read
450
+ } catch { /* not a job file */ }
451
+ }
452
+ };
453
+ // EVERY QUEUE ONCE. A directory can be reached both ways — `config.queueDirs`
454
+ // lists the workspace queues too — and reading one twice would list every job in it twice and give
455
+ // each row two positions in the line.
456
+ const scannedQueues = new Set();
457
+ const scanQueue = (dir) => {
458
+ const key = pathResolve(dir);
459
+ if (scannedQueues.has(key)) return;
460
+ scannedQueues.add(key);
461
+ readQueued(dir);
462
+ };
463
+ // THE CANONICAL INTAKE FIRST, and it is why this parameter exists. `CLEAROTRON_QUEUE_DIR` is where the
464
+ // enqueue CLI and ops-MCP `start_run` write — which is where the PORTAL's own submissions land, since
465
+ // its `trigger` is an ops-MCP hop. The walk below finds only `workspace-*/studio/clearance-search/queue`,
466
+ // and a documented headless install has no workspaces at all: measured on the test box, the only queue
467
+ // under the whole tree is the configured one, and it holds portal-prefixed jobs. So this scan ran ZERO
468
+ // times there, and a submitted search was invisible on the dashboard from submit until claim — a
469
+ // minute and a half of a client believing their order was lost.
470
+ for (const d of Array.isArray(queueDirs) ? queueDirs : []) {
471
+ if (typeof d === "string" && d) scanQueue(d);
472
+ }
473
+ try {
474
+ for (const ws of readdirSync(workspaceRoot).filter((n) => n.startsWith("workspace-"))) {
475
+ const studio = studioDirFor(join(workspaceRoot, ws));
476
+ let slugs = []; try { slugs = readdirSync(studio); } catch { continue; }
477
+ for (const slug of slugs) {
478
+ // Still walked, so a deployment whose queue is not in `queueDirs` keeps working. The union is
479
+ // deliberate: this must add a place to look, never remove one.
480
+ if (slug === "queue") { scanQueue(join(studio, slug)); continue; }
481
+ if (slug === "archive" || slug.startsWith("_") || slug.startsWith(".")) continue;
482
+ let runs = []; try { runs = readdirSync(join(studio, slug)); } catch { continue; }
483
+ for (const r of runs) readRun(join(studio, slug, r));
484
+ }
485
+ }
486
+ } catch { /* no workspace */ }
487
+ // Assign the ordinals last, across every lane at once. Cross-lane order is genuinely undefined —
488
+ // the lanes are per-agent and drain concurrently against one shared pair of slots — so lanes are
489
+ // ordered by path purely to make the result STABLE. An ordinal that reshuffled between two polls
490
+ // of an unchanged queue would read as the queue churning when nothing had moved.
491
+ queuedRows.sort((a, b) => a.lane.localeCompare(b.lane) || a.laneIdx - b.laneIdx);
492
+ queuedRows.forEach((q, i) => { q.row.queuePos = i + 1; out.push(q.row); });
493
+ return out.sort((a, b) => String(b.date ?? "").localeCompare(String(a.date ?? "")));
494
+ }
495
+
496
+ // A failure `reason` is NOT client-safe, and the listing must not hand it to a browser.
497
+ //
498
+ // The engine writes `reason = String(e?.stack ?? e)` truncated to 200 characters
499
+ // (pipeline.mjs, pipeline-knockout.mjs). That is a raw stack trace: absolute filesystem
500
+ // paths, internal module names, provider error text. Useful to staff, and none of a client's business
501
+ // — and redacting it in the UI would be theatre, because the field still travels over the wire and
502
+ // sits in devtools whatever React chooses to render.
503
+ //
504
+ // A client still learns that the run stopped and roughly where, because the plan is right that an
505
+ // invisible failure is worse than a visible one: they keep `state`, `failedStage` (product vocabulary
506
+ // like "register-probe", not a stack), and a stable sentence telling them what happens next. What they
507
+ // lose is the trace.
508
+ // — the owner's failed-run ruling. ONE author for this sentence now: it was
509
+ // written out here and again in mcp-server/lib/audit-view.mjs, and a reword that fixed two of three
510
+ // copies is how the retired claim survives in whichever surface nobody is looking at.
511
+ const CLIENT_FAILURE_NOTE = clientFailureNote();
512
+
513
+ // The run-slot cap, resolved from the SAME table pipeline.acquireRunSlot resolves it from, so the number
514
+ // the screen states and the number the engine enforces cannot drift apart. It used to re-read
515
+ // `process.env` behind a second copy of the literal 2 — two independent copies of one number is the
516
+ // shape that drifts, and reading the raw environment skipped the alias resolution every other read of
517
+ // this variable gets. `numeric-setting.mjs` is imported at module scope where
518
+ // `driver.config.mjs` cannot be: it pulls in nothing but the alias table this file already imports.
519
+ //
520
+ // It is one global cap over one lock directory, never per brand owner: two owners each running one
521
+ // search fill the whole deployment, and saying it per-owner would over-promise throughput.
522
+ //
523
+ // NULL WHEN THE VALUE IS UNUSABLE, AND THE SCREEN THEN SAYS NOTHING. The engine REFUSES a non-numeric
524
+ // cap; this surface must not, because a misconfiguration that took out the screen an operator reads to
525
+ // find it would be a worse failure than the one being fixed. `slotNote` already renders a null cap by
526
+ // drawing no line at all, so the page states the number it has or stays quiet — never a number nobody
527
+ // chose.
528
+ export const concurrentRunsCap = () => {
529
+ const r = resolveNumericSetting("CLEAROTRON_MAX_CONCURRENT_RUNS");
530
+ return r.ok ? Math.max(1, r.value) : null;
531
+ };
532
+
533
+ export function forRole(runs, principal) {
534
+ // A person who sees everything reads failure reasons verbatim; everyone else gets the plain note. That redaction is the ONLY
535
+ // role-shaping left: the held-run suppression is retired (one report, spec 2026-07-30 §5 — a run you
536
+ // have rights to is always listed; the machine-QC record lives on the audit workbook).
537
+ if (seesEverything(principal)) return runs;
538
+ return runs.map((r) => {
539
+ let out = r;
540
+ // — the redaction must take `reasonDetail` with it. `reason` is replaced by a fixed note for a
541
+ // client session; a second field carrying the engine's raw words would walk straight past that.
542
+ if (r.state === "failed") out = { ...out, reason: CLIENT_FAILURE_NOTE, reasonDetail: null, reasonRedacted: true };
543
+ return out;
544
+ });
545
+ }
546
+
547
+ /** Every account's runs, in one pass. Staff only — the route enforces that, not this function. */
548
+ export function scanAllRuns({ poolRoot, workspaceRoot, queueDirs = [] }) {
549
+ return scanAccountRuns({ poolRoot, workspaceRoot, account: null, queueDirs });
550
+ }
551
+
552
+ /**
553
+ * ── — WHICH RUN IS THIS, ASKED THE WAY THE LIST ASKS IT ────────────────────
554
+ *
555
+ * The Retire control refused every run the owner pressed it on, with `400 unknown run`, because the
556
+ * route resolved the id by reading `<pool>/<runId>/meta.json` — and **a run that was stopped never
557
+ * publishes into the pool**. The Clearances list that offered the button reads a wider set: the pool,
558
+ * the workspaces and the queues. So the screen showed a control for a run the endpoint could not see,
559
+ * and the failed and abandoned ones — the population a reader most wants off the list — were exactly
560
+ * the ones it could never act on.
561
+ *
562
+ * THE POOL READ STAYS FIRST, and that is not an optimisation for its own sake: a delivered run is the
563
+ * common case and one targeted `readFileSync` answers it. The scan is the FALLBACK, so the cost of a
564
+ * directory walk is paid only on the ids the pool cannot answer — which is the case that used to be a
565
+ * refusal, so nothing that worked before got slower.
566
+ *
567
+ * IT ANSWERS WITH THE ACCOUNT, never with a boolean. The account is what the caller needs: the retire
568
+ * and family routes take the owner from the RUN and never from the request body, because a body-supplied
569
+ * owner is a body-supplied tenancy claim. A resolver that returned "yes, it exists" would leave that
570
+ * rule needing a second lookup.
571
+ *
572
+ * @returns `{ account, state }`, or `null` when no surface this deployment lists knows the id.
573
+ */
574
+ export function resolveRunAccount({ poolRoot, workspaceRoot, queueDirs = [], runId }) {
575
+ try {
576
+ const meta = readJson(join(poolRoot, runId, "meta.json"));
577
+ return { account: meta.customerKey || "generic", state: "delivered" };
578
+ } catch { /* not published — which is the whole case this function exists for */ }
579
+ // BOTH DIRECTIONS of the retired filter, because the way BACK from retirement has to resolve a run
580
+ // that is currently hidden. `includeRetired` is exclusive on either setting, so one call cannot see
581
+ // both, and a restore that could not resolve its own id would be a one-way door.
582
+ for (const includeRetired of [false, true]) {
583
+ for (const row of scanAccountRuns({ poolRoot, workspaceRoot, account: null, includeRetired, queueDirs })) {
584
+ if (row.runId === runId) return { account: row.account ?? "generic", state: row.state ?? null };
585
+ }
586
+ }
587
+ return null;
588
+ }