clearotron 0.5.1 → 0.6.0-beta.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (379) hide show
  1. package/.env.example +7 -7
  2. package/INSTALL.md +10 -10
  3. package/QUICKSTART.md +6 -6
  4. package/README.md +2 -2
  5. package/THIRD-PARTY-NOTICES.md +4 -4
  6. package/bin/README.md +2 -2
  7. package/bin/clearotron.mjs +1 -1
  8. package/bin/connect.mjs +1 -1
  9. package/bin/disconnect.mjs +1 -1
  10. package/bin/example.mjs +2 -2
  11. package/bin/grant.mjs +1 -1
  12. package/bin/onboard.mjs +78 -23
  13. package/bin/start.mjs +49 -18
  14. package/bin/update.mjs +13 -3
  15. package/build-info.json +2 -2
  16. package/docs/DELIVERY.md +1 -1
  17. package/docs/PORTAL.md +1 -1
  18. package/docs/RELEASES.md +1 -1
  19. package/docs/architecture/02-architecture.md +10 -2
  20. package/docs/architecture/03-run-lifecycle.md +6 -2
  21. package/docs/architecture/04-configuration-reference.md +3 -3
  22. package/docs/architecture/05-config-governance.md +5 -4
  23. package/docs/architecture/08-development-guide.md +4 -4
  24. package/docs/architecture/09-security-and-data.md +1 -1
  25. package/{driver/skills/clearance-search/SKILL.md → docs/architecture/retired-manuals/clearance-search-spine.md} +17 -30
  26. package/{driver/skills/clearance-search/templates/email/generic.md → docs/architecture/retired-manuals/email-generic.md} +1 -1
  27. package/{driver/skills/clearance-search → docs/architecture/retired-manuals}/template-formatting.md +3 -4
  28. package/docs/configuration.md +1 -1
  29. package/docs/decisions/0002-no-dark-functionality.md +5 -0
  30. package/driver/CHANGELOG.md +60 -0
  31. package/driver/README.md +11 -1
  32. package/driver/accepted-order.mjs +13 -5
  33. package/driver/attempt-rows.mjs +64 -0
  34. package/driver/attributed-span.mjs +1 -1
  35. package/driver/authority-trees.mjs +1 -1
  36. package/driver/best-draft.mjs +3 -3
  37. package/driver/blind-frame-record.mjs +2 -2
  38. package/driver/cancel.mjs +3 -2
  39. package/driver/carry-through.mjs +2 -2
  40. package/driver/citation-census.json +3 -3
  41. package/driver/clearance-variants-record.mjs +4 -10
  42. package/driver/common-law-coverage-status.mjs +3 -3
  43. package/driver/common-law-receipts.mjs +2 -2
  44. package/driver/compare.mjs +1 -1
  45. package/driver/config-inventory.mjs +6 -79
  46. package/driver/consumption-ledger.mjs +2 -1
  47. package/driver/contract-dictation-registry.mjs +5 -0
  48. package/driver/contract-e3-backlog.mjs +45 -66
  49. package/driver/contract-e3-baseline.json +16 -16
  50. package/driver/contract-vocabulary.mjs +8 -6
  51. package/driver/corrections-feedforward.mjs +3 -1
  52. package/driver/coverage-form-io.mjs +7 -8
  53. package/driver/coverage-tool.mjs +1 -1
  54. package/driver/declination-tool.mjs +2 -2
  55. package/driver/degraded-parts.mjs +9 -9
  56. package/driver/demo-container.mjs +5 -4
  57. package/driver/deploy-live-run-guard.mjs +19 -7
  58. package/driver/derived-state.mjs +2 -2
  59. package/driver/dev-portal.mjs +2 -1
  60. package/driver/dispatch-record.mjs +1 -1
  61. package/driver/disposition-tool.mjs +2 -1
  62. package/driver/doubt-closure-tool.mjs +2 -2
  63. package/driver/driver.config.mjs +35 -724
  64. package/driver/e2e-rounds.mjs +3 -4
  65. package/driver/engine/CONTRACT.md +3 -0
  66. package/driver/engine/README.md +2 -0
  67. package/driver/engine/anthropic-agent.mjs +8 -37
  68. package/driver/engine/auth.mjs +74 -0
  69. package/driver/engine/child-record.mjs +1 -1
  70. package/driver/engine/deny-authority-write.mjs +2 -2
  71. package/driver/engine/jx-turn.mjs +10 -2
  72. package/driver/engine/mcp/README.md +1 -1
  73. package/driver/engine/mcp/band-server.mjs +6 -6
  74. package/driver/engine/mcp/codex-config.mjs +1 -1
  75. package/driver/engine/mcp/declination-server.mjs +2 -3
  76. package/driver/engine/mcp/dispositions-server.mjs +3 -3
  77. package/driver/engine/mcp/gather-config.mjs +24 -19
  78. package/driver/engine/mcp/grid-provenance.mjs +1 -1
  79. package/driver/engine/mcp/held-answers.mjs +5 -5
  80. package/driver/engine/mcp/perplexity-server.mjs +16 -7
  81. package/driver/engine/mcp/recording-server.mjs +7 -6
  82. package/driver/engine/mcp/register-server.mjs +29 -0
  83. package/driver/engine/mcp/stdio-server.mjs +5 -5
  84. package/driver/engine/mcp/supplemental.mjs +9 -9
  85. package/driver/engine/openai-agent.mjs +5 -2
  86. package/driver/engine/registry.mjs +103 -0
  87. package/driver/engine/run-choices.mjs +162 -0
  88. package/driver/engine/stamps.mjs +35 -0
  89. package/driver/enqueue-schema.mjs +4 -4
  90. package/driver/envelope-settle.mjs +3 -2
  91. package/driver/feedback-issues.mjs +1 -1
  92. package/driver/feedback-mint.mjs +3 -2
  93. package/driver/feedback-store.mjs +3 -2
  94. package/driver/findings-model.mjs +1 -1
  95. package/driver/flag-snapshot.mjs +5 -4
  96. package/driver/floor-duty.mjs +3 -3
  97. package/driver/foreign-record-links.mjs +1 -1
  98. package/driver/frame-diff-record.mjs +2 -8
  99. package/driver/framework.mjs +1 -1
  100. package/driver/gate-metrics.mjs +10 -11
  101. package/driver/gateway.mjs +220 -839
  102. package/driver/goods-evidence.mjs +10 -6
  103. package/driver/jx-lanes.mjs +3 -3
  104. package/driver/jx-units.mjs +31 -37
  105. package/driver/jx.mjs +44 -59
  106. package/driver/knockout-assess-record.mjs +3 -3
  107. package/driver/knockout-caveats.mjs +21 -0
  108. package/driver/knockout-correction-record.mjs +58 -28
  109. package/driver/knockout-frame-record.mjs +2 -2
  110. package/driver/knockout-register-read.mjs +38 -21
  111. package/driver/knockout-register-record.mjs +5 -6
  112. package/driver/knockout-review-record.mjs +12 -11
  113. package/driver/ladder/model-gauge.mjs +88 -0
  114. package/driver/ladder/next-rung.mjs +296 -0
  115. package/driver/ladder/rescue.mjs +146 -0
  116. package/driver/ladder/stage-tools.mjs +57 -0
  117. package/driver/ladder/turn-failure.mjs +166 -0
  118. package/driver/log.mjs +2 -2
  119. package/driver/matter-frame-record.mjs +4 -4
  120. package/driver/methodology-witness.mjs +2 -2
  121. package/driver/narrative-refutation-record.mjs +145 -42
  122. package/driver/one-build-per-run.mjs +62 -0
  123. package/driver/outbox-backoff.mjs +4 -4
  124. package/driver/owner-screen.mjs +0 -10
  125. package/driver/owner-use-check.mjs +2 -28
  126. package/driver/package.json +1 -1
  127. package/driver/partial-payload-baseline.json +1 -1
  128. package/driver/parts-not-completed.mjs +1 -1
  129. package/driver/pipeline-knockout.mjs +1015 -1001
  130. package/driver/pipeline.mjs +511 -9265
  131. package/driver/placement-decisions.mjs +2 -2
  132. package/driver/placement-form-io.mjs +7 -9
  133. package/driver/placement-union.mjs +0 -6
  134. package/driver/plan-stability.mjs +7 -10
  135. package/driver/portal-acks.mjs +3 -2
  136. package/driver/portal-confirmation.mjs +48 -0
  137. package/driver/portal-families.mjs +3 -2
  138. package/driver/portal-local-auth.mjs +1 -2
  139. package/driver/portal-routes/README.md +24 -0
  140. package/driver/portal-routes/admin.mjs +425 -0
  141. package/driver/portal-routes/compose.mjs +66 -0
  142. package/driver/portal-routes/config.mjs +118 -0
  143. package/driver/portal-routes/connect.mjs +283 -0
  144. package/driver/portal-routes/feedback.mjs +178 -0
  145. package/driver/portal-routes/me.mjs +165 -0
  146. package/driver/portal-routes/queue.mjs +64 -0
  147. package/driver/portal-routes/report.mjs +106 -0
  148. package/driver/portal-routes/run.mjs +508 -0
  149. package/driver/portal-routes/runs.mjs +127 -0
  150. package/driver/portal-routes/usage.mjs +82 -0
  151. package/driver/portal-runs.mjs +588 -0
  152. package/driver/portal-service.mjs +78 -2592
  153. package/driver/portal-static.mjs +3 -1
  154. package/driver/predelivery-lint.mjs +92 -9
  155. package/driver/production-pool-guard.mjs +1 -1
  156. package/driver/profiles.mjs +5 -4
  157. package/driver/progress.mjs +29 -24
  158. package/driver/publish/README.md +10 -5
  159. package/driver/publish/archive-tags.mjs +3 -2
  160. package/driver/publish/demo-marking.mjs +2 -2
  161. package/driver/publish/index.mjs +215 -140
  162. package/driver/publish/knockout.mjs +153 -107
  163. package/driver/publish/office-record-links.mjs +22 -0
  164. package/driver/publish/parse.mjs +20 -5
  165. package/driver/publish/pool-admin.mjs +9 -3
  166. package/driver/publish/render.mjs +11 -3
  167. package/driver/publish/report-dates.mjs +3 -4
  168. package/driver/publish/report-registry.mjs +7 -10
  169. package/driver/publish/seed-pool.mjs +3 -2
  170. package/driver/publish/shell.mjs +106 -0
  171. package/driver/publish/templates/report.css +3 -1
  172. package/driver/queue-order.mjs +4 -3
  173. package/driver/record-carry.mjs +0 -9
  174. package/driver/record-discard.mjs +1 -4
  175. package/driver/record-fold.mjs +3 -3
  176. package/driver/record-goods.mjs +5 -5
  177. package/driver/reference-score.mjs +2 -3
  178. package/driver/register-capabilities.mjs +0 -6
  179. package/driver/register-count.mjs +3 -2
  180. package/driver/register-digest-record.mjs +7 -7
  181. package/driver/register-fixture-marker.mjs +3 -3
  182. package/driver/register-plan.mjs +2 -2
  183. package/driver/register-records.mjs +2 -2
  184. package/driver/register-taint.mjs +3 -3
  185. package/driver/register-unit-record.mjs +48 -9
  186. package/driver/register-unreachable.mjs +4 -3
  187. package/driver/registry-fidelity.mjs +79 -34
  188. package/driver/repair-composers.mjs +14 -9
  189. package/driver/repair-digest.mjs +4 -6
  190. package/driver/repair-scope.mjs +3 -3
  191. package/driver/repair-targets.mjs +24 -9
  192. package/driver/repairs.mjs +44 -58
  193. package/driver/replay-archive.mjs +7 -7
  194. package/driver/report-card-record.mjs +3 -3
  195. package/driver/report-overview-record.mjs +4 -4
  196. package/driver/research-answers.mjs +38 -6
  197. package/driver/research-checks.mjs +4 -4
  198. package/driver/result-noun-fields.mjs +28 -11
  199. package/driver/review-addresses.mjs +163 -0
  200. package/driver/rule-shape.mjs +1 -1
  201. package/driver/run-delivered.mjs +340 -0
  202. package/driver/run-economics.mjs +8 -26
  203. package/driver/run-failed.mjs +545 -0
  204. package/driver/run-integrity.mjs +1 -1
  205. package/driver/run-outcome.mjs +314 -0
  206. package/driver/run-park.mjs +23 -0
  207. package/driver/run-quote.mjs +32 -0
  208. package/driver/run-record.mjs +352 -0
  209. package/driver/run-requirements.mjs +22 -0
  210. package/driver/run-shell.mjs +55 -0
  211. package/driver/runner.mjs +71 -33
  212. package/driver/saved-register-pages.mjs +4 -4
  213. package/driver/score-redaction.mjs +2 -2
  214. package/driver/search-policy.mjs +12 -13
  215. package/driver/settle-stamp.mjs +4 -3
  216. package/driver/skeptic-record.mjs +2 -2
  217. package/driver/skeptic-search.mjs +1 -1
  218. package/driver/skills/README.md +7 -7
  219. package/driver/skills/blind-frame/SKILL.md +1 -2
  220. package/driver/skills/case-law-citation/SKILL.md +9 -37
  221. package/driver/skills/case-law-citation/sources/courtlistener.md +1 -3
  222. package/driver/skills/case-law-citation/sources/eurlex.md +8 -11
  223. package/driver/skills/case-law-citation/sources/legaldatahunter.md +1 -1
  224. package/driver/skills/clearance-common-law/SKILL.md +45 -111
  225. package/driver/skills/clearance-common-law/perplexity-prompts.md +7 -79
  226. package/driver/skills/clearance-register/SKILL.md +15 -33
  227. package/driver/skills/clearance-register/digest.md +31 -92
  228. package/driver/skills/clearance-register/providers/clarivate.md +2 -2
  229. package/driver/skills/clearance-register/providers/corsearch.md +5 -5
  230. package/driver/skills/clearance-register/providers/euipo.md +1 -2
  231. package/driver/skills/clearance-register/providers/free-tier.md +0 -19
  232. package/driver/skills/clearance-register/providers/signa.md +6 -25
  233. package/driver/skills/clearance-register/providers/uspto-local.md +0 -24
  234. package/driver/skills/clearance-register/register-recipes.md +8 -15
  235. package/driver/skills/clearance-register/status-rules.md +6 -24
  236. package/driver/skills/clearance-register/unit.md +11 -20
  237. package/driver/skills/clearance-search/delivery-contract.md +24 -120
  238. package/driver/skills/clearance-search/field-doctrine-pharma.md +1 -5
  239. package/driver/skills/clearance-search/firm-wide-reasoning.md +24 -43
  240. package/driver/skills/clearance-search/phase2-execution.md +29 -77
  241. package/driver/skills/clearance-search/report-prose.md +3 -4
  242. package/driver/skills/clearance-search/risk-framework-demo.md +1 -1
  243. package/driver/skills/clearance-search/risk-framework-triage.manifest.json +3 -3
  244. package/driver/skills/clearance-search/risk-framework-triage.md +7 -9
  245. package/driver/skills/clearance-search/risk-framework.manifest.json +1 -1
  246. package/driver/skills/clearance-search/risk-framework.md +1 -1
  247. package/driver/skills/clearance-search/synthesis-rules.md +30 -107
  248. package/driver/skills/clearance-search/worked-examples.md +5 -5
  249. package/driver/skills/clearance-variants/SKILL.md +46 -45
  250. package/driver/skills/clearance-variants/transliteration-scripts.md +4 -4
  251. package/driver/skills/frame-diff/SKILL.md +1 -1
  252. package/driver/skills/knockout-assess/SKILL.md +6 -14
  253. package/driver/skills/knockout-frame/SKILL.md +1 -1
  254. package/driver/skills/matter-frame/SKILL.md +7 -12
  255. package/driver/skills/matter-frame/watchlist-reference.md +1 -4
  256. package/driver/skills/narrative-refutation/SKILL.md +20 -30
  257. package/driver/skills/placement-inquiry/SKILL.md +8 -18
  258. package/driver/skills-store-provenance.mjs +1 -1
  259. package/driver/stage-context.mjs +32 -35
  260. package/driver/stage-freshness.mjs +127 -11
  261. package/driver/stages-knockout.mjs +49 -22
  262. package/driver/stages.mjs +88 -283
  263. package/driver/status-snapshot.mjs +2 -1
  264. package/driver/steps/correction-cycle.mjs +311 -0
  265. package/driver/steps/corrections.mjs +644 -0
  266. package/driver/steps/delivery.mjs +1287 -0
  267. package/driver/steps/frame-comparison.mjs +922 -0
  268. package/driver/steps/intake.mjs +84 -0
  269. package/driver/steps/open-run.mjs +419 -0
  270. package/driver/steps/overview-and-cards.mjs +899 -0
  271. package/driver/steps/placement-and-digest.mjs +23 -0
  272. package/driver/steps/register-sweep.mjs +1563 -0
  273. package/driver/steps/skeptic-and-follow-up.mjs +831 -0
  274. package/driver/steps/synthesis.mjs +261 -0
  275. package/driver/steps/verdict-gate.mjs +968 -0
  276. package/driver/suite-census.json +403 -91
  277. package/driver/surface-exit-verdict.mjs +0 -8
  278. package/driver/synthesis-record.mjs +72 -6
  279. package/driver/terminal-clamp.mjs +10 -0
  280. package/driver/tokens.mjs +8 -62
  281. package/driver/tool-calls.mjs +2 -2
  282. package/driver/unit-state-verdict.mjs +1 -1
  283. package/driver/usage-ledger.mjs +2 -1
  284. package/driver/verify-knockout.mjs +20 -35
  285. package/driver/verify.mjs +47 -36
  286. package/driver/web-grid.mjs +3 -4
  287. package/driver/whatif-memo-run.mjs +2 -2
  288. package/driver/whatif-queue.mjs +4 -3
  289. package/driver/withheld-families.mjs +14 -15
  290. package/driver/worker-heartbeat.mjs +3 -2
  291. package/driver/write-up-form.mjs +0 -3
  292. package/mcp-server/CHANGELOG.md +4 -0
  293. package/mcp-server/http-server.mjs +1 -1
  294. package/mcp-server/lib/brief.mjs +22 -4
  295. package/mcp-server/lib/events.mjs +2 -2
  296. package/mcp-server/lib/evidence.mjs +3 -2
  297. package/mcp-server/lib/findings.mjs +2 -1
  298. package/mcp-server/lib/knockout.mjs +9 -10
  299. package/mcp-server/lib/ops.mjs +9 -9
  300. package/mcp-server/lib/runs.mjs +9 -10
  301. package/mcp-server/lib/trace.mjs +1 -1
  302. package/mcp-server/lib/whatif.mjs +2 -3
  303. package/mcp-server/package.json +1 -1
  304. package/mcp-server/server.mjs +5 -5
  305. package/package.json +2 -1
  306. package/portal-ui/dist/assets/{index-fPqAU0sx.js → index-D5rkCjDc.js} +26 -14
  307. package/portal-ui/dist/index.html +1 -1
  308. package/portal-ui/package.json +3 -3
  309. package/providers/README.md +1 -1
  310. package/providers/_shared/answer-memory.mjs +4 -5
  311. package/providers/_shared/execute-plan.mjs +48 -1
  312. package/providers/_shared/records-from-search.mjs +46 -0
  313. package/providers/clarivate/README.md +2 -2
  314. package/providers/clarivate/src/adapter.js +147 -0
  315. package/providers/clarivate/src/core.js +1 -14
  316. package/{driver/engine/mcp/clarivate-server.mjs → providers/clarivate/src/mount.js} +5 -10
  317. package/providers/corsearch/README.md +3 -3
  318. package/providers/corsearch/src/adapter.js +80 -0
  319. package/providers/corsearch/src/core.js +14 -11
  320. package/{driver/engine/mcp/corsearch-server.mjs → providers/corsearch/src/mount.js} +5 -10
  321. package/providers/euipo/README.md +2 -2
  322. package/providers/euipo/src/adapter.js +85 -0
  323. package/providers/euipo/src/core.js +1 -1
  324. package/providers/euipo/src/euipo-client.js +1 -2
  325. package/{driver/engine/mcp/euipo-server.mjs → providers/euipo/src/mount.js} +5 -10
  326. package/providers/free-tier/README.md +2 -2
  327. package/providers/free-tier/src/adapter.js +127 -0
  328. package/{driver/engine/mcp/free-tier-server.mjs → providers/free-tier/src/mount.js} +5 -10
  329. package/providers/jx-subclass/coverage.mjs +1 -6
  330. package/providers/jx-subclass/score-truth.mjs +2 -1
  331. package/providers/oauth-mcp-bridge/CHANGELOG.md +4 -0
  332. package/providers/oauth-mcp-bridge/package.json +1 -1
  333. package/providers/perplexity/src/core.js +2 -2
  334. package/providers/signa/README.md +2 -2
  335. package/providers/signa/src/adapter.js +157 -0
  336. package/providers/signa/src/capabilities.js +0 -3
  337. package/providers/signa/src/core.js +2 -2
  338. package/{driver/engine/mcp/signa-server.mjs → providers/signa/src/mount.js} +7 -12
  339. package/providers/signa/src/offices.generated.js +17 -15
  340. package/providers/uspto-local/README.md +1 -1
  341. package/providers/uspto-local/bin/verify-index.mjs +1 -1
  342. package/providers/uspto-local/src/adapter.js +75 -0
  343. package/{driver/engine/mcp/uspto-local-server.mjs → providers/uspto-local/src/mount.js} +5 -10
  344. package/scripts/band-shape-probe.mjs +2 -2
  345. package/scripts/citation-line-check.mjs +7 -7
  346. package/scripts/compare.mjs +1 -1
  347. package/scripts/dead-names.mjs +2 -2
  348. package/scripts/e2e-first-time.mjs +19 -7
  349. package/scripts/e2e.mjs +13 -13
  350. package/scripts/engine-probe.mjs +1 -1
  351. package/scripts/env-audit.mjs +7 -4
  352. package/scripts/env-classify.mjs +5 -1
  353. package/scripts/feedback-mint.mjs +1 -1
  354. package/scripts/freeze-example-run.mjs +7 -7
  355. package/scripts/mint-suite-census.mjs +2 -2
  356. package/scripts/nightly-notice.mjs +1 -1
  357. package/scripts/release-cut-decision.mjs +7 -2
  358. package/scripts/release-note-required.mjs +26 -9
  359. package/scripts/release-notes-lint.mjs +3 -2
  360. package/scripts/release-version-pr-checks.mjs +1 -1
  361. package/scripts/settings-render-check.mjs +23 -3
  362. package/scripts/test-run.mjs +5 -5
  363. package/scripts/travelling-predicates.mjs +1 -1
  364. package/scripts/undeclared-field-census.mjs +1 -1
  365. package/scripts/unexecuted-asserts.mjs +1 -1
  366. package/scripts/verify-publishable.mjs +1 -1
  367. package/shared/client-door.mjs +1 -1
  368. package/shared/connect-clients.mjs +1 -1
  369. package/shared/connector-signin-probe.mjs +1 -1
  370. package/shared/env-aliases.mjs +1 -1
  371. package/shared/invocation.mjs +14 -2
  372. package/shared/names-in-force.mjs +2 -0
  373. package/shared/register-selection.mjs +2 -2
  374. package/shared/store-in-repo.mjs +3 -3
  375. package/shared/summary-blocks.mjs +0 -3
  376. package/shared/trigger-lane.mjs +1 -1
  377. package/shared/vacuous-pass.mjs +2 -2
  378. package/shared/verb-shim.mjs +4 -2
  379. package/node_modules/exceljs/README.md +0 -3023
@@ -0,0 +1,508 @@
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-routes/run.mjs — a search from plan to start: the confirmed plan, the order that spends, stopping a run, and a
5
+ // run's summary.
6
+ //
7
+ // One of the portal service's route groups, moved out of its dispatcher unchanged; makePortalService says how it asks them.
8
+ import { join } from "node:path";
9
+ import { BRAND } from "../../shared/brand.mjs";
10
+ import { gateResolvedRequest, resolveForDoor } from "../door-gates.mjs";
11
+ import { validateJob } from "../enqueue-schema.mjs";
12
+ import { assertPrincipal, mayReadRun, seesEverything } from "../portal-access.mjs";
13
+ import { jobHashOf, mintConfirmation, verifyConfirmation } from "../portal-confirmation.mjs";
14
+ import { batchSummaryOf } from "../portal-report.mjs";
15
+ import { scanAccountRuns } from "../portal-runs.mjs";
16
+ import { baseTurnaroundFor, productRow } from "../product-rows.mjs";
17
+ import { quoteForJob } from "../run-quote.mjs";
18
+ import { readJson } from "../run-record.mjs";
19
+ import { countJobMarks, coverageDisclosure, kebabCollisions, policyFor, productAvailability, UNAVAILABLE_NOTE } from "../search-policy.mjs";
20
+ import { accountUsage, DEFAULT_CLIENT_DAILY_RUNS } from "../usage-ledger.mjs";
21
+
22
+ export async function runRoutes({ poolRoot, workspaceRoot, secret, queueDirs, trigger, stopRun, demo, orderRefusal, audit, upstream, readBuilt, readCanCount, readTerritories, loadProfilesImpl, usedJtis, sweepJtis, jobFor, selectorOf, refusalFor, allowanceExhaustedLine }, { method, parts, principal, body, query }) {
23
+ // shared plan-time gates — run at BOTH doors so a body that would 422 at plan can never be
24
+ // submitted at run behind a token minted for a clean body (review 2026-07-18)
25
+ const planGates = (job) => {
26
+ // Availability FIRST, before validation spends any effort on a job that cannot run whatever it
27
+ // says. This is the door that used to be missing: /plan happily minted a confirmation token for
28
+ // a knockout on a box that reported knockout unavailable, and the user found out only after
29
+ // pressing Start — a spend-shaped button that could never spend, which reads as a broken product
30
+ // rather than an unavailable one. Refusing here means the composer and the gate agree.
31
+ //
32
+ // The recipeKey arm that used to sit here (a 422 when saved searches were "not switched on") went
33
+ // with CLEAROTRON_RECIPES_MODE on 2026-07-27: a saved search is now honoured wherever it resolves.
34
+ // Asked of the RESOLVED product, not of the body: a request that names none resolves through
35
+ // the account's default and its own territories, and the old read (`body.searchLevel || "clearance"`)
36
+ // answered about a product nobody had chosen. `resolveFor` fails open to a null resolution, and a
37
+ // null one is not judged here — validateJob and the scope rules below still run, and the runner
38
+ // is the wall.
39
+ {
40
+ const { resolved } = resolveFor(job);
41
+ const cause = resolved && !resolved.clarify
42
+ ? productAvailability(policyFor(resolved.product), {
43
+ built: readBuilt(), registerCanCount: readCanCount(),
44
+ registerTerritories: readTerritories(), geography: productRow(resolved.product)?.geography ?? null,
45
+ demo, // — the wall reads the same cause the label does
46
+ })
47
+ : null;
48
+ if (cause) {
49
+ // The registry's NAME, never the internal key — the report-identity rule. It leads here for
50
+ // the same reason it leads everywhere else: "Knockout search is unavailable" names something
51
+ // a client can act on, "Depth 2 is unavailable" names our pricing ladder.
52
+ const row = productRow(resolved.product);
53
+ return { fail: { status: 422, json: { ok: false, errors: [`${row?.name ?? "That search"} is unavailable. ${UNAVAILABLE_NOTE[cause]}`] } } };
54
+ }
55
+ }
56
+ const probe = { ...job, msgId: `<plan@portal>`, conversationId: job.id };
57
+ const v = validateJob(probe);
58
+ // validateJob NORMALIZES IN PLACE (the dedupe, the bare-string fix, the worldwide token), and it
59
+ // was doing it to a throwaway copy — so the review summary and the rules below read a scope the
60
+ // runner would never receive. A literal "Worldwide" survived here as a one-element territory
61
+ // list, which frames as scope AND counts as one territory against the deep-dive rule: the guard
62
+ // would have waved a worldwide deep dive straight through. Carried back instead. Safe against
63
+ // the confirmation token: jobHashOf does not cover jurisdictions, so plan and run still agree,
64
+ // and a cleared list means the runner applies the account's defaults — what the wall would have
65
+ // done with the token anyway.
66
+ if ("jurisdictions" in probe) job.jurisdictions = probe.jurisdictions; else delete job.jurisdictions;
67
+ // AND THE GEOGRAPHY STAMP WITH IT. validateJob writes it (worldwide / named / account-default),
68
+ // and carrying back only the territories left the real job unstamped — so `resolveEffectiveScope`
69
+ // read "unrecorded" and a worldwide request fell straight back through to the account's own
70
+ // territories at this door, while the CLI and start_run honoured it. That is the same defect this
71
+ // build exists to end, surviving inside the one door that gates the money button.
72
+ if ("geography" in probe) job.geography = probe.geography; else delete job.geography;
73
+ if (!v.ok) return { fail: { status: 422, json: { ok: false, classify: v.classify, errors: v.errors } } };
74
+ const collisions = kebabCollisions((job.marks ?? [{ name: job.markName }]).map((m) => m.name));
75
+ if (collisions.length) return { fail: { status: 422, json: { ok: false, errors: [`marks ${collisions.map(([a, b]) => `"${a}"/"${b}"`).join(", ")} are duplicates or differ only in punctuation — reword or drop one`] } } };
76
+ // The (product × scope) combination rules, said HERE so a client reads them on the review step
77
+ // instead of watching a run park itself minutes later. The runner is the wall; this is the
78
+ // courtesy. It reads the SAME resolution the review step prints from (`resolveFor`), which is
79
+ // what keeps a refusal from contradicting the scope shown beside it. Fails OPEN by the same rule
80
+ // that resolution does: a profile or recipe store the resolver cannot read must not stop someone
81
+ // starting a search.
82
+ let rules = { errors: [], warnings: [] };
83
+ try {
84
+ const { profile, resolved } = resolveFor(job);
85
+ if (!profile && !resolved) throw new Error("resolution unavailable");
86
+ // EVERY resolved-product check, not just the combination rules. This door had `resolveFor(job)`
87
+ // in hand and budgeted nothing on it, so a two-name request under an account whose default
88
+ // product is a clearance passed the money button and parked at the wall (Finding 2c).
89
+ // `availability:false` — the branch above already refused it in the client's own words, and the
90
+ // staff-prose twin must never reach a browser (door-gates.mjs header).
91
+ rules = gateResolvedRequest({ job, profile, resolved, readable: true }, { availability: false });
92
+ // classify:"clarify", exactly as validateJob's own 422 above does it and as the runner files the
93
+ // identical rule. A 422 without it decodes as a collision (contract/api.ts), which the composer
94
+ // renders under "That cannot be searched as written" — a dead end, for a rule whose whole answer
95
+ // is one field: name the territories the product reads, or order the product that reads these.
96
+ if (rules.errors.length) return { fail: { status: 422, json: { ok: false, classify: "clarify", errors: rules.errors } } };
97
+ } catch (e) {
98
+ // Unreadable config never blocks a run here — the wall still holds. Audited rather than
99
+ // swallowed: a deployment pointed at the wrong profile store loses this gate for EVERY account,
100
+ // and silence is how that goes unnoticed (the roster-blindness class of incident).
101
+ audit({ event: "plan-gate-skipped", gate: "scope-rules", error: String(e?.message ?? e) });
102
+ }
103
+ return { warnings: [...(v.warnings ?? []), ...rules.warnings] };
104
+ };
105
+ /**
106
+ * The daily allowance, checked at the doors so the refusal arrives BEFORE the money button.
107
+ *
108
+ * This is the courteous layer, not the control. The runner's admission gate is the wall — it
109
+ * covers every door including email and CLI, and it is what actually stops a run. Checking here
110
+ * as well means a client who is out of allowance is told so on the review step, in a sentence
111
+ * that says when it resets, instead of pressing Start and watching a run park itself minutes
112
+ * later. The two can disagree by a run under concurrency; the wall is the one that decides, and
113
+ * it refuses by CLARIFYING rather than dropping, so nothing is ever lost to the gap.
114
+ *
115
+ * A person who sees everything is never checked; the cap binds everyone else, decided here from the principal.
116
+ */
117
+ // WHICH PRODUCT IS THIS, AND WHERE WOULD IT POINT — asked ONCE, and everything the plan says
118
+ // derives from that one answer: the availability gate, the name, the scope shown at review, and the
119
+ // effort figure the run is stamped with.
120
+ //
121
+ // The resolution used to live inside effortFor, so the plan door quoted effort off the RESOLVED
122
+ // policy while naming the product from the body's own selector — a second, cruder answer that never
123
+ // consulted the customer's own default and was null outright on the recipeKey arm. The two
124
+ // disagreed exactly where it mattered most: a saved search showed the headline "saved search" over
125
+ // an effort figure quoting a recipe, and an account whose profile defaults to a knockout was shown
126
+ // a full-clearance headline for a quick screen.
127
+ //
128
+ // Fails OPEN to nulls: this feeds a description shown beside the real gates, and a profile store
129
+ // the resolver cannot read must not stop someone starting a search. The runner is the wall.
130
+ // ONE implementation, shared with every other door (door-gates.mjs resolveForDoor). It was written
131
+ // here first and copied nowhere, which is why start_run and the CLI resolved nothing at all.
132
+ const resolveFor = resolveForDoor;
133
+ const effortFrom = ({ job, profile, resolved }) => {
134
+ if (!profile || !resolved || resolved.clarify) return null;
135
+ try { return quoteForJob({ job, profile, searchPolicy: resolved }); } catch { return null; }
136
+ };
137
+
138
+ const quotaRefusal = async (account, organisation = null) => {
139
+ if (seesEverything(principal) || !upstream) return null;
140
+ let caps = null, capsRead = false;
141
+ try {
142
+ // Generic's caps are the neutral profile's — one file, every organisation's lane — so they are
143
+ // read from the store rather than through the settings wall, which answers per company.
144
+ if (account === "generic") { caps = (await loadProfilesImpl()).get("generic")?.runCaps ?? null; capsRead = true; }
145
+ else {
146
+ const r = await upstream.getProfile(principal, account);
147
+ if (r.status === 200) { caps = r.json?.readOnly?.runCaps ?? null; capsRead = true; }
148
+ }
149
+ } catch { return null; } // cannot read the cap ⇒ do not invent one; the wall still holds
150
+ // The same DEFAULT the wall applies (runner.mjs DEFAULT_CLIENT_DAILY_RUNS): a profile READ
151
+ // successfully with no dailyRuns is capped, not uncapped. Mirrored rather than imported because
152
+ // portal-service must not pull the runner into a request path; a test pins the two constants.
153
+ // An UNREADABLE profile is different and gets no pre-check at all — inventing a limit we could
154
+ // not read would refuse a client whose profile may say something larger. The wall still holds.
155
+ if (!capsRead) return null;
156
+ const limit = Number.isInteger(caps?.dailyRuns) ? caps.dailyRuns : DEFAULT_CLIENT_DAILY_RUNS;
157
+ if (!Number.isInteger(limit)) return null;
158
+ const used = accountUsage({ queueDirs: queueDirs(), account, organisation });
159
+ // A COUNT WE COULD NOT TAKE IS NOT A ZERO. `complete: false` means no ledger was reachable, and
160
+ // 0 would then mean "nothing recorded" and "nothing readable" at once — the exact confusion that
161
+ // made this refusal unreachable for as long as the path was wrong. Same call the branch
162
+ // above already makes for an unreadable profile, for the same reason: this is a pre-check whose
163
+ // only job is a better sentence, the runner's checkRunCaps is the actual control, and refusing a
164
+ // client on evidence we do not have costs them a search we cannot show they spent. So it stays
165
+ // quiet — but it says so in the audit trail rather than silently, because a gate that cannot read
166
+ // its input is an operational fact, not a non-event.
167
+ //
168
+ // `basis` rides along because "no-ledger" and "unreadable" are fixed by different people: the
169
+ // first is a queue this service was never pointed at, the second is a file it cannot open. One
170
+ // row per request while a deployment is misconfigured, at both call sites, is the intended
171
+ // volume — a gate that has been blind since boot should be as loud as the traffic it is blind to.
172
+ if (!used.complete) {
173
+ audit({ event: "quota-precheck-blind", by: principal.email, account, basis: used.basis });
174
+ return null;
175
+ }
176
+ if (used.today + 1 <= limit) return null;
177
+ return { status: 429, json: { ok: false, errors: [allowanceExhaustedLine(limit, BRAND.name)] } };
178
+ };
179
+
180
+ // ── AN INSTALL THAT CANNOT SEARCH REFUSES HERE, WHERE THE PERSON IS ─────────────────────────
181
+ //
182
+ // The runner asks this at intake and refuses the order there (runner.mjs, `orderTimeRefusal`). The portal
183
+ // asked nothing: it said "queued", the runner's refusal reached only its terminal and a sidecar in the
184
+ // queue, and the order then vanished from every page, which is the outcome the queue scan's own rule
185
+ // above says belongs at submission. So the review and the start both ask the runner's question, of the
186
+ // runner's tables, and nothing is queued. Neither sentence names a setting, which a browser must never be
187
+ // shown: the client one the runner already writes, or what is missing and the command that sets it, for the
188
+ // person who runs the install (refusalFor). A demo walks its own flow and is not asked.
189
+ // `code` lets the screen give the box its own heading rather than the edited-review one, and the audit row is
190
+ // the operator's record of the refusal: the order doors are not admin writes, so nothing files one for them.
191
+ const configurationRefusal = async (door, account) => {
192
+ if (demo) return null;
193
+ const refusal = await orderRefusal();
194
+ if (!refusal) return null;
195
+ audit({ event: door === "plan" ? "plan" : "trigger", by: principal.email, account, ok: false, refused: "not_configured", missing: refusal.names });
196
+ return { status: 409, json: { ok: false, errors: [refusalFor(principal, refusal)], code: "not_configured" } };
197
+ };
198
+
199
+ // /portal/api/run/plan — the confirmation gate (no spend)
200
+ if (parts[1] === "api" && parts[2] === "run" && parts[3] === "plan" && method === "POST") {
201
+ const tenant = body.tenant ?? query.tenant ?? null;
202
+ const account = assertPrincipal(principal, { account: body.account ?? query.account ?? null, tenant, run: true });
203
+ if (!account) return { status: 400, json: { error: "name an account (?account=)" } };
204
+ const job = jobFor({ principal, account, tenant, body });
205
+ const notConfigured = await configurationRefusal("plan", account);
206
+ if (notConfigured) return notConfigured;
207
+ const gates = planGates(job);
208
+ if (gates.fail) return gates.fail;
209
+ const overQuota = await quotaRefusal(account, job.tenant ?? null);
210
+ if (overQuota) return overQuota;
211
+ // ONE resolution, and the name, the stage, the turnaround and the effort all come off it.
212
+ const { profile: planProfile, resolved: planResolved, scope: planScope } = resolveFor(job);
213
+ const planRow = productRow(planResolved?.product);
214
+ // `name` leads. stageLabel stays on the wire for an older bundle, which
215
+ // reads `name || stageLabel` — and for a resolution that clarified, where there is no row and
216
+ // "saved search" is still the honest thing to call it.
217
+ const name = planRow?.name ?? null;
218
+ const stageLabel = planRow?.stageLabel ?? planResolved?.stageLabel ?? "saved search";
219
+ const nMarks = countJobMarks(job);
220
+ const selector = selectorOf(body);
221
+ // WHAT WOULD ACTUALLY BE SEARCHED, resolved by the same ladder plan_run uses. Without this the
222
+ // review step could show a depth and a mark count while saying nothing about the territories or
223
+ // marketplaces the user had just picked — a summary that omits the thing being confirmed is a
224
+ // worse gate than none, because it looks like it checked.
225
+ const scope = planScope;
226
+ const token = mintConfirmation({ secret, account, email: principal.email, jobHash: jobHashOf(job) });
227
+ audit({ event: "plan", by: principal.email, account, selector, marks: nMarks });
228
+ // ── — THE LIMIT, STATED WHERE THE TICKET IS SPENT ─────────────────
229
+ //
230
+ // The issue's ruling is that the coverage limit is "stated at the point of choosing"; this is
231
+ // the OTHER point, and it is the one that matters most. A worldwide search is orderable on a
232
+ // partial register now, and the review step is the last thing a reader sees before money is
233
+ // committed — so "you are buying a worldwide search that will not reach most of the world"
234
+ // belongs here rather than in the report they read afterwards.
235
+ //
236
+ // It also puts the honest reading of the QUOTE in front of them: `run-quote.mjs` sizes the
237
+ // turnaround from the territories ASKED FOR, not from the ones the register will reach, so the
238
+ // hours quoted for a worldwide search on a partial register overstate the work. That is not a
239
+ // bill — the quote is hours, and nothing on this path converts to currency — and it is recorded
240
+ // on the issue rather than silently adjusted here.
241
+ const planCoverage = coverageDisclosure(planRow?.geography ?? null, readTerritories());
242
+ return { status: 200, json: { ok: true, account, selector, name, stageLabel, marks: nMarks,
243
+ coverage: planCoverage ? { reached: planCoverage.reached, missing: planCoverage.missing, note: planCoverage.note } : null,
244
+ // The PRODUCT's floor, and the client reads `effort.turnaround` in preference to it — that one
245
+ // is computed against THIS request (names, lanes, territories) where this is the product with
246
+ // nothing added. Kept as the degraded answer for when the quote cannot be taken. Read off the
247
+ // SAME resolution as the name above, so the two cannot describe different products.
248
+ turnaround: baseTurnaroundFor(policyFor(planResolved?.product)).text,
249
+ warnings: gates.warnings, scope,
250
+ effort: effortFrom({ job, profile: planProfile, resolved: planResolved }),
251
+ confirmationToken: token, note: "Nothing runs until you confirm. Review the summary, then start the search." } };
252
+ }
253
+ // /portal/api/run — verify + trigger (the ONLY spend path)
254
+ if (parts[1] === "api" && parts[2] === "run" && parts.length === 3 && method === "POST") {
255
+ const account = assertPrincipal(principal, { account: body.account ?? null, tenant: body.tenant ?? null, run: true });
256
+ if (!account) return { status: 400, json: { error: "name an account" } };
257
+ const job = jobFor({ principal, account, tenant: body.tenant ?? null, body });
258
+ const notConfigured = await configurationRefusal("trigger", account); // asked again: the install may have changed since the review
259
+ if (notConfigured) return notConfigured;
260
+ const gates = planGates(job); // re-gated: the token is necessary, never sufficient
261
+ if (gates.fail) return gates.fail;
262
+ // re-checked for the same reason the gates are: a token minted while the account still had
263
+ // allowance must not spend it after another tab has used the last one.
264
+ const overQuota = await quotaRefusal(account, job.tenant ?? null);
265
+ if (overQuota) return overQuota;
266
+ sweepJtis();
267
+ const bad = verifyConfirmation({ secret, token: body.confirmationToken, account, email: principal.email,
268
+ jobHash: jobHashOf(job), usedJtis });
269
+ if (bad) return { status: 409, json: { ok: false, error: bad } };
270
+ const selector = selectorOf(body);
271
+ // ── — A DEMO WALKS THE REAL FLOW AND LANDS ON A FINISHED RUN ─────────
272
+ //
273
+ // Ruling, 2026-08-31, revising his own ruling of an hour earlier: "i think its OK for
274
+ // someone to be able to press New Clearance in demo mode and see it work and get the static
275
+ // results, right?" — so the form is real, the plan is real, the confirmation is real, and the
276
+ // only thing that is not real is the dispatch.
277
+ //
278
+ // EVERYTHING ABOVE THIS LINE HAS ALREADY RUN: the gates, the quota, and the confirmation token.
279
+ // That is deliberate rather than incidental — "walks the real flow" means the same validation
280
+ // and the same refusals a real order meets, and a demo that skipped them would be the separate
281
+ // viewer this whole track exists to retire. What it must never do is reach `trigger`, and this
282
+ // returns before it: no engine turn, no register call, no queue entry, no run directory.
283
+ //
284
+ // THE MAPPING IS STATED, NOT CLEVER, in the ruling's own words: which finished run the visitor
285
+ // lands on follows from WHICH SEARCH THEY PICKED. "Picking the fourth product and receiving the
286
+ // first one's report would teach the wrong thing about all four."
287
+ //
288
+ // SO A PRODUCT WITH NO FINISHED EXAMPLE REFUSES, and says which one. That is the honest state of
289
+ // a pool that holds fewer than four — today it holds one — and it is what keeps the mapping's
290
+ // promise while the rest are captured. Landing somewhere approximate would break exactly the
291
+ // rule the ruling spends a paragraph on.
292
+ //
293
+ // RESOLVED THROUGH THE SAME OWNERSHIP SCAN EVERY OTHER SURFACE USES, so a demo can never land on
294
+ // a run this principal could not otherwise open. There is no demo-only read path here.
295
+ if (demo) {
296
+ const { resolved } = resolveFor(job);
297
+ const want = resolved && !resolved.clarify ? resolved.product : null;
298
+ const row = productRow(want);
299
+ const deliveredFor = (scope) => scanAccountRuns({ poolRoot, workspaceRoot, account: scope, queueDirs: queueDirs() })
300
+ .filter((x) => x.state === "delivered" && x.product === want);
301
+ let finished = deliveredFor(account);
302
+ // GENERIC HOLDS NO EXAMPLE OF ITS OWN. A demo's reports are filed under the company that carries them, and
303
+ // Generic is first on the picker and marked Default, so every search ordered from it was refused while the
304
+ // banner said each one opens a report. It looks across what this principal may open, which keeps the rule above.
305
+ if (!finished.length && account === "generic") finished = deliveredFor(principal.accounts === "*" ? null : principal.accounts);
306
+ if (!finished.length) {
307
+ audit({ event: "demo-order", by: principal.email, account, selector, product: want ?? null, landedOn: null });
308
+ return { status: 409, json: { ok: false, errors: [
309
+ `This demo does not carry a finished ${row?.name ?? "search"} to show you yet. `
310
+ + `Nothing was started and nothing was charged — every search here resolves to a report that `
311
+ + `already exists, and this one has not been captured. Pick a search the demo has a report for.`,
312
+ ] } };
313
+ }
314
+ // NEWEST FIRST, by the same comparison the listing sorts on, so two examples of one product
315
+ // resolve predictably rather than by directory order.
316
+ const landed = [...finished].sort((a, b) =>
317
+ String(b.issuedAt ?? b.date ?? "").localeCompare(String(a.issuedAt ?? a.date ?? "")))[0];
318
+ audit({ event: "demo-order", by: principal.email, account, selector, product: want ?? null, landedOn: landed.runId });
319
+ // `queued: false` and a NAMED landing, because the one thing this must not do is read like a
320
+ // run that just started. The report it opens is dated as it is and says on its own face that
321
+ // it is an example; the response says the same thing to the client that navigates there.
322
+ return { status: 200, json: { ok: true, queued: false, id: landed.runId,
323
+ landedOn: landed.runId, landedProduct: want ?? null } };
324
+ }
325
+ let r;
326
+ try {
327
+ // FORWARD THE WHOLE JOB, not a hand-picked subset. This call used to name eight fields, so
328
+ // anything else the composer sent was validated at the plan gate, shown back in the review
329
+ // step, hashed into the confirmation token — and then dropped on the floor here. A field that
330
+ // survives every check and vanishes at the last hop is the worst shape available: the user is
331
+ // told it was accepted and the report is quietly narrower than the one they confirmed.
332
+ // Enumerating fields at a pass-through hop guarantees the list rots; the job is already
333
+ // server-stamped and validated, so it goes as it is.
334
+ // — this used to destructure `msgId` and `conversationId` off the job before forwarding.
335
+ // `jobFor` no longer mints them (it is an allow-list, so no body value can put them here
336
+ // either), and a strip that can never remove anything reads as though the job might carry
337
+ // them. It cannot. The comment above is the rule: forward the whole job.
338
+ // — THE DEPLOYMENT DECLARES A DEMO RUN, READ FROM THE ACCOUNT'S OWN
339
+ // PROFILE. The rule `demoRun` lives under is that a REQUESTER may not decide whether their own
340
+ // report is fiction. It is not that a demo account cannot be run from the portal — and its own
341
+ // words are "operator doors declare it, the client door does not". THIS HOP IS THE OPERATOR
342
+ // DOOR: it calls `start_run` with the ops token, and `START_RUN_JOB_FIELDS.carries` lists
343
+ // `demoRun` for exactly that reason. The requester still never supplies it; the account's own
344
+ // profile does, which is the deployment's statement about the account.
345
+ //
346
+ // WITHOUT THIS, `demoRunAgreement` sees a demo profile and an ordinary job and REFUSES every
347
+ // portal submission on a `demoData` account — so the demo account, which exists to be shown,
348
+ // was the one account the UI could not run. Measured 2026-09-02 on demo-brand-owner.
349
+ //
350
+ // FAIL CLOSED. A profile that cannot be read leaves the flag unset and the run is refused by
351
+ // the agreement wall in its own words. The dangerous direction is the opposite one — marking a
352
+ // REAL account's report as fiction — and an unreadable profile must never be able to reach it.
353
+ let demoRunFlag = false;
354
+ try { demoRunFlag = (await loadProfilesImpl()).get(account)?.demoData === true; }
355
+ catch { demoRunFlag = false; }
356
+ r = await trigger({
357
+ ...job,
358
+ profileKey: account,
359
+ // The daily-allowance stamp. Set ONLY here, on everyone but a person who sees everything —
360
+ // this is the one place in the system where that is decided. See checkRunCaps for why the
361
+ // polarity is positive-only and why every inferred alternative fails unsafely.
362
+ ...(!seesEverything(principal) ? { clientPrincipal: true } : {}),
363
+ ...(demoRunFlag ? { demoRun: true } : {}),
364
+ });
365
+ } catch (e) {
366
+ // an upstream refusal is AUDITED in full — never an opaque 500 with no trace
367
+ const detail = String(e?.message ?? e).slice(0, 300);
368
+ audit({ event: "trigger", by: principal.email, account, selector, id: job.id, ok: false, error: detail });
369
+ // …but the AUDIT is where the detail belongs, not the response. Upstream messages are written
370
+ // for operators and name infrastructure: the unwired-trigger case reads "PORTAL_MCP_URL /
371
+ // PORTAL_OPS_TOKEN unset", which is an internal variable name rendered in a client's browser.
372
+ // Staff get it verbatim because they are the ones who can act on it; a client gets the fact.
373
+ const staff = seesEverything(principal);
374
+ // One cause is worth distinguishing even for staff: an instance with no engine attached is not
375
+ // a failure, it is an instance that was never finished. Saying "could not be queued" invites
376
+ // someone to retry, re-read logs and file a bug against a working system.
377
+ const unwired = /trigger lane is not wired/i.test(detail);
378
+ const error = unwired
379
+ ? (staff
380
+ ? `this instance has no search engine attached (${detail}) — nothing was started`
381
+ : `Searches cannot be started from this instance yet. Nothing was started, and nothing was charged.`)
382
+ : (staff
383
+ ? `the run could not be queued (${detail}) — nothing was started`
384
+ : `The run could not be started just now. Nothing was started, and nothing was charged — ${BRAND.name} can see what happened.`);
385
+ return { status: 502, json: { ok: false, error, unwired } };
386
+ }
387
+ audit({ event: "trigger", by: principal.email, account, selector, id: job.id, ok: Boolean(r?.ok ?? r?.queued) });
388
+ return { status: 200, json: { ok: true, queued: true, id: job.id, upstream: r ?? null } };
389
+ }
390
+
391
+ // ── STOPPING ───────────────────────────────────────────────────────────────────────────────
392
+ // Deliberately NOT behind the confirmation-token dance. That gate exists to stop money being
393
+ // spent by accident; stopping is its opposite, and asking someone to confirm twice while a run
394
+ // they no longer want keeps billing would be the wrong instinct wearing a safety hat.
395
+ //
396
+ // /portal/api/run/<runId>/stop — end a run that has already started.
397
+ if (parts[1] === "api" && parts[2] === "run" && parts[3] && parts[4] === "stop" && method === "POST") {
398
+ const account = assertPrincipal(principal, { account: query.account ?? null, tenant: query.tenant ?? null, run: true });
399
+ if (!account) return { status: 400, json: { error: "name an account (?account=)" } };
400
+ const runId = decodeURIComponent(parts[3]);
401
+ // OWNERSHIP FIRST, and off the run list rather than off the request: the engine's own account
402
+ // gate would refuse a foreign run anyway, but it would do so with an upstream error, and an
403
+ // upstream error is a different observable from a 404. A run you may not touch must be
404
+ // indistinguishable from one that does not exist.
405
+ const mine = scanAccountRuns({ poolRoot, workspaceRoot, account, queueDirs: queueDirs() }).find((r) => r.runId === runId);
406
+ if (!mine) return { status: 404, json: { error: "not_found" } };
407
+ if (mine.state === "delivered" || mine.state === "failed" || mine.state === "cancelled")
408
+ return { status: 409, json: { ok: false, error: "This run has already finished.", state: mine.state } };
409
+ // ── — WHICH STOP THE READER ASKED FOR ────────────────────────────────
410
+ //
411
+ // Ruling, on his second encounter with the same wait: "a stop is a stop — maybe it should
412
+ // be a 'stop immediately or at next boundary to preserve data' kind of question when you press
413
+ // it." The driver half landed the mode; this carries the reader's answer to it.
414
+ //
415
+ // EXPLICIT `=== true`, so anything else is the boundary stop. This is the control that ends a
416
+ // run mid-turn, and a truthy string arriving from a hand-rolled POST must not read as consent
417
+ // to lose the step in flight. The safe path is the one an unrecognised body gets.
418
+ const immediate = body?.immediate === true;
419
+ let r = null;
420
+ try {
421
+ // — the human, forwarded. The portal has verified them (it is what every audit line on
422
+ // this path already records); the engine cannot see them, because every UI stop arrives on one
423
+ // shared ops token. Without this the run dir can say a stop came from the portal and never
424
+ // which person pressed it, on a surface that travels into the archived matter record.
425
+ r = await stopRun({ runId, immediate, onBehalfOf: principal.email });
426
+ } catch (e) {
427
+ const detail = String(e?.message ?? e);
428
+ audit({ event: "stop", by: principal.email, account, runId, ok: false, error: detail });
429
+ // The token is VERB-SCOPED, and a portal minted `--verbs start_run` cannot stop anything. That
430
+ // refusal arrives from upstream looking like an engine fault, so name it as a posture problem
431
+ // for operators while telling the user only that it did not happen.
432
+ const unwired = /not wired|verb|scope/i.test(detail);
433
+ return { status: 502, json: { ok: false, unwired,
434
+ error: seesEverything(principal) ? detail : `The run could not be stopped just now. It is still running, and ${BRAND.name} can see what happened.` } };
435
+ }
436
+ // ── — WHICH STOP IS ACTUALLY IN PROGRESS, AND NOTHING ELSE ──────────
437
+ //
438
+ // The mode is read off the ANSWER, never off the press. An immediate stop that found no turn to
439
+ // end IS a boundary stop, and the driver says so — presenting it as immediate because that is
440
+ // what the button said would be the second silent thing in a row on this control, which is the
441
+ // complaint this issue was opened with.
442
+ //
443
+ // AND THE RAW TOOL RESULT STOPS TRAVELLING. This route returned `upstream: r` wholesale, which
444
+ // was harmless while the tool answered in states and sentences. It is not now: `stop_run`'s
445
+ // immediate mode carries `immediate.pid` — a process id on the box — and this response goes to
446
+ // a browser. Nothing in the client has ever read `upstream`; what a reader needs is which stop
447
+ // is happening and the sentence the driver already composed for them.
448
+ //
449
+ // AND "IMMEDIATE" MEANS THE STEP WAS SEEN TO END. `signalled` says only that a signal was accepted
450
+ // for delivery; `ended` is what the driver saw afterwards. An answer without it, an older driver's
451
+ // `ended: null` included, is the boundary stop: that is the honest reading of an answer that does
452
+ // not say.
453
+ const mode = r?.immediate?.attempted && r?.immediate?.ended === true ? "immediate" : "boundary";
454
+ audit({ event: "stop", by: principal.email, account, runId, ok: Boolean(r?.ok), action: r?.action ?? null,
455
+ // ASKED and TAKEN, both, because they differ exactly when something went wrong — a reader
456
+ // pressed "stop now" and got the boundary stop, which is the row somebody will come looking
457
+ // for. `why` is the driver's own words about its own machinery and stays on this side.
458
+ stopAsked: immediate ? "immediate" : "boundary", stopTaken: mode,
459
+ ...(immediate && mode === "boundary" ? { stopFellBack: r?.immediate?.why ?? r?.immediate?.error ?? "no reason given" } : {}) });
460
+ return { status: 200, json: { ok: true, runId, action: r?.action ?? null,
461
+ stop: { mode, note: typeof r?.note === "string" ? r.note : null } } };
462
+ }
463
+
464
+ // GET /portal/api/run/<runId>/summary — THE CROSS-MARK PARAGRAPH for a grouped run.
465
+ //
466
+ // A knockout over several names has no combined document, so its assessment — the one piece of
467
+ // prose that reads the names against each other — is written to `report.md` and, until this route,
468
+ // reached nobody: `meta.reports` lists the per-mark HTMLs only, and the pool path is not one the
469
+ // edge serves. Ruling 2026-08-26: the grouped page carries it.
470
+ //
471
+ // ITS OWN ROUTE RATHER THAN A FIELD ON THE RUN ROW. The row is what /portal/api/runs returns for
472
+ // every run the caller owns, and it is fetched by every screen that lists runs — where this prose
473
+ // is never rendered. Riding it there would send a paragraph per batch to a browser that had no use
474
+ // for it, on every listing, growing with the pool.
475
+ //
476
+ // Ownership is read off the run's OWN meta, the same way /portal/report/<runId> reads it, so a
477
+ // foreign run is 404 and never 403: a run you may not read must be indistinguishable from one that
478
+ // does not exist.
479
+ if (parts[1] === "api" && parts[2] === "run" && parts[3] && parts[4] === "summary" && method === "GET") {
480
+ assertPrincipal(principal, { door: true }); // door only — ownership is the meta check below
481
+ const runId = parts[3];
482
+ if (!/^[A-Za-z0-9][A-Za-z0-9._-]{0,180}$/.test(runId) || runId.includes(".."))
483
+ return { status: 404, json: { error: "not_found" } };
484
+ const dir = join(poolRoot, runId);
485
+ let meta; try { meta = readJson(join(dir, "meta.json")); } catch { return { status: 404, json: { error: "not_found" } }; }
486
+ const owner = meta.customerKey || "generic";
487
+ if (!mayReadRun(principal, { owner, organisation: meta.organisation ?? null })) return { status: 404, json: { error: "not_found" } };
488
+ // ANSWERED FOR EVERY RUN THAT HAS ONE, grouped or not. A gate to grouped runs only stood here
489
+ // and was wrong in the way this file keeps guarding against: a single-document run HAS this
490
+ // prose — `report.md` is written on every run — so 404 would have said "there is none" about
491
+ // something that exists, and `report.md` would have been a published file with no address on
492
+ // exactly the runs where it is a duplicate rather than the original.
493
+ //
494
+ // The rule it was reaching for is real and belongs on the client: never print the same
495
+ // paragraph twice on one screen. A single-document run's assessment is already rendered inside
496
+ // the document the screen frames, so the screen does not ask (`showsAssessment` in
497
+ // portal-ui/src/contract/reads.ts). Which view shows what is the screen's question; whether the
498
+ // run has a summary is this one's.
499
+ const summary = batchSummaryOf(dir);
500
+ // AN ABSENCE, ANSWERED AS ONE. A run whose summary was composed empty has no paragraph, and a
501
+ // 200 carrying [] would have the client render an empty panel that says nothing and explains
502
+ // nothing. 404 means there is none, which the screen renders as no panel at all.
503
+ if (!summary.length) return { status: 404, json: { error: "not_found" } };
504
+ return { status: 200, json: { runId, summary } };
505
+ }
506
+
507
+ return undefined;
508
+ }