clearotron 0.5.1 → 0.6.0-beta.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (390) hide show
  1. package/.env.example +7 -7
  2. package/INSTALL.md +10 -10
  3. package/QUICKSTART.md +6 -6
  4. package/README.md +2 -2
  5. package/THIRD-PARTY-NOTICES.md +4 -4
  6. package/bin/README.md +2 -2
  7. package/bin/clearotron.mjs +1 -1
  8. package/bin/connect.mjs +1 -1
  9. package/bin/disconnect.mjs +1 -1
  10. package/bin/example.mjs +2 -2
  11. package/bin/grant.mjs +1 -1
  12. package/bin/onboard.mjs +78 -23
  13. package/bin/start.mjs +88 -33
  14. package/bin/update.mjs +13 -3
  15. package/build-info.json +2 -2
  16. package/docs/DELIVERY.md +1 -1
  17. package/docs/PORTAL.md +1 -1
  18. package/docs/RELEASES.md +1 -1
  19. package/docs/architecture/02-architecture.md +10 -2
  20. package/docs/architecture/03-run-lifecycle.md +6 -2
  21. package/docs/architecture/04-configuration-reference.md +3 -3
  22. package/docs/architecture/05-config-governance.md +5 -4
  23. package/docs/architecture/08-development-guide.md +4 -4
  24. package/docs/architecture/09-security-and-data.md +1 -1
  25. package/{driver/skills/clearance-search/SKILL.md → docs/architecture/retired-manuals/clearance-search-spine.md} +17 -30
  26. package/{driver/skills/clearance-search/templates/email/generic.md → docs/architecture/retired-manuals/email-generic.md} +1 -1
  27. package/{driver/skills/clearance-search → docs/architecture/retired-manuals}/template-formatting.md +3 -4
  28. package/docs/configuration.md +1 -1
  29. package/docs/decisions/0002-no-dark-functionality.md +5 -0
  30. package/driver/CHANGELOG.md +69 -0
  31. package/driver/README.md +11 -1
  32. package/driver/accepted-order.mjs +13 -5
  33. package/driver/attempt-rows.mjs +64 -0
  34. package/driver/attributed-span.mjs +1 -1
  35. package/driver/authority-trees.mjs +1 -1
  36. package/driver/band-shape.mjs +21 -3
  37. package/driver/best-draft.mjs +3 -3
  38. package/driver/blind-frame-record.mjs +2 -2
  39. package/driver/cancel.mjs +3 -2
  40. package/driver/carry-through.mjs +2 -2
  41. package/driver/citation-census.json +3 -3
  42. package/driver/clearance-variants-record.mjs +4 -10
  43. package/driver/common-law-coverage-status.mjs +3 -3
  44. package/driver/common-law-receipts.mjs +2 -2
  45. package/driver/commonlaw-carry-floor.json +3 -3
  46. package/driver/compare.mjs +1 -1
  47. package/driver/config-inventory.mjs +6 -79
  48. package/driver/consumption-ledger.mjs +2 -1
  49. package/driver/contract-arm2-baseline.json +2 -3
  50. package/driver/contract-dictation-registry.mjs +5 -0
  51. package/driver/contract-e3-backlog.mjs +45 -66
  52. package/driver/contract-e3-baseline.json +16 -16
  53. package/driver/contract-vocabulary.mjs +8 -6
  54. package/driver/corrections-feedforward.mjs +3 -1
  55. package/driver/coverage-form-io.mjs +7 -8
  56. package/driver/coverage-tool.mjs +1 -1
  57. package/driver/declination-tool.mjs +2 -2
  58. package/driver/degraded-parts.mjs +9 -9
  59. package/driver/demo-container.mjs +5 -4
  60. package/driver/demo-posture.mjs +17 -0
  61. package/driver/deploy-live-run-guard.mjs +19 -7
  62. package/driver/derived-state.mjs +2 -2
  63. package/driver/dev-portal.mjs +2 -1
  64. package/driver/dispatch-record.mjs +1 -1
  65. package/driver/disposition-tool.mjs +2 -1
  66. package/driver/doubt-closure-tool.mjs +2 -2
  67. package/driver/driver.config.mjs +35 -724
  68. package/driver/e2e-rounds.mjs +3 -4
  69. package/driver/engine/CONTRACT.md +3 -0
  70. package/driver/engine/README.md +2 -0
  71. package/driver/engine/anthropic-agent.mjs +13 -42
  72. package/driver/engine/auth.mjs +74 -0
  73. package/driver/engine/child-record.mjs +1 -1
  74. package/driver/engine/deny-authority-write.mjs +2 -2
  75. package/driver/engine/jx-turn.mjs +10 -2
  76. package/driver/engine/mcp/README.md +1 -1
  77. package/driver/engine/mcp/band-server.mjs +20 -13
  78. package/driver/engine/mcp/codex-config.mjs +1 -1
  79. package/driver/engine/mcp/declination-server.mjs +2 -3
  80. package/driver/engine/mcp/dispositions-server.mjs +3 -3
  81. package/driver/engine/mcp/gather-config.mjs +24 -19
  82. package/driver/engine/mcp/grid-provenance.mjs +1 -1
  83. package/driver/engine/mcp/held-answers.mjs +5 -5
  84. package/driver/engine/mcp/perplexity-server.mjs +16 -7
  85. package/driver/engine/mcp/recording-server.mjs +7 -6
  86. package/driver/engine/mcp/register-server.mjs +29 -0
  87. package/driver/engine/mcp/stdio-server.mjs +5 -5
  88. package/driver/engine/mcp/supplemental.mjs +9 -9
  89. package/driver/engine/openai-agent.mjs +5 -2
  90. package/driver/engine/registry.mjs +103 -0
  91. package/driver/engine/run-choices.mjs +162 -0
  92. package/driver/engine/stamps.mjs +35 -0
  93. package/driver/enqueue-schema.mjs +4 -4
  94. package/driver/envelope-settle.mjs +3 -2
  95. package/driver/feedback-issues.mjs +1 -1
  96. package/driver/feedback-mint.mjs +3 -2
  97. package/driver/feedback-store.mjs +3 -2
  98. package/driver/findings-model.mjs +1 -1
  99. package/driver/flag-snapshot.mjs +5 -4
  100. package/driver/floor-duty.mjs +3 -3
  101. package/driver/foreign-record-links.mjs +1 -1
  102. package/driver/frame-diff-record.mjs +2 -8
  103. package/driver/framework.mjs +1 -1
  104. package/driver/gate-metrics.mjs +10 -11
  105. package/driver/gateway.mjs +220 -839
  106. package/driver/goods-evidence.mjs +26 -14
  107. package/driver/jx-lanes.mjs +3 -3
  108. package/driver/jx-units.mjs +31 -37
  109. package/driver/jx.mjs +44 -59
  110. package/driver/knockout-assess-record.mjs +3 -3
  111. package/driver/knockout-caveats.mjs +21 -0
  112. package/driver/knockout-correction-record.mjs +58 -28
  113. package/driver/knockout-frame-record.mjs +2 -2
  114. package/driver/knockout-register-read.mjs +38 -21
  115. package/driver/knockout-register-record.mjs +5 -6
  116. package/driver/knockout-review-record.mjs +12 -11
  117. package/driver/ladder/model-gauge.mjs +88 -0
  118. package/driver/ladder/next-rung.mjs +296 -0
  119. package/driver/ladder/rescue.mjs +146 -0
  120. package/driver/ladder/stage-tools.mjs +57 -0
  121. package/driver/ladder/turn-failure.mjs +166 -0
  122. package/driver/log.mjs +2 -2
  123. package/driver/matter-frame-record.mjs +4 -4
  124. package/driver/methodology-witness.mjs +2 -2
  125. package/driver/named-band.mjs +60 -3
  126. package/driver/narrative-refutation-record.mjs +145 -42
  127. package/driver/one-build-per-run.mjs +62 -0
  128. package/driver/outbox-backoff.mjs +4 -4
  129. package/driver/owner-screen.mjs +0 -10
  130. package/driver/owner-use-check.mjs +2 -28
  131. package/driver/package.json +1 -1
  132. package/driver/partial-payload-baseline.json +1 -1
  133. package/driver/parts-not-completed.mjs +1 -1
  134. package/driver/pipeline-knockout.mjs +1015 -1001
  135. package/driver/pipeline.mjs +714 -9351
  136. package/driver/placement-decisions.mjs +2 -2
  137. package/driver/placement-form-io.mjs +7 -9
  138. package/driver/placement-union.mjs +0 -6
  139. package/driver/plan-stability.mjs +7 -10
  140. package/driver/portal-acks.mjs +3 -2
  141. package/driver/portal-confirmation.mjs +48 -0
  142. package/driver/portal-families.mjs +3 -2
  143. package/driver/portal-local-auth.mjs +1 -2
  144. package/driver/portal-routes/README.md +24 -0
  145. package/driver/portal-routes/admin.mjs +425 -0
  146. package/driver/portal-routes/compose.mjs +66 -0
  147. package/driver/portal-routes/config.mjs +118 -0
  148. package/driver/portal-routes/connect.mjs +283 -0
  149. package/driver/portal-routes/feedback.mjs +178 -0
  150. package/driver/portal-routes/me.mjs +165 -0
  151. package/driver/portal-routes/queue.mjs +64 -0
  152. package/driver/portal-routes/report.mjs +106 -0
  153. package/driver/portal-routes/run.mjs +508 -0
  154. package/driver/portal-routes/runs.mjs +127 -0
  155. package/driver/portal-routes/usage.mjs +82 -0
  156. package/driver/portal-runs.mjs +588 -0
  157. package/driver/portal-service.mjs +82 -2593
  158. package/driver/portal-static.mjs +3 -1
  159. package/driver/predelivery-lint.mjs +101 -9
  160. package/driver/production-pool-guard.mjs +1 -1
  161. package/driver/profiles.mjs +5 -4
  162. package/driver/progress.mjs +29 -24
  163. package/driver/publish/README.md +10 -5
  164. package/driver/publish/archive-tags.mjs +3 -2
  165. package/driver/publish/demo-marking.mjs +2 -2
  166. package/driver/publish/index.mjs +215 -140
  167. package/driver/publish/knockout.mjs +153 -107
  168. package/driver/publish/office-record-links.mjs +22 -0
  169. package/driver/publish/parse.mjs +20 -5
  170. package/driver/publish/pool-admin.mjs +9 -3
  171. package/driver/publish/render.mjs +11 -3
  172. package/driver/publish/report-dates.mjs +3 -4
  173. package/driver/publish/report-registry.mjs +7 -10
  174. package/driver/publish/seed-pool.mjs +3 -2
  175. package/driver/publish/shell.mjs +106 -0
  176. package/driver/publish/templates/report.css +9 -7
  177. package/driver/queue-order.mjs +4 -3
  178. package/driver/record-carry.mjs +0 -9
  179. package/driver/record-discard.mjs +1 -4
  180. package/driver/record-fold.mjs +3 -3
  181. package/driver/record-goods.mjs +79 -23
  182. package/driver/reference-score.mjs +2 -3
  183. package/driver/register-capabilities.mjs +0 -6
  184. package/driver/register-count.mjs +3 -2
  185. package/driver/register-digest-record.mjs +7 -7
  186. package/driver/register-fixture-marker.mjs +3 -3
  187. package/driver/register-plan.mjs +2 -2
  188. package/driver/register-records.mjs +2 -2
  189. package/driver/register-taint.mjs +3 -3
  190. package/driver/register-unit-record.mjs +48 -9
  191. package/driver/register-unreachable.mjs +4 -3
  192. package/driver/registry-fidelity.mjs +79 -34
  193. package/driver/repair-composers.mjs +14 -9
  194. package/driver/repair-digest.mjs +4 -6
  195. package/driver/repair-scope.mjs +3 -3
  196. package/driver/repair-targets.mjs +24 -9
  197. package/driver/repairs.mjs +44 -58
  198. package/driver/replay-archive.mjs +7 -7
  199. package/driver/report-card-record.mjs +3 -3
  200. package/driver/report-overview-record.mjs +4 -4
  201. package/driver/research-answers.mjs +38 -6
  202. package/driver/research-checks.mjs +4 -4
  203. package/driver/result-noun-fields.mjs +28 -11
  204. package/driver/review-addresses.mjs +163 -0
  205. package/driver/rule-shape.mjs +1 -1
  206. package/driver/run-delivered.mjs +340 -0
  207. package/driver/run-economics.mjs +8 -26
  208. package/driver/run-failed.mjs +545 -0
  209. package/driver/run-integrity.mjs +1 -1
  210. package/driver/run-outcome.mjs +314 -0
  211. package/driver/run-park.mjs +23 -0
  212. package/driver/run-quote.mjs +32 -0
  213. package/driver/run-record.mjs +352 -0
  214. package/driver/run-requirements.mjs +22 -0
  215. package/driver/run-shell.mjs +55 -0
  216. package/driver/runner.mjs +71 -33
  217. package/driver/saved-register-pages.mjs +4 -4
  218. package/driver/score-redaction.mjs +2 -2
  219. package/driver/search-policy.mjs +12 -13
  220. package/driver/settle-stamp.mjs +4 -3
  221. package/driver/skeptic-record.mjs +2 -2
  222. package/driver/skeptic-search.mjs +1 -1
  223. package/driver/skills/README.md +7 -7
  224. package/driver/skills/blind-frame/SKILL.md +1 -2
  225. package/driver/skills/case-law-citation/SKILL.md +9 -37
  226. package/driver/skills/case-law-citation/sources/courtlistener.md +1 -3
  227. package/driver/skills/case-law-citation/sources/eurlex.md +8 -11
  228. package/driver/skills/case-law-citation/sources/legaldatahunter.md +1 -1
  229. package/driver/skills/clearance-common-law/SKILL.md +45 -111
  230. package/driver/skills/clearance-common-law/perplexity-prompts.md +7 -79
  231. package/driver/skills/clearance-register/SKILL.md +15 -33
  232. package/driver/skills/clearance-register/digest.md +35 -96
  233. package/driver/skills/clearance-register/providers/clarivate.md +2 -2
  234. package/driver/skills/clearance-register/providers/corsearch.md +5 -5
  235. package/driver/skills/clearance-register/providers/euipo.md +1 -2
  236. package/driver/skills/clearance-register/providers/free-tier.md +0 -19
  237. package/driver/skills/clearance-register/providers/signa.md +6 -25
  238. package/driver/skills/clearance-register/providers/uspto-local.md +0 -24
  239. package/driver/skills/clearance-register/register-recipes.md +8 -15
  240. package/driver/skills/clearance-register/status-rules.md +6 -24
  241. package/driver/skills/clearance-register/unit.md +11 -20
  242. package/driver/skills/clearance-search/delivery-contract.md +24 -120
  243. package/driver/skills/clearance-search/field-doctrine-pharma.md +1 -5
  244. package/driver/skills/clearance-search/firm-wide-reasoning.md +24 -43
  245. package/driver/skills/clearance-search/phase2-execution.md +29 -77
  246. package/driver/skills/clearance-search/report-prose.md +3 -4
  247. package/driver/skills/clearance-search/risk-framework-demo.md +1 -1
  248. package/driver/skills/clearance-search/risk-framework-triage.manifest.json +3 -3
  249. package/driver/skills/clearance-search/risk-framework-triage.md +7 -9
  250. package/driver/skills/clearance-search/risk-framework.manifest.json +1 -1
  251. package/driver/skills/clearance-search/risk-framework.md +1 -1
  252. package/driver/skills/clearance-search/synthesis-rules.md +30 -107
  253. package/driver/skills/clearance-search/worked-examples.md +5 -5
  254. package/driver/skills/clearance-variants/SKILL.md +46 -45
  255. package/driver/skills/clearance-variants/transliteration-scripts.md +4 -4
  256. package/driver/skills/frame-diff/SKILL.md +1 -1
  257. package/driver/skills/knockout-assess/SKILL.md +6 -14
  258. package/driver/skills/knockout-frame/SKILL.md +1 -1
  259. package/driver/skills/matter-frame/SKILL.md +7 -12
  260. package/driver/skills/matter-frame/watchlist-reference.md +1 -4
  261. package/driver/skills/narrative-refutation/SKILL.md +20 -30
  262. package/driver/skills/placement-inquiry/SKILL.md +10 -20
  263. package/driver/skills-store-provenance.mjs +1 -1
  264. package/driver/stage-context.mjs +32 -35
  265. package/driver/stage-freshness.mjs +127 -11
  266. package/driver/stages-knockout.mjs +49 -22
  267. package/driver/stages.mjs +89 -288
  268. package/driver/status-snapshot.mjs +2 -1
  269. package/driver/steps/correction-cycle.mjs +311 -0
  270. package/driver/steps/corrections.mjs +644 -0
  271. package/driver/steps/delivery.mjs +1287 -0
  272. package/driver/steps/frame-comparison.mjs +927 -0
  273. package/driver/steps/intake.mjs +84 -0
  274. package/driver/steps/open-run.mjs +419 -0
  275. package/driver/steps/overview-and-cards.mjs +899 -0
  276. package/driver/steps/placement-and-digest.mjs +23 -0
  277. package/driver/steps/register-sweep.mjs +1563 -0
  278. package/driver/steps/skeptic-and-follow-up.mjs +836 -0
  279. package/driver/steps/synthesis.mjs +261 -0
  280. package/driver/steps/verdict-gate.mjs +968 -0
  281. package/driver/suite-census.json +456 -96
  282. package/driver/surface-exit-verdict.mjs +0 -8
  283. package/driver/synthesis-record.mjs +72 -6
  284. package/driver/terminal-clamp.mjs +10 -0
  285. package/driver/tokens.mjs +8 -62
  286. package/driver/tool-calls.mjs +2 -2
  287. package/driver/unexecuted-asserts.json +2 -2
  288. package/driver/unit-state-verdict.mjs +1 -1
  289. package/driver/usage-ledger.mjs +2 -1
  290. package/driver/verify-knockout.mjs +20 -35
  291. package/driver/verify.mjs +47 -36
  292. package/driver/web-grid.mjs +3 -4
  293. package/driver/whatif-memo-run.mjs +2 -2
  294. package/driver/whatif-queue.mjs +4 -3
  295. package/driver/withheld-families.mjs +14 -15
  296. package/driver/worker-heartbeat.mjs +3 -2
  297. package/driver/write-up-form.mjs +0 -3
  298. package/mcp-server/CHANGELOG.md +8 -0
  299. package/mcp-server/http-server.mjs +11 -12
  300. package/mcp-server/lib/brief.mjs +22 -4
  301. package/mcp-server/lib/events.mjs +2 -2
  302. package/mcp-server/lib/evidence.mjs +3 -2
  303. package/mcp-server/lib/findings.mjs +2 -1
  304. package/mcp-server/lib/knockout.mjs +9 -10
  305. package/mcp-server/lib/ops.mjs +9 -9
  306. package/mcp-server/lib/runs.mjs +9 -10
  307. package/mcp-server/lib/trace.mjs +1 -1
  308. package/mcp-server/lib/whatif.mjs +2 -3
  309. package/mcp-server/package.json +1 -1
  310. package/mcp-server/server.mjs +5 -5
  311. package/node_modules/buffers/package.json +1 -1
  312. package/package.json +2 -1
  313. package/portal-ui/dist/assets/{index-fPqAU0sx.js → index-CYaO2ygd.js} +26 -14
  314. package/portal-ui/dist/assets/{index-AtB9ZpDH.css → index-izLa9apq.css} +2 -2
  315. package/portal-ui/dist/index.html +4 -4
  316. package/portal-ui/package.json +3 -3
  317. package/providers/README.md +1 -1
  318. package/providers/_shared/answer-memory.mjs +4 -5
  319. package/providers/_shared/execute-plan.mjs +48 -1
  320. package/providers/_shared/records-from-search.mjs +46 -0
  321. package/providers/clarivate/README.md +2 -2
  322. package/providers/clarivate/src/adapter.js +147 -0
  323. package/providers/clarivate/src/core.js +1 -14
  324. package/{driver/engine/mcp/clarivate-server.mjs → providers/clarivate/src/mount.js} +5 -10
  325. package/providers/corsearch/README.md +3 -3
  326. package/providers/corsearch/src/adapter.js +80 -0
  327. package/providers/corsearch/src/core.js +14 -11
  328. package/{driver/engine/mcp/corsearch-server.mjs → providers/corsearch/src/mount.js} +5 -10
  329. package/providers/euipo/README.md +2 -2
  330. package/providers/euipo/src/adapter.js +85 -0
  331. package/providers/euipo/src/core.js +1 -1
  332. package/providers/euipo/src/euipo-client.js +1 -2
  333. package/{driver/engine/mcp/euipo-server.mjs → providers/euipo/src/mount.js} +5 -10
  334. package/providers/free-tier/README.md +2 -2
  335. package/providers/free-tier/src/adapter.js +127 -0
  336. package/{driver/engine/mcp/free-tier-server.mjs → providers/free-tier/src/mount.js} +5 -10
  337. package/providers/jx-subclass/coverage.mjs +1 -6
  338. package/providers/jx-subclass/score-truth.mjs +2 -1
  339. package/providers/oauth-mcp-bridge/CHANGELOG.md +8 -0
  340. package/providers/oauth-mcp-bridge/package.json +1 -1
  341. package/providers/perplexity/src/core.js +2 -2
  342. package/providers/signa/README.md +2 -2
  343. package/providers/signa/src/adapter.js +157 -0
  344. package/providers/signa/src/capabilities.js +0 -3
  345. package/providers/signa/src/core.js +2 -2
  346. package/{driver/engine/mcp/signa-server.mjs → providers/signa/src/mount.js} +7 -12
  347. package/providers/signa/src/offices.generated.js +17 -15
  348. package/providers/uspto-local/README.md +1 -1
  349. package/providers/uspto-local/bin/verify-index.mjs +1 -1
  350. package/providers/uspto-local/src/adapter.js +75 -0
  351. package/{driver/engine/mcp/uspto-local-server.mjs → providers/uspto-local/src/mount.js} +5 -10
  352. package/scripts/band-shape-probe.mjs +2 -2
  353. package/scripts/citation-line-check.mjs +7 -7
  354. package/scripts/compare.mjs +1 -1
  355. package/scripts/dead-names.mjs +2 -2
  356. package/scripts/e2e-first-time.mjs +19 -7
  357. package/scripts/e2e.mjs +13 -13
  358. package/scripts/engine-probe.mjs +1 -1
  359. package/scripts/env-audit.mjs +7 -4
  360. package/scripts/env-classify.mjs +5 -1
  361. package/scripts/feedback-mint.mjs +1 -1
  362. package/scripts/freeze-example-run.mjs +7 -7
  363. package/scripts/mint-suite-census.mjs +2 -2
  364. package/scripts/nightly-notice.mjs +1 -1
  365. package/scripts/release-cut-decision.mjs +7 -2
  366. package/scripts/release-note-required.mjs +26 -9
  367. package/scripts/release-notes-lint.mjs +3 -2
  368. package/scripts/release-version-pr-checks.mjs +1 -1
  369. package/scripts/render-check.mjs +1 -1
  370. package/scripts/settings-render-check.mjs +23 -3
  371. package/scripts/test-run.mjs +5 -5
  372. package/scripts/travelling-predicates.mjs +1 -1
  373. package/scripts/undeclared-field-census.mjs +1 -1
  374. package/scripts/unexecuted-asserts.mjs +3 -3
  375. package/scripts/verify-publishable.mjs +1 -1
  376. package/shared/client-door.mjs +1 -1
  377. package/shared/connect-clients.mjs +1 -1
  378. package/shared/connector-signin-probe.mjs +1 -1
  379. package/shared/customer-store.mjs +3 -2
  380. package/shared/env-aliases.mjs +1 -1
  381. package/shared/invocation.mjs +14 -2
  382. package/shared/names-in-force.mjs +2 -0
  383. package/shared/register-selection.mjs +2 -2
  384. package/shared/store-in-repo.mjs +3 -3
  385. package/shared/summary-blocks.mjs +0 -3
  386. package/shared/trigger-lane.mjs +1 -1
  387. package/shared/vacuous-pass.mjs +2 -2
  388. package/shared/verb-shim.mjs +4 -2
  389. package/vendor/buffers/package.json +1 -1
  390. package/node_modules/exceljs/README.md +0 -3023
@@ -0,0 +1,283 @@
1
+ // SPDX-License-Identifier: AGPL-3.0-only
2
+ // Copyright 2026 Cordillera Sàrl. Additional terms under section 7 of the AGPL-3.0 apply — see ADDITIONAL-TERMS.md
3
+ //
4
+ // portal-routes/connect.mjs — connecting a reader's own AI assistant: whether the connector's door answers and whether the
5
+ // reader has connected, a key minted for the caller, and the connection help page.
6
+ //
7
+ // One of the portal service's route groups, moved out of its dispatcher unchanged; makePortalService says how it asks them.
8
+ import { readFileSync } from "node:fs";
9
+ import { join } from "node:path";
10
+ import { connectOffers, offersForWire } from "../../shared/connect-clients.mjs";
11
+ import { doorKind } from "../../shared/mcp-challenge.mjs";
12
+ import { mintToken } from "../../shared/scope.mjs";
13
+ import { STDIO_SHAPES, stdioConnectFor, stdioConnectOffer } from "../../shared/stdio-connect.mjs";
14
+ import { isWsl, wslTarget } from "../../shared/wsl.mjs";
15
+ import { isDemo } from "../demo-posture.mjs";
16
+ import { claudeNamer } from "../engine/probe.mjs";
17
+ import { assertPrincipal, seesEverything } from "../portal-access.mjs";
18
+
19
+ export async function connectRoutes({ demo, audit, auditLog, INSTALL_ROOT, connectCaches }, { method, parts, identity, principal, body }) {
20
+ // ── ONE READING OF THE CONNECTOR'S OWN DOOR, CACHED ────────────────────────────────────────────────
21
+ //
22
+ // The same unauthenticated probe `doctor` makes, asked here so the connector steps follow what the door
23
+ // actually answers. Bounded three ways, because this sits on a page load: a short timeout, a one-minute
24
+ // cache, and a failure that answers `null` rather than throwing — a page that cannot read its door says
25
+ // so, which is the honest half of this change.
26
+ //
27
+ // Both caches live on the service (`connectCaches`, made once in makePortalService), not here: this
28
+ // function runs once per request, and a cache declared in it starts empty on every one.
29
+ // ── WHETHER A READER HAS AN ASSISTANT ON THIS INSTALLATION ────────────────────────────────────────
30
+ //
31
+ // The only evidence either process holds is the connector's own access log: enrolment says a person MAY
32
+ // connect, never that they did. `readConnections` is the connector's reader, imported rather than
33
+ // rebuilt here — the path this log lives at is the connector's fact, and a portal deriving it from its
34
+ // own environment is how a live key's record nearly got struck on a split install.
35
+ //
36
+ // TWO INSTALLATION SHAPES, AND THE SPLIT IS THE ONE THE ROUTE ALREADY MAKES. A hosted install has a
37
+ // published client door and many signed-in people, so the question is answered per person: is this
38
+ // email in the log. A local install has no client door, one reader, and a connector that cannot know
39
+ // who it is serving — so the local route's own record answers for the only person who could be asking.
40
+ // Reading a local record as an answer on a HOSTED install would mark every reader connected the moment
41
+ // one member of staff ran the server by hand, which is why it is gated on there being no client door.
42
+ //
43
+ // Returns null, never false, when there was nothing to read. See the route for why that matters.
44
+ //
45
+ // CACHED FOR A MINUTE, the same as the door probe above and for the same reason: this is a page load,
46
+ // not a check. It runs on every report a reader opens, and reading the tail of a log each time to
47
+ // answer a question whose answer changes once, ever, would be paid on the client-facing screen.
48
+ // KEYED ON THE FILES IT READ, not on time alone. The log's location is configuration and does not move
49
+ // under a running service — but a cache that ignored it would answer about the wrong file for a minute
50
+ // after it did, and it is what makes this cache testable at the route rather than only at the helper.
51
+ const CONNECTIONS_TTL_MS = 60_000;
52
+
53
+ async function readerHasConnectedAi(principal) {
54
+ const email = String(principal?.email ?? "").trim().toLowerCase();
55
+ let seen = null;
56
+ // Imported here rather than at the top, the way every other reach into mcp-server/lib from this file
57
+ // is: the driver does not depend on the connector, and the import-cycle walk is what keeps it so.
58
+ let audit = null;
59
+ try { audit = await import("../../mcp-server/lib/audit.mjs"); }
60
+ catch { return null; } // best-effort: never fail a page load
61
+ const key = audit.auditPaths().join("\u0000");
62
+ const cached = connectCaches.connections;
63
+ if (cached.seen && cached.key === key && Date.now() - cached.at < CONNECTIONS_TTL_MS) {
64
+ seen = cached.seen;
65
+ } else {
66
+ try { seen = audit.readConnections(); } catch { return null; }
67
+ connectCaches.connections = { at: Date.now(), key, seen };
68
+ }
69
+ if (!seen.available) return null;
70
+ if (email && seen.emails.has(email)) return true;
71
+ if (!process.env.CLEAROTRON_CLIENT_MCP_URL && seen.local) return true;
72
+ return false;
73
+ }
74
+
75
+ const DOOR_KIND_TTL_MS = 60_000;
76
+ async function connectorDoorKind(url) {
77
+ if (!url) return null;
78
+ const now = Date.now();
79
+ const cached = connectCaches.door;
80
+ if (cached.url === url && now - cached.at < DOOR_KIND_TTL_MS) return cached.kind;
81
+ let probe = null;
82
+ try {
83
+ const res = await fetch(url, { method: "GET", redirect: "manual", signal: AbortSignal.timeout(2000) });
84
+ let body = null;
85
+ if (res.status === 401) { try { body = (await res.text()).slice(0, 400); } catch { body = null; } }
86
+ probe = { ok: res.status < 500, status: res.status, error: null, challenge: res.headers.get("www-authenticate"), body };
87
+ } catch (e) { probe = { ok: false, status: null, error: String(e?.cause?.code ?? e?.name ?? e?.message ?? e) }; }
88
+ const kind = doorKind(probe);
89
+ connectCaches.door = { at: now, url, kind };
90
+ return kind;
91
+ }
92
+
93
+ if (parts[1] === "api" && parts[2] === "mcp-access" && method === "GET") {
94
+ assertPrincipal(principal, { door: true }); // throws PortalDeny(403) for an unmapped identity
95
+ const url = process.env.CLEAROTRON_CLIENT_MCP_URL || null;
96
+ const keyUrl = process.env.CLEAROTRON_AGENT_MCP_URL || null;
97
+ // ── THE ROUTE THAT NEEDS NO ADDRESS ──────────────────────────────────
98
+ //
99
+ // Both addresses above are null on a local install and always will be: there is no hosted door
100
+ // to point at. The surfaces built on them then render nothing — correctly, by their own rule —
101
+ // and the owner met that as a wall on his own first install, with the one route that DOES work
102
+ // sitting unmentioned on his disk.
103
+ //
104
+ // STAFF ONLY, and that boundary is honest rather than a guess about deployment shape. The
105
+ // command is a true fact about THIS INSTALL'S OWN DISK, useful to anyone with a shell on the
106
+ // box and useless to a hosted client who has no checkout. On a local install the reader IS the
107
+ // operator, which is why the split that already exists does the work an "is this deployment
108
+ // local" inference would have done badly. Agreed before building, because it
109
+ // changes what a signed-in staff user is shown.
110
+ //
111
+ // COMPOSED IN ONE PLACE and handed over as a string. The browser cannot know this install's
112
+ // path, so the three surfaces stating this route cannot drift apart even if someone tries.
113
+ //
114
+ // AND IT NAMES THE DISTRIBUTION, like every other surface that states this route. Without the
115
+ // target this one composer answers as it does for an install that is not under WSL at all, so on
116
+ // a WSL box this field alone carried the inside-WSL line while the rows beside it led with the
117
+ // Windows-side one. Nothing draws this field today; it is on the wire, and a field that answers
118
+ // differently from the rows is a trap for whoever draws it next.
119
+ const stdio = seesEverything(principal)
120
+ ? stdioConnectOffer({ workDir: process.env.CLEAROTRON_WORK_DIR || null, reportsDir: process.env.CLEAROTRON_REPORTS_DIR || null, wsl: wslTarget(), demo: isDemo(process.env) })
121
+ : null;
122
+
123
+ // ── THE PAGE IS HANDED ANSWERS, NOT FACTS TO REASON FROM ─────────────
124
+ //
125
+ // The browser used to hold its own client table on its own axis — `door` × `reach` — and derive
126
+ // offered-versus-withheld from `url`, `keyUrl` and `enabled`. Two tables partitioning the same
127
+ // clients on different axes did not merely risk drifting; they had already drifted. The page
128
+ // said Codex needs a key address, which is `null` on a local install, so it named a one-line
129
+ // command in its own instructions and then rendered no command. That is this issue's defect,
130
+ // living inside the page written to answer it.
131
+ //
132
+ // So the resolution happens HERE, once, through `shared/connect-clients.mjs`, and the page
133
+ // renders what it is handed. This is not a preference for server-side logic: the install's own
134
+ // filesystem path is not a browser fact, and any derivation needing it must happen where it is
135
+ // known. `assistantsFor` and `addressFor` are DELETED rather than kept in step, because a
136
+ // second author kept in step by hand is exactly what broke.
137
+ //
138
+ // STAFF-ONLY STDIO SURVIVES THE MOVE. The command is a true fact about this install's own disk
139
+ // — useful to anyone with a shell on the box, useless to a hosted client who has no checkout —
140
+ // so a client is handed no stdio routes at all and the rows that need one resolve to a stated
141
+ // absence rather than to a command they cannot run.
142
+ const offers = connectOffers({
143
+ stdioRoutes: stdio
144
+ ? Object.fromEntries(Object.keys(STDIO_SHAPES).map((shape) =>
145
+ [shape, stdioConnectFor(shape, { workDir: process.env.CLEAROTRON_WORK_DIR || null, reportsDir: process.env.CLEAROTRON_REPORTS_DIR || null, wsl: wslTarget(), demo: isDemo(process.env) })]))
146
+ : {},
147
+ wsl: isWsl(),
148
+ nameClaude: claudeNamer(),
149
+ demo: isDemo(process.env),
150
+ // ONE ADDRESS, and it is the publicly reachable one ( §5). The
151
+ // `localAddress` and `clientDoorStanding` inputs are gone with the axis that read them: no
152
+ // surface serves a loopback address to anybody, and the door's running-or-not stopped being
153
+ // a question the moment it auto-started with the product.
154
+ publicAddress: url,
155
+ // THE KEY DOOR'S OWN HOST, when one is deployed. Beside a sign-in door its steps ride along for
156
+ // the page to fold away; they are never resolved against `url`, which refuses a key.
157
+ keyAddress: keyUrl,
158
+ operator: principal.email ?? null,
159
+ // WHAT THE DOOR ANSWERS, read from the door rather than assumed by the row. The steps used to
160
+ // be fixed: Claude's said to paste a key and set authentication to None, which is right for a
161
+ // self-hosted door and cannot work on any deployment behind an identity provider — the key is
162
+ // minted for nothing and the warning the reader is told to ignore IS the sign-in. Cached
163
+ // because this is a page load, not a check: one reading serves every reader for a minute, and
164
+ // a door that could not be read leaves this null so the page says so instead of guessing.
165
+ door: await connectorDoorKind(url),
166
+ });
167
+ return { status: 200, json: {
168
+ url, // null ⇒ the UI keeps its honest empty state
169
+ keyUrl, // the API-key door; null until it is deployed
170
+ email: principal.email ?? null, // the identity to sign in with — what they already use
171
+ enabled: !!url,
172
+ stdio, // the local route, or null for a client
173
+ // ── HAS THIS READER ALREADY CONNECTED AN ASSISTANT? ──────────────────────────────────────
174
+ //
175
+ // Folded into this route rather than given its own, because the Ask-AI control on a report
176
+ // already loads it and a second request per report open buys nothing.
177
+ //
178
+ // `null` IS A THIRD STATE AND THE SCREEN HAS TO DRAW IT. True, false and "no log to read" are
179
+ // different facts: an installation whose access log has not been written yet, or cannot be
180
+ // read, has not told us this reader never connected — it has told us nothing. The control
181
+ // treats null the way it treats false, because offering the menu to somebody with no
182
+ // assistant reproduces the defect this is fixing, and because the panel carries its own way
183
+ // past ("Already connected? Ask anyway"). What it must not do is claim the measurement.
184
+ aiConnected: await readerHasConnectedAi(principal),
185
+ // Every client, already resolved: served or not, with what it needs or why it cannot be.
186
+ //
187
+ // ── `steps` COMES BACK, on the owner's 2026-09-03 ruling ─────────
188
+ //
189
+ // It was dropped here deliberately under his 2026-08-31 cut, which said the page shows no
190
+ // recipes and the per-assistant blocks "become the one italic link at the bottom". His
191
+ // re-inspection reverses that for one specific thing: *"The page must lead each vendor with
192
+ // the path that vendor's UI user actually takes; a CLI command is at most a collapsed
193
+ // 'advanced' detail."*
194
+ //
195
+ // The two rulings are consistent once you separate what was actually objected to. "Settings →
196
+ // Connectors → Add custom connector" is not a recipe in the sense the cut banned — it is the
197
+ // reader's OWN vocabulary, three taps in an app they already have open. The technical thing,
198
+ // the part irrelevant to a reader connecting from Cowork, is the command, and that is what moves behind
199
+ // a fold. So the steps travel and the command demotes.
200
+ //
201
+ // They are resolved HERE and not composed in the browser, for the reason this route already
202
+ // exists: the step that names an address must name the address this deployment actually
203
+ // resolved, and a page that built its own would drift from it.
204
+ offers: offersForWire(offers),
205
+ } };
206
+ }
207
+
208
+ // /portal/api/connect-key — mint THIS caller's own access, for the clipboard, never for the page.
209
+ //
210
+ // ── THE OWNER'S RULING, 2026-08-31 ───────────────────────────────────────────────────────────
211
+ //
212
+ // *"The page never shows a key, in any state."* Three reasons he gave, and the second is the one
213
+ // that shapes this endpoint: *"A rendered key outlives the moment. It's in the DOM, in the
214
+ // screenshot someone takes, in the browser cache, on a screen left open. A key that's never text
215
+ // on a page has none of that."*
216
+ //
217
+ // So the key still reaches the browser — a clipboard write needs it — and never becomes text. The
218
+ // page holds it in a local variable for the length of one press.
219
+ //
220
+ // ── MINTED PER CALLER, AND `sub` NEVER COMES FROM THE REQUEST ────────────────────────────────
221
+ //
222
+ // The rule this replaces existed because a key shown on a shared page made one person's
223
+ // credential everyone's. Moving it to the clipboard does NOT answer that on its own: anybody who
224
+ // loads the page can still press the button. What answers it is that each press mints a key for
225
+ // THE CALLER, from the authenticated principal and never from anything the request said — so a
226
+ // colleague pressing it gets their own credential, attributable in the audit log and revocable by
227
+ // name, rather than a copy of somebody else's.
228
+ //
229
+ // ENROLMENT IS CHECKED FIRST, for the same reason `clearotron connect` checks it: a key issued to
230
+ // an identity the guest list has never heard of authenticates and is then refused on every
231
+ // request, which is a credential that opens nothing and a reader who believes they are finished.
232
+ if (parts[1] === "api" && parts[2] === "connect-key" && method === "POST") {
233
+ assertPrincipal(principal, { door: true });
234
+ const url = process.env.CLEAROTRON_CLIENT_MCP_URL || null;
235
+ if (!url) return { status: 409, json: { error: "no_connector" } };
236
+ const identity = principal.email ?? null;
237
+ if (!identity) return { status: 403, json: { error: "no_identity" } };
238
+ // Enrolled means a principal exists: the door check above has already refused an address with no
239
+ // access anywhere. Asking for a company list here instead read a person whose only reach is their
240
+ // organisation's Generic as not enrolled.
241
+ let key;
242
+ try { key = mintToken({ scope: "account", sub: identity, ttlSec: 90 * 24 * 3600 }); }
243
+ catch { return { status: 503, json: { error: "cannot_issue" } }; }
244
+ auditLog(`connect-key issued for=${identity}`); // WHO, never WHAT — the token itself is never logged
245
+ return {
246
+ status: 200,
247
+ json: { address: url, key },
248
+ // NEVER CACHED, by any hop. A credential sitting in a proxy or a disk cache is the "outlives
249
+ // the moment" failure the ruling is about, arriving by a route the page cannot see.
250
+ headers: { "cache-control": "no-store, no-cache, must-revalidate, private", "pragma": "no-cache" },
251
+ };
252
+ }
253
+
254
+ // /portal/connect-help — the by-hand setup instructions, for the one link the page carries.
255
+ //
256
+ // ── WHY THIS ROUTE EXISTS AT ALL ─────────────────────────────────────
257
+ //
258
+ // The owner's cut ends the Use-your-AI page with *"Not connecting? [Set it up by hand](…)"* and
259
+ // left the target open. There was no document route on this portal, so the link had nowhere to
260
+ // go — and a link to nowhere is the same defect class as a button that cannot work. The
261
+ // instructions already exist and carry exactly the recipes the cut removed from the page, so this
262
+ // serves them rather than inventing a fourth description of how to connect.
263
+ //
264
+ // THE SIX BANNED WORDS DO NOT APPLY HERE, deliberately. "No connector, no key, no address" is a
265
+ // rule about the PAGE, whose reader is choosing an assistant and nothing else. This is the escape
266
+ // hatch for the reader who wants the mechanism, and withholding the vocabulary from them would
267
+ // make the page's simplicity a lie rather than a kindness.
268
+ //
269
+ // READ-ONLY, DOOR-CHECKED, AND SERVED AS ESCAPED TEXT. It runs nothing and loads nothing, so it
270
+ // gets `docCsp()` rather than the report policy, which permits inline script for frozen artefacts
271
+ // that need it. Before this shipped the document named the private repository in an illustrative
272
+ // path six times; nothing that reaches a client may carry that, so the placeholder now names the
273
+ // install. Anything added to that file is published by this route — check it before you add it.
274
+ if (parts[1] === "connect-help" && method === "GET") {
275
+ assertPrincipal(principal, { door: true });
276
+ let md;
277
+ try { md = readFileSync(join(INSTALL_ROOT, "mcp-server", "CONNECT.md"), "utf8"); }
278
+ catch { return { status: 404, json: { error: "not_found" } }; }
279
+ return { status: 200, doc: md };
280
+ }
281
+
282
+ return undefined;
283
+ }
@@ -0,0 +1,178 @@
1
+ // SPDX-License-Identifier: AGPL-3.0-only
2
+ // Copyright 2026 Cordillera Sàrl. Additional terms under section 7 of the AGPL-3.0 apply — see ADDITIONAL-TERMS.md
3
+ //
4
+ // portal-routes/feedback.mjs — /portal/api/feedback, a reader's flag on one finding of a delivered report.
5
+ //
6
+ // One of the portal service's route groups, moved out of its dispatcher unchanged; makePortalService says how it asks them.
7
+ import { join } from "node:path";
8
+ import { appendFlag, feedbackDir, MAX_WHY, VERDICTS } from "../feedback-store.mjs";
9
+ import { assertPrincipal, mayReadRun } from "../portal-access.mjs";
10
+ import { readJson } from "../run-record.mjs";
11
+
12
+ export async function feedbackRoutes({ poolRoot, audit, feedbackCapture }, { method, parts, principal, body }) {
13
+ // POST /portal/api/feedback — a lawyer flags one finding on a delivered report.
14
+ //
15
+ // This is the SECOND POST under /portal/api that spends nothing (compose/read is the other). It
16
+ // mints no confirmation token, queues nothing and changes no report: flagging is an observation
17
+ // ABOUT a delivered artifact, never an instruction to the engine.
18
+ //
19
+ // THE RULE THAT MAKES A FLAG EVIDENCE: every identifying field is read SERVER-SIDE from the run's
20
+ // own artifacts. The request supplies exactly three things — which run, which ordinal, and the
21
+ // reader's own words. Mark, band, disposition, matter, account, engine build and the excerpt all
22
+ // come from meta.json and report-data.json on disk. A client who could name the mark on a flag
23
+ // could label another customer's finding with it, which is how the predecessor system's Triage
24
+ // grouping was attacked (spec 61 critic finding 1) — and beyond the attack, a locator the reader
25
+ // typed is a locator that cannot be trusted to still point anywhere.
26
+ if (parts[1] === "api" && parts[2] === "feedback" && method === "POST") {
27
+ assertPrincipal(principal, { door: true });
28
+ // — RETIRED, 2026-08-20. It REFUSES; it does not disappear.
29
+ //
30
+ // AFTER assertPrincipal ON PURPOSE. A 410 says "this existed and is gone", which is exactly what
31
+ // a reader on a report published before today needs to be told and exactly what an unauthenticated
32
+ // prober should not learn. The door check runs first, so only a principal who could have used the
33
+ // control sees the answer.
34
+ //
35
+ // 410 RATHER THAN 404, which is what every other refusal in this handler returns. The difference
36
+ // is the audit log: `isAdminWrite` still names this path, so a POST here still files an outcome
37
+ // row, and a retired-endpoint row is a different fact from a not-yours row. If an old open tab is
38
+ // still clicking Flag, that is a thing worth being able to count.
39
+ //
40
+ // WHAT IS DELIBERATELY STILL BELOW THIS LINE: the whole resolver — the two-lane shape, the
41
+ // disposition read, the server-side-locator rule. The owner ruled "disable services and any code",
42
+ // and the acceptance criterion says re-enabling must be a switch and not a rebuild. Deleting 130
43
+ // lines of hard-won doctrine would have made it a rebuild.
44
+ if (!feedbackCapture) return { status: 410, json: { code: "retired", error: "Flagging a finding is switched off." } };
45
+ const runId = typeof body?.runId === "string" ? body.runId : "";
46
+ if (!/^[A-Za-z0-9][A-Za-z0-9._-]{0,180}$/.test(runId) || runId.includes(".."))
47
+ return { status: 404, json: { error: "not_found" } };
48
+ const dir = join(poolRoot, runId);
49
+ let meta; try { meta = readJson(join(dir, "meta.json")); } catch { return { status: 404, json: { error: "not_found" } }; }
50
+ // Ownership, exactly as GET /portal/report/<id> checks it — foreign is 404, never 403, and
51
+ // a Generic run is its organisation's. A reader who cannot READ the report cannot flag it either.
52
+ const owner = meta.customerKey || "generic";
53
+ if (!mayReadRun(principal, { owner, organisation: meta.organisation ?? null })) return { status: 404, json: { error: "not_found" } };
54
+
55
+ const verdict = typeof body?.verdict === "string" ? body.verdict : "";
56
+ if (!VERDICTS.has(verdict))
57
+ return { status: 400, json: { code: "bad_verdict", error: "A flag is good or bad." } };
58
+ const why = typeof body?.why === "string" ? body.why.trim() : "";
59
+ 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." } };
60
+ 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.` } };
61
+
62
+ // The ordinal names a POSITION; the finding's own facts are read back from the run so the flag
63
+ // survives the contiguous renumber every republish performs.
64
+ //
65
+ // — THE TWO LANES SHAPE report-data.json DIFFERENTLY, and the resolver used to know one.
66
+ //
67
+ // Clearance writes a top-level `findings[]` numbered once across the document. Knockout writes
68
+ // `marks.findings`, and restarts the ordinals at 1 FOR EACH MARK, so every mark in a
69
+ // batch has a finding 1. Reading `data.findings` on a knockout run therefore found nothing, and
70
+ // a flag on the knockout lane resolved to no facts at all — silently, because a flag with an
71
+ // unresolved ordinal is a legitimate state (a run published before report-data.json existed).
72
+ //
73
+ // Branching on the SHAPE ON DISK rather than on what the request sent is the load-bearing part.
74
+ // If a knockout flag arrives with no markIndex, this resolves NOTHING rather than falling back
75
+ // to an ordinal lookup that would silently attach a lawyer's correction to the FIRST mark's
76
+ // finding of that number. The issue is explicit that the wrong mark is worse than no mark.
77
+ const ordinal = Number.isInteger(body?.ordinal) && body.ordinal > 0 ? body.ordinal : null;
78
+ const markIndex = Number.isInteger(body?.markIndex) && body.markIndex >= 0 ? body.markIndex : null;
79
+ let found = null, searchedMark = null, foundLane = null, engineCommitOf = meta.engineCommit ?? null;
80
+ try {
81
+ const data = readJson(join(dir, "report-data.json"));
82
+ engineCommitOf = data.engineCommit ?? engineCommitOf;
83
+ if (ordinal != null) {
84
+ if (Array.isArray(data.findings)) {
85
+ found = data.findings.find((f) => f.ordinal === ordinal) ?? null;
86
+ if (found) foundLane = "clearance";
87
+ } else if (Array.isArray(data.marks) && markIndex != null) {
88
+ const m = data.marks[markIndex] ?? null;
89
+ found = (m?.findings ?? []).find((f) => f.ordinal === ordinal) ?? null;
90
+ if (found) { foundLane = "knockout"; searchedMark = m?.name ?? null; }
91
+ }
92
+ }
93
+ } catch { /* a run published before report-data.json: the ordinal still locates, the facts do not */ }
94
+
95
+ // — THE DISPOSITION COMES FROM findings.json, NOT FROM report-data.json.
96
+ //
97
+ // report-data.json is the CLIENT CUT by construction, and `disposition` is a placement key in the
98
+ // engine's own spelling — it stopped being served there in the same commit as this read. That
99
+ // deletion on its own would have started writing `null` into the locator of every flag captured
100
+ // from that moment on, and a flag is already-minted evidence a revert cannot repair. So the source
101
+ // moves rather than disappearing: publish copies the run's findings.json into the pool run dir
102
+ // (publish/index.mjs copyRO, both the strict and the lenient parse), which satisfies the rule this
103
+ // handler states above — every identifying field read SERVER-SIDE from the run's own artifacts.
104
+ //
105
+ // JOINED ON ORDINAL **AND** MARK, and it resolves NOTHING on a mismatch. report-data projects the
106
+ // same parsed findings array publish read from that same findings.json, so the ordinals are one
107
+ // set — but a wrong disposition on a lawyer's flag is worse than no disposition (the ruling on
108
+ // the batch lane, applied here), so the mark is checked rather than assumed.
109
+ //
110
+ // CLEARANCE ONLY, on purpose. publish/knockout.mjs emits no disposition, so `found?.disposition`
111
+ // was already null on that lane and this must not invent one from a differently-shaped file.
112
+ //
113
+ // ABSENT IS NULL, NEVER AN ERROR. A run with no findings.json (no register, or a top-level parse
114
+ // failure that published a structured-light report) resolves to null — the same honest "the
115
+ // ordinal locates, this fact does not" state a pre-report-data run records — and the flag still
116
+ // saves. The audit line below records whether it resolved, so the absence is visible rather than
117
+ // silent.
118
+ let disposition = null;
119
+ if (foundLane === "clearance") {
120
+ try {
121
+ const fj = readJson(join(dir, "findings.json"));
122
+ const rec = (Array.isArray(fj?.findings) ? fj.findings : []).find((f) => f?.ordinal === ordinal) ?? null;
123
+ if (rec && String(rec.mark ?? "") === String(found.mark ?? "")) disposition = rec.disposition ?? null;
124
+ } catch { /* no findings.json in the run dir: the finding still locates, its posture does not */ }
125
+ }
126
+
127
+ let rec;
128
+ try {
129
+ rec = appendFlag(feedbackDir(poolRoot), {
130
+ runId, verdict, why,
131
+ capturedBy: principal.email ?? null,
132
+ locator: {
133
+ ordinal,
134
+ // — the drill-through key the report page and the workbook both print
135
+ // (`<MARK> #<ordinal>`,), read off the resolved finding rather than composed here or
136
+ // taken from the request. It is what a human reading the flag store or a minted issue
137
+ // needs in order to find the row again, and on a batch it is the only thing that says
138
+ // WHICH mark. Null on the clearance lane, which has no such key.
139
+ ref: found?.ref ?? null,
140
+ // The searched mark on the knockout lane, where `mark` below is the CONFLICTING name.
141
+ searchedMark,
142
+ // Clearance calls the conflicting name `mark`; the knockout view calls it `name`.
143
+ mark: found?.mark ?? found?.name ?? null,
144
+ band: found?.band ?? null,
145
+ // — read above, from findings.json. NOT `found.disposition`: report-data.json no
146
+ // longer serves the placement key, and a `?? null` fallback onto it would read as working.
147
+ disposition,
148
+ section: typeof body?.section === "string" ? body.section.slice(0, 120) : null,
149
+ },
150
+ // The sentence the reader was looking at, from the RUN rather than the request — the same
151
+ // reason as the locator, and it keeps from putting attacker-authored prose in an issue.
152
+ excerpt: found ? (found.net ?? found.impact ?? null) : null,
153
+ run: {
154
+ account: owner, matter: meta.matter ?? null, markName: meta.markName ?? null,
155
+ product: meta.searchLevel ?? null, issuedAt: meta.issuedAt ?? null,
156
+ engineCommit: engineCommitOf, runDir: dir,
157
+ },
158
+ });
159
+ } catch (e) {
160
+ audit({ event: "report-feedback", by: principal.email, runId, ok: false, error: String(e?.message ?? e) });
161
+ return { status: 500, json: { code: "not_saved", error: "The flag was not saved. Nothing was lost from the report — try again." } };
162
+ }
163
+ // Length and location, never the words. A why is the lawyer's own reading of a client matter,
164
+ // and an audit log is a different disclosure surface from the flag store.
165
+ //
166
+ // — `dispositionResolved` rides here because the disposition now comes from a SECOND file:
167
+ // a clearance flag that located its finding but read no posture means findings.json was absent or
168
+ // did not agree, and a null that nobody can see is how the paired edit would have failed silently.
169
+ // Only on the lane that can carry one, so a knockout flag's honest null is not logged as a miss.
170
+ audit({
171
+ event: "report-feedback", by: principal.email, runId, account: owner, verdict, ordinal, markIndex,
172
+ resolved: Boolean(found), ...(foundLane === "clearance" ? { dispositionResolved: Boolean(disposition) } : {}),
173
+ chars: why.length, id: rec.id, ok: true, status: 201,
174
+ });
175
+ return { status: 201, json: { id: rec.id } };
176
+ }
177
+ return undefined;
178
+ }
@@ -0,0 +1,165 @@
1
+ // SPDX-License-Identifier: AGPL-3.0-only
2
+ // Copyright 2026 Cordillera Sàrl. Additional terms under section 7 of the AGPL-3.0 apply — see ADDITIONAL-TERMS.md
3
+ //
4
+ // portal-routes/me.mjs — who the signed-in reader is and what they may do (/portal/api/me), the about page's facts, and
5
+ // the searches an account can order.
6
+ //
7
+ // One of the portal service's route groups, moved out of its dispatcher unchanged; makePortalService says how it asks them.
8
+ import { ADMINISTRATOR_CONTACT, ORGANISATION_NAME } from "../../shared/brand.mjs";
9
+ import { browserCommand, installRoute } from "../../shared/invocation.mjs";
10
+ import { productIdentity } from "../../shared/product-identity.mjs";
11
+ import { assertPrincipal, principalView, seesEverything } from "../portal-access.mjs";
12
+ import { flagView } from "../portal-config-view.mjs";
13
+ import { concurrentRunsCap } from "../portal-runs.mjs";
14
+
15
+ export async function meRoutes({ poolRoot, stopControl, demo, orderRefusal, loadProfilesImpl, searchesFor, engineProgramDisputed, INSTALL_CHANNEL, refusalFor }, { method, parts, principal, grantsHere, query }) {
16
+ // /portal/api/me
17
+ if (parts[1] === "api" && parts[2] === "me" && method === "GET") {
18
+ assertPrincipal(principal, { door: true }); // door check only — a multi-account client enters and gets the picker list
19
+ // `accountNames` — the DISPLAY name of each account this identity holds, and nothing else.
20
+ //
21
+ // Every profile carries a name ("Vantor Labs", "Foxglade Interactive"); the account KEY is a
22
+ // slug ("vantor"). Staff read names because the account picker fetches the staff-only
23
+ // roster; a client had no name source at all, so the identical screen printed the slug at them.
24
+ // The same brand owner therefore read two different ways depending on who signed in, which is
25
+ // what this field ends.
26
+ //
27
+ // SCOPED TO THE GRANTED ACCOUNTS, never the roster. A name map covering everything would put
28
+ // Cordillera's customer list on the one route every signed-in identity can reach — the exact
29
+ // leak /profiles is never proxied for (portal-upstream: "a client reaching it would learn the
30
+ // customer base"). `"*"` identities get {} and keep using the roster, which is staff-gated.
31
+ //
32
+ // `accountFacts` rides in the SAME loop, under the SAME scoping decision, for the same reason
33
+ // the names do: the pick panel shows industry, marketplace count and territories per company,
34
+ // and a client with several grants meets that panel. One loop, so there is one answer to
35
+ // "which accounts may this identity learn about" rather than two that can drift apart. A `"*"`
36
+ // identity gets {} here exactly as it does for names and keeps reading the staff-only roster.
37
+ let accountNames = {};
38
+ let accountFacts = {};
39
+ let meRoster = null; // read once for this answer: the names below and the house marketplaces
40
+ // GENERIC IS NAMED TOO when the person sees an organisation's Generic. It is not a company, so it is
41
+ // never in `accounts`, and without a name here the switcher printed the raw key at everyone below
42
+ // everything. An organisation with no company yet is the case with an empty `accounts`, so the
43
+ // guard is on the names to look up, not on the company list.
44
+ const named = Array.isArray(principal.accounts)
45
+ ? [...principal.accounts, ...(principal.genericOrgs?.length ? ["generic"] : [])] : [];
46
+ if (named.length) {
47
+ try {
48
+ const { companyFactsOf } = await import("../profiles.mjs");
49
+ const profiles = meRoster = await loadProfilesImpl();
50
+ for (const key of named) {
51
+ const profile = profiles.get(key);
52
+ const name = profile?.name;
53
+ if (typeof name === "string" && name) accountNames[key] = name;
54
+ if (profile) accountFacts[key] = companyFactsOf(profile);
55
+ }
56
+ } catch {
57
+ // A name is a nicety; the door is not. An unreadable profile store must not lock a user
58
+ // out of the portal, so this degrades to the keys the UI already falls back to.
59
+ accountNames = {};
60
+ accountFacts = {};
61
+ }
62
+ }
63
+ // HOW MANY RUNS THIS DEPLOYMENT EXECUTES AT ONCE. Deployment-wide, not account-scoped, which is
64
+ // why it rides here rather than on /usage: it is the same number for everyone, /me is fetched
65
+ // once by every screen, and a multi-brand account has no single /usage to read it from.
66
+ //
67
+ // Home states it in its section header. It was written into the UI as a literal `2` — right on
68
+ // the day, and silently wrong the moment CLEAROTRON_MAX_CONCURRENT_RUNS is set to anything else,
69
+ // which is exactly the shape of over-promise this screen exists to avoid.
70
+ // WHO OPERATES THIS DEPLOYMENT. The portal named the operator in three places as a
71
+ // string literal — the role label was the operator's own name, which a fork would have shipped
72
+ // about a company it has nothing to do with. `CLEAROTRON_BRAND_NAME` has been the brand seam all
73
+ // along and TRADEMARKS.md already listed portal nav as a consumer; it simply was not one.
74
+ // Riding on /me because that is where the ROLE comes from, and the label is role plus operator.
75
+ // WHICH MODE THIS INSTALL IS. Same rationale as concurrentRuns above: it is the
76
+ // same answer for everyone, /me is fetched once by every screen, and the screen that needs it
77
+ // most — New clearance — has no other deployment-wide source.
78
+ //
79
+ // READ, NEVER COMPUTED. This process deliberately has no engine environment (see this file's
80
+ // own header, three times over), so `engineInventory(process.env)` here would report demo on
81
+ // every install — a confident wrong answer. `flagView` reads the snapshot `bin/start.mjs`
82
+ // writes at boot and derives the mode from `binaryPresent`, which that snapshot already
83
+ // carries. NULL when there is no snapshot to read, and null means THIS CANNOT ANSWER — the UI
84
+ // must leave the button alone rather than infer demo from an absent file.
85
+ // READ ONCE. The payload names it and the program reading below is gated on it; two calls to
86
+ // `flagView` here would be two reads of the same file that could disagree with each other.
87
+ //
88
+ // A DEMO ANSWERS NULL. No order in a demo reaches an engine: the run route below resolves each one
89
+ // to the finished example for the search picked (`if (demo)`), which is what the demo's banner
90
+ // promises. The demo's snapshot still describes the machine, so on a machine with no engine program
91
+ // this read "demo", and New clearance drew the no-engine notice where Review search belongs: the
92
+ // one flow the demo exists to show could not be started. Null leaves the button alone, as it does
93
+ // on a fresh install, and the configuration page still reads the snapshot for itself.
94
+ const meEngineMode = demo ? null : flagView(poolRoot).engineMode;
95
+ const searchRefusal = demo ? null : await orderRefusal();
96
+ // THE HOUSE MARKETPLACES, offered as suggestions wherever a company's marketplaces are edited. A new
97
+ // company starts with none (the owner's ruling of 2026-09-23) and somebody picks; these are the
98
+ // Generic default's own list, read from the store so an install that changed it offers its own.
99
+ // Deployment-wide and the same for everyone, like concurrentRuns. [] when the store cannot be read:
100
+ // the box still takes any marketplace typed into it.
101
+ let houseMarketplaces = [];
102
+ try {
103
+ const house = (meRoster ?? await loadProfilesImpl()).get("generic")?.platforms;
104
+ if (Array.isArray(house)) houseMarketplaces = house.filter((d) => typeof d === "string" && d.trim());
105
+ } catch { /* a suggestion list is a nicety; the door is not */ }
106
+ return { status: 200, json: { email: principal.email, ...principalView(principal, grantsHere, accountNames),
107
+ accounts: principal.accounts, accountNames, accountFacts,
108
+ concurrentRuns: concurrentRunsCap(), brand: ORGANISATION_NAME, engineMode: meEngineMode, houseMarketplaces,
109
+ // WHERE A PERSON ASKS FOR A CHANGE TO THEIR SIGN-IN, beside the brand and read where it is read:
110
+ // an href Preferences links "Clearotron administrator" to, or null, and then the words are plain.
111
+ administratorContact: ADMINISTRATOR_CONTACT,
112
+ // WHETHER THE PROGRAM IS ON THIS BOX WHILE THE ENGINE CANNOT SEE IT — true, false, or null
113
+ // for "this could not be checked". The screen above renders one of three remedies from it,
114
+ // and they are different remedies: install the CLI, restart the service that cannot see it,
115
+ // or the general advice when nothing could be read. Only `engineMode: "demo"` can make this
116
+ // anything but false; see `engineProgramDisputed`.
117
+ engineProgramDisputed: await engineProgramDisputed(meEngineMode),
118
+ // WHETHER THIS INSTALL CAN RUN A SEARCH AT ALL, by the runner's own order-time test (`orderRefusal`), and when
119
+ // it cannot, the refusal the review would give this person: Home shows it in place of its invite, and New
120
+ // clearance shows it and holds its start, so nobody fills in a search the install would refuse. A demo walks
121
+ // its own ordering flow, so it reads as able.
122
+ canSearch: !searchRefusal,
123
+ ...(searchRefusal ? { searchRefusal: refusalFor(principal, searchRefusal) } : {}),
124
+ // HOW THIS INSTALL ARRIVED, so a screen can name the setup command the reader can actually
125
+ // type. `npm run setup` and `npx clearotron install` are the same wizard and each one is
126
+ // unrunnable on the other route; the no-engine notice named one of them and was wrong for
127
+ // half its readers. A WORD, never a command line and never a prefix: `invocationForm` can
128
+ // answer with this machine's absolute path, and this value is rendered in a browser.
129
+ setupRoute: installRoute(),
130
+ // WHICH RELEASE CHANNEL THIS INSTALL CAME FROM, read off its own version as `update` reads it, so the
131
+ // setup command a screen names fetches this channel. `npx clearotron install` fetches the stable, and
132
+ // the stable's setup then moves itself into ~/.local over a beta. A WORD, like the route above.
133
+ channel: INSTALL_CHANNEL,
134
+ // THE COMMAND THAT FILES AN ORGANISATION, for the screen that cannot create a company without one.
135
+ // `browserCommand`'s rule: no path on this machine, and from npx's cache the published version
136
+ // rather than a bare name that reader does not have.
137
+ organisationCommand: browserCommand('start --organisation "<name>"'),
138
+ // — a button that always fails must not render as available. The reason is
139
+ // operator-shaped and staff-only; a client reads the generic sentence the button carries.
140
+ controls: { stop: { available: stopControl.available !== false,
141
+ reason: seesEverything(principal) ? (stopControl.reason ?? null) : null } } } };
142
+ }
143
+ // /portal/api/about — the AGPL §13 source offer ()
144
+ //
145
+ // UNAUTHENTICATED, DELIBERATELY, and it is the only route here that is. §13 obliges an operator
146
+ // running a modified version to offer the source to the users interacting with it — the offer is
147
+ // owed to whoever reaches the service, and a licence notice you must first sign in to read is not
148
+ // an offer. Nothing here is private either: the product's name, its version, its licence and the
149
+ // commit it is running are all facts about code that is published under a licence requiring
150
+ // exactly that. The sha is not a secret; it is the thing being offered.
151
+ //
152
+ // SERVED, NOT BUILT. The bundle cannot carry its own commit — portal-ui/dist is committed and CI
153
+ // fails when dist and source disagree, so a hash baked in at build time is not known until after
154
+ // the commit that would carry it. The server knows what it is running; the page asks.
155
+ if (parts[1] === "api" && parts[2] === "about" && method === "GET") {
156
+ return { status: 200, json: productIdentity() };
157
+ }
158
+ // /portal/api/searches
159
+ if (parts[1] === "api" && parts[2] === "searches" && method === "GET") {
160
+ const account = assertPrincipal(principal, { account: query.account ?? null });
161
+ if (!account) return { status: 400, json: { error: "name an account (?account=)" } };
162
+ return { status: 200, json: { account, ...searchesFor(account, principal) } };
163
+ }
164
+ return undefined;
165
+ }