clearotron 0.5.1 → 0.6.0-beta.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (379) hide show
  1. package/.env.example +7 -7
  2. package/INSTALL.md +10 -10
  3. package/QUICKSTART.md +6 -6
  4. package/README.md +2 -2
  5. package/THIRD-PARTY-NOTICES.md +4 -4
  6. package/bin/README.md +2 -2
  7. package/bin/clearotron.mjs +1 -1
  8. package/bin/connect.mjs +1 -1
  9. package/bin/disconnect.mjs +1 -1
  10. package/bin/example.mjs +2 -2
  11. package/bin/grant.mjs +1 -1
  12. package/bin/onboard.mjs +78 -23
  13. package/bin/start.mjs +49 -18
  14. package/bin/update.mjs +13 -3
  15. package/build-info.json +2 -2
  16. package/docs/DELIVERY.md +1 -1
  17. package/docs/PORTAL.md +1 -1
  18. package/docs/RELEASES.md +1 -1
  19. package/docs/architecture/02-architecture.md +10 -2
  20. package/docs/architecture/03-run-lifecycle.md +6 -2
  21. package/docs/architecture/04-configuration-reference.md +3 -3
  22. package/docs/architecture/05-config-governance.md +5 -4
  23. package/docs/architecture/08-development-guide.md +4 -4
  24. package/docs/architecture/09-security-and-data.md +1 -1
  25. package/{driver/skills/clearance-search/SKILL.md → docs/architecture/retired-manuals/clearance-search-spine.md} +17 -30
  26. package/{driver/skills/clearance-search/templates/email/generic.md → docs/architecture/retired-manuals/email-generic.md} +1 -1
  27. package/{driver/skills/clearance-search → docs/architecture/retired-manuals}/template-formatting.md +3 -4
  28. package/docs/configuration.md +1 -1
  29. package/docs/decisions/0002-no-dark-functionality.md +5 -0
  30. package/driver/CHANGELOG.md +60 -0
  31. package/driver/README.md +11 -1
  32. package/driver/accepted-order.mjs +13 -5
  33. package/driver/attempt-rows.mjs +64 -0
  34. package/driver/attributed-span.mjs +1 -1
  35. package/driver/authority-trees.mjs +1 -1
  36. package/driver/best-draft.mjs +3 -3
  37. package/driver/blind-frame-record.mjs +2 -2
  38. package/driver/cancel.mjs +3 -2
  39. package/driver/carry-through.mjs +2 -2
  40. package/driver/citation-census.json +3 -3
  41. package/driver/clearance-variants-record.mjs +4 -10
  42. package/driver/common-law-coverage-status.mjs +3 -3
  43. package/driver/common-law-receipts.mjs +2 -2
  44. package/driver/compare.mjs +1 -1
  45. package/driver/config-inventory.mjs +6 -79
  46. package/driver/consumption-ledger.mjs +2 -1
  47. package/driver/contract-dictation-registry.mjs +5 -0
  48. package/driver/contract-e3-backlog.mjs +45 -66
  49. package/driver/contract-e3-baseline.json +16 -16
  50. package/driver/contract-vocabulary.mjs +8 -6
  51. package/driver/corrections-feedforward.mjs +3 -1
  52. package/driver/coverage-form-io.mjs +7 -8
  53. package/driver/coverage-tool.mjs +1 -1
  54. package/driver/declination-tool.mjs +2 -2
  55. package/driver/degraded-parts.mjs +9 -9
  56. package/driver/demo-container.mjs +5 -4
  57. package/driver/deploy-live-run-guard.mjs +19 -7
  58. package/driver/derived-state.mjs +2 -2
  59. package/driver/dev-portal.mjs +2 -1
  60. package/driver/dispatch-record.mjs +1 -1
  61. package/driver/disposition-tool.mjs +2 -1
  62. package/driver/doubt-closure-tool.mjs +2 -2
  63. package/driver/driver.config.mjs +35 -724
  64. package/driver/e2e-rounds.mjs +3 -4
  65. package/driver/engine/CONTRACT.md +3 -0
  66. package/driver/engine/README.md +2 -0
  67. package/driver/engine/anthropic-agent.mjs +8 -37
  68. package/driver/engine/auth.mjs +74 -0
  69. package/driver/engine/child-record.mjs +1 -1
  70. package/driver/engine/deny-authority-write.mjs +2 -2
  71. package/driver/engine/jx-turn.mjs +10 -2
  72. package/driver/engine/mcp/README.md +1 -1
  73. package/driver/engine/mcp/band-server.mjs +6 -6
  74. package/driver/engine/mcp/codex-config.mjs +1 -1
  75. package/driver/engine/mcp/declination-server.mjs +2 -3
  76. package/driver/engine/mcp/dispositions-server.mjs +3 -3
  77. package/driver/engine/mcp/gather-config.mjs +24 -19
  78. package/driver/engine/mcp/grid-provenance.mjs +1 -1
  79. package/driver/engine/mcp/held-answers.mjs +5 -5
  80. package/driver/engine/mcp/perplexity-server.mjs +16 -7
  81. package/driver/engine/mcp/recording-server.mjs +7 -6
  82. package/driver/engine/mcp/register-server.mjs +29 -0
  83. package/driver/engine/mcp/stdio-server.mjs +5 -5
  84. package/driver/engine/mcp/supplemental.mjs +9 -9
  85. package/driver/engine/openai-agent.mjs +5 -2
  86. package/driver/engine/registry.mjs +103 -0
  87. package/driver/engine/run-choices.mjs +162 -0
  88. package/driver/engine/stamps.mjs +35 -0
  89. package/driver/enqueue-schema.mjs +4 -4
  90. package/driver/envelope-settle.mjs +3 -2
  91. package/driver/feedback-issues.mjs +1 -1
  92. package/driver/feedback-mint.mjs +3 -2
  93. package/driver/feedback-store.mjs +3 -2
  94. package/driver/findings-model.mjs +1 -1
  95. package/driver/flag-snapshot.mjs +5 -4
  96. package/driver/floor-duty.mjs +3 -3
  97. package/driver/foreign-record-links.mjs +1 -1
  98. package/driver/frame-diff-record.mjs +2 -8
  99. package/driver/framework.mjs +1 -1
  100. package/driver/gate-metrics.mjs +10 -11
  101. package/driver/gateway.mjs +220 -839
  102. package/driver/goods-evidence.mjs +10 -6
  103. package/driver/jx-lanes.mjs +3 -3
  104. package/driver/jx-units.mjs +31 -37
  105. package/driver/jx.mjs +44 -59
  106. package/driver/knockout-assess-record.mjs +3 -3
  107. package/driver/knockout-caveats.mjs +21 -0
  108. package/driver/knockout-correction-record.mjs +58 -28
  109. package/driver/knockout-frame-record.mjs +2 -2
  110. package/driver/knockout-register-read.mjs +38 -21
  111. package/driver/knockout-register-record.mjs +5 -6
  112. package/driver/knockout-review-record.mjs +12 -11
  113. package/driver/ladder/model-gauge.mjs +88 -0
  114. package/driver/ladder/next-rung.mjs +296 -0
  115. package/driver/ladder/rescue.mjs +146 -0
  116. package/driver/ladder/stage-tools.mjs +57 -0
  117. package/driver/ladder/turn-failure.mjs +166 -0
  118. package/driver/log.mjs +2 -2
  119. package/driver/matter-frame-record.mjs +4 -4
  120. package/driver/methodology-witness.mjs +2 -2
  121. package/driver/narrative-refutation-record.mjs +145 -42
  122. package/driver/one-build-per-run.mjs +62 -0
  123. package/driver/outbox-backoff.mjs +4 -4
  124. package/driver/owner-screen.mjs +0 -10
  125. package/driver/owner-use-check.mjs +2 -28
  126. package/driver/package.json +1 -1
  127. package/driver/partial-payload-baseline.json +1 -1
  128. package/driver/parts-not-completed.mjs +1 -1
  129. package/driver/pipeline-knockout.mjs +1015 -1001
  130. package/driver/pipeline.mjs +511 -9265
  131. package/driver/placement-decisions.mjs +2 -2
  132. package/driver/placement-form-io.mjs +7 -9
  133. package/driver/placement-union.mjs +0 -6
  134. package/driver/plan-stability.mjs +7 -10
  135. package/driver/portal-acks.mjs +3 -2
  136. package/driver/portal-confirmation.mjs +48 -0
  137. package/driver/portal-families.mjs +3 -2
  138. package/driver/portal-local-auth.mjs +1 -2
  139. package/driver/portal-routes/README.md +24 -0
  140. package/driver/portal-routes/admin.mjs +425 -0
  141. package/driver/portal-routes/compose.mjs +66 -0
  142. package/driver/portal-routes/config.mjs +118 -0
  143. package/driver/portal-routes/connect.mjs +283 -0
  144. package/driver/portal-routes/feedback.mjs +178 -0
  145. package/driver/portal-routes/me.mjs +165 -0
  146. package/driver/portal-routes/queue.mjs +64 -0
  147. package/driver/portal-routes/report.mjs +106 -0
  148. package/driver/portal-routes/run.mjs +508 -0
  149. package/driver/portal-routes/runs.mjs +127 -0
  150. package/driver/portal-routes/usage.mjs +82 -0
  151. package/driver/portal-runs.mjs +588 -0
  152. package/driver/portal-service.mjs +78 -2592
  153. package/driver/portal-static.mjs +3 -1
  154. package/driver/predelivery-lint.mjs +92 -9
  155. package/driver/production-pool-guard.mjs +1 -1
  156. package/driver/profiles.mjs +5 -4
  157. package/driver/progress.mjs +29 -24
  158. package/driver/publish/README.md +10 -5
  159. package/driver/publish/archive-tags.mjs +3 -2
  160. package/driver/publish/demo-marking.mjs +2 -2
  161. package/driver/publish/index.mjs +215 -140
  162. package/driver/publish/knockout.mjs +153 -107
  163. package/driver/publish/office-record-links.mjs +22 -0
  164. package/driver/publish/parse.mjs +20 -5
  165. package/driver/publish/pool-admin.mjs +9 -3
  166. package/driver/publish/render.mjs +11 -3
  167. package/driver/publish/report-dates.mjs +3 -4
  168. package/driver/publish/report-registry.mjs +7 -10
  169. package/driver/publish/seed-pool.mjs +3 -2
  170. package/driver/publish/shell.mjs +106 -0
  171. package/driver/publish/templates/report.css +3 -1
  172. package/driver/queue-order.mjs +4 -3
  173. package/driver/record-carry.mjs +0 -9
  174. package/driver/record-discard.mjs +1 -4
  175. package/driver/record-fold.mjs +3 -3
  176. package/driver/record-goods.mjs +5 -5
  177. package/driver/reference-score.mjs +2 -3
  178. package/driver/register-capabilities.mjs +0 -6
  179. package/driver/register-count.mjs +3 -2
  180. package/driver/register-digest-record.mjs +7 -7
  181. package/driver/register-fixture-marker.mjs +3 -3
  182. package/driver/register-plan.mjs +2 -2
  183. package/driver/register-records.mjs +2 -2
  184. package/driver/register-taint.mjs +3 -3
  185. package/driver/register-unit-record.mjs +48 -9
  186. package/driver/register-unreachable.mjs +4 -3
  187. package/driver/registry-fidelity.mjs +79 -34
  188. package/driver/repair-composers.mjs +14 -9
  189. package/driver/repair-digest.mjs +4 -6
  190. package/driver/repair-scope.mjs +3 -3
  191. package/driver/repair-targets.mjs +24 -9
  192. package/driver/repairs.mjs +44 -58
  193. package/driver/replay-archive.mjs +7 -7
  194. package/driver/report-card-record.mjs +3 -3
  195. package/driver/report-overview-record.mjs +4 -4
  196. package/driver/research-answers.mjs +38 -6
  197. package/driver/research-checks.mjs +4 -4
  198. package/driver/result-noun-fields.mjs +28 -11
  199. package/driver/review-addresses.mjs +163 -0
  200. package/driver/rule-shape.mjs +1 -1
  201. package/driver/run-delivered.mjs +340 -0
  202. package/driver/run-economics.mjs +8 -26
  203. package/driver/run-failed.mjs +545 -0
  204. package/driver/run-integrity.mjs +1 -1
  205. package/driver/run-outcome.mjs +314 -0
  206. package/driver/run-park.mjs +23 -0
  207. package/driver/run-quote.mjs +32 -0
  208. package/driver/run-record.mjs +352 -0
  209. package/driver/run-requirements.mjs +22 -0
  210. package/driver/run-shell.mjs +55 -0
  211. package/driver/runner.mjs +71 -33
  212. package/driver/saved-register-pages.mjs +4 -4
  213. package/driver/score-redaction.mjs +2 -2
  214. package/driver/search-policy.mjs +12 -13
  215. package/driver/settle-stamp.mjs +4 -3
  216. package/driver/skeptic-record.mjs +2 -2
  217. package/driver/skeptic-search.mjs +1 -1
  218. package/driver/skills/README.md +7 -7
  219. package/driver/skills/blind-frame/SKILL.md +1 -2
  220. package/driver/skills/case-law-citation/SKILL.md +9 -37
  221. package/driver/skills/case-law-citation/sources/courtlistener.md +1 -3
  222. package/driver/skills/case-law-citation/sources/eurlex.md +8 -11
  223. package/driver/skills/case-law-citation/sources/legaldatahunter.md +1 -1
  224. package/driver/skills/clearance-common-law/SKILL.md +45 -111
  225. package/driver/skills/clearance-common-law/perplexity-prompts.md +7 -79
  226. package/driver/skills/clearance-register/SKILL.md +15 -33
  227. package/driver/skills/clearance-register/digest.md +31 -92
  228. package/driver/skills/clearance-register/providers/clarivate.md +2 -2
  229. package/driver/skills/clearance-register/providers/corsearch.md +5 -5
  230. package/driver/skills/clearance-register/providers/euipo.md +1 -2
  231. package/driver/skills/clearance-register/providers/free-tier.md +0 -19
  232. package/driver/skills/clearance-register/providers/signa.md +6 -25
  233. package/driver/skills/clearance-register/providers/uspto-local.md +0 -24
  234. package/driver/skills/clearance-register/register-recipes.md +8 -15
  235. package/driver/skills/clearance-register/status-rules.md +6 -24
  236. package/driver/skills/clearance-register/unit.md +11 -20
  237. package/driver/skills/clearance-search/delivery-contract.md +24 -120
  238. package/driver/skills/clearance-search/field-doctrine-pharma.md +1 -5
  239. package/driver/skills/clearance-search/firm-wide-reasoning.md +24 -43
  240. package/driver/skills/clearance-search/phase2-execution.md +29 -77
  241. package/driver/skills/clearance-search/report-prose.md +3 -4
  242. package/driver/skills/clearance-search/risk-framework-demo.md +1 -1
  243. package/driver/skills/clearance-search/risk-framework-triage.manifest.json +3 -3
  244. package/driver/skills/clearance-search/risk-framework-triage.md +7 -9
  245. package/driver/skills/clearance-search/risk-framework.manifest.json +1 -1
  246. package/driver/skills/clearance-search/risk-framework.md +1 -1
  247. package/driver/skills/clearance-search/synthesis-rules.md +30 -107
  248. package/driver/skills/clearance-search/worked-examples.md +5 -5
  249. package/driver/skills/clearance-variants/SKILL.md +46 -45
  250. package/driver/skills/clearance-variants/transliteration-scripts.md +4 -4
  251. package/driver/skills/frame-diff/SKILL.md +1 -1
  252. package/driver/skills/knockout-assess/SKILL.md +6 -14
  253. package/driver/skills/knockout-frame/SKILL.md +1 -1
  254. package/driver/skills/matter-frame/SKILL.md +7 -12
  255. package/driver/skills/matter-frame/watchlist-reference.md +1 -4
  256. package/driver/skills/narrative-refutation/SKILL.md +20 -30
  257. package/driver/skills/placement-inquiry/SKILL.md +8 -18
  258. package/driver/skills-store-provenance.mjs +1 -1
  259. package/driver/stage-context.mjs +32 -35
  260. package/driver/stage-freshness.mjs +127 -11
  261. package/driver/stages-knockout.mjs +49 -22
  262. package/driver/stages.mjs +88 -283
  263. package/driver/status-snapshot.mjs +2 -1
  264. package/driver/steps/correction-cycle.mjs +311 -0
  265. package/driver/steps/corrections.mjs +644 -0
  266. package/driver/steps/delivery.mjs +1287 -0
  267. package/driver/steps/frame-comparison.mjs +922 -0
  268. package/driver/steps/intake.mjs +84 -0
  269. package/driver/steps/open-run.mjs +419 -0
  270. package/driver/steps/overview-and-cards.mjs +899 -0
  271. package/driver/steps/placement-and-digest.mjs +23 -0
  272. package/driver/steps/register-sweep.mjs +1563 -0
  273. package/driver/steps/skeptic-and-follow-up.mjs +831 -0
  274. package/driver/steps/synthesis.mjs +261 -0
  275. package/driver/steps/verdict-gate.mjs +968 -0
  276. package/driver/suite-census.json +403 -91
  277. package/driver/surface-exit-verdict.mjs +0 -8
  278. package/driver/synthesis-record.mjs +72 -6
  279. package/driver/terminal-clamp.mjs +10 -0
  280. package/driver/tokens.mjs +8 -62
  281. package/driver/tool-calls.mjs +2 -2
  282. package/driver/unit-state-verdict.mjs +1 -1
  283. package/driver/usage-ledger.mjs +2 -1
  284. package/driver/verify-knockout.mjs +20 -35
  285. package/driver/verify.mjs +47 -36
  286. package/driver/web-grid.mjs +3 -4
  287. package/driver/whatif-memo-run.mjs +2 -2
  288. package/driver/whatif-queue.mjs +4 -3
  289. package/driver/withheld-families.mjs +14 -15
  290. package/driver/worker-heartbeat.mjs +3 -2
  291. package/driver/write-up-form.mjs +0 -3
  292. package/mcp-server/CHANGELOG.md +4 -0
  293. package/mcp-server/http-server.mjs +1 -1
  294. package/mcp-server/lib/brief.mjs +22 -4
  295. package/mcp-server/lib/events.mjs +2 -2
  296. package/mcp-server/lib/evidence.mjs +3 -2
  297. package/mcp-server/lib/findings.mjs +2 -1
  298. package/mcp-server/lib/knockout.mjs +9 -10
  299. package/mcp-server/lib/ops.mjs +9 -9
  300. package/mcp-server/lib/runs.mjs +9 -10
  301. package/mcp-server/lib/trace.mjs +1 -1
  302. package/mcp-server/lib/whatif.mjs +2 -3
  303. package/mcp-server/package.json +1 -1
  304. package/mcp-server/server.mjs +5 -5
  305. package/package.json +2 -1
  306. package/portal-ui/dist/assets/{index-fPqAU0sx.js → index-D5rkCjDc.js} +26 -14
  307. package/portal-ui/dist/index.html +1 -1
  308. package/portal-ui/package.json +3 -3
  309. package/providers/README.md +1 -1
  310. package/providers/_shared/answer-memory.mjs +4 -5
  311. package/providers/_shared/execute-plan.mjs +48 -1
  312. package/providers/_shared/records-from-search.mjs +46 -0
  313. package/providers/clarivate/README.md +2 -2
  314. package/providers/clarivate/src/adapter.js +147 -0
  315. package/providers/clarivate/src/core.js +1 -14
  316. package/{driver/engine/mcp/clarivate-server.mjs → providers/clarivate/src/mount.js} +5 -10
  317. package/providers/corsearch/README.md +3 -3
  318. package/providers/corsearch/src/adapter.js +80 -0
  319. package/providers/corsearch/src/core.js +14 -11
  320. package/{driver/engine/mcp/corsearch-server.mjs → providers/corsearch/src/mount.js} +5 -10
  321. package/providers/euipo/README.md +2 -2
  322. package/providers/euipo/src/adapter.js +85 -0
  323. package/providers/euipo/src/core.js +1 -1
  324. package/providers/euipo/src/euipo-client.js +1 -2
  325. package/{driver/engine/mcp/euipo-server.mjs → providers/euipo/src/mount.js} +5 -10
  326. package/providers/free-tier/README.md +2 -2
  327. package/providers/free-tier/src/adapter.js +127 -0
  328. package/{driver/engine/mcp/free-tier-server.mjs → providers/free-tier/src/mount.js} +5 -10
  329. package/providers/jx-subclass/coverage.mjs +1 -6
  330. package/providers/jx-subclass/score-truth.mjs +2 -1
  331. package/providers/oauth-mcp-bridge/CHANGELOG.md +4 -0
  332. package/providers/oauth-mcp-bridge/package.json +1 -1
  333. package/providers/perplexity/src/core.js +2 -2
  334. package/providers/signa/README.md +2 -2
  335. package/providers/signa/src/adapter.js +157 -0
  336. package/providers/signa/src/capabilities.js +0 -3
  337. package/providers/signa/src/core.js +2 -2
  338. package/{driver/engine/mcp/signa-server.mjs → providers/signa/src/mount.js} +7 -12
  339. package/providers/signa/src/offices.generated.js +17 -15
  340. package/providers/uspto-local/README.md +1 -1
  341. package/providers/uspto-local/bin/verify-index.mjs +1 -1
  342. package/providers/uspto-local/src/adapter.js +75 -0
  343. package/{driver/engine/mcp/uspto-local-server.mjs → providers/uspto-local/src/mount.js} +5 -10
  344. package/scripts/band-shape-probe.mjs +2 -2
  345. package/scripts/citation-line-check.mjs +7 -7
  346. package/scripts/compare.mjs +1 -1
  347. package/scripts/dead-names.mjs +2 -2
  348. package/scripts/e2e-first-time.mjs +19 -7
  349. package/scripts/e2e.mjs +13 -13
  350. package/scripts/engine-probe.mjs +1 -1
  351. package/scripts/env-audit.mjs +7 -4
  352. package/scripts/env-classify.mjs +5 -1
  353. package/scripts/feedback-mint.mjs +1 -1
  354. package/scripts/freeze-example-run.mjs +7 -7
  355. package/scripts/mint-suite-census.mjs +2 -2
  356. package/scripts/nightly-notice.mjs +1 -1
  357. package/scripts/release-cut-decision.mjs +7 -2
  358. package/scripts/release-note-required.mjs +26 -9
  359. package/scripts/release-notes-lint.mjs +3 -2
  360. package/scripts/release-version-pr-checks.mjs +1 -1
  361. package/scripts/settings-render-check.mjs +23 -3
  362. package/scripts/test-run.mjs +5 -5
  363. package/scripts/travelling-predicates.mjs +1 -1
  364. package/scripts/undeclared-field-census.mjs +1 -1
  365. package/scripts/unexecuted-asserts.mjs +1 -1
  366. package/scripts/verify-publishable.mjs +1 -1
  367. package/shared/client-door.mjs +1 -1
  368. package/shared/connect-clients.mjs +1 -1
  369. package/shared/connector-signin-probe.mjs +1 -1
  370. package/shared/env-aliases.mjs +1 -1
  371. package/shared/invocation.mjs +14 -2
  372. package/shared/names-in-force.mjs +2 -0
  373. package/shared/register-selection.mjs +2 -2
  374. package/shared/store-in-repo.mjs +3 -3
  375. package/shared/summary-blocks.mjs +0 -3
  376. package/shared/trigger-lane.mjs +1 -1
  377. package/shared/vacuous-pass.mjs +2 -2
  378. package/shared/verb-shim.mjs +4 -2
  379. package/node_modules/exceljs/README.md +0 -3023
@@ -7,7 +7,7 @@
7
7
  // spec.output_path itself (never round-trips the grid through the model's bounded turn output).
8
8
  import { existsSync, readFileSync, writeFileSync, mkdirSync, appendFileSync } from "node:fs";
9
9
  import { dirname, basename } from "node:path";
10
- import { driverDir } from "../../../shared/driver-dir.mjs"; //
10
+ import { driverDir, paths, readJson } from "../../run-record.mjs"; //
11
11
  import { underStudioSegment } from "../../../shared/path-seps.mjs"; // Windows builds the path with "\"
12
12
  import { serve } from "./stdio-server.mjs";
13
13
  import { answerBudget } from "../../../shared/answer-parts.mjs";
@@ -30,7 +30,7 @@ import { parsePrRiskResults, connotationObligations, renderConnotationObligation
30
30
  import { obligationsSidecarPath } from "../../disposition-tool.mjs";
31
31
  import { writeGridProvenance } from "./grid-provenance.mjs"; // — what served the grid, beside the ledger
32
32
  import { insideRun } from "../../../shared/inside-run.mjs"; // a path a tool is handed is served only inside this run
33
- import { keepResearchAnswer, isResearchAnswer, replayAnswersFrom, researchReplayOn, savedResearchAnswer } from "../../research-answers.mjs"; // each answer's text, kept for a later attempt of its stage; a replay answers from them
33
+ import { keepResearchAnswer, isResearchAnswer, replayAnswersFrom, researchReplayOn, savedResearchAnswer, researchRequestKey, heldAnswerToRequest } from "../../research-answers.mjs"; // each answer's text, kept for a later attempt of its stage, which is answered from it; a replay answers from them
34
34
 
35
35
  const API_KEY = process.env.PERPLEXITY_API_KEY || "";
36
36
 
@@ -68,7 +68,7 @@ const AGENT = process.env.CLEAROTRON_GATHER_AGENT || "";
68
68
  function logCall(tool, args, result) {
69
69
  if (!RUN_DIR) return;
70
70
  try {
71
- const p = driverDir(RUN_DIR, "reading-log.jsonl");
71
+ const p = paths(RUN_DIR).readingLog;
72
72
  mkdirSync(dirname(p), { recursive: true });
73
73
  appendFileSync(p, JSON.stringify({
74
74
  ts: new Date().toISOString(), tool, args, ...result,
@@ -85,7 +85,7 @@ function logCall(tool, args, result) {
85
85
  const PINNED_QUESTION_PRESET = (() => {
86
86
  if (!RUN_DIR) return null;
87
87
  try {
88
- const p = JSON.parse(readFileSync(driverDir(RUN_DIR, "search-policy.json"), "utf8"))?.web?.questionPreset;
88
+ const p = readJson(paths(RUN_DIR).searchPolicy)?.web?.questionPreset;
89
89
  return typeof p === "string" && isKnownPreset(p) ? p : null;
90
90
  } catch { return null; }
91
91
  })();
@@ -238,7 +238,7 @@ async function research(params) {
238
238
  if (RUN_DIR && !insideRun(RUN_DIR, grid_spec_path))
239
239
  return "ERROR: grid_spec_path is outside this run's folder. The driver writes the spec inside the run; use the path it gave you.";
240
240
  let spec;
241
- try { spec = validateGridSpec(JSON.parse(readFileSync(grid_spec_path, "utf8"))); }
241
+ try { spec = validateGridSpec(readJson(grid_spec_path)); }
242
242
  catch (err) { return `ERROR: grid_spec_path unreadable/invalid (${err.message}). The driver writes this file; do not hand-author it.`; }
243
243
  if (RUN_DIR && !insideRun(RUN_DIR, spec.output_path))
244
244
  return requiredLedgerRefusal("ERROR: the grid spec's output_path is outside this run's folder. The driver writes the spec inside the run; use the path it gave you.", { spec, gridSpecPath: grid_spec_path });
@@ -307,8 +307,17 @@ async function research(params) {
307
307
  // setting decided it rather than the question.
308
308
  const asked = { task, depth: depth ?? null, preset, ...(PINNED_QUESTION_PRESET ? { pinned: true } : {}), allow_fetch, enable_sandbox,
309
309
  ...(domain_filter ? { domain_filter } : {}), ...(modelOverride ? { model: modelOverride } : {}) };
310
+ const body = buildRequestBody({ task, preset, allowFetch: allow_fetch, domainFilter: domain_filter, modelOverride, enableSandbox: enable_sandbox, responseSchema: response_schema, schemaName: schema_name });
311
+ // A QUESTION THIS STAGE ALREADY GOT AN ANSWER TO IS NOT SENT AGAIN (research-answers.mjs): the same request, from
312
+ // this stage or a retry of it, answered by what the run kept. It is logged as a lookup is, marked as reused, so the
313
+ // run's record says which questions were paid for on this pass.
314
+ const request = researchRequestKey(body);
315
+ const held = heldAnswerToRequest(RUN_DIR, SESSION, request);
316
+ if (held) {
317
+ logCall("perplexity_research", asked, { ok: true, bytes: held.text.length, reused: true });
318
+ return held.text;
319
+ }
310
320
  try {
311
- const body = buildRequestBody({ task, preset, allowFetch: allow_fetch, domainFilter: domain_filter, modelOverride, enableSandbox: enable_sandbox, responseSchema: response_schema, schemaName: schema_name });
312
321
  const data = await callAgentAPI(API_KEY, body);
313
322
  keepRaw("question", { task, preset }, data);
314
323
  const text = enable_sandbox ? formatSandboxResponse(data, preset) : formatResponse(data, preset);
@@ -317,7 +326,7 @@ async function research(params) {
317
326
  logCall("perplexity_research", asked, isResearchAnswer(text)
318
327
  ? { ok: true, bytes: String(text ?? "").length, citations: citationCount(data) }
319
328
  : { ok: false, error: String(text ?? "").slice(0, 200) });
320
- keepResearchAnswer(RUN_DIR, { session: SESSION, agent: AGENT, task, preset, text });
329
+ keepResearchAnswer(RUN_DIR, { session: SESSION, agent: AGENT, task, preset, request, text });
321
330
  return text;
322
331
  } catch (err) {
323
332
  // A FAILED LOOKUP IS LOGGED TOO, and that is the half that matters most: without it, "the search
@@ -58,7 +58,7 @@ import { recordClosures } from "../../doubt-closure-tool.mjs";
58
58
  import { MAX_CLOSURES_PER_CALL, CLOSURE_KINDS } from "../../doubt-closure-call.mjs";
59
59
  import { readFileSync, existsSync } from "node:fs"; import { FROZEN_METHOD_FILE } from "../../framework-method.mjs";
60
60
  import { join } from "node:path";
61
- import { driverDir } from "../../../shared/driver-dir.mjs"; //
61
+ import { driverDir, readJson } from "../../run-record.mjs"; //
62
62
  import { VARIANT_CATEGORIES } from "../../variant-manifest-model.mjs";
63
63
  import { DIFF_LAYERS, DIFF_SEVERITIES } from "../../frame-diff-model.mjs";
64
64
  import { REGISTER_AXES } from "../../coverage-ledger.mjs";
@@ -207,7 +207,7 @@ const CLOSURE_SPEC = "doubt-closure-spec.json";
207
207
  * file disagreeing is the whole failure this transport exists to remove.
208
208
  */
209
209
  function loadClosureSpec(runDir) {
210
- const spec = JSON.parse(readFileSync(driverDir(runDir, CLOSURE_SPEC), "utf8"));
210
+ const spec = readJson(driverDir(runDir, CLOSURE_SPEC));
211
211
  const allowedFiles = Array.isArray(spec?.allowedFiles) ? spec.allowedFiles : [];
212
212
  const fileTexts = {};
213
213
  for (const name of allowedFiles) {
@@ -1022,7 +1022,8 @@ serve({
1022
1022
  kind: { type: "string", enum: [...CORRECTION_KINDS], description: "Which kind of defect this is. You declare it from your own read; code only partitions the closed set, never a keyword grep over your prose." },
1023
1023
  text: { type: "string", description: "One line, naming the file and the exact claim. A flag that opens as a list item or heading is refused — the driver renders the list." },
1024
1024
  fix: { type: "string", description: "Optional. One line describing the targeted edit that would settle it." },
1025
- on: { type: "array", items: { type: "integer" }, description: "The finding ordinals this flag is about, 1-based. Omit for a flag about the document rather than a finding." },
1025
+ on: { type: "array", items: { type: "integer" }, description: "The finding ordinals this flag is about, 1-based. Omit for a flag about the document rather than a finding. An ordinal that names no finding this review was handed is refused." },
1026
+ lines: { type: "array", items: { type: "string" }, description: "The address of each part of the report this flag is about that is not a finding: a coverage line, an action, a mark assessment read or a narrative section. Copy each address from the address list in the dispatch. An address not on that list is refused. If none of the flag's targets has a listed address, omit `lines` and name the targets in `text`." },
1026
1027
  positions: { type: "array", items: { type: "string" }, description: "The record id of each excluded position this flag is about, exactly as the writer's exclusions list names it. A flag about an exclusion needs no finding ordinal." },
1027
1028
  },
1028
1029
  },
@@ -1258,7 +1259,7 @@ serve({
1258
1259
  registerEstimate: { type: "string" },
1259
1260
  parodyNote: { type: ["string", "null"] },
1260
1261
  crowdedField: { type: "boolean" },
1261
- purpleNotes: { type: "array", items: { type: "string" }, description: "Reviewer notes appear on the report page and are removed on export." },
1262
+ purpleNotes: { type: "array", items: { type: "string" }, description: "The report never prints a note; it reaches the audit workbook and the assistant." },
1262
1263
  // — DECLARED HERE OR IT IS FOLKLORE.
1263
1264
  //
1264
1265
  // Both fields were built end to end for — instructed in the dispatch,
@@ -1445,8 +1446,8 @@ serve({
1445
1446
  schemaNow: (schema) => knockoutAssessSchemaFor(schema, process.env.CLEAROTRON_BAND_RUN_DIR),
1446
1447
  description:
1447
1448
  "Hand back your repair of the defects you were given, as VALUES, sending only what changes. The driver merges it onto " +
1448
- "the chunk it holds and checks the result as it checks a rated chunk. It refuses a change to a name no defect concerns, " +
1449
- "a moved finding no answer accounts for, and a rating that moves without its dependent answers. A repair turn may send " +
1449
+ "the chunk it holds and checks the result as it checks a rated chunk. It refuses a change to a name no defect concerns, except a finding a defect names that also stands on that name. " +
1450
+ "It refuses a moved finding no answer accounts for, and a rating that moves without its dependent answers. A repair turn may send " +
1450
1451
  "only what it corrects, and what it has repaired is kept.",
1451
1452
  inputSchema: {
1452
1453
  type: "object",
@@ -0,0 +1,29 @@
1
+ #!/usr/bin/env node
2
+ // SPDX-License-Identifier: AGPL-3.0-only
3
+ // Copyright 2026 Cordillera Sàrl. Additional terms under section 7 of the AGPL-3.0 apply — see ADDITIONAL-TERMS.md
4
+ // register-server.mjs — the one MCP server for every trademark register, mounting the provider it is named.
5
+ //
6
+ // node register-server.mjs <provider>
7
+ //
8
+ // A provider states its tools in `providers/<provider>/src/mount.js`: their names, descriptions, schemas and
9
+ // handlers. What every register shares stays here and reaches the mount as arguments, so a provider folder
10
+ // imports nothing from the driver. gather-config names the provider on the command line, from the same row
11
+ // that says which tools a stage is granted.
12
+ import { dirname, join } from "node:path";
13
+ import { fileURLToPath, pathToFileURL } from "node:url";
14
+ import { serve } from "./stdio-server.mjs";
15
+ import { crowdNoteFor } from "./crowd-note.mjs"; // how the unit decides on a crowd, beside an answer that carries one
16
+ import { proposeSupplemental } from "./supplemental.mjs";
17
+ import { narrowingFields } from "./proposal-fields.mjs";
18
+ import { CLARIVATE_PROPOSE_TOOL } from "./clarivate-propose-tool.mjs";
19
+
20
+ const provider = process.argv[2] ?? "";
21
+ if (!/^[a-z][a-z-]*$/.test(provider)) {
22
+ process.stderr.write(`[mcp:register] needs a provider name as its argument, and was given ${JSON.stringify(provider)}\n`);
23
+ process.exit(2);
24
+ }
25
+ const here = dirname(fileURLToPath(import.meta.url));
26
+ const { mount } = await import(pathToFileURL(join(here, "..", "..", "..", "providers", provider, "src", "mount.js")).href);
27
+ const { version, tools } = mount({ proposeSupplemental, narrowingFields, CLARIVATE_PROPOSE_TOOL });
28
+
29
+ serve({ name: "register", version, noteFor: crowdNoteFor, tools });
@@ -11,7 +11,7 @@ import "./http-dispatcher.mjs"; // side effect: raise undici headersTimeout fo
11
11
  import { createInterface } from "node:readline";
12
12
  import { appendFileSync, mkdirSync } from "node:fs";
13
13
  import { dirname } from "node:path";
14
- import { driverDir } from "../../../shared/driver-dir.mjs"; //
14
+ import { paths } from "../../run-record.mjs"; //
15
15
  import { answerBudget, answerPieces, servedPart, partNotHeld, takePart, heldAnswers, withAnswerPart } from "../../../shared/answer-parts.mjs";
16
16
 
17
17
  // ── half 2 — THE TOOL CALL LOG, so a killed call is a FACT and not an inference ────────────────
@@ -38,7 +38,7 @@ import { answerBudget, answerPieces, servedPart, partNotHeld, takePart, heldAnsw
38
38
  // failed write costs this diagnostic and nothing else.
39
39
  const toolLogPath = () => {
40
40
  const dir = process.env.CLEAROTRON_BAND_RUN_DIR;
41
- return dir ? driverDir(dir, "tool-calls.jsonl") : null;
41
+ return dir ? paths(dir).toolCalls : null;
42
42
  };
43
43
 
44
44
  // WHAT GOES IN: the tool's name, the sequence number that pairs the two lines, and — for the plan tools
@@ -106,9 +106,9 @@ export function serve({ name, version = "0.1.0", tools = [], noteFor = null }) {
106
106
  // reaches the open world. A stock server carries them on every tool; ours carried none.
107
107
  //
108
108
  // ✕ THIS IS NOT THE ESTABLISHED CAUSE OF THE CODEX REFUSALS, and nothing here may be read as one. The
109
- // universal claim — "codex cannot call any MCP tool" — was WITHDRAWN on 1968 by the lane that filed
110
- // it: real codex completed 1,292 MCP calls across three pre-rebuild runs. What differs after the
111
- // 2026-08-24 rebuild is open under. The probe below is ONE measurement on ONE CLI
109
+ // universal claim — "codex cannot call any MCP tool" — was WITHDRAWN by those who made it: real
110
+ // codex completed 1,292 MCP calls across three pre-rebuild runs. What differs after the 2026-08-24
111
+ // rebuild is still open. The probe below is ONE measurement on ONE CLI
112
112
  // version, recorded so nobody re-derives it. It is a candidate, not a finding, and this fix does not
113
113
  // rest on it.
114
114
  //
@@ -26,12 +26,12 @@
26
26
  // widening need none. The reading step decides now; every proposal is minted or refused on its own
27
27
  // merits. `mintSupplementalEntries` still takes a cap from a caller that sets one, and none does.
28
28
  //
29
- // Pure orchestration with injected IO/executor (deps) so it tests offline; the corsearch-server handler
29
+ // Pure orchestration with injected IO/executor (deps) so it tests offline; the corsearch mount's handler
30
30
  // binds the live doExecutePlan.
31
31
 
32
- import { readFileSync, writeFileSync, renameSync, existsSync, mkdirSync } from "node:fs";
32
+ import { writeFileSync, renameSync, existsSync, mkdirSync } from "node:fs";
33
33
  import { dirname, join } from "node:path";
34
- import { driverDir } from "../../../shared/driver-dir.mjs"; //
34
+ import { paths, readJson } from "../../run-record.mjs"; //
35
35
  import { PLAN_PREDICATES, PLAN_MAX_OR_WIDTH, PLAN_MAX_NAME_LENGTH, planExactOrWidth, planPhoneticOrWidth, fingerprint, exactOperatorEntries, ownerIntersectionGap, goodsTextGap, resolveRegions, houseElementOf, withoutHouseElementTerms, containsFormSubstitution } from "../../register-plan.mjs";
36
36
  import { entryTermIssues } from "../../../providers/_shared/term-shape.mjs";
37
37
  import { OUTSTANDING_REASON, runDriverDirOf } from "../../../providers/_shared/follow-up-searches.mjs";
@@ -416,7 +416,7 @@ export async function proposeSupplemental(params, tctx, deps) {
416
416
  // unchanged.
417
417
  let planRegions = [], planClasses = [], house = null, bound = { addedClasses: [], addedClassQuestions: [] }, scriptMarkets = null, scriptQuestionsAsked = [];
418
418
  try {
419
- const frozen = JSON.parse(readFileSync(driverDir(dirname(dirname(outPath)), "register-plan.json"), "utf8"));
419
+ const frozen = readJson(paths(dirname(dirname(outPath))).registerPlan);
420
420
  house = houseElementOf(frozen);
421
421
  bound = addedClassBound(frozen);
422
422
  if (Array.isArray(frozen?.script_markets)) { scriptMarkets = frozen.script_markets; scriptQuestionsAsked = Array.isArray(frozen?.script_questions_asked) ? frozen.script_questions_asked : []; }
@@ -429,7 +429,7 @@ export async function proposeSupplemental(params, tctx, deps) {
429
429
  let supp = { schema: "register-plan/1", plan_version: 1, derived_from: { job_key: `supplemental:${axis}`, variants_fingerprint: "supplemental" }, regions: planRegions, entries: [] };
430
430
  if (existsSync(suppPath)) {
431
431
  try {
432
- const prior = JSON.parse(readFileSync(suppPath, "utf8"));
432
+ const prior = readJson(suppPath);
433
433
  if (prior && Array.isArray(prior.entries)) supp = { ...prior, regions: (Array.isArray(prior.regions) && prior.regions.length) ? prior.regions : planRegions };
434
434
  } catch { /* a torn supplemental file is rebuilt — minted qids are deterministic, nothing is lost */ }
435
435
  }
@@ -558,7 +558,7 @@ export async function proposeSupplemental(params, tctx, deps) {
558
558
  // inheritance above — the executor reads suppPath FROM DISK, so an in-memory-only backfill would
559
559
  // leave a reused-qid re-execution running region-less again.
560
560
  const staleOnDisk = existsSync(suppPath) && planRegions.length && !(() => {
561
- try { const d = JSON.parse(readFileSync(suppPath, "utf8")); return Array.isArray(d?.regions) && d.regions.length; }
561
+ try { const d = readJson(suppPath); return Array.isArray(d?.regions) && d.regions.length; }
562
562
  catch { return false; }
563
563
  })();
564
564
  // PR-6 (C1 — persist what evaporates): rejections used to live ONLY in this tool's response text.
@@ -586,7 +586,7 @@ export async function proposeSupplemental(params, tctx, deps) {
586
586
  let reusedHeld = [];
587
587
  try {
588
588
  const own = new Map();
589
- const { blocks } = bandWithSlicesOut(JSON.parse(readFileSync(outPath, "utf8")), slicesTakenOutByAxis(dirname(dirname(outPath))).get(axis));
589
+ const { blocks } = bandWithSlicesOut(readJson(outPath), slicesTakenOutByAxis(dirname(dirname(outPath))).get(axis));
590
590
  for (const b of blocks) if (b?.qid) own.set(String(b.qid), b);
591
591
  reusedHeld = reused.filter((q) => { const b = own.get(String(q)); return b && b.error !== true && !enrichedQids.includes(q) && !staleOnDisk; });
592
592
  } catch { reusedHeld = []; }
@@ -610,7 +610,7 @@ export async function proposeSupplemental(params, tctx, deps) {
610
610
  const refusedHere = outstanding.filter((q) => mintedHere.has(q));
611
611
  if (refusedHere.length) {
612
612
  let cur = supp;
613
- try { cur = JSON.parse(readFileSync(suppPath, "utf8")); } catch { /* the in-memory plan is what was written */ }
613
+ try { cur = readJson(suppPath); } catch { /* the in-memory plan is what was written */ }
614
614
  const gone = new Set(refusedHere);
615
615
  cur = withRejected({ ...cur, entries: (Array.isArray(cur?.entries) ? cur.entries : []).filter((e) => !gone.has(e?.qid)) },
616
616
  // The markets and goods ride on the row: the ask ledger keeps one ask per (issue, proposal), and the compact
@@ -627,7 +627,7 @@ export async function proposeSupplemental(params, tctx, deps) {
627
627
  // read the results BACK FROM THE BAND — the reasoning payload is never model-transcribed
628
628
  const results = {};
629
629
  try {
630
- const band = JSON.parse(readFileSync(outPath, "utf8"));
630
+ const band = readJson(outPath);
631
631
  const blocks = Array.isArray(band) ? band : [];
632
632
  for (const b of blocks) {
633
633
  if (!b || typeof b !== "object" || !b.qid || !(qids.includes(b.qid) || reusedHeld.includes(b.qid))) continue;
@@ -911,6 +911,9 @@ function errResult(t0, e, resumeRef) {
911
911
 
912
912
  export const openaiAgentEngine = {
913
913
  name: "openai-agent",
914
+ // A home that lasts for one stage, so its repair turns can resume the session. An engine with no such need omits both.
915
+ makeStageHome: (stage) => makeCodexHome(`stage-${String(stage).replace(/[^a-z0-9-]/gi, "_")}-`),
916
+ releaseStageHome: releaseCodexHome,
914
917
  // — WHAT THIS ENGINE GUARANTEES ABOUT SEAT WRITES: NOTHING, and the record now says so.
915
918
  // The boundary is a `claude -p` PreToolUse hook and codex has no PreToolUse — an absence by
916
919
  // construction, not a misconfiguration. The stage's permission profile grants the whole run folder,
@@ -926,7 +929,7 @@ export const openaiAgentEngine = {
926
929
  // Honest provenance for the telemetry stamp: on an openai run, `modelUsed` must be the GPT id, NOT the
927
930
  // anthropic-catalog resolution. Non-throwing (unknown → the input) so a stray alias never breaks logging.
928
931
  resolveModelId(model) { try { return openaiModel(model) ?? model; } catch { return model; } },
929
- // — `codexHome` is the CALLER'S if it passes one, and the caller then owns its lifetime.
932
+ // — `stageHome` is the CALLER'S if it passes one, and the caller then owns its lifetime.
930
933
  //
931
934
  // codex stores sessions under $CODEX_HOME/sessions/ and resolves `resume <id>` against them. Creating
932
935
  // and deleting a home per TURN meant every warm resume pointed at a directory that had never heard of
@@ -934,7 +937,7 @@ export const openaiAgentEngine = {
934
937
  // `thread/resume failed: no rollout found for thread id ... (code -32600)`, exit 1 — with the control
935
938
  // (same id, same binary, its own home) resuming cleanly. So every warm-patch retry and every
936
939
  // form-repair sub-turn on the codex arm has been failing.
937
- async runTurn({ message, model, thinking, timeoutSec, resumeRef, mcpConfig, allowedTools, cwd, skillsDir, skillsGrantRoots, profilesDir, resolveSkill, runDir, stallSec, codexHome: providedHome, streamFile = null } = {}) {
940
+ async runTurn({ message, model, thinking, timeoutSec, resumeRef, mcpConfig, allowedTools, cwd, skillsDir, skillsGrantRoots, profilesDir, resolveSkill, runDir, stallSec, stageHome: providedHome, streamFile = null } = {}) {
938
941
  if (!message) throw new Error("openai-agent.runTurn: message is required");
939
942
  const t0 = Date.now();
940
943
  let codexHome;
@@ -0,0 +1,103 @@
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
+ // registry.mjs — which engine adapters this driver ships, and which one this activation runs.
4
+ //
5
+ // The gateway asks this module and names no engine itself, so an engine is added here and in its own
6
+ // adapter, and the stage ladder does not change.
7
+
8
+ import { resolveModel } from "../driver.config.mjs";
9
+ import { anthropicAgentEngine } from "./anthropic-agent.mjs";
10
+ import { openaiAgentEngine } from "./openai-agent.mjs";
11
+ import { RUN_CHOICES_FILE, readRunChoices } from "./run-choices.mjs";
12
+
13
+ // ── Engine seam (CLEAROTRON_AI) ──────────────────────────────────────────────────────────────────
14
+ // The 14 stages run on the anthropic-agent engine (`claude -p` off-gateway with the stall-watchdog; see
15
+ // engine/CONTRACT.md). Its runTurn() returns the normalized tuple runStage consumes
16
+ // ({code,killed,wall,stdout,stderr,laneWaitMs,json,usage,sessionRef,signals}); all the
17
+ // classification/retry/warm logic below is engine-agnostic. There is no second exec path beside it —
18
+ // the comms one-shots that used to have one now write outbox packets and spawn nothing.
19
+ //
20
+ // Engine registry (provider adapters). The driver orchestration + the classification/retry/warm ladder are
21
+ // ENGINE-AGNOSTIC: everything provider-specific lives behind an engine's runTurn() → the normalized tuple. So
22
+ // provider CHOICE (e.g. Anthropic → OpenAI) = which adapter is registered and selected via CLEAROTRON_AI —
23
+ // NOT a model-name swap: each provider needs its own agentic-runtime adapter (MCP/tools/skills/streaming/resume).
24
+ // One is implemented today: `anthropic-agent` (`claude -p`, off-gateway). Adding e.g. `openai-agent` = write
25
+ // engine/openai-agent.mjs implementing the same runTurn() contract (engine/CONTRACT.md §1), registerEngine() it,
26
+ // and select it via CLEAROTRON_AI — runStage is untouched. (The legacy gateway-bin engine removed in the
27
+ // extraction was a *runtime*, not a provider choice, and coupled the driver to one integrator platform.) An
28
+ // unknown CLEAROTRON_AI fails loud — no silent wrong-provider run. There are no comms stages: every
29
+ // requester-facing event is an outbox packet (docs/DELIVERY.md).
30
+ const ENGINES = new Map([
31
+ [anthropicAgentEngine.name, anthropicAgentEngine],
32
+ [openaiAgentEngine.name, openaiAgentEngine], // second provider adapter (codex exec) — CLEAROTRON_AI=openai-agent
33
+ ]);
34
+ export const DEFAULT_ENGINE = anthropicAgentEngine.name; // "anthropic-agent" — production default UNCHANGED
35
+ /**
36
+ * The ids this registry actually holds — read-only, so a SECOND list can be pinned against the first
37
+ * rather than drifting away from it in silence. `ENGINE_BINARIES` in driver.config names the
38
+ * binary variable per engine and the wizard builds its menu from it; without this, "the wizard offers
39
+ * an engine the driver does not ship" and "the driver ships an engine setup cannot reach" are both
40
+ * invisible until a reader picks the row that does not exist. Same guarantee the register-provider
41
+ * list already has (onboard-wizard.test.mjs, "a new adapter must not be invisible to setup").
42
+ */
43
+ export function registeredEngines() { return [...ENGINES.keys()]; }
44
+ export function registerEngine(engine) {
45
+ if (!engine?.name || typeof engine.runTurn !== "function") throw new Error("registerEngine: expected an { name, runTurn } engine adapter");
46
+ ENGINES.set(engine.name.toLowerCase(), engine);
47
+ }
48
+
49
+ /**
50
+ * The machine's engine: the one a run STARTS on. PROCESS-WIDE, and the missing parameter is the point. A run
51
+ * that has started serves its turns from the engine it recorded then (`engineForRun` below, reading engine/run-choices.mjs), so
52
+ * a later change to `CLEAROTRON_AI` reaches new runs only.
53
+ *
54
+ * This took a `_stageName` it ignored, under a call-site comment reading "per-stage: CLEAROTRON_AI base,
55
+ * comms forced to the gateway, override-able". None of that existed: no per-stage override, no comms
56
+ * forcing, no per-job override. `CLEAROTRON_AI` is read from the process env at every activation and
57
+ * governs every stage of every job in it.
58
+ *
59
+ * A comment describing a capability that does not exist is worse than no comment — it gets believed and
60
+ * planned against, and the plan only fails once someone tries to use it. Corrected rather than built:
61
+ * per-stage selection is an architecture change (a job spec would have to carry the engine, and the
62
+ * routing would have to survive resume), not a comment fix.
63
+ *
64
+ * WHAT THE ABSENCE COSTS, stated so a round plan does not discover it mid-round: **an A/B cannot run
65
+ * both engines concurrently on one instance.** Comparing codex against anthropic means flipping
66
+ * CLEAROTRON_AI and running sequentially, or standing up a second instance with its own env, pool and
67
+ * ports. The same absence blocks routing the refutation reviewer to a different engine for family
68
+ * diversity (ENGINE-OPENAI-ADAPTER §6). Recorded in docs/E2E.md, which is where a round plan looks.
69
+ */
70
+ /** The registered adapter for one engine name, or null: no fallback to the machine's engine. */
71
+ export function engineNamed(id) { return ENGINES.get(String(id ?? "").trim().toLowerCase()) ?? null; }
72
+
73
+ export function selectEngine() {
74
+ const id = (process.env.CLEAROTRON_AI || DEFAULT_ENGINE).toLowerCase();
75
+ const engine = ENGINES.get(id);
76
+ if (!engine) throw new Error(`CLEAROTRON_AI="${id}" is not a registered engine adapter (available: ${[...ENGINES.keys()].join(", ")}). Implement one and registerEngine() it — see engine/CONTRACT.md.`);
77
+ return engine;
78
+ }
79
+
80
+ /**
81
+ * The engine that serves this run's turns. A run with a record gets its recorded engine whatever the machine's
82
+ * setting now says; a run with none gets the machine's engine, as every run did before the record existed.
83
+ * A recorded engine this driver cannot serve, or a record that does not read back, throws by name: the run's
84
+ * turns never fall through to a different engine.
85
+ */
86
+ export function engineForRun(runDir) {
87
+ const rec = readRunChoices(runDir);
88
+ if (rec.state === "none") return selectEngine();
89
+ if (rec.state === "unreadable")
90
+ throw new Error(`this run's engine record (_driver/${RUN_CHOICES_FILE}) ${rec.detail}, so its turns are not run on the machine's engine in its place`);
91
+ const engine = engineNamed(rec.engine);
92
+ if (!engine)
93
+ throw new Error(`this run started on the "${rec.engine}" engine, which this driver does not have registered (${registeredEngines().join(", ")}); it keeps that engine rather than switch to ${String(process.env.CLEAROTRON_AI ?? "").trim().toLowerCase() || DEFAULT_ENGINE}`);
94
+ return engine;
95
+ }
96
+
97
+ /**
98
+ * The model id a turn's rows record as asked for: the engine's own `resolveModelId`, or, for an adapter
99
+ * that declares none, Claude's catalog (`resolveModel`), which is what every such row has carried.
100
+ */
101
+ export function modelIdOf(engine, model) {
102
+ return engine.resolveModelId ? engine.resolveModelId(model) : resolveModel(model);
103
+ }
@@ -0,0 +1,162 @@
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
+ // run-choices.mjs — the engine and the register a run started on, frozen in the run so a resume keeps them.
4
+ //
5
+ // Both used to be read from the environment at every activation and recorded nowhere. A run parked on one engine
6
+ // and resumed after the machine's setting changed carried on under the other, and nothing in its record said so.
7
+ // The choice is now written once, when the run starts, and belongs to the run from then on:
8
+ //
9
+ // - a later change to the machine's setting applies to new runs only;
10
+ // - a resumed run keeps its recorded engine, and one this driver cannot serve is refused by name rather than
11
+ // swapped for the machine's default;
12
+ // - a run with no record is left without one. Nothing here writes a record for a run that has already started,
13
+ // because that would date today's setting back to a start nobody recorded.
14
+ //
15
+ // The record holds the two names and nothing else. Each must name an engine this driver ships or a register it
16
+ // knows, so no other string (a credential included) can be written into it.
17
+ //
18
+ // A LEAF: it reads the shipped-engine table, not the engine registry. The jurisdiction lanes' turn runner reads the
19
+ // record, tool servers reach that runner, and the registry would bring both engine adapters and every setting they
20
+ // read into each tool server's imports. The registry's `engineForRun` serves a run's turns from this record.
21
+ import { existsSync, readFileSync, renameSync, writeFileSync } from "node:fs";
22
+ import { driverDir, ensureDriverDir } from "../../shared/driver-dir.mjs";
23
+ import { ENGINE_BINARIES, PROVIDERS, REGISTER_PROVIDER, activeProvider } from "../driver.config.mjs";
24
+
25
+ export const RUN_CHOICES_FILE = "run-choices.json";
26
+
27
+ const nameOf = (v) => (v == null ? null : String(v).trim().toLowerCase() || null);
28
+
29
+ /**
30
+ * Write the run's engine and register, once. A record already on disk is never rewritten: the call answers
31
+ * with what is there and `written: false`, so a cold start that is retried keeps its first choice.
32
+ * `register` is null when the machine has none set; that is recorded as it was, not guessed.
33
+ */
34
+ export function recordRunChoices(runDir, { engine, register }) {
35
+ const held = readRunChoices(runDir);
36
+ if (held.state !== "none") return { written: false, ...held };
37
+ const e = nameOf(engine), r = nameOf(register);
38
+ if (!e || !Object.hasOwn(ENGINE_BINARIES, e))
39
+ throw new Error(`run-choices: "${e}" is not an engine this driver ships (${Object.keys(ENGINE_BINARIES).join(", ")})`);
40
+ if (r !== null && !Object.hasOwn(PROVIDERS, r))
41
+ throw new Error(`run-choices: "${r}" is not a register this driver knows (${Object.keys(PROVIDERS).join(", ")})`);
42
+ ensureDriverDir(runDir);
43
+ const p = driverDir(runDir, RUN_CHOICES_FILE);
44
+ writeFileSync(`${p}.tmp`, JSON.stringify({ schema: 1, engine: e, register: r }, null, 2) + "\n");
45
+ renameSync(`${p}.tmp`, p);
46
+ return { written: true, state: "recorded", engine: e, register: r };
47
+ }
48
+
49
+ /**
50
+ * What the run recorded: `{ state: "recorded", engine, register }`, `{ state: "none" }` for a run that has no
51
+ * record, or `{ state: "unreadable", detail }` for one whose record does not read back as the two names.
52
+ */
53
+ export function readRunChoices(runDir) {
54
+ if (!runDir) return { state: "none" };
55
+ const p = driverDir(runDir, RUN_CHOICES_FILE);
56
+ if (!existsSync(p)) return { state: "none" };
57
+ let o;
58
+ try { o = JSON.parse(readFileSync(p, "utf8")); }
59
+ catch (err) { return { state: "unreadable", detail: `does not parse: ${String(err?.message ?? err).slice(0, 200)}` }; }
60
+ const engine = nameOf(o?.engine), register = nameOf(o?.register);
61
+ if (!engine) return { state: "unreadable", detail: "names no engine" };
62
+ if (o?.register != null && typeof o.register !== "string") return { state: "unreadable", detail: "its register is not a name" };
63
+ return { state: "recorded", engine, register };
64
+ }
65
+
66
+ /**
67
+ * A resumed run whose recorded engine or register this process cannot serve.
68
+ *
69
+ * It is a PARK, not a failure. It is raised before any check spends anything and before the run's markers are cleared,
70
+ * so the run keeps every stage it finished, and `dependency` names what it waits for. The pipeline holds the run until
71
+ * a process that serves the recorded choice resumes it. There is no deadline, and the run is never moved to the
72
+ * machine's choice. `run` is the run's identity, because this is raised before the pipeline holds one.
73
+ *
74
+ * `kind` is one of:
75
+ * register this runner cannot serve the run's register: a credential or a capability it needs is missing here;
76
+ * engine this driver has no adapter for the run's engine;
77
+ * engine-program the run's engine program is not installed here;
78
+ * engine-sign-in the run's engine refused a turn for a configuration fault (signed out, no key).
79
+ */
80
+ export const RUN_CHOICE_KINDS = Object.freeze(["register", "engine", "engine-program", "engine-sign-in"]);
81
+ export class RunChoiceUnavailable extends Error {
82
+ constructor({ kind, recorded, machine = null, detail = null, run = null }) {
83
+ if (!RUN_CHOICE_KINDS.includes(kind)) throw new Error(`RunChoiceUnavailable: unknown kind "${kind}"`);
84
+ const what = kind === "register" ? `the ${recorded} register` : `the ${recorded} engine`;
85
+ const why = kind === "register" ? "this runner cannot serve it"
86
+ : kind === "engine" ? "this driver has no adapter for it"
87
+ : kind === "engine-program" ? "its program is not installed here"
88
+ : "it cannot take a turn here";
89
+ super(`run ${run?.codename ?? "(unnamed)"} started on ${what}, and ${why}${detail ? ` (${String(detail).slice(0, 300)})` : ""}. It is parked with its work kept, and resumes on ${what}.`);
90
+ this.name = "RunChoiceUnavailable";
91
+ this.dependency = { kind, recorded, machine, detail: detail == null ? null : String(detail).slice(0, 300) };
92
+ this.run = run;
93
+ // For the park's own record, as the rate-limit park writes its two lines: what it waits for, and what ends the wait.
94
+ this.waitingOn = `${what}, which this run started on (${why})`;
95
+ this.resolvedBy = kind === "register"
96
+ ? `${what}'s credentials and capabilities set for this runner, on this build; the run resumes where it stopped`
97
+ : `${what} made available to this runner (installed and signed in), on this build; the run resumes where it stopped`;
98
+ }
99
+ }
100
+
101
+ /**
102
+ * Which recorded choice this process cannot serve, before anything is checked or spent, or null. The engine is
103
+ * unservable here only when no adapter is registered for it; a missing program or sign-in is found by the engine doors.
104
+ * The register is not decided here: a recorded register is served wherever this runner holds what it needs, whatever
105
+ * the machine's default, and the register's own door finds out (`registerEnvFor`, steps/open-run.mjs). PURE.
106
+ */
107
+ export function unservedChoice(recorded, { engineRegistered }) {
108
+ if (recorded?.state !== "recorded") return null;
109
+ if (!engineRegistered) return { kind: "engine", recorded: recorded.engine, machine: null };
110
+ return null;
111
+ }
112
+
113
+ /**
114
+ * The environment the register's door checks for this run: a copy of `env` naming the run's recorded register, or `env`
115
+ * itself for a run with no record or one that started with none set. A copy, so one run's register never changes the
116
+ * process environment every concurrent run shares. PURE.
117
+ */
118
+ export function registerEnvFor(recorded, env = process.env) {
119
+ return recorded?.state === "recorded" && recorded.register ? { ...env, CLEAROTRON_DATABASE: recorded.register } : env;
120
+ }
121
+
122
+ /**
123
+ * The register door a run meets: null where it skips the door, else `{ env, parks }`. `env` is what the door checks
124
+ * (`registerEnvFor`), and `parks` says a refusal parks the run rather than failing it, which it does only for a
125
+ * recorded register that is not the machine's. A run whose record fetches are injected (an offline replay) skips the
126
+ * door. So does a Knockout on the machine's own register, as it always has; a Knockout recorded on another register
127
+ * meets the door, because its counts and filings are that register's. PURE.
128
+ */
129
+ export function registerDoor(recorded, { machineRegister = null, knockout = false, fetchesInjected = false, env = process.env } = {}) {
130
+ if (fetchesInjected) return null;
131
+ const differs = recorded?.state === "recorded" && Boolean(recorded.register) && recorded.register !== (machineRegister ?? null);
132
+ if (knockout && !differs) return null;
133
+ return { env: registerEnvFor(recorded, env), parks: differs };
134
+ }
135
+
136
+ /**
137
+ * The register that serves this run: the one it recorded when it started, or the machine's for a run with no record or
138
+ * one that started with none set, whatever the machine's default is now. It is the one place a run's register is
139
+ * decided. A recorded register this runner cannot serve parks the run at the register's door before any stage. PURE
140
+ * but for reading the record.
141
+ */
142
+ export function registerForRun(runDir) {
143
+ const rec = readRunChoices(runDir);
144
+ return rec.state === "recorded" && rec.register ? rec.register : (REGISTER_PROVIDER ?? null);
145
+ }
146
+
147
+ /** The register the run recorded, or null for a run with no record or one that started with none set. PURE but for the read. */
148
+ export function recordedRegister(runDir) {
149
+ const rec = readRunChoices(runDir);
150
+ return rec.state === "recorded" && rec.register ? rec.register : null;
151
+ }
152
+
153
+ /**
154
+ * The register adapter for a run's register (`ctx.register`), or the machine's when none is named: the one way a place
155
+ * that reads a register for a run asks for its adapter. A name this driver does not know throws, as `activeProvider` does.
156
+ */
157
+ export function registerAdapter(register = null) {
158
+ if (!register) return activeProvider();
159
+ const a = PROVIDERS[register];
160
+ if (!a) throw new Error(`[register-provider] unknown register "${register}". Known: ${Object.keys(PROVIDERS).join(", ")}`);
161
+ return a;
162
+ }
@@ -0,0 +1,35 @@
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
+ // stamps.mjs — what the `engine` word on a saved attempt row means.
4
+ //
5
+ // It imports nothing, so the rollup readers can ask it without joining an import loop or loading an adapter.
6
+ // The word on a row is wider than the registered engines: this table is about rows already on disk.
7
+ //
8
+ // A CLOSED TABLE, NOT A PREFIX RULE. `anthropic-*` → anthropic is shorter and would silently adopt any
9
+ // future engine whose name began that way, which is how a vendor claim becomes a guess. An engine this
10
+ // table does not know is reported BY NAME and blocks the single-vendor claim, because "I do not know who
11
+ // billed this" and "one vendor" are different answers and only one of them is safe to print.
12
+ //
13
+ // THE NATIVE-LANGUAGE ROWS STAMP THE VENDOR ITSELF. jxBillingStamp (jx-lanes.mjs) writes as the row's
14
+ // engine the provider the engine door resolved, `anthropic` or `openai` (engine/auth.mjs), so those two
15
+ // names are engines this table must place. Without them an Anthropic-only run with a native-language turn
16
+ // named `anthropic` as an engine that bills to no vendor, in the same sentence that named anthropic as its
17
+ // one vendor. Two exact names, still a closed table.
18
+ //
19
+ // `catalog` says how to key a row with no `modelUsed`: "tier" reads its `model` through Claude's catalog
20
+ // (`resolveModel`), "served" keys it as the id it carries, and a stamp without the field has no honest key.
21
+ // `nativeLanguage` marks a row whose `model` is the id that served the turn and not the tier it asked for.
22
+ const ENGINE_STAMPS = Object.freeze({
23
+ "anthropic-agent": { vendor: "anthropic", catalog: "tier" },
24
+ "anthropic-direct": { vendor: "anthropic" },
25
+ "anthropic-completions": { vendor: "anthropic" },
26
+ "openai-agent": { vendor: "openai" },
27
+ "anthropic": { vendor: "anthropic", catalog: "tier", nativeLanguage: true },
28
+ "openai": { vendor: "openai", catalog: "served", nativeLanguage: true },
29
+ });
30
+
31
+ /** What this table says about a stamp, or an empty record when it does not name it. */
32
+ export const engineStamp = (engine) => (Object.hasOwn(ENGINE_STAMPS, String(engine ?? "")) ? ENGINE_STAMPS[String(engine)] : {});
33
+
34
+ /** The vendor an engine bills to, or null when the table does not name one. */
35
+ export const vendorOf = (engine) => engineStamp(engine).vendor ?? null;
@@ -183,7 +183,7 @@ export function undeclaredFieldsWarning(names) {
183
183
  return `job carries ${names.length} field(s) no door declares: ${list} — DECLARED_JOB_FIELDS does not `
184
184
  + `name them, so nothing validates them, no door gate can rule on them, and any assembling door `
185
185
  + `drops them silently. Declare them in driver/enqueue-schema.mjs if they are meaningful, or stop `
186
- + `writing them. #1085`;
186
+ + `writing them.`;
187
187
  }
188
188
 
189
189
  // — "DID THE REQUEST NAME ANY CLASSES?", ONCE.
@@ -206,7 +206,7 @@ export function undeclaredFieldsWarning(names) {
206
206
  // which is softer — and softer is why it would survive a reading and not a run.
207
207
  //
208
208
  // So the door owns the vocabulary and the framing builders read it. `driver/stages.mjs` still carries
209
- // its own correct copy (that file belongs to another lane's active work); the three are pinned against
209
+ // its own correct copy; the three are pinned against
210
210
  // each other in driver/test/knockout-classes-predicate.test.mjs, so a copy that drifts is a red suite
211
211
  // rather than a prompt aimed at the wrong goods.
212
212
  export function requestNamesClasses(job) {
@@ -409,7 +409,7 @@ export function validateJob(job, { atClaim = false } = {}) {
409
409
  const sidecarNote = `promptParts declares the prose rides as SIDECAR files and none arrived — expected `
410
410
  + `one or more of ${Object.values(PROSE_PARTS).map((x) => `<base>${x}`).join(", ")} beside the manifest. `
411
411
  + `A mis-named manifest is the observed cause: sidecars key on the BARE base, so <base>.manifest.json `
412
- + `leaves them unmatched. #1085`;
412
+ + `leaves them unmatched.`;
413
413
  if (sidecarsMissing) warnings.push(sidecarNote);
414
414
 
415
415
  if (!hasMark) errs.push(sidecarsMissing ? `missing mark name(s) — ${sidecarNote}` : "missing mark name(s)");
@@ -924,7 +924,7 @@ export function validateJob(job, { atClaim = false } = {}) {
924
924
  job.deadline = new Date(t).toISOString();
925
925
  }
926
926
  }
927
- if (!job.ref && !job.tmp) warnings.push("no ref/tmp (TMP Reference No.) — proceeding with no reference");
927
+ if (!job.ref && !job.tmp) warnings.push("No reference number was given, so this search has none.");
928
928
  // Repair-first phase 3 (the teal-causeway msgId defect): a 32-hex msgId is the SANITIZED HASH base
929
929
  // (the job-id derivation), not a Graph message id — the delivery send-tool's inReplyTo lookup will fail and the
930
930
  // notice/delivery falls back off the client thread. Never blocks (still deliverable via fallback);