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
@@ -34,7 +34,7 @@
34
34
  // (stageLabel), never a client's recipe label; every trigger is audited (JSONL) with the human email.
35
35
  import "../shared/env-local.mjs"; // — FIRST: applies the CLEAROTRON_* translation before any module-top
36
36
  // capture evaluates. Reads no `.env` here — that load is gated on isCliEntry(argv[1]).
37
- import { readFileSync, existsSync, readdirSync, statSync } from "node:fs";
37
+ import { existsSync, readdirSync } from "node:fs";
38
38
  import { hostname as osHostname, homedir } from "node:os"; // — the address a refusal page names when nothing else identifies this instance
39
39
 
40
40
  // The port this service listens on when nobody says otherwise. Declared here rather than at the
@@ -44,14 +44,8 @@ import { hostname as osHostname, homedir } from "node:os"; // — the address
44
44
  const PORTAL_PORT_DEFAULT = 18802;
45
45
  import { storeInRepo, storeOutsideRepoMessage, makeCommittableAudit, resolveStoreRepoRoot, makeStoreCommit } from "../shared/store-in-repo.mjs"; //,
46
46
  import { customerStoreDir, customerStoreLine } from "../shared/customer-store.mjs"; // — one store for the surface and the runs
47
- import { clientFailureNote } from "../shared/client-failure-note.mjs"; // — one sentence, three surfaces
48
- import { bareInvocation, browserCommand, invocationPrefix, installRoute, npxVersionOf } from "../shared/invocation.mjs"; // — and why this one surface is by NAME
49
- import { channelOf, channelPackage, ownVersion } from "../shared/permanent-install.mjs"; // — which release channel this install came from
50
- import { stdioConnectOffer, stdioConnectFor, STDIO_SHAPES } from "../shared/stdio-connect.mjs"; // — ONE author for the connect route
51
- import { isWsl, wslTarget } from "../shared/wsl.mjs"; // — on WSL, the connect lines say where they run and cross the boundary themselves
52
- import { doorKind } from "../shared/mcp-challenge.mjs"; // — one reading of what a connector asks for, shared with doctor
53
- import { claudeNamer } from "./engine/probe.mjs"; // names the copy setup installed, which is not on PATH
54
- import { connectOffers, offersForWire } from "../shared/connect-clients.mjs"; // — ONE table, resolved server-side
47
+ import { bareInvocation, browserCommand, invocationPrefix, npxVersionOf, reachableCommand } from "../shared/invocation.mjs"; // — and why this one surface is by NAME
48
+ import { channelOf, ownVersion } from "../shared/permanent-install.mjs"; // — which release channel this install came from
55
49
 
56
50
  /**
57
51
  * The ops credential for one trigger call: the boot token's cap, re-taken against the roster now.
@@ -90,8 +84,8 @@ export function opsTokenFor({ bootToken, roster, mint }) {
90
84
  // `EnvironmentFile=%h/.env`, and `childEnv` passes the same value to the portal child — so this process
91
85
  // has held the signing secret on both start paths for as long as both have existed. The comment has been
92
86
  // corrected in place rather than left to be trusted.
93
- import { mintToken, loadGrants, resolvePerson, addressesInGrants } from "../shared/scope.mjs";
94
- import { withPerson, withoutPerson, personPoints, withCompany } from "../shared/grants-edit.mjs";
87
+ import { mintToken, addressesInGrants } from "../shared/scope.mjs";
88
+ import { withCompany } from "../shared/grants-edit.mjs";
95
89
  import { resolvePort } from "../shared/listen.mjs"; // — the port SOURCE, decided once
96
90
  import { fileURLToPath } from "node:url";
97
91
 
@@ -131,25 +125,17 @@ export const allowanceExhaustedLine = (cap, who) =>
131
125
  const INSTALL_ROOT = join(dirname(fileURLToPath(import.meta.url)), "..");
132
126
 
133
127
  const READ_OFF_NOTE = "Reading a brief is not available on this instance — set the search up below.";
134
- import { basename, dirname, join, resolve as pathResolve } from "node:path"; import { studioDirFor } from "../shared/pre-rename-spellings.mjs";
135
- import { driverDir } from "../shared/driver-dir.mjs"; //
136
- import { createHmac, timingSafeEqual, randomBytes } from "node:crypto";
137
- import { makePrincipal, assertPrincipal, genericOrgOf, mayReadRun, reachCovers, principalView, seesEverything, mayRun,
138
- PortalDeny } from "./portal-access.mjs";
128
+ import { dirname, join, resolve as pathResolve } from "node:path";
129
+ import { makePrincipal, genericOrgOf, seesEverything, PortalDeny } from "./portal-access.mjs";
139
130
  // — the THIRD identity source (after the CF Access edge and, until, the deleted bypass). It
140
131
  // decides nothing about access: it turns a passphrase into an email string, which then goes through
141
132
  // makePrincipal and assertPrincipal exactly as a Cloudflare-verified address does.
142
133
  import { readLocalCredential, establishCredential, checkPassphrase, mintSession, verifySession,
143
134
  makeAttemptLimiter, credentialPathFor,
144
135
  localCredentialHandoff, firstRunCredentialLines, passphraseResetCommand, signInResetCommand } from "./portal-local-auth.mjs";
145
- import { appendFlag, feedbackDir, MAX_WHY, VERDICTS } from "./feedback-store.mjs";
146
- import { loadRecipes, PRODUCT_POLICIES, policyFor, countJobMarks, kebabCollisions,
147
- gateResolvedPolicy, productAvailability, UNAVAILABLE_NOTE, coverageDisclosure, reportIdentityFor } from "./search-policy.mjs";
136
+ import { loadRecipes, PRODUCT_POLICIES, productAvailability, UNAVAILABLE_NOTE } from "./search-policy.mjs";
148
137
  import { PLAN_MAX_NAME_LENGTH } from "./register-plan.mjs"; // — the budget the screen states
149
- import { productRows, productRow, baseTurnaroundFor } from "./product-rows.mjs";
150
- import { resolveForDoor, gateResolvedRequest } from "./door-gates.mjs";
151
- import { resolveEffectiveScope } from "./effective-scope.mjs";
152
- import { quoteForJob } from "./run-quote.mjs";
138
+ import { productRows } from "./product-rows.mjs";
153
139
  import { readFlagSnapshot, builtFor, registerCanCountFor, registerTerritoriesFor, registerLabelFor, caseLawReadyFor } from "./flag-snapshot.mjs";
154
140
  import { isDemo, demoPostureLine } from "./demo-posture.mjs";
155
141
  import { orderTimeRefusal } from "./run-requirements.mjs"; // the runner's own test for "can this install run a search"
@@ -157,15 +143,10 @@ import { runTables } from "./order-tables.mjs"; // …asked of the
157
143
  import { howItRuns } from "./how-it-runs.mjs"; // …and the remedy, for how this portal runs
158
144
  import { triggerCapGap, triggerCapWarning } from "./trigger-cap.mjs"; // F51 — one answer, three surfaces
159
145
  import { makeUpstream } from "./portal-upstream.mjs";
160
- import { flagView, accessView, observedView, authView } from "./portal-config-view.mjs";
146
+ import { flagView } from "./portal-config-view.mjs";
161
147
  import { livePosture } from "./flag-snapshot.mjs"; // — for the capture-vs-box comparison only, never for a value
162
- import { familiesView, groupRuns, ungroupRuns } from "./portal-families.mjs";
163
- import { validateJob } from "./enqueue-schema.mjs";
164
- import { orderedQueueFiles, reorderQueue } from "./queue-order.mjs"; // the SAME sort drainQueue admits by
165
- import { drainingState } from "./worker-heartbeat.mjs"; // / — is anything draining this install
166
- import { batchMarkName } from "./mark-name.mjs";
167
148
  import { DEFAULT_CLIENT_DAILY_RUNS, accountUsage } from "./usage-ledger.mjs";
168
- import { productIdentity, SOURCE_REPO } from "../shared/product-identity.mjs"; // AGPL §13 — one answer, three surfaces
149
+ import { SOURCE_REPO } from "../shared/product-identity.mjs"; // AGPL §13 — one answer, three surfaces
169
150
  import { engineCommit } from "./engine-build.mjs"; // — the SAME stamp pool meta records
170
151
  // — siblings, on their own line: the guard pins the line above and its subject is the JOIN
171
152
  // (this endpoint and pool meta stamp the same function), not the import list. Kept separate so that
@@ -175,29 +156,40 @@ import { classifySkillsStore } from "./skills-store-provenance.mjs";
175
156
  import { makeStaticHandler, reportCsp, docCsp } from "./portal-static.mjs";
176
157
  import { crossSiteReason, bodyNotJson } from "./portal-request-origin.mjs";
177
158
  import { bundleVerdict, healthUi } from "../shared/bundle-freshness.mjs"; // one definition of a usable bundle, shared with `doctor`
178
- import { readReport, reportsOf, resolveReportFile, batchSummaryOf } from "./portal-report.mjs";
179
- import { readArchivedSet, updateArchived } from "./publish/archive-tags.mjs";
180
- import { readAcks, setAck, withAcks, ACKNOWLEDGEABLE } from "./portal-acks.mjs";
159
+ import { adminRoutes } from "./portal-routes/admin.mjs"; // the route groups the dispatcher below asks in turn
160
+ import { composeRoutes } from "./portal-routes/compose.mjs";
161
+ import { configRoutes } from "./portal-routes/config.mjs";
162
+ import { connectRoutes } from "./portal-routes/connect.mjs";
163
+ import { feedbackRoutes } from "./portal-routes/feedback.mjs";
164
+ import { meRoutes } from "./portal-routes/me.mjs";
165
+ import { queueRoutes } from "./portal-routes/queue.mjs";
166
+ import { reportRoutes } from "./portal-routes/report.mjs";
167
+ import { runRoutes } from "./portal-routes/run.mjs";
168
+ import { runsRoutes } from "./portal-routes/runs.mjs";
169
+ import { usageRoutes } from "./portal-routes/usage.mjs";
181
170
  import { MAX_BRIEF, makeReadBudget } from "./compose-read.mjs";
182
- import { BRAND, ORGANISATION_NAME, ADMINISTRATOR_CONTACT, PALETTE, FAVICON_LINK, bracketMark, DOOR_ROOT, DOOR_ROOT_DARK, DOOR_THEME_INIT } from "../shared/brand.mjs";
171
+ import { BRAND, ORGANISATION_NAME, PALETTE, FAVICON_LINK, bracketMark, DOOR_ROOT, DOOR_ROOT_DARK, DOOR_THEME_INIT } from "../shared/brand.mjs";
183
172
  import { TEXT_FONT_STYLE } from "../shared/brand-fonts.mjs"; // the text face, carried in the page rather than fetched
184
173
  import { envFrom, pinEnv } from "../shared/env-aliases.mjs"; // — a refusal names the name in force
185
174
  import { accessAudience, audienceLabel } from "../shared/access-audience.mjs"; // — F54; jose-free on purpose
186
- import { resolveNumericSetting } from "./numeric-setting.mjs"; // — the same table the engine enforces, without the throw a rendering surface must not take
187
175
  import { isEntrypoint } from "../shared/is-entrypoint.mjs"; // — one entry-point test, all spellings
188
176
  import { deploymentBox } from "../shared/deployment-box.mjs"; // — the box names itself; one rule
189
- import { stageNow } from "./progress.mjs"; // the stage a live run is in now, for the card and the row
190
- // A run in one of these has finished; its step is the one its terminal write set, not the stage it last entered.
191
- const TERMINAL_STATES = new Set(["delivered", "failed", "cancelled"]);
177
+ import { jobHashOf, mintConfirmation, verifyConfirmation } from "./portal-confirmation.mjs";
178
+ import { concurrentRunsCap, resolveRunAccount, scanAccountRuns, scanAllRuns } from "./portal-runs.mjs";
179
+ export { jobHashOf, mintConfirmation, verifyConfirmation, concurrentRunsCap, resolveRunAccount, scanAccountRuns, scanAllRuns };
192
180
  // This install's release channel, `beta` or `latest`, read once off its own version. /me carries it.
193
181
  const INSTALL_CHANNEL = channelOf(ownVersion());
194
182
 
195
183
  /**
196
- * The operator's line when the brief reader cannot be built: why, and the check to run, ON THIS CHANNEL.
197
- * `npx clearotron doctor` fetches the stable, which on a beta reads the beta's install with the other code.
184
+ * The operator's line when the brief reader cannot be built: why, and the check to run, as THIS install is
185
+ * reached. `npx clearotron doctor` fetches the stable, which on a beta reads the beta's install with the other
186
+ * code; and a channel's package fetched through npx was named to a global install too, which has its own
187
+ * `clearotron` on PATH (measured in a stranger walk of a beta, 2026-11-10). The supervisor hands down how it
188
+ * was invoked, so the command is the one doctor and start print: the installed name, or from npx's cache the
189
+ * published version.
198
190
  */
199
- export function briefReadingOffLine(reason, pkg = channelPackage()) {
200
- return `brief reading OFF — ${reason}. Describe-it stays disabled; \`npx ${pkg} doctor\` reports the engine's auth state.`;
191
+ export function briefReadingOffLine(reason, command = reachableCommand("doctor")) {
192
+ return `brief reading OFF — ${reason}. Describe-it stays disabled; \`${command}\` reports the engine's auth state.`;
201
193
  }
202
194
 
203
195
  // The offering the portal menus build from — product-rows.mjs's row, unchanged.
@@ -217,615 +209,6 @@ const registryProducts = productRows;
217
209
  // (`truthyFlag` lived here to test a kill switch's value. The switches were retired 2026-07-27 and no
218
210
  // gate on this path reads an environment variable any more.)
219
211
 
220
- // ── the confirmation token (the what_if_plan → what_if_run idiom): HMAC over the EXACT server-
221
- // stamped job the user confirmed (classes/goods/marks/markName/selector — review 2026-07-18: a
222
- // names-only binding let a mutated resubmit spend) + the confirming identity, short TTL, ONE-SHOT
223
- // (jti consumed on fire — a replay within the TTL never spends twice). ─────────────────────────────
224
- const canonical = (o) => JSON.stringify(o, Object.keys(o).sort());
225
- // The trigger-identity hash: every field of the server-stamped job that shapes scope/cost/identity.
226
- // Sorted-array JSON (never a delimiter join — a '|' in a mark name aliased two mark sets to one key).
227
- export function jobHashOf(job) {
228
- const marks = (job.marks ?? (job.markName ? [{ name: job.markName }] : []))
229
- .map((m) => ({ name: String(m?.name ?? m).trim().toLowerCase(), classes: Array.isArray(m?.classes) ? [...m.classes].sort() : undefined, ref: m?.ref }))
230
- .sort((a, b) => a.name.localeCompare(b.name));
231
- return createHmac("sha256", "job-id").update(canonical({
232
- marks: JSON.stringify(marks), markName: String(job.markName ?? "").toLowerCase(),
233
- classes: JSON.stringify([...(job.classes ?? [])].sort()), goods: String(job.goods ?? ""),
234
- product: job.product ?? null, recipeKey: job.recipeKey ?? null,
235
- })).digest("base64url");
236
- }
237
- export function mintConfirmation({ secret, account, email, jobHash, now = Date.now(), ttlMs = 10 * 60 * 1000 }) {
238
- const jti = createHmac("sha256", secret).update(`${account}|${jobHash}|${now}|${randomBytes(16).toString("hex")}`).digest("base64url").slice(0, 24);
239
- const payload = { account, email, jobHash, jti, exp: now + ttlMs };
240
- const body = Buffer.from(canonical(payload)).toString("base64url");
241
- const sig = createHmac("sha256", secret).update(body).digest("base64url");
242
- return `${body}.${sig}`;
243
- }
244
- export function verifyConfirmation({ secret, token, account, email, jobHash, now = Date.now(), usedJtis = null }) {
245
- const [body, sig] = String(token ?? "").split(".");
246
- if (!body || !sig) return "confirmation token malformed — re-run the plan step";
247
- const want = createHmac("sha256", secret).update(body).digest("base64url");
248
- const a = Buffer.from(sig), b = Buffer.from(want);
249
- if (a.length !== b.length || !timingSafeEqual(a, b)) return "confirmation token invalid — re-run the plan step";
250
- let p; try { p = JSON.parse(Buffer.from(body, "base64url").toString("utf8")); } catch { return "confirmation token unreadable — re-run the plan step"; }
251
- if (!(typeof p.exp === "number" && p.exp >= now)) return "confirmation expired — review the plan again and re-confirm";
252
- if (p.account !== account || p.jobHash !== jobHash)
253
- return "the request changed after confirmation — review the plan again and re-confirm";
254
- if (p.email !== email) return "this confirmation belongs to a different sign-in — review the plan and confirm yourself";
255
- if (usedJtis) {
256
- if (usedJtis.has(p.jti)) return "this confirmation was already used — plan again for another run";
257
- usedJtis.set(p.jti, p.exp); // consume (one-shot); the caller sweeps expired entries
258
- }
259
- return null;
260
- }
261
-
262
- // The band ladder a run was rated against, and the tone of the band it landed on.
263
- //
264
- // Tone, not label, is what the UI colours and sorts by, and the join has to happen HERE because the
265
- // server is the only side that knows the framework. Ladders are framework-scoped: house-default has four
266
- // stops and says "Moderate" where house-triage says "Medium". A client that mapped labels to colours
267
- // itself would mis-colour every customer whose framework is not the one it was written against.
268
- //
269
- // A run with no framework (every run archived before doc-50) yields an empty ladder and a null tone. That
270
- // is honest — it was not rated against a ladder — and the UI renders the label alone, uncoloured.
271
- function ladderOf(meta) {
272
- const bands = Array.isArray(meta.framework?.bands)
273
- ? meta.framework.bands.filter((b) => b && typeof b.label === "string" && typeof b.tone === "string")
274
- .map((b) => ({ label: b.label, tone: b.tone }))
275
- : [];
276
- const toneFor = (label) => bands.find((b) => b.label === label)?.tone ?? null;
277
- return { bands, toneFor };
278
- }
279
-
280
- // ── run listing: delivered (pool metas) + live (workspace status + frozen profile sidecar) ─────────
281
- //
282
- // `account` null means EVERY account — the staff "All brand owners" view. Every row carries its own
283
- // `account` either way, so the caller never has to infer ownership from the request it made.
284
- /** The registry's display face for a stored product key, or null for one it does not know. It answers for
285
- * a RETIRED key too — a delivered run keeps the name it was sold under, which is the whole reason those
286
- * rows still exist (search-policy.mjs RETIRED_POLICIES). */
287
- const stageLabelOf = (product) => (typeof product === "string" ? policyFor(product)?.stageLabel ?? null : null);
288
-
289
- /** THE PRODUCT'S CLIENT-FACING NAME for a run row — the same resolver, and the same field, the
290
- * delivered report's masthead prints. The browser used to hold its own switch from product key to label
291
- * (`home.ts depthLabel`), which is a mapping table in a second place: it drifted once already, listing
292
- * only the five retired slugs so every run this build creates rendered a blank chip.
293
- *
294
- * `.identity`, never `.banner` or `stageLabel` — on a RETIRED row those carry "Depth 4", and a depth
295
- * number must never reach a client's screen. Null for a level the registry has forgotten: the chip goes
296
- * blank rather than naming a search the run may not have been. */
297
- const productNameOf = (product) => (typeof product === "string" ? reportIdentityFor(product).identity ?? null : null);
298
-
299
- // `account` accepts one key, or an ARRAY of keys for an identity that holds several — the multi-brand
300
- // client asking for all of its own work at once. An array is exactly the union of what that caller can
301
- // already fetch one key at a time, so it widens no boundary; it just spares the browser one request per
302
- // brand owner against a 120/min limit. It is NOT a wildcard: an empty array matches nothing, which is
303
- // the safe direction, and `null` (every account) stays reachable only from scanAllRuns.
304
- export function scanAccountRuns({ poolRoot, workspaceRoot, account = null, generic = null, includeRetired = false,
305
- // — THE QUEUES THE RUNNER ACTUALLY DRAINS, which is not the same set as the
306
- // directories under `workspaceRoot`. Defaults to [] so a caller that passes none keeps exactly the
307
- // behaviour it had; the service passes `config.queueDirs`, the same getter the allowance counter reads.
308
- queueDirs = [] }) {
309
- const out = [];
310
- const only = Array.isArray(account) ? new Set(account) : null;
311
- // GENERIC IS MATCHED BY ORGANISATION when the caller says which. `generic` is `{ all: true }` or
312
- // `{ orgs, unfiled }`: a Generic run matches when it was filed under one of `orgs`, or was filed under
313
- // none and `unfiled` asks for those too. Without it, `account` alone decides, exactly as before.
314
- const mine = (owner, organisation = null) => {
315
- if (owner === "generic" && generic) return generic.all === true
316
- || (organisation != null ? (generic.orgs ?? []).includes(organisation) : generic.unfiled === true);
317
- return only ? only.has(owner) : account === null || owner === account;
318
- };
319
- // RETIRED RUNS ARE NOT LISTED HERE — unless the caller is the staff retired view, and asks.
320
- //
321
- // `pool-admin archive` has always written this sidecar, and until now the ONLY reader was the old
322
- // static index — the surface the edge stopped serving at the portal cutover. So the command reported
323
- // success, the staff index it re-rendered was unreachable, and the run stayed in full view on the one
324
- // page anybody actually opens. A curation verb that silently does nothing to the live surface is worse
325
- // than not having one: it is a control that lies about having worked.
326
- //
327
- // Retired for EVERY reader, staff included: that has not changed, and `includeRetired` does not widen
328
- // it. What changed is where the CONTROL lives. This comment used to argue that a portal fold
329
- // would be "a second place to look, out of step with the CLI" — true while retiring was only a CLI
330
- // act, and wrong the moment staff could retire from the screen they are already on. A control whose
331
- // inverse lives in a terminal on another host is a one-way door. So the portal now carries both, and
332
- // `includeRetired` is what the staff-only "Show retired" route reads. The default is unchanged, every
333
- // client-facing caller takes it, and nothing a client can request reaches this flag.
334
- //
335
- // Read once per scan rather than per run: a scan is a directory walk over the whole pool and this is
336
- // one small file, so re-reading it per entry would be the only O(n) sidecar read in the function.
337
- //
338
- // THE REPORT ROUTE IS DELIBERATELY NOT GATED ON THIS. Retiring a run takes it off the list; it does
339
- // not revoke a link. Report URLs are in email we have already sent, and the Caddyfile's legacy-report
340
- // rewrite exists precisely so those keep resolving — 404ing them here would rot them from a curation
341
- // command, which is not what "archive" means to the person typing it. Ownership is still enforced at
342
- // that route, unchanged; retirement is about what the pool ADVERTISES, not about who may read what.
343
- const retired = readArchivedSet(poolRoot);
344
- try {
345
- for (const name of readdirSync(poolRoot)) {
346
- const metaPath = join(poolRoot, name, "meta.json");
347
- if (!existsSync(metaPath)) continue;
348
- try {
349
- const meta = JSON.parse(readFileSync(metaPath, "utf8"));
350
- const owner = meta.customerKey || "generic";
351
- if (!mine(owner, meta.organisation ?? null)) continue;
352
- // Tagged by runId — the same key pool-admin writes, which is the pool DIRECTORY name. Checking
353
- // both guards the one case where they differ: a meta whose runId was rewritten by a republish.
354
- const isRetired = retired.has(meta.runId ?? name) || retired.has(name);
355
- if (isRetired && !includeRetired) continue;
356
- // The retired view is EXCLUSIVELY retired runs, not the whole pool with a flag: it is the fold
357
- // you open to find something you filed, and mixing the live list into it would make "Show
358
- // retired" a second copy of the page you are already looking at.
359
- if (!isRetired && includeRetired) continue;
360
- // ONE report, one audience rule: a run you have rights to is always listed and served (spec
361
- // 2026-07-30 §5). The client gate's "held" state is retired — the machine-QC record lives in
362
- // meta.clientGate for the workbook/staff-index surfaces and decides nothing here.
363
- // WHICH DOCUMENTS THIS RUN HAS, off its own meta. `existsSync("report.html")` was the
364
- // test, and a knockout batch no longer publishes that file — every batch would have listed as
365
- // having no report at all while carrying three. reportsOf() reads the published list and answers
366
- // `report.html` for a run that predates it, which is every archived run and every clearance.
367
- const docs = reportsOf(meta).filter((r) => existsSync(join(poolRoot, name, r.file)));
368
- const hasReport = docs.length > 0;
369
- const { bands, toneFor } = ladderOf(meta);
370
- const band = meta.overall ?? null; // the rating; a meta's retired `verdict` held the reviewer's sign-off on the full-search lane
371
- out.push({ runId: meta.runId ?? name, account: owner, ...(owner === "generic" ? { organisation: meta.organisation ?? null } : {}),
372
- title: meta.title ?? meta.matter ?? name, kind: meta.kind ?? "clearance",
373
- // THE MARK, separate from the report's headline.
374
- //
375
- // `title` is model-authored front matter: a real run carries "AquaPlus — US Preliminary
376
- // Trademark Clearance" as its title while the typed mark is "AquaPlus". The UI needs the mark
377
- // to name a row and to group reads; it needs the headline for nothing. Written into meta at
378
- // publish, so runs delivered before that carry null and consumers fall back to title.
379
- markName: typeof meta.markName === "string" ? meta.markName : null,
380
- // WHICH PROJECT (engagement) THIS RAN UNDER.
381
- //
382
- // Stamped into meta at publish from the run's frozen profile sidecar. Absent on every run
383
- // delivered before that stamp, and deliberately not back-filled: the sidecar is the only
384
- // honest source and it does not travel with a pool dir. Null therefore means "we do not know",
385
- // never "no project" — so nothing downstream may render it as "no project".
386
- projectKey: typeof meta.projectKey === "string" ? meta.projectKey : null,
387
- projectName: typeof meta.projectName === "string" ? meta.projectName : null,
388
- // Which read this is, for the Stages cell.
389
- //
390
- // THE REGISTRY FIRST, the frozen stamp only as a last resort — the same rule reportIdentityFor
391
- // follows, and it has to be the same rule or the product has two names on one screen. This read
392
- // the stamp FIRST, so after the Depth 1-5 renumbering a run's report banner said "Depth 2" while
393
- // its own row in this list still said "Stage 0.5". One system: the label is a pure function of
394
- // the level, so deriving it from the level names every run the way the product is named today.
395
- //
396
- // `meta.stageLabel` survives as the fallback for a run whose LEVEL the registry no longer knows
397
- // (a retired row) — there is no current answer there and the stamp beats a blank. A run older
398
- // than the level registry carries neither and stays null: the cell goes blank rather than
399
- // inventing a depth that never ran.
400
- // `meta.searchLevel` is the STORED key on a delivered run's meta.json and keeps its name on
401
- // disk — an archived run's record is not this build's to rewrite. What the wire carries is
402
- // `product`, because that is the word every client-facing surface uses now.
403
- product: meta.searchLevel ?? null,
404
- stageLabel: stageLabelOf(meta.searchLevel) ?? meta.stageLabel ?? null,
405
- productName: productNameOf(meta.searchLevel),
406
- state: "delivered", date: meta.date ?? null,
407
- // WHEN IT FINISHED, to the second. `date` is DAY precision and always was — it is
408
- // parsed out of the run directory name. Two reads of one mark delivered on the same day
409
- // therefore TIE, Array.prototype.sort is stable, and which one the parent row spoke for was
410
- // decided by readdirSync order rather than by recency.
411
- //
412
- // `issuedAt` has been written full-ISO into meta.json at every publish for as long as there
413
- // has been a publisher; it simply never crossed the wire. Measured on the test instance
414
- // 2026-08-04, the two House-default reads differ by 2m08s in this field and in nothing else
415
- // the page renders — which is the whole.
416
- issuedAt: typeof meta.issuedAt === "string" ? meta.issuedAt : null,
417
- // `overall` stays for the existing consumers; `band` is the same value under the name the UI
418
- // uses, alongside the ladder it belongs to.
419
- overall: band, band, tone: toneFor(band), bands,
420
- // Knockout batches summarise per name — the list renders "N names, worst: <band>" from this.
421
- // Each mark's band is resolved against the SAME ladder, so a batch cannot mix vocabularies.
422
- marks: Array.isArray(meta.marks)
423
- ? meta.marks.filter((m) => m && typeof m.name === "string")
424
- .map((m) => ({ name: m.name, band: m.band ?? null, tone: toneFor(m.band ?? null) }))
425
- : [],
426
- // Present ⇒ the run has a report-data.json and can render natively. Absent ⇒ legacy: the Result
427
- // screen iframes the baked file. Legacy is identified by ABSENCE, so this must stay undefined
428
- // rather than defaulting to 0 or 1.
429
- // BOTH writers (publish/knockout.mjs and the clearance producer) stamp the STRING
430
- // 'report-data/1' — gating on `typeof === "number"` alone meant the native-render flag NEVER
431
- // armed, even for runs with a report-data.json on disk (2026-07-29, filed during PR-9). The
432
- // string form maps to its numeric version; a bare number is honoured; anything else is legacy.
433
- reportSchema: typeof meta.reportSchema === "number" ? meta.reportSchema
434
- : typeof meta.reportSchema === "string" && /^report-data\/(\d+)$/.test(meta.reportSchema)
435
- ? Number(meta.reportSchema.slice("report-data/".length)) : null,
436
- // `report` is the run-level link and it is NULL for a batch — there is no run-level document
437
- // to open. `reports` is the list, one entry per name, and it is what a batch's row renders.
438
- // A single-document run carries both, pointing at the same place, so nothing that reads
439
- // `report` today changes shape.
440
- //
441
- // BOTH ARE DOCUMENT URLS, and `path` STAYS one. The obvious repair for "the per-mark
442
- // links open outside the portal" is to point `path` at the portal route instead — and it is
443
- // wrong twice. `report` is consumed as an IFRAME SOURCE, not as a link, so making its sibling
444
- // mean something else leaves two fields of the same name-shape with different kinds, and the
445
- // client that framed one would frame the other and load the shell inside itself. The client
446
- // needs to build a route; what it lacks for that is the NAME of the document, not a second
447
- // spelling of its address. That is `slug`, below.
448
- //
449
- // `slug` is null on a single-document run: there is one document and no name to pick between,
450
- // which is the same thing `report` being non-null already says.
451
- report: docs.length === 1 ? `/portal/report/${encodeURIComponent(name)}/` : null,
452
- reports: docs.map((r) => ({
453
- mark: r.mark,
454
- slug: r.slug ?? null,
455
- path: r.slug
456
- ? `/portal/report/${encodeURIComponent(name)}/${encodeURIComponent(r.slug)}/`
457
- : `/portal/report/${encodeURIComponent(name)}/`,
458
- })),
459
- // — stamped only where it is true. A row that says nothing about retirement is a live
460
- // row, on every surface that has ever consumed this listing; a `retired: false` on all of
461
- // them would be a new field for every reader to ignore.
462
- ...(isRetired ? { retired: true } : {}) });
463
- } catch { /* unreadable meta — skip */ }
464
- }
465
- } catch { /* no pool yet */ }
466
- // live runs: status.json + the frozen profile sidecar (freezeProfile writes `profileKey`)
467
- const readRun = (dir) => {
468
- try {
469
- const s = JSON.parse(readFileSync(join(dir, "status.json"), "utf8"));
470
- const p = JSON.parse(readFileSync(driverDir(dir, "profile.json"), "utf8"));
471
- const owner = p.profileKey ?? p.key ?? "generic";
472
- if (!mine(owner, p.organisation ?? null)) return;
473
- if (s.state === "delivered") return; // the pool row is the delivered face
474
- // ── — RETIREMENT REACHES A RUN THAT NEVER PUBLISHED ──────────────────
475
- //
476
- // The pool branch above has honoured the sidecar since; this branch never did, so a tag
477
- // written for a run that ended without publishing sat in the file doing nothing and the run
478
- // stayed on the list. That is worse than the refusal it replaces: a control that reports success
479
- // and changes nothing is the failure `scanAccountRuns`'s own retirement comment is about.
480
- //
481
- // The failed and abandoned runs are exactly the ones a reader most wants off the list, so this is
482
- // the population the control was wanted for, not an edge of it. Same key as the pool branch —
483
- // the runId — and the same two-way filter, so "Show retired" stays exclusively retired.
484
- const liveRetired = retired.has(s.runId) || retired.has(basename(dir));
485
- if (liveRetired && !includeRetired) return;
486
- if (!liveRetired && includeRetired) return;
487
- // A live run already HAS the typed mark — status.json is where it has always lived. The frozen
488
- // search-policy sidecar carries the stage. Both are read here so a run does not change identity
489
- // when it crosses from live to delivered: same mark, same stage, same thread.
490
- let sp = null;
491
- try { sp = JSON.parse(readFileSync(driverDir(dir, "search-policy.json"), "utf8")); } catch { /* legacy/early run */ }
492
- // A PAUSE IS NOT A RUN. The engine writes `postponed` (a rate-limit park, auto-resuming at
493
- // `resetsAt`) and `recovering` (an auto-retry backing off), and the portal contract knows neither
494
- // — its coercion treats anything unrecognised as `running`. So a run parked for five hours showed
495
- // "Running", with the step it had reached before it stopped, and the customer had no way to tell a
496
- // pause from work. The UI has had a `paused` state and a `.dot.paused` rule the whole time, and
497
- // nothing on the wire could ever reach them.
498
- //
499
- // Mapped here rather than in the browser: the run listing is the one place that already turns
500
- // engine vocabulary into the words a client reads, and a second translation in the UI is a second
501
- // thing to keep in step. `pausedKind` keeps the two apart, because they say different things to
502
- // the person waiting — one has a time, the other is the system retrying itself.
503
- // `parked-for-human` (A5): the engine's grace-exit park — the runner was stopped (deploy restart)
504
- // with the run in flight. Mapped HERE, like the other two, so the wire NEVER carries the raw
505
- // value: the portal contract would coerce an unknown state to "running", which is exactly the
506
- // zombie face this state exists to end. pausedKind "operator" tells the UI which words to use.
507
- const paused = s.state === "postponed" || s.state === "recovering" || s.state === "parked-for-human";
508
- out.push({ ...(liveRetired ? { retired: true } : {}),
509
- runId: s.runId, account: owner, ...(owner === "generic" ? { organisation: p.organisation ?? null } : {}), title: s.markName ?? s.slug,
510
- // THE RUN’S OWN PIPELINE, off the frozen policy sidecar this branch already reads — the same
511
- // source the `product` field two lines down takes, so a row cannot contradict its own product.
512
- // `s.lane` is the runner’s queue directory and it is not that: a knockout claimed from any other
513
- // lane arrived here as a clearance, and Home then quoted it the clearance turnaround — hours,
514
- // against a search that finishes in minutes. The queued rows below were fixed for exactly this
515
- // and this row was left on the weaker field. The lane stays as the fallback for a run whose
516
- // sidecar predates the stamp, and an unplaceable product stays a clearance, which is what every
517
- // listing has always shown for something it could not identify.
518
- kind: (policyFor(sp?.level)?.pipeline ?? (s.lane === "knockout" ? "knockout" : null)) === "knockout" ? "knockout-batch" : "clearance",
519
- markName: typeof s.markName === "string" ? s.markName : null,
520
- // The project, straight off the frozen sidecar this branch already reads as `p`. A LIVE run needs
521
- // no publish stamp and no back-fill — the sidecar is right there, and freezeProfile has written
522
- // both fields since spec 62.
523
- projectKey: typeof p.projectKey === "string" ? p.projectKey : null,
524
- projectName: typeof p.projectName === "string" ? p.projectName : null,
525
- // Registry first here too — a live run's frozen policy sidecar names WHICH level is running; what
526
- // that level is CALLED comes from the registry, so an in-flight run and a delivered one agree.
527
- product: sp?.level ?? null, stageLabel: stageLabelOf(sp?.level) ?? sp?.stageLabel ?? null,
528
- productName: productNameOf(sp?.level),
529
- state: paused ? "paused" : (s.state ?? "running"),
530
- pausedKind: paused ? (s.state === "recovering" ? "recovering" : s.state === "parked-for-human" ? "operator" : "rate-limit") : null,
531
- // The ONE honest ETA this system possesses. The engine computes it from the provider's own
532
- // reset header and has always written it; it reached the ops surface and stopped one hop short
533
- // of the browser. Absent for a recovery park, which backs off on a schedule rather than to a
534
- // stated time — so the UI must not promise a clock it does not have.
535
- resetsAt: typeof s.resetsAt === "string" ? s.resetsAt : null,
536
- // Elapsed, so a card can say how long this has been going without inventing a finish time.
537
- startedAt: typeof s.startedAt === "string" ? s.startedAt : null,
538
- // THE STAGE IT IS IN NOW, a step back into an earlier stage included (owner, 2026-09-19): see
539
- // stageNow. Only while it is live; a run that has finished keeps the step its terminal write set.
540
- ...(TERMINAL_STATES.has(s.state)
541
- ? { step: s.stepLabel ?? null, stepN: s.stepN ?? null, stepTotal: s.stepTotal ?? null }
542
- : stageNow(s)),
543
- // — a requested stop is a state the screen shows. Stamped by stop_run,
544
- // preserved by writeRunStatus's spread-merge, replaced by the terminal when the honour check
545
- // fires. The UI derives "Stopping…" from this beside a non-terminal state.
546
- stopRequestedAt: typeof s.stopRequestedAt === "string" ? s.stopRequestedAt : null,
547
- // — whether a stop can still prevent delivery. FALSE only once a lane has written it, at the
548
- // moment it commits to publishing. Absent means the run has not reached that point, which is
549
- // the truthful reading on this build: both lanes write it immediately after their last cancel
550
- // read. The screen shows its promise on true and withdraws it on false.
551
- stoppable: s.stoppable === false ? false : true,
552
- // A failed run with no reason on screen is a run the user has to phone somebody about. Both
553
- // fields are already written by every failure path (pipeline-knockout.mjs, the driver's
554
- // writeRunStatus); the listing simply used to drop them.
555
- reason: s.reason ?? null, failedStage: s.failedStage ?? null,
556
- // — the engine's OPEN-SET payload, its own field so the portal can show the sentence and
557
- // hide this. Staff only: the client redaction below replaces `reason` and must drop this too,
558
- // or the redaction would be defeated by the field that carries the raw words.
559
- reasonDetail: s.reasonDetail ?? null,
560
- date: (s.updatedAt ?? "").slice(0, 10), overall: s.tier ?? null, // the rating, never the reviewer's sign-off word
561
- // A live run has not been issued, so its last progress write is the honest ordering key — the
562
- // same role issuedAt plays for a delivered one, never presented as a finish time.
563
- issuedAt: typeof s.updatedAt === "string" ? s.updatedAt : null,
564
- // A live run has not been rated yet, so it has no band and no ladder. The UI shows an em-dash.
565
- //
566
- // `marks` IS NOT THE BAND LADDER. One array answered two questions and the second answer was a
567
- // false one: the Result screen reads its LENGTH as a name count, so an empty array told the
568
- // customer a three-name knockout batch had "0 names" for the entire run — on a row whose own mark
569
- // string beside it said the batch had three. The names are known from the moment the batch is
570
- // planned; the BANDS are what a live run does not have, and they stay null here.
571
- band: null, tone: null, bands: [],
572
- marks: Array.isArray(s.marks)
573
- ? s.marks.filter((m) => m && typeof m.name === "string").map((m) => ({ name: m.name, band: null, tone: null }))
574
- : [],
575
- reportSchema: null, report: null });
576
- } catch { /* not a run dir */ }
577
- };
578
- // QUEUED BUT NOT YET PICKED UP — the gap between pressing Start and the driver writing a status.json.
579
- //
580
- // The queue directory used to be skipped outright, so for that window a started clearance appeared in
581
- // NOTHING: not the pool, not the live list. The screen that had just promised "it will appear in
582
- // Clearances" was, for those seconds, wrong — and to anyone who pressed Start and went straight to
583
- // the list, indistinguishable from a run that never started at all. That ambiguity is the whole
584
- // reason this exists; the window itself is short (prelim-driver.path fires on the file landing).
585
- //
586
- // A PENDING job is `<id>.json` with no suffix — the runner renames to `.done`/`.failed` when it is
587
- // through, and those are history the pool and live scans already own. Reading only the bare `.json`
588
- // is therefore what keeps a finished run from appearing twice.
589
- //
590
- // ── AND THE TERMINAL MARKERS STAY OUT. THIS IS A DEAD-LETTER STORE, NOT A WORK SURFACE. ────────────
591
- //
592
- // 2026-07-28: this scan was briefly widened to also read `<id>.failed` / `.duplicate` /
593
- // `.manifest.failed`, reasoning that a job refused at the runner's intake gate never gets a run dir,
594
- // never gets a status.json, and so appears in no surface at all — the row says "Queued · Waiting to
595
- // start" and then silently disappears. The reasoning was sound. The inference from the data was not.
596
- //
597
- // The evidence offered for it was "the live queue is holding thirty of these". What that actually
598
- // meant is that THIS DIRECTORY HAS NO RETENTION AND NOBODY EVER CLEANS IT. The thirty spanned six
599
- // weeks and were test artefacts, raw Outlook message ids from the email door, and `mcp-*` dev runs;
600
- // twenty-six had no `.reason` sidecar at all, so each rendered as a row saying, in effect, something
601
- // stopped and we cannot say what or why. Twelve carried no `profileKey` and fell through to `generic`.
602
- // Home and Clearances both read this scan, so both filled with six weeks of dead letters on a morning
603
- // when nothing was running.
604
- //
605
- // A job refused at intake deserves an answer. That answer belongs AT SUBMISSION — the door that
606
- // refused it knows why, immediately, and can say so to the person standing there. It does not belong
607
- // to a directory that never forgets. Narrowing this by age or by owner would only make the junk
608
- // smaller: the source would still be a store with no retention, one policy change away from returning.
609
- //
610
- // So: a PENDING job is `<id>.json` with no suffix. The runner renames to `.done`/`.failed` when it is
611
- // through, and those are history the pool and live scans already own. Reading only the bare `.json` is
612
- // what keeps a finished run from appearing twice — and what keeps this list about work in progress.
613
- //
614
- // ORDER. The rows come back in the order the runner will ADMIT them (queue-order.mjs — the same
615
- // function drainQueue sorts with, so the list and the engine can never disagree), and each carries
616
- // a dense 1-based `queuePos`.
617
- //
618
- // Dense over the rows THIS CALLER CAN SEE, not the raw index in the lane. A client whose two jobs
619
- // sit at lane positions 4 and 9 must not be told "4" and "9" — that publishes how much work other
620
- // tenants have queued, which is the same thing the 404-never-403 rule exists to prevent. Staff
621
- // reading across every account see the true lane depth anyway, because for them every row is visible.
622
- const queuedRows = []; // { row, lane, laneIdx } — positions assigned once the whole scan is in
623
- // — READ ONCE per scan, not per row: every row of one response must agree about whether a worker
624
- // exists, and a boundary crossed mid-scan would otherwise put "waiting its turn" and "waiting for a
625
- // worker" in the same list. A queued job cannot answer this itself — it has no claim and no sidecar, so
626
- // claim liveness is silent on precisely the rows that need it.
627
- //
628
- // `null` means NOT KNOWN, and that is the default EVERYWHERE except a local install. A deployed instance
629
- // drains through the systemd path/timer units, which run `main({once:true})` and write no heartbeat — so
630
- // a service that read a missing heartbeat as "no worker" would put a false alarm on every queued row in
631
- // production. Only the launcher that actually supervises a worker claims to know, and it is the same
632
- // launcher that sets the lock dir, so the two can never be set without each other.
633
- const draining = drainingState();
634
- const readQueued = (dir) => {
635
- let files = []; try { files = readdirSync(dir); } catch { return; }
636
- const ordered = orderedQueueFiles(dir, files.filter((f) => f.endsWith(".json") && !f.startsWith(".")));
637
- for (const [laneIdx, f] of ordered.entries()) {
638
- try {
639
- const j = JSON.parse(readFileSync(join(dir, f), "utf8"));
640
- const owner = j.profileKey ?? "generic";
641
- if (!mine(owner, j.tenant ?? null)) continue;
642
- // ALL the names, spelled the way the run's own status.json and its delivered meta.json spell
643
- // them — this took `marks[0].name` and named ONE mark of N, so a client who had just ordered a
644
- // three-name knockout screen saw a single name on the row that tells them it went in.
645
- const mark = batchMarkName(j.marks, typeof j.markName === "string" && j.markName ? j.markName : undefined);
646
- 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"),
647
- // THE JOB'S OWN PIPELINE, not the literal "clearance". The row already carried
648
- // `product: "knockout-search"` and still called itself a clearance, so it was the one row in
649
- // the listing that contradicted its own product field — and Result.tsx gates the names line on
650
- // this, so a queued batch showed no names at all. A product the registry cannot place stays a
651
- // clearance: that is what the listing has always shown for anything it could not identify.
652
- kind: policyFor(j.product)?.pipeline === "knockout" ? "knockout-batch" : "clearance",
653
- markName: mark,
654
- // The job carries the KEY (portal-service stamps it from the composer) but no name — the name
655
- // is resolved by the engine when the run starts, and this job has not started. Null name, real
656
- // key: a consumer that wants a label falls back to the key rather than being told the run has
657
- // no project when it has one.
658
- projectKey: typeof j.projectKey === "string" && j.projectKey ? j.projectKey : null,
659
- projectName: null,
660
- // The ORDER's product, and its name off the same resolver every other row uses. The name was
661
- // missing here alone, and the browser covered for it by joining `product` against the composer
662
- // menu; with that join deleted a queued row would have degraded to a bare date — the one
663
- // row a client looks at straight after pressing Start. `stageLabel` stays null: nothing is
664
- // frozen until the run starts, and the registry answers for every product this door accepts.
665
- product: j.product ?? null, stageLabel: null,
666
- productName: productNameOf(j.product),
667
- // — "Waiting to start" is true of both a job behind other work and a job nothing will
668
- // ever pick up, and those are not the same thing to whoever just pressed Start. The position
669
- // still says where it sits in the line; this says whether the line is moving at all.
670
- state: "queued", step: draining === false ? "Waiting for a worker" : "Waiting to start", stepN: null, stepTotal: null,
671
- reason: null, failedStage: null,
672
- // Part of the row contract now; a job that has not started has none of them.
673
- pausedKind: null, resetsAt: null, startedAt: null,
674
- // A job file has no updatedAt — it has not run. Its MTIME is when it was queued, which is a
675
- // real fact rather than a fabricated one, sorts a just-queued run to the top where the
676
- // person who pressed Start will look, and is deterministic under test.
677
- date: new Date(statSync(join(dir, f)).mtimeMs).toISOString().slice(0, 10), overall: null,
678
- // Queued: its mtime, at full precision, for the same reason the day-level `date` uses it.
679
- issuedAt: new Date(statSync(join(dir, f)).mtimeMs).toISOString(),
680
- // The names the job was submitted with — no bands, because nothing has been rated. Same rule as
681
- // the live row: this array answers "which names", and only the delivered row can answer "at
682
- // what band".
683
- band: null, tone: null, bands: [],
684
- marks: (Array.isArray(j.marks) ? j.marks : [])
685
- .filter((m) => m && typeof m.name === "string" && m.name.trim())
686
- .map((m) => ({ name: m.name, band: null, tone: null })),
687
- reportSchema: null, report: null,
688
- queuePos: null } }); // filled below, once every lane has been read
689
- } catch { /* not a job file */ }
690
- }
691
- };
692
- // EVERY QUEUE ONCE. A directory can be reached both ways — `config.queueDirs`
693
- // lists the workspace queues too — and reading one twice would list every job in it twice and give
694
- // each row two positions in the line.
695
- const scannedQueues = new Set();
696
- const scanQueue = (dir) => {
697
- const key = pathResolve(dir);
698
- if (scannedQueues.has(key)) return;
699
- scannedQueues.add(key);
700
- readQueued(dir);
701
- };
702
- // THE CANONICAL INTAKE FIRST, and it is why this parameter exists. `CLEAROTRON_QUEUE_DIR` is where the
703
- // enqueue CLI and ops-MCP `start_run` write — which is where the PORTAL's own submissions land, since
704
- // its `trigger` is an ops-MCP hop. The walk below finds only `workspace-*/studio/clearance-search/queue`,
705
- // and a documented headless install has no workspaces at all: measured on the test box, the only queue
706
- // under the whole tree is the configured one, and it holds portal-prefixed jobs. So this scan ran ZERO
707
- // times there, and a submitted search was invisible on the dashboard from submit until claim — a
708
- // minute and a half of a client believing their order was lost.
709
- for (const d of Array.isArray(queueDirs) ? queueDirs : []) {
710
- if (typeof d === "string" && d) scanQueue(d);
711
- }
712
- try {
713
- for (const ws of readdirSync(workspaceRoot).filter((n) => n.startsWith("workspace-"))) {
714
- const studio = studioDirFor(join(workspaceRoot, ws));
715
- let slugs = []; try { slugs = readdirSync(studio); } catch { continue; }
716
- for (const slug of slugs) {
717
- // Still walked, so a deployment whose queue is not in `queueDirs` keeps working. The union is
718
- // deliberate: this must add a place to look, never remove one.
719
- if (slug === "queue") { scanQueue(join(studio, slug)); continue; }
720
- if (slug === "archive" || slug.startsWith("_") || slug.startsWith(".")) continue;
721
- let runs = []; try { runs = readdirSync(join(studio, slug)); } catch { continue; }
722
- for (const r of runs) readRun(join(studio, slug, r));
723
- }
724
- }
725
- } catch { /* no workspace */ }
726
- // Assign the ordinals last, across every lane at once. Cross-lane order is genuinely undefined —
727
- // the lanes are per-agent and drain concurrently against one shared pair of slots — so lanes are
728
- // ordered by path purely to make the result STABLE. An ordinal that reshuffled between two polls
729
- // of an unchanged queue would read as the queue churning when nothing had moved.
730
- queuedRows.sort((a, b) => a.lane.localeCompare(b.lane) || a.laneIdx - b.laneIdx);
731
- queuedRows.forEach((q, i) => { q.row.queuePos = i + 1; out.push(q.row); });
732
- return out.sort((a, b) => String(b.date ?? "").localeCompare(String(a.date ?? "")));
733
- }
734
-
735
- // A failure `reason` is NOT client-safe, and the listing must not hand it to a browser.
736
- //
737
- // The engine writes `reason = String(e?.stack ?? e)` truncated to 200 characters
738
- // (pipeline.mjs, pipeline-knockout.mjs). That is a raw stack trace: absolute filesystem
739
- // paths, internal module names, provider error text. Useful to staff, and none of a client's business
740
- // — and redacting it in the UI would be theatre, because the field still travels over the wire and
741
- // sits in devtools whatever React chooses to render.
742
- //
743
- // A client still learns that the run stopped and roughly where, because the plan is right that an
744
- // invisible failure is worse than a visible one: they keep `state`, `failedStage` (product vocabulary
745
- // like "register-probe", not a stack), and a stable sentence telling them what happens next. What they
746
- // lose is the trace.
747
- // — the owner's failed-run ruling. ONE author for this sentence now: it was
748
- // written out here and again in mcp-server/lib/audit-view.mjs, and a reword that fixed two of three
749
- // copies is how the retired claim survives in whichever surface nobody is looking at.
750
- const CLIENT_FAILURE_NOTE = clientFailureNote();
751
-
752
- // The run-slot cap, resolved from the SAME table pipeline.acquireRunSlot resolves it from, so the number
753
- // the screen states and the number the engine enforces cannot drift apart. It used to re-read
754
- // `process.env` behind a second copy of the literal 2 — two independent copies of one number is the
755
- // shape that drifts, and reading the raw environment skipped the alias resolution every other read of
756
- // this variable gets. `numeric-setting.mjs` is imported at module scope where
757
- // `driver.config.mjs` cannot be: it pulls in nothing but the alias table this file already imports.
758
- //
759
- // It is one global cap over one lock directory, never per brand owner: two owners each running one
760
- // search fill the whole deployment, and saying it per-owner would over-promise throughput.
761
- //
762
- // NULL WHEN THE VALUE IS UNUSABLE, AND THE SCREEN THEN SAYS NOTHING. The engine REFUSES a non-numeric
763
- // cap; this surface must not, because a misconfiguration that took out the screen an operator reads to
764
- // find it would be a worse failure than the one being fixed. `slotNote` already renders a null cap by
765
- // drawing no line at all, so the page states the number it has or stays quiet — never a number nobody
766
- // chose.
767
- export const concurrentRunsCap = () => {
768
- const r = resolveNumericSetting("CLEAROTRON_MAX_CONCURRENT_RUNS");
769
- return r.ok ? Math.max(1, r.value) : null;
770
- };
771
-
772
- function forRole(runs, principal) {
773
- // A person who sees everything reads failure reasons verbatim; everyone else gets the plain note. That redaction is the ONLY
774
- // role-shaping left: the held-run suppression is retired (one report, spec 2026-07-30 §5 — a run you
775
- // have rights to is always listed; the machine-QC record lives on the audit workbook).
776
- if (seesEverything(principal)) return runs;
777
- return runs.map((r) => {
778
- let out = r;
779
- // — the redaction must take `reasonDetail` with it. `reason` is replaced by a fixed note for a
780
- // client session; a second field carrying the engine's raw words would walk straight past that.
781
- if (r.state === "failed") out = { ...out, reason: CLIENT_FAILURE_NOTE, reasonDetail: null, reasonRedacted: true };
782
- return out;
783
- });
784
- }
785
-
786
- /** Every account's runs, in one pass. Staff only — the route enforces that, not this function. */
787
- export function scanAllRuns({ poolRoot, workspaceRoot, queueDirs = [] }) {
788
- return scanAccountRuns({ poolRoot, workspaceRoot, account: null, queueDirs });
789
- }
790
-
791
- /**
792
- * ── — WHICH RUN IS THIS, ASKED THE WAY THE LIST ASKS IT ────────────────────
793
- *
794
- * The Retire control refused every run the owner pressed it on, with `400 unknown run`, because the
795
- * route resolved the id by reading `<pool>/<runId>/meta.json` — and **a run that was stopped never
796
- * publishes into the pool**. The Clearances list that offered the button reads a wider set: the pool,
797
- * the workspaces and the queues. So the screen showed a control for a run the endpoint could not see,
798
- * and the failed and abandoned ones — the population a reader most wants off the list — were exactly
799
- * the ones it could never act on.
800
- *
801
- * THE POOL READ STAYS FIRST, and that is not an optimisation for its own sake: a delivered run is the
802
- * common case and one targeted `readFileSync` answers it. The scan is the FALLBACK, so the cost of a
803
- * directory walk is paid only on the ids the pool cannot answer — which is the case that used to be a
804
- * refusal, so nothing that worked before got slower.
805
- *
806
- * IT ANSWERS WITH THE ACCOUNT, never with a boolean. The account is what the caller needs: the retire
807
- * and family routes take the owner from the RUN and never from the request body, because a body-supplied
808
- * owner is a body-supplied tenancy claim. A resolver that returned "yes, it exists" would leave that
809
- * rule needing a second lookup.
810
- *
811
- * @returns `{ account, state }`, or `null` when no surface this deployment lists knows the id.
812
- */
813
- export function resolveRunAccount({ poolRoot, workspaceRoot, queueDirs = [], runId }) {
814
- try {
815
- const meta = JSON.parse(readFileSync(join(poolRoot, runId, "meta.json"), "utf8"));
816
- return { account: meta.customerKey || "generic", state: "delivered" };
817
- } catch { /* not published — which is the whole case this function exists for */ }
818
- // BOTH DIRECTIONS of the retired filter, because the way BACK from retirement has to resolve a run
819
- // that is currently hidden. `includeRetired` is exclusive on either setting, so one call cannot see
820
- // both, and a restore that could not resolve its own id would be a one-way door.
821
- for (const includeRetired of [false, true]) {
822
- for (const row of scanAccountRuns({ poolRoot, workspaceRoot, account: null, includeRetired, queueDirs })) {
823
- if (row.runId === runId) return { account: row.account ?? "generic", state: row.state ?? null };
824
- }
825
- }
826
- return null;
827
- }
828
-
829
212
  // ── the routing core (injected IO — unit-tests offline) ────────────────────────────────────────────
830
213
  /**
831
214
  * THE FIRST PATH SEGMENTS THE AUTHENTICATED SERVICE OWNS UNDER /portal.
@@ -865,7 +248,7 @@ export function resolveRunAccount({ poolRoot, workspaceRoot, queueDirs = [], run
865
248
  // `sign-out` joins them for the reason the comment above gives: a head the server answers but does not
866
249
  // RESERVE falls into the static handler and returns the app shell with a 200, which for a route whose
867
250
  // whole job is to end a session is the worst possible silent success ( — F47).
868
- export const SERVER_ROUTE_HEADS = Object.freeze(["api", "report", "admin", "health", "login", "logout", "sign-out", "connect-help"]);
251
+ export { SERVER_ROUTE_HEADS } from "./portal-static.mjs";
869
252
 
870
253
  /**
871
254
  * THE PORTAL'S HALF OF THE DECLARED-FIELD PARTITION (enqueue-schema DECLARED_JOB_FIELDS).
@@ -1349,6 +732,9 @@ export function makePortalService({
1349
732
  const grantsNow = () => (typeof grants === "function" ? grants() : grants);
1350
733
  // one-shot confirmation jtis (in-memory: ONE portal process per instance — documented POC bound)
1351
734
  const usedJtis = new Map();
735
+ // The connect group's two one-minute caches, the connector's door and its access log: one pair per service,
736
+ // which is one per process in production. Made here because a route group runs once per request.
737
+ const connectCaches = { door: { at: 0, url: null, kind: null }, connections: { at: 0, key: null, seen: null } };
1352
738
  const sweepJtis = (now = Date.now()) => { for (const [k, exp] of usedJtis) if (exp < now) usedJtis.delete(k); };
1353
739
 
1354
740
  const searchesFor = (account, principal) => {
@@ -1622,1949 +1008,32 @@ export function makePortalService({
1622
1008
  }
1623
1009
  }
1624
1010
 
1011
+ // THE ROUTE GROUPS (portal-routes/). Each group is handed two objects: what this service holds (`svc`), with the module's
1012
+ // own constants a group prints or answers with, and what the request carries (`request`). A group answers a request it serves and returns undefined for any other, and the dispatcher asks the
1013
+ // groups in the order its routes have always been matched, so a request is answered by the route that answered it before.
1014
+ const svc = { poolRoot, workspaceRoot, secret, grants, localSignIn, writeGrants, revokeConnectorKeys, queueDirs, trigger,
1015
+ stopRun, stopControl, demo, orderRefusal, audit, auditPath, auditLog, feedbackCapture, readBuilt, readCanCount,
1016
+ readTerritories, upstream, composeRead, readBudget, loadProfilesImpl, usedJtis, sweepJtis, searchesFor, jobFor, selectorOf,
1017
+ engineProgramDisputed, connectCaches, INSTALL_ROOT, INSTALL_CHANNEL, READ_OFF_NOTE, refusalFor, allowanceExhaustedLine };
1018
+
1625
1019
  async function route(method, path, identity, body = {}, query = {}) {
1626
1020
  const grantsHere = grantsNow();
1627
1021
  const principal = makePrincipal({ email: identity?.email, grants: grantsHere });
1628
1022
  const parts = path.replace(/\/+$/, "").split("/").filter(Boolean); // ["portal", ...]
1629
1023
  if (parts[0] !== "portal") return { status: 404, json: { error: "not_found" } };
1024
+ const request = { method, path, parts, identity, principal, grantsHere, body, query }; // what a route group reads of the request
1630
1025
  try {
1631
- // /portal/api/me
1632
- if (parts[1] === "api" && parts[2] === "me" && method === "GET") {
1633
- assertPrincipal(principal, { door: true }); // door check only — a multi-account client enters and gets the picker list
1634
- // `accountNames` — the DISPLAY name of each account this identity holds, and nothing else.
1635
- //
1636
- // Every profile carries a name ("Vantor Labs", "Foxglade Interactive"); the account KEY is a
1637
- // slug ("vantor"). Staff read names because the account picker fetches the staff-only
1638
- // roster; a client had no name source at all, so the identical screen printed the slug at them.
1639
- // The same brand owner therefore read two different ways depending on who signed in, which is
1640
- // what this field ends.
1641
- //
1642
- // SCOPED TO THE GRANTED ACCOUNTS, never the roster. A name map covering everything would put
1643
- // Cordillera's customer list on the one route every signed-in identity can reach — the exact
1644
- // leak /profiles is never proxied for (portal-upstream: "a client reaching it would learn the
1645
- // customer base"). `"*"` identities get {} and keep using the roster, which is staff-gated.
1646
- //
1647
- // `accountFacts` rides in the SAME loop, under the SAME scoping decision, for the same reason
1648
- // the names do: the pick panel shows industry, marketplace count and territories per company,
1649
- // and a client with several grants meets that panel. One loop, so there is one answer to
1650
- // "which accounts may this identity learn about" rather than two that can drift apart. A `"*"`
1651
- // identity gets {} here exactly as it does for names and keeps reading the staff-only roster.
1652
- let accountNames = {};
1653
- let accountFacts = {};
1654
- let meRoster = null; // read once for this answer: the names below and the house marketplaces
1655
- // GENERIC IS NAMED TOO when the person sees an organisation's Generic. It is not a company, so it is
1656
- // never in `accounts`, and without a name here the switcher printed the raw key at everyone below
1657
- // everything. An organisation with no company yet is the case with an empty `accounts`, so the
1658
- // guard is on the names to look up, not on the company list.
1659
- const named = Array.isArray(principal.accounts)
1660
- ? [...principal.accounts, ...(principal.genericOrgs?.length ? ["generic"] : [])] : [];
1661
- if (named.length) {
1662
- try {
1663
- const { companyFactsOf } = await import("./profiles.mjs");
1664
- const profiles = meRoster = await loadProfilesImpl();
1665
- for (const key of named) {
1666
- const profile = profiles.get(key);
1667
- const name = profile?.name;
1668
- if (typeof name === "string" && name) accountNames[key] = name;
1669
- if (profile) accountFacts[key] = companyFactsOf(profile);
1670
- }
1671
- } catch {
1672
- // A name is a nicety; the door is not. An unreadable profile store must not lock a user
1673
- // out of the portal, so this degrades to the keys the UI already falls back to.
1674
- accountNames = {};
1675
- accountFacts = {};
1676
- }
1677
- }
1678
- // HOW MANY RUNS THIS DEPLOYMENT EXECUTES AT ONCE. Deployment-wide, not account-scoped, which is
1679
- // why it rides here rather than on /usage: it is the same number for everyone, /me is fetched
1680
- // once by every screen, and a multi-brand account has no single /usage to read it from.
1681
- //
1682
- // Home states it in its section header. It was written into the UI as a literal `2` — right on
1683
- // the day, and silently wrong the moment CLEAROTRON_MAX_CONCURRENT_RUNS is set to anything else,
1684
- // which is exactly the shape of over-promise this screen exists to avoid.
1685
- // WHO OPERATES THIS DEPLOYMENT. The portal named the operator in three places as a
1686
- // string literal — the role label was the operator's own name, which a fork would have shipped
1687
- // about a company it has nothing to do with. `CLEAROTRON_BRAND_NAME` has been the brand seam all
1688
- // along and TRADEMARKS.md already listed portal nav as a consumer; it simply was not one.
1689
- // Riding on /me because that is where the ROLE comes from, and the label is role plus operator.
1690
- // WHICH MODE THIS INSTALL IS. Same rationale as concurrentRuns above: it is the
1691
- // same answer for everyone, /me is fetched once by every screen, and the screen that needs it
1692
- // most — New clearance — has no other deployment-wide source.
1693
- //
1694
- // READ, NEVER COMPUTED. This process deliberately has no engine environment (see this file's
1695
- // own header, three times over), so `engineInventory(process.env)` here would report demo on
1696
- // every install — a confident wrong answer. `flagView` reads the snapshot `bin/start.mjs`
1697
- // writes at boot and derives the mode from `binaryPresent`, which that snapshot already
1698
- // carries. NULL when there is no snapshot to read, and null means THIS CANNOT ANSWER — the UI
1699
- // must leave the button alone rather than infer demo from an absent file.
1700
- // READ ONCE. The payload names it and the program reading below is gated on it; two calls to
1701
- // `flagView` here would be two reads of the same file that could disagree with each other.
1702
- //
1703
- // A DEMO ANSWERS NULL. No order in a demo reaches an engine: the run route below resolves each one
1704
- // to the finished example for the search picked (`if (demo)`), which is what the demo's banner
1705
- // promises. The demo's snapshot still describes the machine, so on a machine with no engine program
1706
- // this read "demo", and New clearance drew the no-engine notice where Review search belongs: the
1707
- // one flow the demo exists to show could not be started. Null leaves the button alone, as it does
1708
- // on a fresh install, and the configuration page still reads the snapshot for itself.
1709
- const meEngineMode = demo ? null : flagView(poolRoot).engineMode;
1710
- const searchRefusal = demo ? null : await orderRefusal();
1711
- // THE HOUSE MARKETPLACES, offered as suggestions wherever a company's marketplaces are edited. A new
1712
- // company starts with none (the owner's ruling of 2026-09-23) and somebody picks; these are the
1713
- // Generic default's own list, read from the store so an install that changed it offers its own.
1714
- // Deployment-wide and the same for everyone, like concurrentRuns. [] when the store cannot be read:
1715
- // the box still takes any marketplace typed into it.
1716
- let houseMarketplaces = [];
1717
- try {
1718
- const house = (meRoster ?? await loadProfilesImpl()).get("generic")?.platforms;
1719
- if (Array.isArray(house)) houseMarketplaces = house.filter((d) => typeof d === "string" && d.trim());
1720
- } catch { /* a suggestion list is a nicety; the door is not */ }
1721
- return { status: 200, json: { email: principal.email, ...principalView(principal, grantsHere, accountNames),
1722
- accounts: principal.accounts, accountNames, accountFacts,
1723
- concurrentRuns: concurrentRunsCap(), brand: ORGANISATION_NAME, engineMode: meEngineMode, houseMarketplaces,
1724
- // WHERE A PERSON ASKS FOR A CHANGE TO THEIR SIGN-IN, beside the brand and read where it is read:
1725
- // an href Preferences links "Clearotron administrator" to, or null, and then the words are plain.
1726
- administratorContact: ADMINISTRATOR_CONTACT,
1727
- // WHETHER THE PROGRAM IS ON THIS BOX WHILE THE ENGINE CANNOT SEE IT — true, false, or null
1728
- // for "this could not be checked". The screen above renders one of three remedies from it,
1729
- // and they are different remedies: install the CLI, restart the service that cannot see it,
1730
- // or the general advice when nothing could be read. Only `engineMode: "demo"` can make this
1731
- // anything but false; see `engineProgramDisputed`.
1732
- engineProgramDisputed: await engineProgramDisputed(meEngineMode),
1733
- // WHETHER THIS INSTALL CAN RUN A SEARCH AT ALL, by the runner's own order-time test (`orderRefusal`), and when
1734
- // it cannot, the refusal the review would give this person: Home shows it in place of its invite, and New
1735
- // clearance shows it and holds its start, so nobody fills in a search the install would refuse. A demo walks
1736
- // its own ordering flow, so it reads as able.
1737
- canSearch: !searchRefusal,
1738
- ...(searchRefusal ? { searchRefusal: refusalFor(principal, searchRefusal) } : {}),
1739
- // HOW THIS INSTALL ARRIVED, so a screen can name the setup command the reader can actually
1740
- // type. `npm run setup` and `npx clearotron install` are the same wizard and each one is
1741
- // unrunnable on the other route; the no-engine notice named one of them and was wrong for
1742
- // half its readers. A WORD, never a command line and never a prefix: `invocationForm` can
1743
- // answer with this machine's absolute path, and this value is rendered in a browser.
1744
- setupRoute: installRoute(),
1745
- // WHICH RELEASE CHANNEL THIS INSTALL CAME FROM, read off its own version as `update` reads it, so the
1746
- // setup command a screen names fetches this channel. `npx clearotron install` fetches the stable, and
1747
- // the stable's setup then moves itself into ~/.local over a beta. A WORD, like the route above.
1748
- channel: INSTALL_CHANNEL,
1749
- // THE COMMAND THAT FILES AN ORGANISATION, for the screen that cannot create a company without one.
1750
- // `browserCommand`'s rule: no path on this machine, and from npx's cache the published version
1751
- // rather than a bare name that reader does not have.
1752
- organisationCommand: browserCommand('start --organisation "<name>"'),
1753
- // — a button that always fails must not render as available. The reason is
1754
- // operator-shaped and staff-only; a client reads the generic sentence the button carries.
1755
- controls: { stop: { available: stopControl.available !== false,
1756
- reason: seesEverything(principal) ? (stopControl.reason ?? null) : null } } } };
1757
- }
1758
- // /portal/api/about — the AGPL §13 source offer ()
1759
- //
1760
- // UNAUTHENTICATED, DELIBERATELY, and it is the only route here that is. §13 obliges an operator
1761
- // running a modified version to offer the source to the users interacting with it — the offer is
1762
- // owed to whoever reaches the service, and a licence notice you must first sign in to read is not
1763
- // an offer. Nothing here is private either: the product's name, its version, its licence and the
1764
- // commit it is running are all facts about code that is published under a licence requiring
1765
- // exactly that. The sha is not a secret; it is the thing being offered.
1766
- //
1767
- // SERVED, NOT BUILT. The bundle cannot carry its own commit — portal-ui/dist is committed and CI
1768
- // fails when dist and source disagree, so a hash baked in at build time is not known until after
1769
- // the commit that would carry it. The server knows what it is running; the page asks.
1770
- if (parts[1] === "api" && parts[2] === "about" && method === "GET") {
1771
- return { status: 200, json: productIdentity() };
1772
- }
1773
- // /portal/api/searches
1774
- if (parts[1] === "api" && parts[2] === "searches" && method === "GET") {
1775
- const account = assertPrincipal(principal, { account: query.account ?? null });
1776
- if (!account) return { status: 400, json: { error: "name an account (?account=)" } };
1777
- return { status: 200, json: { account, ...searchesFor(account, principal) } };
1778
- }
1779
- // /portal/api/compose/read — turn a pasted brief into a filled-in composer.
1780
- //
1781
- // THE ONE THING TO KEEP TRUE ABOUT THIS ROUTE: it is the only POST under /portal/api that is not
1782
- // a step towards spending money. It mints no confirmation token, writes nothing, queues nothing
1783
- // and returns a draft. If it ever grows a side effect, it stops being safe to leave un-gated
1784
- // behind the composer's first click and belongs beside plan/run instead.
1785
- if (parts[1] === "api" && parts[2] === "compose" && parts[3] === "read" && method === "POST") {
1786
- // Door check only. The read touches no account data, so demanding an account here would be a
1787
- // gate with nothing behind it — and a staff member composing for a client they have not yet
1788
- // picked would be refused a form-filler for no reason.
1789
- assertPrincipal(principal, { door: true });
1790
- // `error` carries the SENTENCE, `code` the machine word — the convention every other route on
1791
- // this service follows, and what portal-ui's decoder reads. A code in `error` reaches a client
1792
- // screen as the literal word "read_failed".
1793
- if (!composeRead) {
1794
- return { status: 501, json: { code: "unavailable", error: READ_OFF_NOTE } };
1795
- }
1796
- if (readBudget && !readBudget.take(principal.email)) {
1797
- return { status: 429, json: { code: "rate_limited", error: "That is a lot of reading in one hour — set this one up below." } };
1798
- }
1799
- let out;
1800
- try {
1801
- out = await composeRead(typeof body?.brief === "string" ? body.brief : "");
1802
- } catch (e) {
1803
- // A provider outage is not a portal fault and must not read as one. The composer shows the
1804
- // sentence and keeps every field the user already typed — the brief is still in the box.
1805
- audit({ event: "compose-read", by: principal.email, ok: false, error: String(e?.message ?? e) });
1806
- // NOT "just now": a throw says nothing about whether it will pass, and that wording sent a reader
1807
- // back to the button for a failure no retry fixes. It names the check instead.
1808
- return { status: 502, json: { code: "read_failed",
1809
- error: `The request could not be read: the reader failed. \`${browserCommand("doctor --probe-engine")}\` finds out why — set the search up below meanwhile.` } };
1810
- }
1811
- // Length, never content. A brief is client material — whose mark, for whose product, before
1812
- // whose deadline — and an audit log is a different disclosure surface from a run store.
1813
- audit({ event: "compose-read", by: principal.email, ok: out.ok === true,
1814
- chars: String(body?.brief ?? "").length, ...(out.ok ? {} : { error: out.error }) });
1815
- if (!out.ok) {
1816
- // "engine" IS AN UPSTREAM FAULT AND KEEPS ITS 502. Before this the reader
1817
- // built its own client and a provider outage THREW, landing in the catch above as a 502. Going
1818
- // through the engine door made it a returned refusal instead — total rather than throwing — and
1819
- // routing that to 422 would have told the user their brief was unprocessable when the engine
1820
- // was simply unreachable. Same fault, same status as before; the reader changed, not the
1821
- // meaning. `unreadable` and `shape` stay 422 beside it: those ARE answers, just untrustworthy
1822
- // ones, and 422 is what this route has always said about them.
1823
- if (out.error === "engine") {
1824
- audit({ event: "compose-read", by: principal.email, ok: false, error: out.cause ?? "engine" });
1825
- return { status: 502, json: { code: "read_failed", error: out.message } };
1826
- }
1827
- const status = out.error === "too_long" || out.error === "empty" ? 400 : 422;
1828
- return { status, json: { code: out.error, error: out.message } };
1829
- }
1830
- return { status: 200, json: { read: out.read } };
1831
- }
1832
- // shared plan-time gates — run at BOTH doors so a body that would 422 at plan can never be
1833
- // submitted at run behind a token minted for a clean body (review 2026-07-18)
1834
- const planGates = (job) => {
1835
- // Availability FIRST, before validation spends any effort on a job that cannot run whatever it
1836
- // says. This is the door that used to be missing: /plan happily minted a confirmation token for
1837
- // a knockout on a box that reported knockout unavailable, and the user found out only after
1838
- // pressing Start — a spend-shaped button that could never spend, which reads as a broken product
1839
- // rather than an unavailable one. Refusing here means the composer and the gate agree.
1840
- //
1841
- // The recipeKey arm that used to sit here (a 422 when saved searches were "not switched on") went
1842
- // with CLEAROTRON_RECIPES_MODE on 2026-07-27: a saved search is now honoured wherever it resolves.
1843
- // Asked of the RESOLVED product, not of the body: a request that names none resolves through
1844
- // the account's default and its own territories, and the old read (`body.searchLevel || "clearance"`)
1845
- // answered about a product nobody had chosen. `resolveFor` fails open to a null resolution, and a
1846
- // null one is not judged here — validateJob and the scope rules below still run, and the runner
1847
- // is the wall.
1848
- {
1849
- const { resolved } = resolveFor(job);
1850
- const cause = resolved && !resolved.clarify
1851
- ? productAvailability(policyFor(resolved.product), {
1852
- built: readBuilt(), registerCanCount: readCanCount(),
1853
- registerTerritories: readTerritories(), geography: productRow(resolved.product)?.geography ?? null,
1854
- demo, // — the wall reads the same cause the label does
1855
- })
1856
- : null;
1857
- if (cause) {
1858
- // The registry's NAME, never the internal key — the report-identity rule. It leads here for
1859
- // the same reason it leads everywhere else: "Knockout search is unavailable" names something
1860
- // a client can act on, "Depth 2 is unavailable" names our pricing ladder.
1861
- const row = productRow(resolved.product);
1862
- return { fail: { status: 422, json: { ok: false, errors: [`${row?.name ?? "That search"} is unavailable. ${UNAVAILABLE_NOTE[cause]}`] } } };
1863
- }
1864
- }
1865
- const probe = { ...job, msgId: `<plan@portal>`, conversationId: job.id };
1866
- const v = validateJob(probe);
1867
- // validateJob NORMALIZES IN PLACE (the dedupe, the bare-string fix, the worldwide token), and it
1868
- // was doing it to a throwaway copy — so the review summary and the rules below read a scope the
1869
- // runner would never receive. A literal "Worldwide" survived here as a one-element territory
1870
- // list, which frames as scope AND counts as one territory against the deep-dive rule: the guard
1871
- // would have waved a worldwide deep dive straight through. Carried back instead. Safe against
1872
- // the confirmation token: jobHashOf does not cover jurisdictions, so plan and run still agree,
1873
- // and a cleared list means the runner applies the account's defaults — what the wall would have
1874
- // done with the token anyway.
1875
- if ("jurisdictions" in probe) job.jurisdictions = probe.jurisdictions; else delete job.jurisdictions;
1876
- // AND THE GEOGRAPHY STAMP WITH IT. validateJob writes it (worldwide / named / account-default),
1877
- // and carrying back only the territories left the real job unstamped — so `resolveEffectiveScope`
1878
- // read "unrecorded" and a worldwide request fell straight back through to the account's own
1879
- // territories at this door, while the CLI and start_run honoured it. That is the same defect this
1880
- // build exists to end, surviving inside the one door that gates the money button.
1881
- if ("geography" in probe) job.geography = probe.geography; else delete job.geography;
1882
- if (!v.ok) return { fail: { status: 422, json: { ok: false, classify: v.classify, errors: v.errors } } };
1883
- const collisions = kebabCollisions((job.marks ?? [{ name: job.markName }]).map((m) => m.name));
1884
- 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`] } } };
1885
- // The (product × scope) combination rules, said HERE so a client reads them on the review step
1886
- // instead of watching a run park itself minutes later. The runner is the wall; this is the
1887
- // courtesy. It reads the SAME resolution the review step prints from (`resolveFor`), which is
1888
- // what keeps a refusal from contradicting the scope shown beside it. Fails OPEN by the same rule
1889
- // that resolution does: a profile or recipe store the resolver cannot read must not stop someone
1890
- // starting a search.
1891
- let rules = { errors: [], warnings: [] };
1892
- try {
1893
- const { profile, resolved } = resolveFor(job);
1894
- if (!profile && !resolved) throw new Error("resolution unavailable");
1895
- // EVERY resolved-product check, not just the combination rules. This door had `resolveFor(job)`
1896
- // in hand and budgeted nothing on it, so a two-name request under an account whose default
1897
- // product is a clearance passed the money button and parked at the wall (Finding 2c).
1898
- // `availability:false` — the branch above already refused it in the client's own words, and the
1899
- // staff-prose twin must never reach a browser (door-gates.mjs header).
1900
- rules = gateResolvedRequest({ job, profile, resolved, readable: true }, { availability: false });
1901
- // classify:"clarify", exactly as validateJob's own 422 above does it and as the runner files the
1902
- // identical rule. A 422 without it decodes as a collision (contract/api.ts), which the composer
1903
- // renders under "That cannot be searched as written" — a dead end, for a rule whose whole answer
1904
- // is one field: name the territories the product reads, or order the product that reads these.
1905
- if (rules.errors.length) return { fail: { status: 422, json: { ok: false, classify: "clarify", errors: rules.errors } } };
1906
- } catch (e) {
1907
- // Unreadable config never blocks a run here — the wall still holds. Audited rather than
1908
- // swallowed: a deployment pointed at the wrong profile store loses this gate for EVERY account,
1909
- // and silence is how that goes unnoticed (the roster-blindness class of incident).
1910
- audit({ event: "plan-gate-skipped", gate: "scope-rules", error: String(e?.message ?? e) });
1911
- }
1912
- return { warnings: [...(v.warnings ?? []), ...rules.warnings] };
1913
- };
1914
- /**
1915
- * The daily allowance, checked at the doors so the refusal arrives BEFORE the money button.
1916
- *
1917
- * This is the courteous layer, not the control. The runner's admission gate is the wall — it
1918
- * covers every door including email and CLI, and it is what actually stops a run. Checking here
1919
- * as well means a client who is out of allowance is told so on the review step, in a sentence
1920
- * that says when it resets, instead of pressing Start and watching a run park itself minutes
1921
- * later. The two can disagree by a run under concurrency; the wall is the one that decides, and
1922
- * it refuses by CLARIFYING rather than dropping, so nothing is ever lost to the gap.
1923
- *
1924
- * A person who sees everything is never checked; the cap binds everyone else, decided here from the principal.
1925
- */
1926
- // WHICH PRODUCT IS THIS, AND WHERE WOULD IT POINT — asked ONCE, and everything the plan says
1927
- // derives from that one answer: the availability gate, the name, the scope shown at review, and the
1928
- // effort figure the run is stamped with.
1929
- //
1930
- // The resolution used to live inside effortFor, so the plan door quoted effort off the RESOLVED
1931
- // policy while naming the product from the body's own selector — a second, cruder answer that never
1932
- // consulted the customer's own default and was null outright on the recipeKey arm. The two
1933
- // disagreed exactly where it mattered most: a saved search showed the headline "saved search" over
1934
- // an effort figure quoting a recipe, and an account whose profile defaults to a knockout was shown
1935
- // a full-clearance headline for a quick screen.
1936
- //
1937
- // Fails OPEN to nulls: this feeds a description shown beside the real gates, and a profile store
1938
- // the resolver cannot read must not stop someone starting a search. The runner is the wall.
1939
- // ONE implementation, shared with every other door (door-gates.mjs resolveForDoor). It was written
1940
- // here first and copied nowhere, which is why start_run and the CLI resolved nothing at all.
1941
- const resolveFor = resolveForDoor;
1942
- const effortFrom = ({ job, profile, resolved }) => {
1943
- if (!profile || !resolved || resolved.clarify) return null;
1944
- try { return quoteForJob({ job, profile, searchPolicy: resolved }); } catch { return null; }
1945
- };
1946
-
1947
- const quotaRefusal = async (account, organisation = null) => {
1948
- if (seesEverything(principal) || !upstream) return null;
1949
- let caps = null, capsRead = false;
1950
- try {
1951
- // Generic's caps are the neutral profile's — one file, every organisation's lane — so they are
1952
- // read from the store rather than through the settings wall, which answers per company.
1953
- if (account === "generic") { caps = (await loadProfilesImpl()).get("generic")?.runCaps ?? null; capsRead = true; }
1954
- else {
1955
- const r = await upstream.getProfile(principal, account);
1956
- if (r.status === 200) { caps = r.json?.readOnly?.runCaps ?? null; capsRead = true; }
1957
- }
1958
- } catch { return null; } // cannot read the cap ⇒ do not invent one; the wall still holds
1959
- // The same DEFAULT the wall applies (runner.mjs DEFAULT_CLIENT_DAILY_RUNS): a profile READ
1960
- // successfully with no dailyRuns is capped, not uncapped. Mirrored rather than imported because
1961
- // portal-service must not pull the runner into a request path; a test pins the two constants.
1962
- // An UNREADABLE profile is different and gets no pre-check at all — inventing a limit we could
1963
- // not read would refuse a client whose profile may say something larger. The wall still holds.
1964
- if (!capsRead) return null;
1965
- const limit = Number.isInteger(caps?.dailyRuns) ? caps.dailyRuns : DEFAULT_CLIENT_DAILY_RUNS;
1966
- if (!Number.isInteger(limit)) return null;
1967
- const used = accountUsage({ queueDirs: queueDirs(), account, organisation });
1968
- // A COUNT WE COULD NOT TAKE IS NOT A ZERO. `complete: false` means no ledger was reachable, and
1969
- // 0 would then mean "nothing recorded" and "nothing readable" at once — the exact confusion that
1970
- // made this refusal unreachable for as long as the path was wrong. Same call the branch
1971
- // above already makes for an unreadable profile, for the same reason: this is a pre-check whose
1972
- // only job is a better sentence, the runner's checkRunCaps is the actual control, and refusing a
1973
- // client on evidence we do not have costs them a search we cannot show they spent. So it stays
1974
- // quiet — but it says so in the audit trail rather than silently, because a gate that cannot read
1975
- // its input is an operational fact, not a non-event.
1976
- //
1977
- // `basis` rides along because "no-ledger" and "unreadable" are fixed by different people: the
1978
- // first is a queue this service was never pointed at, the second is a file it cannot open. One
1979
- // row per request while a deployment is misconfigured, at both call sites, is the intended
1980
- // volume — a gate that has been blind since boot should be as loud as the traffic it is blind to.
1981
- if (!used.complete) {
1982
- audit({ event: "quota-precheck-blind", by: principal.email, account, basis: used.basis });
1983
- return null;
1984
- }
1985
- if (used.today + 1 <= limit) return null;
1986
- return { status: 429, json: { ok: false, errors: [allowanceExhaustedLine(limit, BRAND.name)] } };
1987
- };
1988
-
1989
- // ── AN INSTALL THAT CANNOT SEARCH REFUSES HERE, WHERE THE PERSON IS ─────────────────────────
1990
- //
1991
- // The runner asks this at intake and refuses the order there (runner.mjs, `orderTimeRefusal`). The portal
1992
- // asked nothing: it said "queued", the runner's refusal reached only its terminal and a sidecar in the
1993
- // queue, and the order then vanished from every page, which is the outcome the queue scan's own rule
1994
- // above says belongs at submission. So the review and the start both ask the runner's question, of the
1995
- // runner's tables, and nothing is queued. Neither sentence names a setting, which a browser must never be
1996
- // shown: the client one the runner already writes, or what is missing and the command that sets it, for the
1997
- // person who runs the install (refusalFor). A demo walks its own flow and is not asked.
1998
- // `code` lets the screen give the box its own heading rather than the edited-review one, and the audit row is
1999
- // the operator's record of the refusal: the order doors are not admin writes, so nothing files one for them.
2000
- const configurationRefusal = async (door, account) => {
2001
- if (demo) return null;
2002
- const refusal = await orderRefusal();
2003
- if (!refusal) return null;
2004
- audit({ event: door === "plan" ? "plan" : "trigger", by: principal.email, account, ok: false, refused: "not_configured", missing: refusal.names });
2005
- return { status: 409, json: { ok: false, errors: [refusalFor(principal, refusal)], code: "not_configured" } };
2006
- };
2007
-
2008
- // /portal/api/run/plan — the confirmation gate (no spend)
2009
- if (parts[1] === "api" && parts[2] === "run" && parts[3] === "plan" && method === "POST") {
2010
- const tenant = body.tenant ?? query.tenant ?? null;
2011
- const account = assertPrincipal(principal, { account: body.account ?? query.account ?? null, tenant, run: true });
2012
- if (!account) return { status: 400, json: { error: "name an account (?account=)" } };
2013
- const job = jobFor({ principal, account, tenant, body });
2014
- const notConfigured = await configurationRefusal("plan", account);
2015
- if (notConfigured) return notConfigured;
2016
- const gates = planGates(job);
2017
- if (gates.fail) return gates.fail;
2018
- const overQuota = await quotaRefusal(account, job.tenant ?? null);
2019
- if (overQuota) return overQuota;
2020
- // ONE resolution, and the name, the stage, the turnaround and the effort all come off it.
2021
- const { profile: planProfile, resolved: planResolved, scope: planScope } = resolveFor(job);
2022
- const planRow = productRow(planResolved?.product);
2023
- // `name` leads. stageLabel stays on the wire for an older bundle, which
2024
- // reads `name || stageLabel` — and for a resolution that clarified, where there is no row and
2025
- // "saved search" is still the honest thing to call it.
2026
- const name = planRow?.name ?? null;
2027
- const stageLabel = planRow?.stageLabel ?? planResolved?.stageLabel ?? "saved search";
2028
- const nMarks = countJobMarks(job);
2029
- const selector = selectorOf(body);
2030
- // WHAT WOULD ACTUALLY BE SEARCHED, resolved by the same ladder plan_run uses. Without this the
2031
- // review step could show a depth and a mark count while saying nothing about the territories or
2032
- // marketplaces the user had just picked — a summary that omits the thing being confirmed is a
2033
- // worse gate than none, because it looks like it checked.
2034
- const scope = planScope;
2035
- const token = mintConfirmation({ secret, account, email: principal.email, jobHash: jobHashOf(job) });
2036
- audit({ event: "plan", by: principal.email, account, selector, marks: nMarks });
2037
- // ── — THE LIMIT, STATED WHERE THE TICKET IS SPENT ─────────────────
2038
- //
2039
- // The issue's ruling is that the coverage limit is "stated at the point of choosing"; this is
2040
- // the OTHER point, and it is the one that matters most. A worldwide search is orderable on a
2041
- // partial register now, and the review step is the last thing a reader sees before money is
2042
- // committed — so "you are buying a worldwide search that will not reach most of the world"
2043
- // belongs here rather than in the report they read afterwards.
2044
- //
2045
- // It also puts the honest reading of the QUOTE in front of them: `run-quote.mjs` sizes the
2046
- // turnaround from the territories ASKED FOR, not from the ones the register will reach, so the
2047
- // hours quoted for a worldwide search on a partial register overstate the work. That is not a
2048
- // bill — the quote is hours, and nothing on this path converts to currency — and it is recorded
2049
- // on the issue rather than silently adjusted here.
2050
- const planCoverage = coverageDisclosure(planRow?.geography ?? null, readTerritories());
2051
- return { status: 200, json: { ok: true, account, selector, name, stageLabel, marks: nMarks,
2052
- coverage: planCoverage ? { reached: planCoverage.reached, missing: planCoverage.missing, note: planCoverage.note } : null,
2053
- // The PRODUCT's floor, and the client reads `effort.turnaround` in preference to it — that one
2054
- // is computed against THIS request (names, lanes, territories) where this is the product with
2055
- // nothing added. Kept as the degraded answer for when the quote cannot be taken. Read off the
2056
- // SAME resolution as the name above, so the two cannot describe different products.
2057
- turnaround: baseTurnaroundFor(policyFor(planResolved?.product)).text,
2058
- warnings: gates.warnings, scope,
2059
- effort: effortFrom({ job, profile: planProfile, resolved: planResolved }),
2060
- confirmationToken: token, note: "Nothing runs until you confirm. Review the summary, then start the search." } };
2061
- }
2062
- // /portal/api/run — verify + trigger (the ONLY spend path)
2063
- if (parts[1] === "api" && parts[2] === "run" && parts.length === 3 && method === "POST") {
2064
- const account = assertPrincipal(principal, { account: body.account ?? null, tenant: body.tenant ?? null, run: true });
2065
- if (!account) return { status: 400, json: { error: "name an account" } };
2066
- const job = jobFor({ principal, account, tenant: body.tenant ?? null, body });
2067
- const notConfigured = await configurationRefusal("trigger", account); // asked again: the install may have changed since the review
2068
- if (notConfigured) return notConfigured;
2069
- const gates = planGates(job); // re-gated: the token is necessary, never sufficient
2070
- if (gates.fail) return gates.fail;
2071
- // re-checked for the same reason the gates are: a token minted while the account still had
2072
- // allowance must not spend it after another tab has used the last one.
2073
- const overQuota = await quotaRefusal(account, job.tenant ?? null);
2074
- if (overQuota) return overQuota;
2075
- sweepJtis();
2076
- const bad = verifyConfirmation({ secret, token: body.confirmationToken, account, email: principal.email,
2077
- jobHash: jobHashOf(job), usedJtis });
2078
- if (bad) return { status: 409, json: { ok: false, error: bad } };
2079
- const selector = selectorOf(body);
2080
- // ── — A DEMO WALKS THE REAL FLOW AND LANDS ON A FINISHED RUN ─────────
2081
- //
2082
- // Ruling, 2026-08-31, revising his own ruling of an hour earlier: "i think its OK for
2083
- // someone to be able to press New Clearance in demo mode and see it work and get the static
2084
- // results, right?" — so the form is real, the plan is real, the confirmation is real, and the
2085
- // only thing that is not real is the dispatch.
2086
- //
2087
- // EVERYTHING ABOVE THIS LINE HAS ALREADY RUN: the gates, the quota, and the confirmation token.
2088
- // That is deliberate rather than incidental — "walks the real flow" means the same validation
2089
- // and the same refusals a real order meets, and a demo that skipped them would be the separate
2090
- // viewer this whole track exists to retire. What it must never do is reach `trigger`, and this
2091
- // returns before it: no engine turn, no register call, no queue entry, no run directory.
2092
- //
2093
- // THE MAPPING IS STATED, NOT CLEVER, in the ruling's own words: which finished run the visitor
2094
- // lands on follows from WHICH SEARCH THEY PICKED. "Picking the fourth product and receiving the
2095
- // first one's report would teach the wrong thing about all four."
2096
- //
2097
- // SO A PRODUCT WITH NO FINISHED EXAMPLE REFUSES, and says which one. That is the honest state of
2098
- // a pool that holds fewer than four — today it holds one — and it is what keeps the mapping's
2099
- // promise while the rest are captured. Landing somewhere approximate would break exactly the
2100
- // rule the ruling spends a paragraph on.
2101
- //
2102
- // RESOLVED THROUGH THE SAME OWNERSHIP SCAN EVERY OTHER SURFACE USES, so a demo can never land on
2103
- // a run this principal could not otherwise open. There is no demo-only read path here.
2104
- if (demo) {
2105
- const { resolved } = resolveFor(job);
2106
- const want = resolved && !resolved.clarify ? resolved.product : null;
2107
- const row = productRow(want);
2108
- const finished = scanAccountRuns({ poolRoot, workspaceRoot, account, queueDirs: queueDirs() })
2109
- .filter((x) => x.state === "delivered" && x.product === want);
2110
- if (!finished.length) {
2111
- audit({ event: "demo-order", by: principal.email, account, selector, product: want ?? null, landedOn: null });
2112
- return { status: 409, json: { ok: false, errors: [
2113
- `This demo does not carry a finished ${row?.name ?? "search"} to show you yet. `
2114
- + `Nothing was started and nothing was charged — every search here resolves to a report that `
2115
- + `already exists, and this one has not been captured. Pick a search the demo has a report for.`,
2116
- ] } };
2117
- }
2118
- // NEWEST FIRST, by the same comparison the listing sorts on, so two examples of one product
2119
- // resolve predictably rather than by directory order.
2120
- const landed = [...finished].sort((a, b) =>
2121
- String(b.issuedAt ?? b.date ?? "").localeCompare(String(a.issuedAt ?? a.date ?? "")))[0];
2122
- audit({ event: "demo-order", by: principal.email, account, selector, product: want ?? null, landedOn: landed.runId });
2123
- // `queued: false` and a NAMED landing, because the one thing this must not do is read like a
2124
- // run that just started. The report it opens is dated as it is and says on its own face that
2125
- // it is an example; the response says the same thing to the client that navigates there.
2126
- return { status: 200, json: { ok: true, queued: false, id: landed.runId,
2127
- landedOn: landed.runId, landedProduct: want ?? null } };
2128
- }
2129
- let r;
2130
- try {
2131
- // FORWARD THE WHOLE JOB, not a hand-picked subset. This call used to name eight fields, so
2132
- // anything else the composer sent was validated at the plan gate, shown back in the review
2133
- // step, hashed into the confirmation token — and then dropped on the floor here. A field that
2134
- // survives every check and vanishes at the last hop is the worst shape available: the user is
2135
- // told it was accepted and the report is quietly narrower than the one they confirmed.
2136
- // Enumerating fields at a pass-through hop guarantees the list rots; the job is already
2137
- // server-stamped and validated, so it goes as it is.
2138
- // — this used to destructure `msgId` and `conversationId` off the job before forwarding.
2139
- // `jobFor` no longer mints them (it is an allow-list, so no body value can put them here
2140
- // either), and a strip that can never remove anything reads as though the job might carry
2141
- // them. It cannot. The comment above is the rule: forward the whole job.
2142
- // — THE DEPLOYMENT DECLARES A DEMO RUN, READ FROM THE ACCOUNT'S OWN
2143
- // PROFILE. The rule `demoRun` lives under is that a REQUESTER may not decide whether their own
2144
- // report is fiction. It is not that a demo account cannot be run from the portal — and its own
2145
- // words are "operator doors declare it, the client door does not". THIS HOP IS THE OPERATOR
2146
- // DOOR: it calls `start_run` with the ops token, and `START_RUN_JOB_FIELDS.carries` lists
2147
- // `demoRun` for exactly that reason. The requester still never supplies it; the account's own
2148
- // profile does, which is the deployment's statement about the account.
2149
- //
2150
- // WITHOUT THIS, `demoRunAgreement` sees a demo profile and an ordinary job and REFUSES every
2151
- // portal submission on a `demoData` account — so the demo account, which exists to be shown,
2152
- // was the one account the UI could not run. Measured 2026-09-02 on demo-brand-owner.
2153
- //
2154
- // FAIL CLOSED. A profile that cannot be read leaves the flag unset and the run is refused by
2155
- // the agreement wall in its own words. The dangerous direction is the opposite one — marking a
2156
- // REAL account's report as fiction — and an unreadable profile must never be able to reach it.
2157
- let demoRunFlag = false;
2158
- try { demoRunFlag = (await loadProfilesImpl()).get(account)?.demoData === true; }
2159
- catch { demoRunFlag = false; }
2160
- r = await trigger({
2161
- ...job,
2162
- profileKey: account,
2163
- // The daily-allowance stamp. Set ONLY here, on everyone but a person who sees everything —
2164
- // this is the one place in the system where that is decided. See checkRunCaps for why the
2165
- // polarity is positive-only and why every inferred alternative fails unsafely.
2166
- ...(!seesEverything(principal) ? { clientPrincipal: true } : {}),
2167
- ...(demoRunFlag ? { demoRun: true } : {}),
2168
- });
2169
- } catch (e) {
2170
- // an upstream refusal is AUDITED in full — never an opaque 500 with no trace
2171
- const detail = String(e?.message ?? e).slice(0, 300);
2172
- audit({ event: "trigger", by: principal.email, account, selector, id: job.id, ok: false, error: detail });
2173
- // …but the AUDIT is where the detail belongs, not the response. Upstream messages are written
2174
- // for operators and name infrastructure: the unwired-trigger case reads "PORTAL_MCP_URL /
2175
- // PORTAL_OPS_TOKEN unset", which is an internal variable name rendered in a client's browser.
2176
- // Staff get it verbatim because they are the ones who can act on it; a client gets the fact.
2177
- const staff = seesEverything(principal);
2178
- // One cause is worth distinguishing even for staff: an instance with no engine attached is not
2179
- // a failure, it is an instance that was never finished. Saying "could not be queued" invites
2180
- // someone to retry, re-read logs and file a bug against a working system.
2181
- const unwired = /trigger lane is not wired/i.test(detail);
2182
- const error = unwired
2183
- ? (staff
2184
- ? `this instance has no search engine attached (${detail}) — nothing was started`
2185
- : `Searches cannot be started from this instance yet. Nothing was started, and nothing was charged.`)
2186
- : (staff
2187
- ? `the run could not be queued (${detail}) — nothing was started`
2188
- : `The run could not be started just now. Nothing was started, and nothing was charged — ${BRAND.name} can see what happened.`);
2189
- return { status: 502, json: { ok: false, error, unwired } };
2190
- }
2191
- audit({ event: "trigger", by: principal.email, account, selector, id: job.id, ok: Boolean(r?.ok ?? r?.queued) });
2192
- return { status: 200, json: { ok: true, queued: true, id: job.id, upstream: r ?? null } };
2193
- }
2194
-
2195
- // ── STOPPING ───────────────────────────────────────────────────────────────────────────────
2196
- // Deliberately NOT behind the confirmation-token dance. That gate exists to stop money being
2197
- // spent by accident; stopping is its opposite, and asking someone to confirm twice while a run
2198
- // they no longer want keeps billing would be the wrong instinct wearing a safety hat.
2199
- //
2200
- // /portal/api/run/<runId>/stop — end a run that has already started.
2201
- if (parts[1] === "api" && parts[2] === "run" && parts[3] && parts[4] === "stop" && method === "POST") {
2202
- const account = assertPrincipal(principal, { account: query.account ?? null, tenant: query.tenant ?? null, run: true });
2203
- if (!account) return { status: 400, json: { error: "name an account (?account=)" } };
2204
- const runId = decodeURIComponent(parts[3]);
2205
- // OWNERSHIP FIRST, and off the run list rather than off the request: the engine's own account
2206
- // gate would refuse a foreign run anyway, but it would do so with an upstream error, and an
2207
- // upstream error is a different observable from a 404. A run you may not touch must be
2208
- // indistinguishable from one that does not exist.
2209
- const mine = scanAccountRuns({ poolRoot, workspaceRoot, account, queueDirs: queueDirs() }).find((r) => r.runId === runId);
2210
- if (!mine) return { status: 404, json: { error: "not_found" } };
2211
- if (mine.state === "delivered" || mine.state === "failed" || mine.state === "cancelled")
2212
- return { status: 409, json: { ok: false, error: "This run has already finished.", state: mine.state } };
2213
- // ── — WHICH STOP THE READER ASKED FOR ────────────────────────────────
2214
- //
2215
- // Ruling, on his second encounter with the same wait: "a stop is a stop — maybe it should
2216
- // be a 'stop immediately or at next boundary to preserve data' kind of question when you press
2217
- // it." The driver half landed the mode; this carries the reader's answer to it.
2218
- //
2219
- // EXPLICIT `=== true`, so anything else is the boundary stop. This is the control that ends a
2220
- // run mid-turn, and a truthy string arriving from a hand-rolled POST must not read as consent
2221
- // to lose the step in flight. The safe path is the one an unrecognised body gets.
2222
- const immediate = body?.immediate === true;
2223
- let r = null;
2224
- try {
2225
- // — the human, forwarded. The portal has verified them (it is what every audit line on
2226
- // this path already records); the engine cannot see them, because every UI stop arrives on one
2227
- // shared ops token. Without this the run dir can say a stop came from the portal and never
2228
- // which person pressed it, on a surface that travels into the archived matter record.
2229
- r = await stopRun({ runId, immediate, onBehalfOf: principal.email });
2230
- } catch (e) {
2231
- const detail = String(e?.message ?? e);
2232
- audit({ event: "stop", by: principal.email, account, runId, ok: false, error: detail });
2233
- // The token is VERB-SCOPED, and a portal minted `--verbs start_run` cannot stop anything. That
2234
- // refusal arrives from upstream looking like an engine fault, so name it as a posture problem
2235
- // for operators while telling the user only that it did not happen.
2236
- const unwired = /not wired|verb|scope/i.test(detail);
2237
- return { status: 502, json: { ok: false, unwired,
2238
- error: seesEverything(principal) ? detail : `The run could not be stopped just now. It is still running, and ${BRAND.name} can see what happened.` } };
2239
- }
2240
- // ── — WHICH STOP IS ACTUALLY IN PROGRESS, AND NOTHING ELSE ──────────
2241
- //
2242
- // The mode is read off the ANSWER, never off the press. An immediate stop that found no turn to
2243
- // end IS a boundary stop, and the driver says so — presenting it as immediate because that is
2244
- // what the button said would be the second silent thing in a row on this control, which is the
2245
- // complaint this issue was opened with.
2246
- //
2247
- // AND THE RAW TOOL RESULT STOPS TRAVELLING. This route returned `upstream: r` wholesale, which
2248
- // was harmless while the tool answered in states and sentences. It is not now: `stop_run`'s
2249
- // immediate mode carries `immediate.pid` — a process id on the box — and this response goes to
2250
- // a browser. Nothing in the client has ever read `upstream`; what a reader needs is which stop
2251
- // is happening and the sentence the driver already composed for them.
2252
- //
2253
- // AND "IMMEDIATE" MEANS THE STEP WAS SEEN TO END. `signalled` says only that a signal was accepted
2254
- // for delivery; `ended` is what the driver saw afterwards. An answer without it, an older driver's
2255
- // `ended: null` included, is the boundary stop: that is the honest reading of an answer that does
2256
- // not say.
2257
- const mode = r?.immediate?.attempted && r?.immediate?.ended === true ? "immediate" : "boundary";
2258
- audit({ event: "stop", by: principal.email, account, runId, ok: Boolean(r?.ok), action: r?.action ?? null,
2259
- // ASKED and TAKEN, both, because they differ exactly when something went wrong — a reader
2260
- // pressed "stop now" and got the boundary stop, which is the row somebody will come looking
2261
- // for. `why` is the driver's own words about its own machinery and stays on this side.
2262
- stopAsked: immediate ? "immediate" : "boundary", stopTaken: mode,
2263
- ...(immediate && mode === "boundary" ? { stopFellBack: r?.immediate?.why ?? r?.immediate?.error ?? "no reason given" } : {}) });
2264
- return { status: 200, json: { ok: true, runId, action: r?.action ?? null,
2265
- stop: { mode, note: typeof r?.note === "string" ? r.note : null } } };
2266
- }
2267
-
2268
- // GET /portal/api/run/<runId>/summary — THE CROSS-MARK PARAGRAPH for a grouped run.
2269
- //
2270
- // A knockout over several names has no combined document, so its assessment — the one piece of
2271
- // prose that reads the names against each other — is written to `report.md` and, until this route,
2272
- // reached nobody: `meta.reports` lists the per-mark HTMLs only, and the pool path is not one the
2273
- // edge serves. Ruling 2026-08-26: the grouped page carries it.
2274
- //
2275
- // ITS OWN ROUTE RATHER THAN A FIELD ON THE RUN ROW. The row is what /portal/api/runs returns for
2276
- // every run the caller owns, and it is fetched by every screen that lists runs — where this prose
2277
- // is never rendered. Riding it there would send a paragraph per batch to a browser that had no use
2278
- // for it, on every listing, growing with the pool.
2279
- //
2280
- // Ownership is read off the run's OWN meta, the same way /portal/report/<runId> reads it, so a
2281
- // foreign run is 404 and never 403: a run you may not read must be indistinguishable from one that
2282
- // does not exist.
2283
- if (parts[1] === "api" && parts[2] === "run" && parts[3] && parts[4] === "summary" && method === "GET") {
2284
- assertPrincipal(principal, { door: true }); // door only — ownership is the meta check below
2285
- const runId = parts[3];
2286
- if (!/^[A-Za-z0-9][A-Za-z0-9._-]{0,180}$/.test(runId) || runId.includes(".."))
2287
- return { status: 404, json: { error: "not_found" } };
2288
- const dir = join(poolRoot, runId);
2289
- let meta; try { meta = JSON.parse(readFileSync(join(dir, "meta.json"), "utf8")); } catch { return { status: 404, json: { error: "not_found" } }; }
2290
- const owner = meta.customerKey || "generic";
2291
- if (!mayReadRun(principal, { owner, organisation: meta.organisation ?? null })) return { status: 404, json: { error: "not_found" } };
2292
- // ANSWERED FOR EVERY RUN THAT HAS ONE, grouped or not. A gate to grouped runs only stood here
2293
- // and was wrong in the way this file keeps guarding against: a single-document run HAS this
2294
- // prose — `report.md` is written on every run — so 404 would have said "there is none" about
2295
- // something that exists, and `report.md` would have been a published file with no address on
2296
- // exactly the runs where it is a duplicate rather than the original.
2297
- //
2298
- // The rule it was reaching for is real and belongs on the client: never print the same
2299
- // paragraph twice on one screen. A single-document run's assessment is already rendered inside
2300
- // the document the screen frames, so the screen does not ask (`showsAssessment` in
2301
- // portal-ui/src/contract/reads.ts). Which view shows what is the screen's question; whether the
2302
- // run has a summary is this one's.
2303
- const summary = batchSummaryOf(dir);
2304
- // AN ABSENCE, ANSWERED AS ONE. A run whose summary was composed empty has no paragraph, and a
2305
- // 200 carrying [] would have the client render an empty panel that says nothing and explains
2306
- // nothing. 404 means there is none, which the screen renders as no panel at all.
2307
- if (!summary.length) return { status: 404, json: { error: "not_found" } };
2308
- return { status: 200, json: { runId, summary } };
2309
- }
2310
-
2311
- // /portal/api/queue/<id>/cancel — drop a job that has not started. No spend has happened, so
2312
- // there is nothing to account for and no row is left behind.
2313
- if (parts[1] === "api" && parts[2] === "queue" && parts[3] && parts[4] === "cancel" && method === "POST") {
2314
- const account = assertPrincipal(principal, { account: query.account ?? null, tenant: query.tenant ?? null, run: true });
2315
- if (!account) return { status: 400, json: { error: "name an account (?account=)" } };
2316
- const id = decodeURIComponent(parts[3]);
2317
- const mine = scanAccountRuns({ poolRoot, workspaceRoot, account, queueDirs: queueDirs() }).find((r) => r.runId === id && r.state === "queued");
2318
- if (!mine) return { status: 404, json: { error: "not_found" } };
2319
- let r = null;
2320
- try {
2321
- r = await stopRun({ id, onBehalfOf: principal.email }); // — same lane, same reason
2322
- } catch (e) {
2323
- const detail = String(e?.message ?? e);
2324
- audit({ event: "queue-cancel", by: principal.email, account, id, ok: false, error: detail });
2325
- return { status: 502, json: { ok: false, unwired: /not wired|verb|scope/i.test(detail),
2326
- error: seesEverything(principal) ? detail : "It could not be cancelled just now. Nothing has been charged." } };
2327
- }
2328
- audit({ event: "queue-cancel", by: principal.email, account, id, ok: Boolean(r?.ok), action: r?.action ?? null });
2329
- // ALREADY-CLAIMED IS A RACE, NOT AN ERROR. The runner picked it up between the click and the
2330
- // request. Say so plainly and let the caller re-read the list, where it is now a running card —
2331
- // never dress a lost race as a failure, and never pre-emptively disable the control to avoid it.
2332
- if (r && r.ok === false && r.action === "already-claimed")
2333
- return { status: 409, json: { ok: false, action: "already-claimed", id,
2334
- error: "It started just before this reached us. It is running now — stop it from the card." } };
2335
- return { status: 200, json: { ok: true, id, action: r?.action ?? null } };
2336
- }
2337
-
2338
- // /portal/api/queue/order — the order queued jobs are admitted in.
2339
- //
2340
- // Written straight to the shared order file rather than through the MCP: reordering spends
2341
- // nothing and starts nothing, so putting it behind an ops verb would widen that token's authority
2342
- // for no gain. The tenancy wall is the same one every other route uses — the caller's resolved
2343
- // account — applied per id.
2344
- if (parts[1] === "api" && parts[2] === "queue" && parts[3] === "order" && method === "POST") {
2345
- const account = assertPrincipal(principal, { account: query.account ?? null, tenant: query.tenant ?? null, run: true });
2346
- if (!account) return { status: 400, json: { error: "name an account (?account=)" } };
2347
- const asked = Array.isArray(body?.order) ? body.order.filter((s) => typeof s === "string" && s) : null;
2348
- if (!asked) return { status: 400, json: { error: "send { order: [id, …] }" } };
2349
- // Only ids this caller actually holds, and only ones still queued. Anything else is dropped
2350
- // SILENTLY rather than refused: a rejection that named the offending id would confirm that some
2351
- // other tenant's job exists, which is the one thing every refusal here is shaped to avoid.
2352
- const ownQueued = new Map(
2353
- scanAccountRuns({ poolRoot, workspaceRoot, account, queueDirs: queueDirs() })
2354
- .filter((r) => r.state === "queued")
2355
- .map((r) => [r.runId, r]),
2356
- );
2357
- const wanted = asked.filter((id) => ownQueued.has(id));
2358
- const applied = reorderQueue({ workspaceRoot, order: wanted, allowed: new Set(ownQueued.keys()) });
2359
- audit({ event: "queue-order", by: principal.email, account, ids: wanted.length, lanes: applied.lanes });
2360
- return { status: 200, json: { ok: true, order: wanted, lanes: applied.lanes } };
2361
- }
2362
- // ── /portal/api/config/* — the settings surface ────────────────────────────────────────────
2363
- // Every route here goes through portal-upstream, which is the ONLY tenancy wall in front of
2364
- // profile-service. Nothing in this block resolves an account itself; doing so would create a
2365
- // second implementation of tenancy that has to agree with the first one forever.
2366
- if (parts[1] === "api" && parts[2] === "config") {
2367
- // THE DOOR FIRST — before the wiring check, before the method check, before anything whose
2368
- // answer depends on what this deployment happens to have.
2369
- //
2370
- // This block used to answer 405 method_not_allowed to a caller who had not been admitted at all:
2371
- // POST /portal/api/config/profile from an unenrolled address returned a crisp "that endpoint
2372
- // exists and you used the wrong verb on it", from the one surface that reads and writes tenant
2373
- // configuration. GET on the same path already 403'd (the door check happens inside
2374
- // portal-upstream's resolveAccount), so the surface answered two different ways to the same
2375
- // stranger depending only on the method — and the chattier answer was the one no identity check
2376
- // had run in front of.
2377
- //
2378
- // Now every method behaves identically for an unadmitted identity: the same PortalDeny(403) the
2379
- // rest of the API gives, carrying nothing this caller could not already read off /portal/api/me.
2380
- // 403-at-the-door is the deliberate doctrine here (portal-access.mjs: "an unmapped identity gets
2381
- // NO principal (403 at the door)") and it is what the denial page in makeHttpHandler exists to
2382
- // render; 404 is the doctrine for FOREIGN and NONEXISTENT resources, which is the case handled
2383
- // on the method line below.
2384
- assertPrincipal(principal, { door: true });
2385
- // 404 WITH A NAMED REASON. The status is unchanged and deliberately so —
2386
- // `portal-service.test.mjs` pins "never a 500" for this branch, and a config surface that failed
2387
- // to construct is a clean refusal rather than a fault. What changes is the BODY: `not_found` was
2388
- // the only thing the client had, so the screens rendered "Projects are not available to you" to
2389
- // the owner of the account when the real cause was that `PROFILE_REPO_ROOT` does not contain the
2390
- // customer store. That reason existed only in a boot log, and it cost the owner a morning.
2391
- //
2392
- // The 404-never-403 rule is untouched, and this code cannot weaken it. The rule protects the
2393
- // EXISTENCE of tenant-scoped resources from probing; this answer is tenant-INDEPENDENT — every
2394
- // admitted identity on this deployment gets exactly it, so it separates no account from any
2395
- // other. The door check above still answers 403 first, so an unadmitted caller never reaches
2396
- // this line. A 503 was the other candidate and was rejected: it would have reversed a pinned
2397
- // contract for nothing the reader gains, and it says "try again later" about a condition that
2398
- // needs a configuration change.
2399
- if (!upstream) return { status: 404, json: { error: "config_surface_unavailable" } };
2400
- const acct = query.account ?? body.account ?? null;
2401
-
2402
- // /portal/api/config/profile
2403
- if (parts[3] === "profile" && parts.length === 4) {
2404
- if (method === "GET") return await upstream.getProfile(principal, acct);
2405
- // 404, not 405 — the 404-never-403 rule applied to SHAPE as well as ownership. A foreign
2406
- // account already reads here as not-found (portal-upstream rule 2), so answering
2407
- // method_not_allowed for a wrong verb made ONE endpoint distinguishable from an endpoint that
2408
- // does not exist, which is precisely the fact the 404 rule is protecting. The other half of
2409
- // this same block has always fallen through to the not_found below for the identical mistake
2410
- // (a POST to /portal/api/config/projects) — the two halves disagreed, and this was the wrong
2411
- // half. Byte-identical body, so nothing downstream can tell them apart either.
2412
- return { status: 404, json: { error: "not_found" } };
2413
- }
2414
- // /portal/api/config/profile/{validate,save}
2415
- if (parts[3] === "profile" && parts.length === 5 && method === "POST") {
2416
- const r = await upstream.writeProfile(principal, acct, parts[4], body);
2417
- if (parts[4] === "save" && r.status === 200) {
2418
- audit({ event: "profile-save", by: principal.email, account: r.json?.account ?? acct });
2419
- }
2420
- return r;
2421
- }
2422
- // /portal/api/config/companies — CREATE. No account segment, because there is no account yet.
2423
- //
2424
- // It does not hang off `profile` for a reason worth stating: every route under that word acts on
2425
- // ONE company, resolved from the caller, and this one is the act of there not being one. Reusing
2426
- // the noun would put "the company you are in" and "the company you are making" behind the same
2427
- // path, which is the conflation the pick panel exists to remove.
2428
- //
2429
- // The audit row is written upstream by the create route itself, in the same commit as the file,
2430
- // so there is none here. An audit call copied from its neighbours would also be wrong twice: it
2431
- // would test `status === 200` against a 201, and file nothing.
2432
- if (parts[3] === "companies") {
2433
- if (parts.length === 4 && method === "POST") return await upstream.createCompany(principal, body);
2434
- // 404 for a wrong verb, as the profile branch above explains at length: 405 would make this
2435
- // endpoint distinguishable from one that does not exist.
2436
- return { status: 404, json: { error: "not_found" } };
2437
- }
2438
- // /portal/api/config/projects[/:project[/{validate,save}]]
2439
- if (parts[3] === "projects") {
2440
- if (parts.length === 4 && method === "GET") return await upstream.listProjects(principal, acct);
2441
- if (parts.length === 5 && method === "GET") return await upstream.getProject(principal, acct, parts[4]);
2442
- if (parts.length === 6 && method === "POST") {
2443
- const r = await upstream.writeProject(principal, acct, parts[4], parts[5], body);
2444
- if (parts[5] === "save" && r.status === 200) {
2445
- audit({ event: "project-save", by: principal.email, account: acct, project: parts[4] });
2446
- }
2447
- return r;
2448
- }
2449
- }
2450
- // /portal/api/config/searches[/:slug[/{validate,save}]] — saved searches, client-authorable.
2451
- // Same shape as projects because it is the same discipline: list, read one, validate, save.
2452
- // Archive is a save carrying archived:true; there is no delete verb to mount.
2453
- if (parts[3] === "searches") {
2454
- if (parts.length === 4 && method === "GET") return await upstream.listSearches(principal, acct);
2455
- if (parts.length === 5 && method === "GET") return await upstream.getSearch(principal, acct, parts[4]);
2456
- if (parts.length === 6 && method === "POST") {
2457
- const r = await upstream.writeSearch(principal, acct, parts[4], parts[5], body);
2458
- if (parts[5] === "save" && r.status === 200) {
2459
- audit({ event: "saved-search-save", by: principal.email, account: acct, slug: parts[4],
2460
- version: r.json?.version ?? null, archived: Boolean(body?.recipe?.archived) });
2461
- }
2462
- return r;
2463
- }
2464
- }
2465
- return { status: 404, json: { error: "not_found" } };
2466
- }
2467
-
2468
- // /portal/api/usage — what this account has used against its allowance.
2469
- //
2470
- // Its own route rather than a field on /portal/api/me, because it is per-ACCOUNT and `me` is
2471
- // per-identity: a staff member acting for three clients has three different answers, and one of
2472
- // them is never "yours". Cheap enough to fetch beside the composer and the run list.
2473
- if (parts[1] === "api" && parts[2] === "usage" && method === "GET") {
2474
- const account = assertPrincipal(principal, { account: query.account ?? null, tenant: query.tenant ?? null });
2475
- if (!account) return { status: 400, json: { error: "name an account (?account=)" } };
2476
- // Generic is counted per organisation — the lane the wall caps (runner.mjs checkRunCaps).
2477
- const organisation = account === "generic" ? genericOrgOf(principal, query.tenant ?? null) : null;
2478
- // Caps live on the customer profile and are code-owned (never client-editable). A deployment
2479
- // with no config surface still answers, with counts and no caps — "we cannot tell you your
2480
- // limit" is a better answer than a fabricated one.
2481
- let caps = null, capsRead = false;
2482
- if (upstream) {
2483
- try {
2484
- if (account === "generic") { caps = (await loadProfilesImpl()).get("generic")?.runCaps ?? null; capsRead = true; }
2485
- else {
2486
- const r = await upstream.getProfile(principal, account);
2487
- if (r.status === 200) { caps = r.json?.readOnly?.runCaps ?? null; capsRead = true; }
2488
- }
2489
- } catch { /* a settings surface fault must not take the counter down */ }
2490
- }
2491
- // `complete` rides out with the counts (see usage-ledger.mjs): false means no ledger was read and
2492
- // these numbers are a floor. The UI can render that as "—" the way it already renders an
2493
- // unreadable cap as null, instead of a confident 0 nobody counted.
2494
- //
2495
- // `basis` is dropped here on purpose. What a client is owed is "we could not count", which
2496
- // `complete` says; WHICH kind of nothing it was is an operator's diagnosis of our deployment and
2497
- // belongs in the audit trail, where the quota pre-check puts it.
2498
- const { basis: _basis, ...used } = accountUsage({ queueDirs: queueDirs(), account, organisation });
2499
- return { status: 200, json: { account, ...(account === "generic" ? { tenant: organisation } : {}), ...used,
2500
- // The EFFECTIVE daily allowance: the profile's value, else the default the wall applies — a
2501
- // client reading "—" while the wall enforces 2 is the same lie as a wrong count. But a profile
2502
- // we could NOT read still reports null: "we cannot tell you your limit" is a different
2503
- // statement from "your limit is 2", and only one of them is honest when settings are down.
2504
- dailyRuns: Number.isInteger(caps?.dailyRuns) ? caps.dailyRuns : (capsRead ? DEFAULT_CLIENT_DAILY_RUNS : null),
2505
- monthlyRuns: caps?.monthlyRuns ?? null, maxQueued: caps?.maxQueued ?? null,
2506
- // A person who sees everything is not capped, and the UI needs to know that to avoid showing an
2507
- // allowance to someone it does not bind. See checkRunCaps for why it is decided here and nowhere else.
2508
- capped: !seesEverything(principal) } };
2509
- }
2510
-
2511
- // /portal/api/mcp-access — the connection details for driving the engine from your own assistant.
2512
- //
2513
- // The Use-your-AI screen shipped deliberately EMPTY: there was no API that reported a host, so the
2514
- // page said so rather than printing a plausible placeholder (a genericised host has gone out of this
2515
- // codebase before and had to be chased). This is that API, and it keeps the same discipline: the URL
2516
- // comes from configuration and is null when unset. A deployment that has not wired the client MCP
2517
- // says "not available here", which is true, instead of showing an address that will not connect.
2518
- //
2519
- // There is no credential in this response, and that is the design rather than an omission: client
2520
- // MCP access is the caller's OWN Cloudflare Access login plus the grants entry that already governs
2521
- // this portal. Nothing to mint, nothing to paste, nothing to leak — and revoking portal access
2522
- // revokes the connector with it.
2523
- //
2524
- // `keyUrl` is the SECOND address: the API-key door, for assistants that cannot do a browser sign-in
2525
- // (a fixed "API key" box, a headless agent). It is a different HOST, never the same one with a key
2526
- // bolted on, and it is reported separately so the page can be honest about which is which. It stays
2527
- // null until that door is deployed — and a key itself is never in this response: keys are issued to a
2528
- // named person out of band, not handed to whoever loads the page.
2529
- // DOOR CHECK, not an account check — and the distinction is the whole bug this once had. Nothing in
2530
- // this answer is per-account: the connector address is one host for the deployment, and the identity
2531
- // to sign in with is the caller's own. Asking assertPrincipal to resolve an ACCOUNT made the route
2532
- // depend on something it never uses, and the failure was silent in the worst way — `assertPrincipal`
2533
- // returns null for STAFF with no acting-for account (portal-access.mjs: "caller decides"), that null
2534
- // became a 400, and the screen fell back to its "not shown here" empty state. So every staff user and
2535
- // every multi-account client was told the connector did not exist yet, while single-account clients
2536
- // saw it. `door:true` is the mode for exactly this question — may this identity enter — and it is what
2537
- // /portal/api/me already uses.
2538
- // ── ONE READING OF THE CONNECTOR'S OWN DOOR, CACHED ────────────────────────────────────────────────
2539
- //
2540
- // The same unauthenticated probe `doctor` makes, asked here so the connector steps follow what the door
2541
- // actually answers. Bounded three ways, because this sits on a page load: a short timeout, a one-minute
2542
- // cache, and a failure that answers `null` rather than throwing — a page that cannot read its door says
2543
- // so, which is the honest half of this change.
2544
- let doorKindCache = { at: 0, url: null, kind: null };
2545
- // ── WHETHER A READER HAS AN ASSISTANT ON THIS INSTALLATION ────────────────────────────────────────
2546
- //
2547
- // The only evidence either process holds is the connector's own access log: enrolment says a person MAY
2548
- // connect, never that they did. `readConnections` is the connector's reader, imported rather than
2549
- // rebuilt here — the path this log lives at is the connector's fact, and a portal deriving it from its
2550
- // own environment is how a live key's record nearly got struck on a split install.
2551
- //
2552
- // TWO INSTALLATION SHAPES, AND THE SPLIT IS THE ONE THE ROUTE ALREADY MAKES. A hosted install has a
2553
- // published client door and many signed-in people, so the question is answered per person: is this
2554
- // email in the log. A local install has no client door, one reader, and a connector that cannot know
2555
- // who it is serving — so the local route's own record answers for the only person who could be asking.
2556
- // Reading a local record as an answer on a HOSTED install would mark every reader connected the moment
2557
- // one member of staff ran the server by hand, which is why it is gated on there being no client door.
2558
- //
2559
- // Returns null, never false, when there was nothing to read. See the route for why that matters.
2560
- //
2561
- // CACHED FOR A MINUTE, the same as the door probe above and for the same reason: this is a page load,
2562
- // not a check. It runs on every report a reader opens, and reading the tail of a log each time to
2563
- // answer a question whose answer changes once, ever, would be paid on the client-facing screen.
2564
- // KEYED ON THE FILES IT READ, not on time alone. The log's location is configuration and does not move
2565
- // under a running service — but a cache that ignored it would answer about the wrong file for a minute
2566
- // after it did, and it is what makes this cache testable at the route rather than only at the helper.
2567
- let connectionsCache = { at: 0, key: null, seen: null };
2568
- const CONNECTIONS_TTL_MS = 60_000;
2569
-
2570
- async function readerHasConnectedAi(principal) {
2571
- const email = String(principal?.email ?? "").trim().toLowerCase();
2572
- let seen = null;
2573
- // Imported here rather than at the top, the way every other reach into mcp-server/lib from this file
2574
- // is: the driver does not depend on the connector, and the import-cycle walk is what keeps it so.
2575
- let audit = null;
2576
- try { audit = await import("../mcp-server/lib/audit.mjs"); }
2577
- catch { return null; } // best-effort: never fail a page load
2578
- const key = audit.auditPaths().join("\u0000");
2579
- if (connectionsCache.seen && connectionsCache.key === key && Date.now() - connectionsCache.at < CONNECTIONS_TTL_MS) {
2580
- seen = connectionsCache.seen;
2581
- } else {
2582
- try { seen = audit.readConnections(); } catch { return null; }
2583
- connectionsCache = { at: Date.now(), key, seen };
2584
- }
2585
- if (!seen.available) return null;
2586
- if (email && seen.emails.has(email)) return true;
2587
- if (!process.env.CLEAROTRON_CLIENT_MCP_URL && seen.local) return true;
2588
- return false;
2589
- }
2590
-
2591
- const DOOR_KIND_TTL_MS = 60_000;
2592
- async function connectorDoorKind(url) {
2593
- if (!url) return null;
2594
- const now = Date.now();
2595
- if (doorKindCache.url === url && now - doorKindCache.at < DOOR_KIND_TTL_MS) return doorKindCache.kind;
2596
- let probe = null;
2597
- try {
2598
- const res = await fetch(url, { method: "GET", redirect: "manual", signal: AbortSignal.timeout(2000) });
2599
- let body = null;
2600
- if (res.status === 401) { try { body = (await res.text()).slice(0, 400); } catch { body = null; } }
2601
- probe = { ok: res.status < 500, status: res.status, error: null, challenge: res.headers.get("www-authenticate"), body };
2602
- } catch (e) { probe = { ok: false, status: null, error: String(e?.cause?.code ?? e?.name ?? e?.message ?? e) }; }
2603
- const kind = doorKind(probe);
2604
- doorKindCache = { at: now, url, kind };
2605
- return kind;
2606
- }
2607
-
2608
- if (parts[1] === "api" && parts[2] === "mcp-access" && method === "GET") {
2609
- assertPrincipal(principal, { door: true }); // throws PortalDeny(403) for an unmapped identity
2610
- const url = process.env.CLEAROTRON_CLIENT_MCP_URL || null;
2611
- const keyUrl = process.env.CLEAROTRON_AGENT_MCP_URL || null;
2612
- // ── THE ROUTE THAT NEEDS NO ADDRESS ──────────────────────────────────
2613
- //
2614
- // Both addresses above are null on a local install and always will be: there is no hosted door
2615
- // to point at. The surfaces built on them then render nothing — correctly, by their own rule —
2616
- // and the owner met that as a wall on his own first install, with the one route that DOES work
2617
- // sitting unmentioned on his disk.
2618
- //
2619
- // STAFF ONLY, and that boundary is honest rather than a guess about deployment shape. The
2620
- // command is a true fact about THIS INSTALL'S OWN DISK, useful to anyone with a shell on the
2621
- // box and useless to a hosted client who has no checkout. On a local install the reader IS the
2622
- // operator, which is why the split that already exists does the work an "is this deployment
2623
- // local" inference would have done badly. Agreed before building, because it
2624
- // changes what a signed-in staff user is shown.
2625
- //
2626
- // COMPOSED IN ONE PLACE and handed over as a string. The browser cannot know this install's
2627
- // path, so the three surfaces stating this route cannot drift apart even if someone tries.
2628
- //
2629
- // AND IT NAMES THE DISTRIBUTION, like every other surface that states this route. Without the
2630
- // target this one composer answers as it does for an install that is not under WSL at all, so on
2631
- // a WSL box this field alone carried the inside-WSL line while the rows beside it led with the
2632
- // Windows-side one. Nothing draws this field today; it is on the wire, and a field that answers
2633
- // differently from the rows is a trap for whoever draws it next.
2634
- const stdio = seesEverything(principal)
2635
- ? stdioConnectOffer({ workDir: process.env.CLEAROTRON_WORK_DIR || null, reportsDir: process.env.CLEAROTRON_REPORTS_DIR || null, wsl: wslTarget(), demo: isDemo(process.env) })
2636
- : null;
2637
-
2638
- // ── THE PAGE IS HANDED ANSWERS, NOT FACTS TO REASON FROM ─────────────
2639
- //
2640
- // The browser used to hold its own client table on its own axis — `door` × `reach` — and derive
2641
- // offered-versus-withheld from `url`, `keyUrl` and `enabled`. Two tables partitioning the same
2642
- // clients on different axes did not merely risk drifting; they had already drifted. The page
2643
- // said Codex needs a key address, which is `null` on a local install, so it named a one-line
2644
- // command in its own instructions and then rendered no command. That is this issue's defect,
2645
- // living inside the page written to answer it.
2646
- //
2647
- // So the resolution happens HERE, once, through `shared/connect-clients.mjs`, and the page
2648
- // renders what it is handed. This is not a preference for server-side logic: the install's own
2649
- // filesystem path is not a browser fact, and any derivation needing it must happen where it is
2650
- // known. `assistantsFor` and `addressFor` are DELETED rather than kept in step, because a
2651
- // second author kept in step by hand is exactly what broke.
2652
- //
2653
- // STAFF-ONLY STDIO SURVIVES THE MOVE. The command is a true fact about this install's own disk
2654
- // — useful to anyone with a shell on the box, useless to a hosted client who has no checkout —
2655
- // so a client is handed no stdio routes at all and the rows that need one resolve to a stated
2656
- // absence rather than to a command they cannot run.
2657
- const offers = connectOffers({
2658
- stdioRoutes: stdio
2659
- ? Object.fromEntries(Object.keys(STDIO_SHAPES).map((shape) =>
2660
- [shape, stdioConnectFor(shape, { workDir: process.env.CLEAROTRON_WORK_DIR || null, reportsDir: process.env.CLEAROTRON_REPORTS_DIR || null, wsl: wslTarget(), demo: isDemo(process.env) })]))
2661
- : {},
2662
- wsl: isWsl(),
2663
- nameClaude: claudeNamer(),
2664
- demo: isDemo(process.env),
2665
- // ONE ADDRESS, and it is the publicly reachable one ( §5). The
2666
- // `localAddress` and `clientDoorStanding` inputs are gone with the axis that read them: no
2667
- // surface serves a loopback address to anybody, and the door's running-or-not stopped being
2668
- // a question the moment it auto-started with the product.
2669
- publicAddress: url,
2670
- // THE KEY DOOR'S OWN HOST, when one is deployed. Beside a sign-in door its steps ride along for
2671
- // the page to fold away; they are never resolved against `url`, which refuses a key.
2672
- keyAddress: keyUrl,
2673
- operator: principal.email ?? null,
2674
- // WHAT THE DOOR ANSWERS, read from the door rather than assumed by the row. The steps used to
2675
- // be fixed: Claude's said to paste a key and set authentication to None, which is right for a
2676
- // self-hosted door and cannot work on any deployment behind an identity provider — the key is
2677
- // minted for nothing and the warning the reader is told to ignore IS the sign-in. Cached
2678
- // because this is a page load, not a check: one reading serves every reader for a minute, and
2679
- // a door that could not be read leaves this null so the page says so instead of guessing.
2680
- door: await connectorDoorKind(url),
2681
- });
2682
- return { status: 200, json: {
2683
- url, // null ⇒ the UI keeps its honest empty state
2684
- keyUrl, // the API-key door; null until it is deployed
2685
- email: principal.email ?? null, // the identity to sign in with — what they already use
2686
- enabled: !!url,
2687
- stdio, // the local route, or null for a client
2688
- // ── HAS THIS READER ALREADY CONNECTED AN ASSISTANT? ──────────────────────────────────────
2689
- //
2690
- // Folded into this route rather than given its own, because the Ask-AI control on a report
2691
- // already loads it and a second request per report open buys nothing.
2692
- //
2693
- // `null` IS A THIRD STATE AND THE SCREEN HAS TO DRAW IT. True, false and "no log to read" are
2694
- // different facts: an installation whose access log has not been written yet, or cannot be
2695
- // read, has not told us this reader never connected — it has told us nothing. The control
2696
- // treats null the way it treats false, because offering the menu to somebody with no
2697
- // assistant reproduces the defect this is fixing, and because the panel carries its own way
2698
- // past ("Already connected? Ask anyway"). What it must not do is claim the measurement.
2699
- aiConnected: await readerHasConnectedAi(principal),
2700
- // Every client, already resolved: served or not, with what it needs or why it cannot be.
2701
- //
2702
- // ── `steps` COMES BACK, on the owner's 2026-09-03 ruling ─────────
2703
- //
2704
- // It was dropped here deliberately under his 2026-08-31 cut, which said the page shows no
2705
- // recipes and the per-assistant blocks "become the one italic link at the bottom". His
2706
- // re-inspection reverses that for one specific thing: *"The page must lead each vendor with
2707
- // the path that vendor's UI user actually takes; a CLI command is at most a collapsed
2708
- // 'advanced' detail."*
2709
- //
2710
- // The two rulings are consistent once you separate what was actually objected to. "Settings →
2711
- // Connectors → Add custom connector" is not a recipe in the sense the cut banned — it is the
2712
- // reader's OWN vocabulary, three taps in an app they already have open. The technical thing,
2713
- // the part irrelevant to a reader connecting from Cowork, is the command, and that is what moves behind
2714
- // a fold. So the steps travel and the command demotes.
2715
- //
2716
- // They are resolved HERE and not composed in the browser, for the reason this route already
2717
- // exists: the step that names an address must name the address this deployment actually
2718
- // resolved, and a page that built its own would drift from it.
2719
- offers: offersForWire(offers),
2720
- } };
2721
- }
2722
-
2723
- // /portal/api/connect-key — mint THIS caller's own access, for the clipboard, never for the page.
2724
- //
2725
- // ── THE OWNER'S RULING, 2026-08-31 ───────────────────────────────────────────────────────────
2726
- //
2727
- // *"The page never shows a key, in any state."* Three reasons he gave, and the second is the one
2728
- // that shapes this endpoint: *"A rendered key outlives the moment. It's in the DOM, in the
2729
- // screenshot someone takes, in the browser cache, on a screen left open. A key that's never text
2730
- // on a page has none of that."*
2731
- //
2732
- // So the key still reaches the browser — a clipboard write needs it — and never becomes text. The
2733
- // page holds it in a local variable for the length of one press.
2734
- //
2735
- // ── MINTED PER CALLER, AND `sub` NEVER COMES FROM THE REQUEST ────────────────────────────────
2736
- //
2737
- // The rule this replaces existed because a key shown on a shared page made one person's
2738
- // credential everyone's. Moving it to the clipboard does NOT answer that on its own: anybody who
2739
- // loads the page can still press the button. What answers it is that each press mints a key for
2740
- // THE CALLER, from the authenticated principal and never from anything the request said — so a
2741
- // colleague pressing it gets their own credential, attributable in the audit log and revocable by
2742
- // name, rather than a copy of somebody else's.
2743
- //
2744
- // ENROLMENT IS CHECKED FIRST, for the same reason `clearotron connect` checks it: a key issued to
2745
- // an identity the guest list has never heard of authenticates and is then refused on every
2746
- // request, which is a credential that opens nothing and a reader who believes they are finished.
2747
- if (parts[1] === "api" && parts[2] === "connect-key" && method === "POST") {
2748
- assertPrincipal(principal, { door: true });
2749
- const url = process.env.CLEAROTRON_CLIENT_MCP_URL || null;
2750
- if (!url) return { status: 409, json: { error: "no_connector" } };
2751
- const identity = principal.email ?? null;
2752
- if (!identity) return { status: 403, json: { error: "no_identity" } };
2753
- // Enrolled means a principal exists: the door check above has already refused an address with no
2754
- // access anywhere. Asking for a company list here instead read a person whose only reach is their
2755
- // organisation's Generic as not enrolled.
2756
- let key;
2757
- try { key = mintToken({ scope: "account", sub: identity, ttlSec: 90 * 24 * 3600 }); }
2758
- catch { return { status: 503, json: { error: "cannot_issue" } }; }
2759
- auditLog(`connect-key issued for=${identity}`); // WHO, never WHAT — the token itself is never logged
2760
- return {
2761
- status: 200,
2762
- json: { address: url, key },
2763
- // NEVER CACHED, by any hop. A credential sitting in a proxy or a disk cache is the "outlives
2764
- // the moment" failure the ruling is about, arriving by a route the page cannot see.
2765
- headers: { "cache-control": "no-store, no-cache, must-revalidate, private", "pragma": "no-cache" },
2766
- };
2767
- }
2768
-
2769
- // /portal/connect-help — the by-hand setup instructions, for the one link the page carries.
2770
- //
2771
- // ── WHY THIS ROUTE EXISTS AT ALL ─────────────────────────────────────
2772
- //
2773
- // The owner's cut ends the Use-your-AI page with *"Not connecting? [Set it up by hand](…)"* and
2774
- // left the target open. There was no document route on this portal, so the link had nowhere to
2775
- // go — and a link to nowhere is the same defect class as a button that cannot work. The
2776
- // instructions already exist and carry exactly the recipes the cut removed from the page, so this
2777
- // serves them rather than inventing a fourth description of how to connect.
2778
- //
2779
- // THE SIX BANNED WORDS DO NOT APPLY HERE, deliberately. "No connector, no key, no address" is a
2780
- // rule about the PAGE, whose reader is choosing an assistant and nothing else. This is the escape
2781
- // hatch for the reader who wants the mechanism, and withholding the vocabulary from them would
2782
- // make the page's simplicity a lie rather than a kindness.
2783
- //
2784
- // READ-ONLY, DOOR-CHECKED, AND SERVED AS ESCAPED TEXT. It runs nothing and loads nothing, so it
2785
- // gets `docCsp()` rather than the report policy, which permits inline script for frozen artefacts
2786
- // that need it. Before this shipped the document named the private repository in an illustrative
2787
- // path six times; nothing that reaches a client may carry that, so the placeholder now names the
2788
- // install. Anything added to that file is published by this route — check it before you add it.
2789
- if (parts[1] === "connect-help" && method === "GET") {
2790
- assertPrincipal(principal, { door: true });
2791
- let md;
2792
- try { md = readFileSync(join(INSTALL_ROOT, "mcp-server", "CONNECT.md"), "utf8"); }
2793
- catch { return { status: 404, json: { error: "not_found" } }; }
2794
- return { status: 200, doc: md };
2795
- }
2796
-
2797
- // /portal/api/runs
2798
- if (parts[1] === "api" && parts[2] === "runs" && method === "GET") {
2799
- // — THE VIEWER'S OWN DISMISSALS, stamped per request because the listing does not know who
2800
- // is asking and must not learn: scanAccountRuns is shared with the staff index and the fold, and
2801
- // a per-reader flag computed inside it would be one reader's preference baked into a cache every
2802
- // other surface reads. So the scan answers "what is there" and this answers "what has THIS
2803
- // reader put down". Every branch below goes through it — a route that stamped only the scope=mine
2804
- // path would leave the same run acknowledged on one screen and not on another.
2805
- const mine = (runs) => withAcks(runs, readAcks(poolRoot, principal?.email));
2806
- // "All brand owners". ONLY FOR A PERSON WHO SEES EVERYTHING, and it is a distinct code path rather
2807
- // than a wildcard passed to assertPrincipal — nobody else may reach a branch that skips the account
2808
- // resolution, even by accident. Anyone else who asks for it gets the same 404 as any account not theirs.
2809
- if (query.account === "*") {
2810
- // THE DOOR FIRST. This branch once read a field off `principal` directly, and `principal` is null
2811
- // for an identity with no access anywhere — the exact caller this route most needs to refuse.
2812
- // Reading a field off null threw a TypeError, which is not a PortalDeny, so the
2813
- // catch at the bottom of route() rethrew it and the handler answered 500 "internal". An
2814
- // unenrolled prober therefore got a SERVER ERROR from the one route that lists every customer,
2815
- // while every other surface refused them cleanly — and a 500 is both the wrong answer and a
2816
- // more interesting one than a refusal. Resolving the principal before checking whether there
2817
- // IS one is the bug; the fix is ordering, not a null-guard.
2818
- //
2819
- // door:true is the same admission check /portal/api/me makes and deliberately resolves NO
2820
- // account (portal-access.mjs), so the staff-only rule below is untouched: a client still gets
2821
- // the plain 404 on the line after this one.
2822
- assertPrincipal(principal, { door: true });
2823
- if (!seesEverything(principal)) return { status: 404, json: { error: "not_found" } };
2824
- // One pass over the pool, not one request per account. The alternative — the browser fanning
2825
- // out across the roster — would spend a roster-sized chunk of the 120/min rate limit on every
2826
- // poll, which is exactly what the limiter is there to stop.
2827
- return { status: 200, json: { account: "*", runs: mine(forRole(scanAllRuns({ poolRoot, workspaceRoot, queueDirs: queueDirs() }), principal)) } };
2828
- }
2829
-
2830
- // ?scope=mine — EVERY BRAND OWNER THIS IDENTITY HOLDS, in one call.
2831
- //
2832
- // Home is account-scoped: it shows what is in flight across every brand owner the account
2833
- // holds, and the sidebar's brand-owner switcher must not empty it. A law firm clearing for
2834
- // three of its own clients cannot have that while "all of mine" costs one request per owner
2835
- // against a 120/min limit.
2836
- //
2837
- // IT IS DELIBERATELY NOT `account=*`. The wildcard means one thing — every account in the
2838
- // deployment, staff only — and it stays that way. Letting a client's `*` quietly resolve to
2839
- // "mine" would teach the browser that `*` is a harmless default worth sending everywhere, and
2840
- // the next path that forgets to re-check it becomes a cross-tenant read. Two capabilities,
2841
- // two names. (The two portal-service tests that pin the wildcard say exactly this.)
2842
- //
2843
- // One request shape for everyone: staff get every account, a client gets its own. Home never
2844
- // has to ask who is looking, which is the whole point — there is no staff layout.
2845
- if (parts[1] === "api" && parts[2] === "runs" && method === "GET" && query.scope === "mine") {
2846
- assertPrincipal(principal, { door: true });
2847
- if (seesEverything(principal)) {
2848
- return { status: 200, json: { account: "*", runs: mine(forRole(scanAllRuns({ poolRoot, workspaceRoot, queueDirs: queueDirs() }), principal)) } };
2849
- }
2850
- // Resolved from `principal.accounts`, NEVER from the query — this is the same set
2851
- // assertPrincipal hands back one key at a time, so it widens no boundary.
2852
- //
2853
- // `accounts === "*"` is the grants-file-absent posture (enforcement OFF). That is a
2854
- // SENTINEL, NOT A LIST: expanding it here would turn a missing config file into a
2855
- // cross-tenant read, so it falls through to the same refusal as holding nothing.
2856
- // Their companies, and the Generic of each organisation they hold whole.
2857
- if (Array.isArray(principal.accounts) && (principal.accounts.length || principal.genericOrgs?.length)) {
2858
- return { status: 200, json: { account: "*", runs: mine(forRole(scanAccountRuns({ poolRoot, workspaceRoot, account: principal.accounts,
2859
- generic: { orgs: principal.genericOrgs ?? [] }, queueDirs: queueDirs() }), principal)) } };
2860
- }
2861
- return { status: 404, json: { error: "not_found" } };
2862
- }
2863
- const account = assertPrincipal(principal, { account: query.account ?? null, tenant: query.tenant ?? null });
2864
- if (!account) return { status: 400, json: { error: "name an account (?account=)" } };
2865
- // GENERIC IS LISTED PER ORGANISATION. assertPrincipal has already refused an organisation whose
2866
- // Generic this person does not see. A named or implied organisation lists its own Generic runs,
2867
- // and a person who sees everything also gets the ones filed under none — on a one-organisation
2868
- // install those are that organisation's. Unnamed, with several organisations, a person who sees
2869
- // everything lists every Generic run, which is what they saw before organisations existed.
2870
- if (account === "generic") {
2871
- const org = genericOrgOf(principal, query.tenant ?? null);
2872
- const generic = org == null ? { all: true } : { orgs: [org], unfiled: seesEverything(principal) };
2873
- return { status: 200, json: { account, tenant: org, runs: mine(forRole(scanAccountRuns({ poolRoot, workspaceRoot, account: [], generic, queueDirs: queueDirs() }), principal)) } };
2874
- }
2875
- return { status: 200, json: { account, runs: mine(forRole(scanAccountRuns({ poolRoot, workspaceRoot, account, queueDirs: queueDirs() }), principal)) } };
2876
- }
2877
- // ── /portal/api/ack — "I have seen that one" ─────────────────────────────────────────────
2878
- //
2879
- // The Home dashboard accumulated failed runs with no way to clear them; on the test instance they
2880
- // were the dominant content, crowding out the work actually running. This dismisses one, FOR THE
2881
- // VIEWER ONLY.
2882
- //
2883
- // NOT STAFF-GATED, and that is the point rather than an oversight — it is the one curation act on
2884
- // this service that changes nothing anybody else can see, so every reader gets it for their own
2885
- // dashboard. Compare /portal/admin/retired: that hides a run from everyone including the
2886
- // brand owner, so it is staff-only and audited. This is neither, because there is nothing to
2887
- // audit: no state moves, no other reader is affected, and the run is untouched in Clearances.
2888
- //
2889
- // NO OWNERSHIP SCAN. Acking an id you cannot see writes one line to your own file and matches
2890
- // nothing on any listing you can reach — the stamp is applied by comparing against rows the scan
2891
- // already decided you may have. Proving ownership here would put a pool walk on a click, to
2892
- // prevent a caller from filling their own 500-entry file with ids that do nothing. The id is
2893
- // shape-checked all the same: it is a key in a file we write.
2894
- if (parts[1] === "api" && parts[2] === "ack" && method === "POST") {
2895
- assertPrincipal(principal, { door: true });
2896
- const runId = String(body?.runId ?? "");
2897
- if (!/^[A-Za-z0-9][A-Za-z0-9._-]{0,180}$/.test(runId) || runId.includes("..")) {
2898
- return { status: 400, json: { error: "unknown run" } };
2899
- }
2900
- const acknowledged = body?.acknowledged !== false;
2901
- const state = String(body?.state ?? "");
2902
- // The rule at the door as well as in the key: a paused or recovering run is one somebody still
2903
- // needs to see. Keying on (runId, state) already makes a lie inert — the stamp only lands while
2904
- // the run still reads that way — but a refusal here is what a caller can act on.
2905
- if (acknowledged && !ACKNOWLEDGEABLE.includes(state)) {
2906
- return { status: 400, json: { error: `only a ${ACKNOWLEDGEABLE.join(" or ")} run can be acknowledged` } };
2907
- }
2908
- const acks = setAck(poolRoot, principal.email, { runId, state, acknowledged });
2909
- return { status: 200, json: { acknowledged, runId, count: acks.size } };
2910
- }
2911
- // /portal/report/<runId>/audit.xlsx — the audit workbook.
2912
- //
2913
- // MUST be branched before the report route below, which matches any parts.length >= 3 and would
2914
- // otherwise answer this with the report's HTML under a spreadsheet's name.
2915
- //
2916
- // The comment this replaces said the portal "does not serve the file", and the embed strip removes
2917
- // the report's own .xlsx link for that reason — so the workbook has been unreachable from the
2918
- // portal since the portal existed. That was treated as a policy. It is not: the workbook is part of
2919
- // the deliverable, and a link that is stripped without being replaced is a feature that quietly
2920
- // stopped existing.
2921
- //
2922
- // The old objection — "a route serving archive files addressed by a path from the URL is the shape
2923
- // of the bypass that leaked reports" — is answered by construction rather than by declining to
2924
- // build it. The URL supplies ONE path segment, the run id, which is validated to be a directory
2925
- // name and nothing else. The FILENAME is read from that run's meta.json. There is no component of
2926
- // the served path a caller can influence, which is precisely what the report route already does.
2927
- if (parts[1] === "report" && parts.length === 4 && parts[3] === "audit.xlsx" && method === "GET") {
2928
- assertPrincipal(principal, { door: true });
2929
- const runId = parts[2];
2930
- if (!/^[A-Za-z0-9][A-Za-z0-9._-]{0,180}$/.test(runId) || runId.includes(".."))
2931
- return { status: 404, json: { error: "not_found" } };
2932
- const dir = join(poolRoot, runId);
2933
- let meta; try { meta = JSON.parse(readFileSync(join(dir, "meta.json"), "utf8")); } catch { return { status: 404, json: { error: "not_found" } }; }
2934
- const owner = meta.customerKey || "generic";
2935
- if (!mayReadRun(principal, { owner, organisation: meta.organisation ?? null })) return { status: 404, json: { error: "not_found" } };
2936
- // NOT staff-only any more. This route used to 404 a client on role alone — "the workbook is the
2937
- // working paper behind the opinion, not the opinion" — with the note that widening it was a
2938
- // disclosure decision and not one to make in passing. The owner made it on 2026-07-27, in the same
2939
- // ruling that retired the two-report split: one report for everyone, and every reader who owns the
2940
- // run may download its workbook. The ownership check two lines up is the boundary that matters and
2941
- // it is unchanged — a client still sees exactly their own accounts' runs and 404s on anyone else's.
2942
- //
2943
- // (An audit's other half: the link we emailed pointed at the archive path, which the edge stopped
2944
- // serving at the portal cutover, so no client had ever reached this gate to be refused by it. Both
2945
- // ends are fixed together — auditUrlFor() in publish/index.mjs is the other one.)
2946
- // (The held-run 404 that stood here is retired — one report, spec 2026-07-30 §5: ownership is
2947
- // the boundary, and the workbook now carries the machine-QC row every owner may read.)
2948
- // The name comes from the RUN, and is re-checked to be a plain basename even so: meta.json is a
2949
- // generated file, and "generated by us" is not the same as "safe to concatenate into a path".
2950
- const name = typeof meta.auditFile === "string" ? meta.auditFile : "";
2951
- if (!/^[A-Za-z0-9][A-Za-z0-9._-]*\.xlsx$/.test(name)) return { status: 404, json: { error: "not_found" } };
2952
- let bytes; try { bytes = readFileSync(join(dir, name)); } catch { return { status: 404, json: { error: "not_found" } }; }
2953
- auditLog(`audit-download run=${runId} by=${principal.email}`);
2954
- return { status: 200, file: {
2955
- body: bytes,
2956
- filename: name,
2957
- contentType: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
2958
- } };
2959
- }
2960
- // /portal/report/<runId>/… — ownership-checked client report; foreign = 404 (never 403)
2961
- if (parts[1] === "report" && parts.length >= 3 && method === "GET") {
2962
- assertPrincipal(principal, { door: true }); // door only — ownership is checked against the META below
2963
- const runId = parts[2];
2964
- // slug gate (review 2026-07-18: the old resolve-vs-resolve clause was a tautology): a runId is a
2965
- // pool dir NAME — one path segment, no dots-only names, nothing traversal-shaped ever reaches fs
2966
- if (!/^[A-Za-z0-9][A-Za-z0-9._-]{0,180}$/.test(runId) || runId.includes(".."))
2967
- return { status: 404, json: { error: "not_found" } };
2968
- const dir = join(poolRoot, runId);
2969
- let meta; try { meta = JSON.parse(readFileSync(join(dir, "meta.json"), "utf8")); } catch { return { status: 404, json: { error: "not_found" } }; }
2970
- const owner = meta.customerKey || "generic";
2971
- // Foreign is 404, never 403, and a Generic run is its organisation's — the same question the connector asks (LEAK-#9 alignment).
2972
- if (!mayReadRun(principal, { owner, organisation: meta.organisation ?? null })) return { status: 404, json: { error: "not_found" } };
2973
- // ONE REPORT PER MARK: `/portal/report/<runId>/` serves a run that has one document, and
2974
- // `/portal/report/<runId>/<slug>/` serves one name's document out of a batch. A batch has no
2975
- // run-level document at all — resolveReportFile returns null and this 404s — because serving mark
2976
- // one of eight as "the report" is the defect the fan-out removed. report.client.html stays
2977
- // retired (the cutover is done: clients.example.com serves through this same readReport
2978
- // preparation). A run you have rights to is always served; the old held-run 404 is deleted with
2979
- // the readiness state it enforced (spec 2026-07-30 §5 — the machine checks moved to the audit
2980
- // workbook and decide nothing here).
2981
- //
2982
- // The slug is matched against the run's OWN list, never used to build a path: `meta.reports` is
2983
- // the only source of a filename here, so a crafted segment can name nothing that is not already a
2984
- // document this run published.
2985
- const wantSlug = parts[3] && parts[3] !== "audit.xlsx" ? parts[3] : null;
2986
- const reportFile = resolveReportFile(meta, wantSlug);
2987
- if (!reportFile || !existsSync(join(dir, reportFile))) return { status: 404, json: { error: "not_found" } };
2988
- // poolRoot is passed so the report's own stylesheet can be inlined: it is linked RELATIVE to the
2989
- // archive (`../assets/chrome.css`) and 404s from under /portal/report/, which is what made every
2990
- // report render with the wrong fonts and a 300px Swiss flag. See portal-report.mjs.
2991
- // — NO FLAG CONTROL IS INJECTED, on this host or any other.
2992
- //
2993
- // `feedback` defaults OFF in prepareReportForEmbed, and this call site was the only opt-in in the
2994
- // tree. Retiring the control is therefore the ABSENCE of an argument rather than a new one — which
2995
- // is why nothing here reads a switch and nothing new was minted to hold one.
2996
- //
2997
- // The injection stays where it is (portal-report.mjs's FEEDBACK_CSS/FEEDBACK_JS, still exercised
2998
- // by portal-report.test.mjs's `feedback: true` arms). The owner ruled disable, not delete, so
2999
- // re-enabling the document half is this argument coming back.
3000
- return { status: 200, html: readReport(dir, { log: auditLog, staff: seesEverything(principal), poolRoot, file: reportFile }) };
3001
- }
3002
- // POST /portal/api/feedback — a lawyer flags one finding on a delivered report.
3003
- //
3004
- // This is the SECOND POST under /portal/api that spends nothing (compose/read is the other). It
3005
- // mints no confirmation token, queues nothing and changes no report: flagging is an observation
3006
- // ABOUT a delivered artifact, never an instruction to the engine.
3007
- //
3008
- // THE RULE THAT MAKES A FLAG EVIDENCE: every identifying field is read SERVER-SIDE from the run's
3009
- // own artifacts. The request supplies exactly three things — which run, which ordinal, and the
3010
- // reader's own words. Mark, band, disposition, matter, account, engine build and the excerpt all
3011
- // come from meta.json and report-data.json on disk. A client who could name the mark on a flag
3012
- // could label another customer's finding with it, which is how the predecessor system's Triage
3013
- // grouping was attacked (spec 61 critic finding 1) — and beyond the attack, a locator the reader
3014
- // typed is a locator that cannot be trusted to still point anywhere.
3015
- if (parts[1] === "api" && parts[2] === "feedback" && method === "POST") {
3016
- assertPrincipal(principal, { door: true });
3017
- // — RETIRED, 2026-08-20. It REFUSES; it does not disappear.
3018
- //
3019
- // AFTER assertPrincipal ON PURPOSE. A 410 says "this existed and is gone", which is exactly what
3020
- // a reader on a report published before today needs to be told and exactly what an unauthenticated
3021
- // prober should not learn. The door check runs first, so only a principal who could have used the
3022
- // control sees the answer.
3023
- //
3024
- // 410 RATHER THAN 404, which is what every other refusal in this handler returns. The difference
3025
- // is the audit log: `isAdminWrite` still names this path, so a POST here still files an outcome
3026
- // row, and a retired-endpoint row is a different fact from a not-yours row. If an old open tab is
3027
- // still clicking Flag, that is a thing worth being able to count.
3028
- //
3029
- // WHAT IS DELIBERATELY STILL BELOW THIS LINE: the whole resolver — the two-lane shape, the
3030
- // disposition read, the server-side-locator rule. The owner ruled "disable services and any code",
3031
- // and the acceptance criterion says re-enabling must be a switch and not a rebuild. Deleting 130
3032
- // lines of hard-won doctrine would have made it a rebuild.
3033
- if (!feedbackCapture) return { status: 410, json: { code: "retired", error: "Flagging a finding is switched off." } };
3034
- const runId = typeof body?.runId === "string" ? body.runId : "";
3035
- if (!/^[A-Za-z0-9][A-Za-z0-9._-]{0,180}$/.test(runId) || runId.includes(".."))
3036
- return { status: 404, json: { error: "not_found" } };
3037
- const dir = join(poolRoot, runId);
3038
- let meta; try { meta = JSON.parse(readFileSync(join(dir, "meta.json"), "utf8")); } catch { return { status: 404, json: { error: "not_found" } }; }
3039
- // Ownership, exactly as GET /portal/report/<id> checks it — foreign is 404, never 403, and
3040
- // a Generic run is its organisation's. A reader who cannot READ the report cannot flag it either.
3041
- const owner = meta.customerKey || "generic";
3042
- if (!mayReadRun(principal, { owner, organisation: meta.organisation ?? null })) return { status: 404, json: { error: "not_found" } };
3043
-
3044
- const verdict = typeof body?.verdict === "string" ? body.verdict : "";
3045
- if (!VERDICTS.has(verdict))
3046
- return { status: 400, json: { code: "bad_verdict", error: "A flag is good or bad." } };
3047
- const why = typeof body?.why === "string" ? body.why.trim() : "";
3048
- if (!why) return { status: 400, json: { code: "why_required", error: "Say what is right or wrong about it — a flag with no reason cannot be acted on." } };
3049
- if (why.length > MAX_WHY) return { status: 400, json: { code: "why_too_long", error: `That is longer than a note — keep it under ${MAX_WHY} characters.` } };
3050
-
3051
- // The ordinal names a POSITION; the finding's own facts are read back from the run so the flag
3052
- // survives the contiguous renumber every republish performs.
3053
- //
3054
- // — THE TWO LANES SHAPE report-data.json DIFFERENTLY, and the resolver used to know one.
3055
- //
3056
- // Clearance writes a top-level `findings[]` numbered once across the document. Knockout writes
3057
- // `marks.findings`, and restarts the ordinals at 1 FOR EACH MARK, so every mark in a
3058
- // batch has a finding 1. Reading `data.findings` on a knockout run therefore found nothing, and
3059
- // a flag on the knockout lane resolved to no facts at all — silently, because a flag with an
3060
- // unresolved ordinal is a legitimate state (a run published before report-data.json existed).
3061
- //
3062
- // Branching on the SHAPE ON DISK rather than on what the request sent is the load-bearing part.
3063
- // If a knockout flag arrives with no markIndex, this resolves NOTHING rather than falling back
3064
- // to an ordinal lookup that would silently attach a lawyer's correction to the FIRST mark's
3065
- // finding of that number. The issue is explicit that the wrong mark is worse than no mark.
3066
- const ordinal = Number.isInteger(body?.ordinal) && body.ordinal > 0 ? body.ordinal : null;
3067
- const markIndex = Number.isInteger(body?.markIndex) && body.markIndex >= 0 ? body.markIndex : null;
3068
- let found = null, searchedMark = null, foundLane = null, engineCommitOf = meta.engineCommit ?? null;
3069
- try {
3070
- const data = JSON.parse(readFileSync(join(dir, "report-data.json"), "utf8"));
3071
- engineCommitOf = data.engineCommit ?? engineCommitOf;
3072
- if (ordinal != null) {
3073
- if (Array.isArray(data.findings)) {
3074
- found = data.findings.find((f) => f.ordinal === ordinal) ?? null;
3075
- if (found) foundLane = "clearance";
3076
- } else if (Array.isArray(data.marks) && markIndex != null) {
3077
- const m = data.marks[markIndex] ?? null;
3078
- found = (m?.findings ?? []).find((f) => f.ordinal === ordinal) ?? null;
3079
- if (found) { foundLane = "knockout"; searchedMark = m?.name ?? null; }
3080
- }
3081
- }
3082
- } catch { /* a run published before report-data.json: the ordinal still locates, the facts do not */ }
3083
-
3084
- // — THE DISPOSITION COMES FROM findings.json, NOT FROM report-data.json.
3085
- //
3086
- // report-data.json is the CLIENT CUT by construction, and `disposition` is a placement key in the
3087
- // engine's own spelling — it stopped being served there in the same commit as this read. That
3088
- // deletion on its own would have started writing `null` into the locator of every flag captured
3089
- // from that moment on, and a flag is already-minted evidence a revert cannot repair. So the source
3090
- // moves rather than disappearing: publish copies the run's findings.json into the pool run dir
3091
- // (publish/index.mjs copyRO, both the strict and the lenient parse), which satisfies the rule this
3092
- // handler states above — every identifying field read SERVER-SIDE from the run's own artifacts.
3093
- //
3094
- // JOINED ON ORDINAL **AND** MARK, and it resolves NOTHING on a mismatch. report-data projects the
3095
- // same parsed findings array publish read from that same findings.json, so the ordinals are one
3096
- // set — but a wrong disposition on a lawyer's flag is worse than no disposition (the ruling on
3097
- // the batch lane, applied here), so the mark is checked rather than assumed.
3098
- //
3099
- // CLEARANCE ONLY, on purpose. publish/knockout.mjs emits no disposition, so `found?.disposition`
3100
- // was already null on that lane and this must not invent one from a differently-shaped file.
3101
- //
3102
- // ABSENT IS NULL, NEVER AN ERROR. A run with no findings.json (no register, or a top-level parse
3103
- // failure that published a structured-light report) resolves to null — the same honest "the
3104
- // ordinal locates, this fact does not" state a pre-report-data run records — and the flag still
3105
- // saves. The audit line below records whether it resolved, so the absence is visible rather than
3106
- // silent.
3107
- let disposition = null;
3108
- if (foundLane === "clearance") {
3109
- try {
3110
- const fj = JSON.parse(readFileSync(join(dir, "findings.json"), "utf8"));
3111
- const rec = (Array.isArray(fj?.findings) ? fj.findings : []).find((f) => f?.ordinal === ordinal) ?? null;
3112
- if (rec && String(rec.mark ?? "") === String(found.mark ?? "")) disposition = rec.disposition ?? null;
3113
- } catch { /* no findings.json in the run dir: the finding still locates, its posture does not */ }
3114
- }
3115
-
3116
- let rec;
3117
- try {
3118
- rec = appendFlag(feedbackDir(poolRoot), {
3119
- runId, verdict, why,
3120
- capturedBy: principal.email ?? null,
3121
- locator: {
3122
- ordinal,
3123
- // — the drill-through key the report page and the workbook both print
3124
- // (`<MARK> #<ordinal>`,), read off the resolved finding rather than composed here or
3125
- // taken from the request. It is what a human reading the flag store or a minted issue
3126
- // needs in order to find the row again, and on a batch it is the only thing that says
3127
- // WHICH mark. Null on the clearance lane, which has no such key.
3128
- ref: found?.ref ?? null,
3129
- // The searched mark on the knockout lane, where `mark` below is the CONFLICTING name.
3130
- searchedMark,
3131
- // Clearance calls the conflicting name `mark`; the knockout view calls it `name`.
3132
- mark: found?.mark ?? found?.name ?? null,
3133
- band: found?.band ?? null,
3134
- // — read above, from findings.json. NOT `found.disposition`: report-data.json no
3135
- // longer serves the placement key, and a `?? null` fallback onto it would read as working.
3136
- disposition,
3137
- section: typeof body?.section === "string" ? body.section.slice(0, 120) : null,
3138
- },
3139
- // The sentence the reader was looking at, from the RUN rather than the request — the same
3140
- // reason as the locator, and it keeps from putting attacker-authored prose in an issue.
3141
- excerpt: found ? (found.net ?? found.impact ?? null) : null,
3142
- run: {
3143
- account: owner, matter: meta.matter ?? null, markName: meta.markName ?? null,
3144
- product: meta.searchLevel ?? null, issuedAt: meta.issuedAt ?? null,
3145
- engineCommit: engineCommitOf, runDir: dir,
3146
- },
3147
- });
3148
- } catch (e) {
3149
- audit({ event: "report-feedback", by: principal.email, runId, ok: false, error: String(e?.message ?? e) });
3150
- return { status: 500, json: { code: "not_saved", error: "The flag was not saved. Nothing was lost from the report — try again." } };
3151
- }
3152
- // Length and location, never the words. A why is the lawyer's own reading of a client matter,
3153
- // and an audit log is a different disclosure surface from the flag store.
3154
- //
3155
- // — `dispositionResolved` rides here because the disposition now comes from a SECOND file:
3156
- // a clearance flag that located its finding but read no posture means findings.json was absent or
3157
- // did not agree, and a null that nobody can see is how the paired edit would have failed silently.
3158
- // Only on the lane that can carry one, so a knockout flag's honest null is not logged as a miss.
3159
- audit({
3160
- event: "report-feedback", by: principal.email, runId, account: owner, verdict, ordinal, markIndex,
3161
- resolved: Boolean(found), ...(foundLane === "clearance" ? { dispositionResolved: Boolean(disposition) } : {}),
3162
- chars: why.length, id: rec.id, ok: true, status: 201,
3163
- });
3164
- return { status: 201, json: { id: rec.id } };
3165
- }
3166
- // /portal/admin/* — the install-wide surfaces, for a person who sees everything, and People, for a
3167
- // person with Manage. Everyone else gets 404: the surface does not exist for them.
3168
- if (parts[1] === "admin") {
3169
- assertPrincipal(principal, parts[2] === "access" || parts[2] === "people"
3170
- ? { door: true, manage: true } : { door: true, everything: true });
3171
- if (parts[2] === "roster" && method === "GET") {
3172
- const profiles = await loadProfilesImpl();
3173
- // `generic` IS in the roster — this route is staff-only (asserted above), and untagged runs
3174
- // are real work that staff have to be able to select. Excluding it made those runs reachable
3175
- // by typing ?account=generic but invisible in the switcher, which is how they stop being
3176
- // looked at. The client-facing boundary is unchanged: /portal/api/runs and the report route
3177
- // both 404 `generic` for a non-staff principal.
3178
- // THE FACTS RIDE WITH THE NAME. The pick panel tells companies apart by industry, marketplace
3179
- // count and territories, and it renders for staff from here and for a client from /me. Shaping
3180
- // both through `companyFactsOf` is what stops the same company reading two ways depending on
3181
- // who signed in. Dynamic import deliberately: `profiles.mjs` captures the store directory at
3182
- // MODULE LOAD (see this file's note above), so it is never pulled in at our own load time.
3183
- const { companyFactsOf } = await import("./profiles.mjs");
3184
- // A company whose file would not load is named with its reason (staff-only route), never left out
3185
- // in silence: a switcher with one company where there were twenty-five reads as deleted work.
3186
- const unreadable = Array.isArray(profiles?.unreadable) ? profiles.unreadable.map((u) => ({ key: u.key, reason: u.reason })) : [];
3187
- return { status: 200, json: { customers: [...profiles.values()].map((p) => ({ key: p.key, name: p.name, ...companyFactsOf(p) })), ...(unreadable.length ? { unreadable } : {}) } };
3188
- }
3189
- // /portal/admin/config — what this deployment actually has switched on. Read from the SNAPSHOT,
3190
- // never from process.env: this process has no engine environment, so asking its own env would
3191
- // report every switch as off on a box where they are on — and this page, of all pages, would be
3192
- // believed.
3193
- if (parts[2] === "config" && method === "GET") {
3194
- // THE AUTH ROW IS READ LIVE, HERE, and not from the snapshot (ruled 2026-08-21).
3195
- // Everything else on this page is RENDERED from the snapshot. The reason recorded here used
3196
- // to be "because this process has no engine environment", and that has not been true since
3197
- // the owner's 2026-08-26 one-configuration-per-server-box ruling gave every unit the same
3198
- // `EnvironmentFile=%h/.env`. The rule stands on a better reason: the snapshot records what
3199
- // the ENGINE last ran under, and that is the fact this page reports. The portal's OWN door is
3200
- // the opposite case: this process reads PORTAL_AUTH_MODE and acts on it a few hundred lines
3201
- // below, so it is the authoritative source. Fed from process.env at the seam rather than
3202
- // inside authView, so the one process entitled to answer is visibly the one reading.
3203
- //
3204
- // AND THE ENVIRONMENT IS READ ONCE MORE, FOR ONE PURPOSE: to say whether
3205
- // the capture still DESCRIBES this box, never to supply a value. A deployment being
3206
- // configured runs nothing, so its capture cannot age into a warning while its contents drift
3207
- // — the disagreement is the signal the age never was. Degraded rather than fatal: a page that
3208
- // refused to render because it could not derive the live posture would be a worse answer than
3209
- // one that reports the capture and says it could not check it.
3210
- let live = null;
3211
- try { live = await livePosture(); } catch { live = null; }
3212
- return {
3213
- status: 200,
3214
- json: {
3215
- ...flagView(poolRoot, { live }),
3216
- auth: authView({
3217
- mode: process.env.PORTAL_AUTH_MODE,
3218
- oidcIssuer: process.env.PORTAL_OIDC_ISSUER,
3219
- team: process.env.CF_ACCESS_TEAM,
3220
- }),
3221
- },
3222
- };
3223
- }
3224
- // /portal/admin/families — the mark families a person has asserted.
3225
- //
3226
- // STAFF ONLY, and by construction rather than by filtering: it hangs off /portal/admin, which
3227
- // asserted staffOnly above and 404s for everyone else. That is a decision, not an oversight. A
3228
- // family name is staff shorthand for a brand line — "Aqua range" can name a launch a client has
3229
- // not announced — and a grouping a client can see but not edit or explain raises more questions
3230
- // than it answers. Revisit when clients have a reason to care; until then the client's list is
3231
- // exactly the mark list, which is what the browser falls back to when this 404s.
3232
- if (parts[2] === "families") {
3233
- const acct = query.account ?? null;
3234
- if (method === "GET") {
3235
- return { status: 200, json: familiesView(poolRoot, acct && acct !== "*" ? acct : null) };
3236
- }
3237
- if (method === "POST") {
3238
- const runIds = Array.isArray(body?.runIds) ? body.runIds.map(String) : [];
3239
- if (!runIds.length) return { status: 400, json: { error: "no runs given" } };
3240
-
3241
- // THE ACCOUNT COMES FROM THE RUNS, NEVER FROM THE BODY.
3242
- //
3243
- // Same rule as jobFor() above and for the same reason: a body-supplied owner is a body-supplied
3244
- // tenancy claim. Each run's account is read from its own meta.json, and a request naming runs
3245
- // from two owners is refused rather than silently filed under one of them — a family's band is
3246
- // rolled up across its marks, and bands are only comparable inside one framework.
3247
- const owners = new Set();
3248
- for (const runId of runIds) {
3249
- if (!/^[A-Za-z0-9][A-Za-z0-9._-]{0,180}$/.test(runId) || runId.includes("..")) {
3250
- return { status: 400, json: { error: "unknown run" } };
3251
- }
3252
- try {
3253
- const meta = JSON.parse(readFileSync(join(poolRoot, runId, "meta.json"), "utf8"));
3254
- owners.add(meta.customerKey || "generic");
3255
- } catch { return { status: 400, json: { error: "unknown run" } }; }
3256
- }
3257
- if (owners.size > 1) {
3258
- return { status: 400, json: { error: "those runs belong to different brand owners — a family covers one" } };
3259
- }
3260
- const account = [...owners][0];
3261
-
3262
- const r = body?.action === "ungroup"
3263
- ? ungroupRuns(poolRoot, { runIds })
3264
- : groupRuns(poolRoot, { name: body?.name, runIds, account });
3265
- if (r.error) return { status: 400, json: { error: r.error } };
3266
- // `status` so the success row and the refusal row above answer the same question the same
3267
- // way: reading down this log, every admin write now says how it ended.
3268
- audit({ event: `family-${body?.action === "ungroup" ? "ungroup" : "group"}`, by: principal.email,
3269
- account, family: r.familyId ?? null, runs: runIds.length, status: 200 });
3270
- return { status: 200, json: r };
3271
- }
3272
- return { status: 404, json: { error: "not_found" } };
3273
- }
3274
- // ── /portal/admin/retired — RETIRE, AND THE WAY BACK ──────────────────────────────────
3275
- //
3276
- // Staff could hide a run from every screen and had no way to do it except a terminal on the pool
3277
- // host. The sidecar, its reader and its semantics were all already here (scanAccountRuns, ~line
3278
- // 168); the only missing piece was a writer that is not a CLI.
3279
- //
3280
- // RETIRE, NEVER DELETE, and the issue is explicit about why: the pool is the published copy of
3281
- // real client matter, so an irreversible control does not belong on a staff screen. This route
3282
- // writes ONE file — archive-tags.json — and touches neither the run directory, the artifacts,
3283
- // nor the matter ledger. Removing the id brings the run back exactly as it was, which is what
3284
- // makes putting the control on the screen safe in the first place.
3285
- //
3286
- // The REPORT ROUTE STAYS OPEN on a retired run, deliberately and as before: retiring changes
3287
- // what the pool advertises, not who may read what, and the link is in mail we have already sent.
3288
- //
3289
- // STAFF ONLY BY CONSTRUCTION — it hangs off /portal/admin, which asserted staffOnly above. That
3290
- // is load-bearing here rather than incidental: retiring hides a run from the brand owner too, so
3291
- // it is a curation act by the firm, not a per-reader preference. The per-reader one is, and
3292
- // it deliberately uses a different store.
3293
- if (parts[2] === "retired") {
3294
- const acct = query.account ?? null;
3295
- const scoped = acct && acct !== "*" ? acct : null;
3296
- if (method === "GET") {
3297
- return { status: 200, json: { account: acct ?? "*",
3298
- runs: forRole(scanAccountRuns({ poolRoot, workspaceRoot, account: scoped, includeRetired: true, queueDirs: queueDirs() }), principal) } };
3299
- }
3300
- if (method === "POST") {
3301
- const runIds = Array.isArray(body?.runIds) ? body.runIds.map(String) : [];
3302
- if (!runIds.length) return { status: 400, json: { error: "no runs given" } };
3303
- const restore = body?.action === "restore";
3304
- // THE ACCOUNT COMES FROM THE RUNS, NEVER FROM THE BODY — the families rule above, for the
3305
- // same reason. Reading each run's own meta.json is also what proves the id names a real pool
3306
- // run: an unchecked id would let a typo write a tag for a run that does not exist, and that
3307
- // tag would sit in the sidecar for ever with nothing to explain it.
3308
- //
3309
- // A RESTORE MUST NOT REQUIRE A READABLE META. It is the way back, and the case where you
3310
- // most want it is the run whose directory has gone strange. So the id is validated as a
3311
- // shape, and the meta read is best-effort on that path.
3312
- //
3313
- // ── — RESOLVED THE WAY THE LIST RESOLVES IT ────────────────────
3314
- //
3315
- // This read `<pool>/<runId>/meta.json` directly, and a run that was STOPPED never publishes
3316
- // into the pool. So every press on a stopped run answered `400 unknown run` — the owner's
3317
- // report, twice in his own audit log — while the list that drew the button had read the
3318
- // run from the workspace. The endpoint and the screen were asking different questions about
3319
- // the same id.
3320
- //
3321
- // `resolveRunAccount` asks the LIST's question, pool first and the wider scan only when the
3322
- // pool cannot answer. The tenancy rule below is untouched: the account still comes from the
3323
- // run, never from the body.
3324
- const owners = new Set();
3325
- for (const runId of runIds) {
3326
- if (!/^[A-Za-z0-9][A-Za-z0-9._-]{0,180}$/.test(runId) || runId.includes("..")) {
3327
- return { status: 400, json: { error: "unknown run" } };
3328
- }
3329
- const found = resolveRunAccount({ poolRoot, workspaceRoot, queueDirs: queueDirs(), runId });
3330
- if (found) owners.add(found.account);
3331
- // A RESTORE MUST NOT REQUIRE A RESOLVABLE RUN — it is the way back, and the case you most
3332
- // want it in is the run whose directory has gone strange. Unchanged from what shipped.
3333
- else if (!restore) return { status: 400, json: { error: "unknown run" } };
3334
- }
3335
- const archived = updateArchived(poolRoot, (set) => {
3336
- for (const id of runIds) { if (restore) set.delete(id); else set.add(id); }
3337
- return set;
3338
- });
3339
- audit({ event: restore ? "run-restore" : "run-retire", by: principal.email,
3340
- account: owners.size === 1 ? [...owners][0] : null, runs: runIds.length, status: 200 });
3341
- return { status: 200, json: { retired: !restore, runs: runIds.length, archived: archived.size } };
3342
- }
3343
- return { status: 404, json: { error: "not_found" } };
3344
- }
3345
- // /portal/admin/access — who is granted what, and where an enrolment is half done.
3346
- if (parts[2] === "access" && method === "GET") {
3347
- const { loadProfiles } = await import("./profiles.mjs");
3348
- const companies = Object.fromEntries([...loadProfiles({ force: true }).values()].map((p) => [p.key, p.name ?? p.key]));
3349
- // Where to go to change this. The stat is done HERE rather than inside accessView because
3350
- // that function is pure and its tests call it with no filesystem at all; giving it IO would
3351
- // cost that for a filename and a date.
3352
- //
3353
- // BASENAME, never the full path. This route is staff-only, so it is not a leak to a client —
3354
- // but a full path bakes a deployment's layout into a JSON body that ends up in browser
3355
- // caches, screenshots and support tickets, and the filename is the whole useful part.
3356
- let grantsFile = null;
3357
- try {
3358
- const p = envFrom(process.env, "CLEAROTRON_ACCESS_FILE");
3359
- if (p) grantsFile = { name: basename(p), modifiedAt: new Date(statSync(p).mtimeMs).toISOString() };
3360
- } catch { /* reported as unknown; a failed stat must not take down the page that explains access */ }
3361
- // WHETHER AN ISSUED KEY CAN BE WITHDRAWN AT ALL. This used to be whether a revocation list was
3362
- // named in this process's environment, because a door with none named checked no list. Every door
3363
- // now reads the install's default list when none is named (isRevoked, shared/scope.mjs), and that
3364
- // is where a revocation from here is written, so keys can be withdrawn whenever this process has
3365
- // a revoker at all.
3366
- const keysRevocable = Boolean(revokeConnectorKeys);
3367
- return { status: 200, json: accessView({ grants: grantsHere, viewer: principal, companies, grantsFile, localSignIn, keysRevocable }) };
3368
- }
3369
- // /portal/admin/people — give someone access. Manage-gated above; everything else is decided here.
3370
- //
3371
- // THE ADDER'S OWN REACH BOUNDS WHAT THEY GIVE. A point outside it is a 404, exactly as asking to
3372
- // see it would be. Switches belong to the person, not to a point, so they are set only when the
3373
- // person's whole access sits inside the adder's; otherwise the points are added, the switches stay
3374
- // as they were, and the answer says which happened. Nobody sets their own switches, and nobody
3375
- // gives Run without holding it.
3376
- if (parts[2] === "people" && parts.length === 3 && method === "POST") {
3377
- // CODE AS ITS OWN FIELD. `error` carries a sentence on most routes here and a token on a few, so
3378
- // a client cannot tell the two apart by looking at it — and the one that reached the page as page
3379
- // copy was a token. A code the client reads as a FIELD is decidable; prose never is.
3380
- if (localSignIn) return { status: 409, json: { error: "local_sign_in", code: "local_sign_in" } };
3381
- if (!writeGrants) return { status: 503, json: { error: "cannot_write_grants" } };
3382
- const email = String(body?.email ?? "").trim().toLowerCase();
3383
- if (!email || email.indexOf("@") <= 0 || email.indexOf("@") !== email.lastIndexOf("@"))
3384
- return { status: 400, json: { error: "Enter one email address." } };
3385
- // ACCESS TO EVERYTHING IS NOT A POINT, and the handler used to treat it as one. The form draws
3386
- // "Everything on this Clearotron" only to somebody who holds it, and sent it as
3387
- // `{kind:"everything"}` alongside the organisation and company points; nothing here matched
3388
- // that kind, so it fell to the 404 below and the page rendered the refusal it keeps for a
3389
- // point outside the adder's reach — "You can only give access to what you have access to
3390
- // yourself" — to the one person on the install for whom that is false. The control had never
3391
- // worked. It lives under `people` as a switch, not in any organisation, so it is read as one.
3392
- const points = [];
3393
- let wantsEverything = false;
3394
- for (const a of Array.isArray(body?.access) ? body.access : []) {
3395
- const key = typeof a?.key === "string" ? a.key : "";
3396
- if (a?.kind === "everything" && seesEverything(principal)) wantsEverything = true;
3397
- else if (a?.kind === "organisation" && (principal.genericOrgs ?? []).includes(key)) points.push({ tenant: key });
3398
- else if (a?.kind === "company" && principal.accountOrgs?.[key]) points.push({ tenant: principal.accountOrgs[key], account: key });
3399
- else return { status: 404, json: { error: "not_found" } };
3400
- }
3401
- if (!points.length && !wantsEverything) return { status: 400, json: { error: "Choose at least one organisation or company this person may see." } };
3402
- const want = { run: body?.permissions?.run === true, manage: body?.permissions?.manage === true, everything: wantsEverything };
3403
- if (want.run && !mayRun(principal)) return { status: 400, json: { error: "You cannot give Run clearances without holding it yourself." } };
3404
- const existing = resolvePerson(email, grantsHere);
3405
- const setSwitches = email !== principal.email && (!existing || reachCovers(principal, existing));
3406
- // THE SWITCHES ARE WHERE ACCESS TO EVERYTHING IS WRITTEN, so a grant of it that cannot write
3407
- // them writes nothing at all — and `withPerson` would return unchanged grants and this route a
3408
- // 201 naming a person who gained nothing. Said instead of returned.
3409
- if (wantsEverything && !setSwitches)
3410
- return { status: 400, json: { error: "Access to everything is part of what a person may do, and that cannot be set from here for this address. Nothing was saved." } };
3411
- let next;
3412
- try { next = withPerson(grantsHere, { email, points, switches: want, setSwitches }); }
3413
- catch (e) { return { status: 400, json: { error: String(e?.message ?? e).slice(0, 300) } }; }
3414
- try { await writeGrants(next); }
3415
- catch (e) {
3416
- audit({ event: "person-add", by: principal.email, person: email, ok: false, error: String(e?.message ?? e).slice(0, 200) });
3417
- return { status: 500, json: { error: "The guest list could not be written, so nobody was added." } };
3418
- }
3419
- audit({ event: "person-add", by: principal.email, person: email, points: points.length, switchesApplied: setSwitches, ok: true, status: 201 });
3420
- const { loadProfiles } = await import("./profiles.mjs");
3421
- const companies = Object.fromEntries([...loadProfiles({ force: true }).values()].map((p) => [p.key, p.name ?? p.key]));
3422
- const person = accessView({ grants: next, viewer: principal, companies }).people.find((p) => p.email === email) ?? null;
3423
- return { status: 201, json: { person, switchesApplied: setSwitches } };
3424
- }
3425
-
3426
- // /portal/admin/people/change — change what somebody may do and see.
3427
- //
3428
- // THE DIFF IS COMPUTED HERE, FROM THE FILE, and never taken from the request. The page sends the
3429
- // state it wants; this reads what the file holds right now, narrows that to the part of the
3430
- // person the caller can see, and works out what to add and what to take away between the two. A
3431
- // page that had been open while somebody else was edited would otherwise write its own stale
3432
- // copy back over them — and the half it would overwrite is the half outside its own view, which
3433
- // nobody looking at either screen could see happen.
3434
- //
3435
- // NOBODY CHANGES THEMSELVES. The Add form already refuses to set the adder's own switches; this
3436
- // refuses the whole act, because a manager who can take their own Manage away can lock the
3437
- // install's last manager out of it with one press, and the way back is a text editor on the box.
3438
- if (parts[2] === "people" && parts[3] === "change" && parts.length === 4 && method === "POST") {
3439
- // CODE AS ITS OWN FIELD. `error` carries a sentence on most routes here and a token on a few, so
3440
- // a client cannot tell the two apart by looking at it — and the one that reached the page as page
3441
- // copy was a token. A code the client reads as a FIELD is decidable; prose never is.
3442
- if (localSignIn) return { status: 409, json: { error: "local_sign_in", code: "local_sign_in" } };
3443
- if (!writeGrants) return { status: 503, json: { error: "cannot_write_grants" } };
3444
- const email = String(body?.email ?? "").trim().toLowerCase();
3445
- if (email === principal.email) return { status: 400, json: { error: "You cannot change your own access. Somebody else who manages this install can." } };
3446
- const existing = resolvePerson(email, grantsHere);
3447
- const held = personPoints(grantsHere, email);
3448
- if (!existing && !held.listed && !held.points.length) return { status: 404, json: { error: "not_found" } };
3449
-
3450
- // What the caller can see of this person, and what they asked for — both in the same shape, so
3451
- // the difference between them is the change.
3452
- const inReach = (pt) => pt.account == null
3453
- ? (principal.genericOrgs ?? []).includes(pt.tenant)
3454
- : principal.accountOrgs?.[pt.account] === pt.tenant;
3455
- const mine = held.points.filter(inReach);
3456
- const want = [];
3457
- for (const a of Array.isArray(body?.access) ? body.access : []) {
3458
- const key = typeof a?.key === "string" ? a.key : "";
3459
- if (a?.kind === "organisation" && (principal.genericOrgs ?? []).includes(key)) want.push({ tenant: key, account: null });
3460
- else if (a?.kind === "company" && principal.accountOrgs?.[key]) want.push({ tenant: principal.accountOrgs[key], account: key });
3461
- else return { status: 404, json: { error: "not_found" } };
3462
- }
3463
- const id = (pt) => `${pt.tenant}/${pt.account ?? "*"}`;
3464
- const wanted = new Set(want.map(id));
3465
- const kept = new Set(mine.map(id));
3466
- const drop = mine.filter((pt) => !wanted.has(id(pt)));
3467
- const add = want.filter((pt) => !kept.has(id(pt)));
3468
- // TAKING THE WHOLE OF SOMEBODY'S VISIBLE ACCESS AWAY IS REMOVAL, and it has its own route, its
3469
- // own confirmation and its own revocation. Reaching it by unticking every row would do half of
3470
- // that act under the word "save".
3471
- if (!want.length) return { status: 400, json: { error: "Leave them at least one organisation or company, or remove them instead." } };
3472
-
3473
- const switches = { run: body?.permissions?.run === true, manage: body?.permissions?.manage === true,
3474
- everything: held.switches.everything };
3475
- if (switches.run && !held.switches.run && !mayRun(principal))
3476
- return { status: 400, json: { error: "You cannot give Run clearances without holding it yourself." } };
3477
- // Switches belong to the person and not to a point, so they are set only when the whole of this
3478
- // person sits inside the caller's reach. Otherwise the points move and the switches stay, and
3479
- // the answer says which happened — the same contract adding already has.
3480
- const setSwitches = reachCovers(principal, existing);
3481
- let next;
3482
- try {
3483
- next = drop.length ? withoutPerson(grantsHere, { email, points: drop }) : grantsHere;
3484
- next = withPerson(next, { email, points: add, switches, setSwitches });
3485
- } catch (e) { return { status: 400, json: { error: String(e?.message ?? e).slice(0, 300) } }; }
3486
- try { await writeGrants(next); }
3487
- catch (e) {
3488
- audit({ event: "person-change", by: principal.email, person: email, ok: false, error: String(e?.message ?? e).slice(0, 200) });
3489
- return { status: 500, json: { error: "The guest list could not be written, so nothing was changed." } };
3490
- }
3491
- audit({ event: "person-change", by: principal.email, person: email, added: add.length, removed: drop.length,
3492
- switchesApplied: setSwitches, ok: true, status: 200 });
3493
- const { loadProfiles } = await import("./profiles.mjs");
3494
- const companies = Object.fromEntries([...loadProfiles({ force: true }).values()].map((p) => [p.key, p.name ?? p.key]));
3495
- const person = accessView({ grants: next, viewer: principal, companies }).people.find((p) => p.email.toLowerCase() === email) ?? null;
3496
- return { status: 200, json: { person, switchesApplied: setSwitches, added: add.length, removed: drop.length } };
3497
- }
3498
-
3499
- // /portal/admin/people/remove — take their access away.
3500
- //
3501
- // HOW FAR IT REACHES IS THE SERVER'S ANSWER, NOT THE REQUEST'S. A caller who can see the whole of
3502
- // this person removes them from the install; a caller who can see one organisation's worth of
3503
- // them takes away that organisation and nothing else. The page draws a different button for each
3504
- // — it reads the same `covered` the view computes — but the request carries no scope to get
3505
- // wrong, so a stale page cannot ask for more than the person pressing it can see.
3506
- if (parts[2] === "people" && parts[3] === "remove" && parts.length === 4 && method === "POST") {
3507
- // CODE AS ITS OWN FIELD. `error` carries a sentence on most routes here and a token on a few, so
3508
- // a client cannot tell the two apart by looking at it — and the one that reached the page as page
3509
- // copy was a token. A code the client reads as a FIELD is decidable; prose never is.
3510
- if (localSignIn) return { status: 409, json: { error: "local_sign_in", code: "local_sign_in" } };
3511
- if (!writeGrants) return { status: 503, json: { error: "cannot_write_grants" } };
3512
- const email = String(body?.email ?? "").trim().toLowerCase();
3513
- if (email === principal.email) return { status: 400, json: { error: "You cannot remove your own access. Somebody else who manages this install can." } };
3514
- const existing = resolvePerson(email, grantsHere);
3515
- const held = personPoints(grantsHere, email);
3516
- if (!existing && !held.listed && !held.points.length) return { status: 404, json: { error: "not_found" } };
3517
- const whole = reachCovers(principal, existing);
3518
- const inReach = (pt) => pt.account == null
3519
- ? (principal.genericOrgs ?? []).includes(pt.tenant)
3520
- : principal.accountOrgs?.[pt.account] === pt.tenant;
3521
- const mine = held.points.filter(inReach);
3522
- if (!whole && !mine.length) return { status: 404, json: { error: "not_found" } };
3523
-
3524
- let next;
3525
- try { next = withoutPerson(grantsHere, whole ? { email, all: true } : { email, points: mine }); }
3526
- catch (e) { return { status: 400, json: { error: String(e?.message ?? e).slice(0, 300) } }; }
3527
-
3528
- // THE KEYS, AND ONLY ON A WHOLE REMOVAL. A narrowing leaves the person on the install with
3529
- // access somewhere else, and their connector key is how they reach that.
3530
- let keys = { checked: false };
3531
- if (whole) {
3532
- if (!revokeConnectorKeys) keys = { checked: false, note: "this installation cannot revoke issued keys from here" };
3533
- else {
3534
- try {
3535
- const { grants: written, ...said } = await revokeConnectorKeys({ email, grants: next });
3536
- next = written ?? next;
3537
- keys = { checked: true, ...said };
3538
- }
3539
- // A REVOCATION THAT FAILED MUST NOT LOOK LIKE ONE THAT HAPPENED, and it must not take the
3540
- // removal with it either: the access record is the gate every surface reads, and leaving
3541
- // it in place because a key file could not be appended would be the larger failure.
3542
- catch (e) { keys = { checked: true, failed: true, note: String(e?.message ?? e).slice(0, 200) }; }
3543
- }
3544
- }
3545
-
3546
- try { await writeGrants(next); }
3547
- catch (e) {
3548
- audit({ event: "person-remove", by: principal.email, person: email, ok: false, error: String(e?.message ?? e).slice(0, 200) });
3549
- return { status: 500, json: { error: "The guest list could not be written, so nothing was changed." } };
3550
- }
3551
- audit({ event: "person-remove", by: principal.email, person: email, scope: whole ? "install" : "organisations",
3552
- organisations: whole ? null : [...new Set(mine.map((pt) => pt.tenant))].length,
3553
- keysRevoked: keys.revoked ?? 0, keysUnrevokable: keys.lateArm ? (keys.jtis?.length ?? 0) : 0, ok: true, status: 200 });
3554
- return { status: 200, json: { removed: whole ? "install" : "organisations",
3555
- organisations: whole ? [] : [...new Set(mine.map((pt) => pt.tenant))], keys } };
3556
- }
3557
- // /portal/admin/observed — who has actually USED this instance lately, from the audit log.
3558
- //
3559
- // ALWAYS 200, even when the log is missing or unreadable, with an `available` boolean — the
3560
- // same contract flagView already uses for a missing snapshot. An error status here would trip
3561
- // the screen's load gate and blank a page whose real job is explaining access, in order to
3562
- // report that an optional extra was unavailable.
3563
- if (parts[2] === "observed" && method === "GET") {
3564
- return { status: 200, json: observedView({ auditPath }) };
3565
- }
3566
- return { status: 404, json: { error: "not_found" } };
3567
- }
1026
+ { const answer = await meRoutes(svc, request); if (answer !== undefined) return answer; } // portal-routes/me.mjs
1027
+ { const answer = await composeRoutes(svc, request); if (answer !== undefined) return answer; } // portal-routes/compose.mjs
1028
+ { const answer = await runRoutes(svc, request); if (answer !== undefined) return answer; } // portal-routes/run.mjs
1029
+ { const answer = await queueRoutes(svc, request); if (answer !== undefined) return answer; } // portal-routes/queue.mjs
1030
+ { const answer = await configRoutes(svc, request); if (answer !== undefined) return answer; } // portal-routes/config.mjs
1031
+ { const answer = await usageRoutes(svc, request); if (answer !== undefined) return answer; } // portal-routes/usage.mjs
1032
+ { const answer = await connectRoutes(svc, request); if (answer !== undefined) return answer; } // portal-routes/connect.mjs
1033
+ { const answer = await runsRoutes(svc, request); if (answer !== undefined) return answer; } // portal-routes/runs.mjs
1034
+ { const answer = await reportRoutes(svc, request); if (answer !== undefined) return answer; } // portal-routes/report.mjs
1035
+ { const answer = await feedbackRoutes(svc, request); if (answer !== undefined) return answer; } // portal-routes/feedback.mjs
1036
+ { const answer = await adminRoutes(svc, request); if (answer !== undefined) return answer; } // portal-routes/admin.mjs
3568
1037
  // GET /portal and every client-routed path below it are served by portal-static.mjs, ABOVE the
3569
1038
  // rate limiter and before this router ever sees them. Reaching here means a path the SPA handler
3570
1039
  // deliberately declined (an unknown /portal/api/* or /portal/report/* shape), which is a 404.
@@ -3736,6 +1205,24 @@ export function accountCapAdvice(posture) {
3736
1205
  + " --accounts <keys>` to make it two walls.";
3737
1206
  }
3738
1207
 
1208
+ /**
1209
+ * The boot line about the Start button's key. The usual key, which may start and stop searches for named accounts
1210
+ * until a known date, is said in plain words; any other key keeps the line that names each field, because what is
1211
+ * unusual about it is what the reader needs to see (measured in a stranger walk of a beta, 2026-11-10: a newcomer's
1212
+ * first `start` printed `ops token sub=portal verbs=start_run,stop_run accounts=generic`). Its first words stay
1213
+ * "trigger lane", the phrase a journal is searched by. PURE.
1214
+ */
1215
+ export function triggerLaneLine(posture, laneWired, expiry = "") {
1216
+ const verbs = [...(posture?.verbs ?? [])].sort().join(",");
1217
+ const plain = posture?.readable && posture.sub === "portal" && verbs === "start_run,stop_run" && posture.accountCapped
1218
+ && posture.accounts.length > 0 && posture.expiresAt && !posture.expired && posture.daysLeft >= 0;
1219
+ if (plain) {
1220
+ return `trigger lane${laneWired ? "" : " (NOT WIRED — see above)"}: the Start button may start and stop searches for `
1221
+ + `${posture.accounts.join(", ")}; its key expires ${posture.expiresAt.slice(0, 10)} (${posture.daysLeft} days)`;
1222
+ }
1223
+ return `trigger lane${laneWired ? "" : " (NOT WIRED — see above)"}: ops token sub=${posture?.sub ?? "-"} verbs=${posture?.verbs?.join(",") ?? "(full ops)"} accounts=${posture?.accounts?.join(",") ?? "UNCAPPED (every account)"}${expiry}${posture?.readable ? "" : " — token payload unreadable, posture unknown"}`;
1224
+ }
1225
+
3739
1226
  export function opsTokenPosture(token, { now = Date.now() } = {}) {
3740
1227
  const none = { readable: false, scope: null, sub: null, verbs: null, accounts: null, accountCapped: false,
3741
1228
  expiresAt: null, daysLeft: null, expired: false, implausibleExp: false };
@@ -3879,7 +1366,6 @@ async function readJsonBody(req, limitBytes = 131072) {
3879
1366
  });
3880
1367
  }
3881
1368
 
3882
-
3883
1369
  /**
3884
1370
  * The instance a refusal page names: its organisation when one is configured, otherwise the host of the
3885
1371
  * sign-in service it sends people to (the OIDC issuer, or the Access team's own domain, derived as the
@@ -4103,7 +1589,7 @@ ${error ? `<p class="err">${escHtml(error)}</p>` : ""}
4103
1589
  <button type="submit">Sign in</button>
4104
1590
  </form>
4105
1591
  <details class="fold"><summary><span>Administrator help</span><svg class="chev" width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.75" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true" focusable="false"><path d="m9 18 6-6-6-6"/></svg></summary>
4106
- <p class="hint">The passphrase was printed once when this ${escHtml(BRAND.name)} first started. Lost it? Run
1592
+ <p class="hint">The passphrase was printed once, when this ${escHtml(BRAND.name)} first started or was last reset. Lost it? Run
4107
1593
  <code>${escHtml(reset)}</code> on the machine running this portal. It prints a new one, once, for the same user.</p>
4108
1594
  <p class="hint">A key from <code>${escHtml(bareInvocation("key"))} issue</code> is for an AI assistant, not for this page.</p>
4109
1595
  <p class="hint">To add people, put it behind a login system such as your company single sign-on. <a href="${escHtml(LOGIN_IN_FRONT_DOC)}" target="_blank" rel="noreferrer">How to set that up</a></p>
@@ -5015,7 +2501,7 @@ const PORT = PORT_CHOICE.port;
5015
2501
  const expiry = posture.expiresAt ? ` expires=${posture.expiresAt.slice(0, 10)} (${posture.daysLeft}d)` : " expires=UNKNOWN";
5016
2502
  // PREFIXED WHEN THE LANE IS DEAD, so this line cannot be read on its own as evidence of a working
5017
2503
  // lane — a journal is skimmed by grepping one phrase, and the phrase people grep is this one.
5018
- log(`trigger lane${laneWired ? "" : " (NOT WIRED — see above)"}: ops token sub=${posture.sub ?? "-"} verbs=${posture.verbs?.join(",") ?? "(full ops)"} accounts=${posture.accounts?.join(",") ?? "UNCAPPED (every account)"}${expiry}${posture.readable ? "" : " — token payload unreadable, posture unknown"}`);
2504
+ log(triggerLaneLine(posture, laneWired, expiry));
5019
2505
  if (!posture.accountCapped) {
5020
2506
  // ── THE PRINTED COMMAND IS DERIVED FROM THE TOKEN IN HAND ──────────────────────────────────────
5021
2507
  //